diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 0000000000..2a4cd2cb93 --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,3 @@ +# Minimum cargo-nextest for this repository: GHSA-vc25-qg58-w57c is fixed in 0.9.150 and CI +# installs exactly that version, so an older nextest refuses to run (exit 92 REQUIRED_VERSION_NOT_MET). +nextest-version = "0.9.150" diff --git a/.github/dependabot.yml b/.github/dependabot.yml index c9de87acfd..d482d6611a 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -10,11 +10,31 @@ updates: interval: "daily" time: "06:00" timezone: "America/New_York" - # Consolidate updates into a single PR rather than one PR per crate groups: - cargo-dependencies: - patterns: - - "*" + # A dependency that matches several groups goes to the first one it matches, so the + # lockstep families are listed before the catch-all cargo-patch group. + # Families that must move together; all update types of a family land in one PR. + egui-stack: # egui/eframe/winit are [patch.crates-io]'d to storytold forks: expect this PR red on upstream releases until the forks move + patterns: ["egui*", "eframe", "epaint*", "ecolor", "emath", "winit", "wgpu*", "naga", "accesskit*"] + font-stack: + patterns: ["harfrust", "skrifa", "read-fonts", "font-types", "fontique", "parley", "write-fonts", "skera", "ttf-parser"] + pdf-render-stack: + patterns: ["hayro*", "krilla*", "vello*", "peniko", "kurbo", "resvg", "usvg", "tiny-skia*", "svgtypes"] + icu-stack: + patterns: ["icu_*", "fixed_decimal"] + ml-stack: + patterns: ["candle-*", "rten*", "ocrs"] + platform-stack: + patterns: ["zbus*", "zvariant*", "x11rb*"] + apple-stack: + patterns: ["objc2*", "block2", "dispatch2"] + rustcrypto: + patterns: ["aes", "sha1", "sha2", "sha3", "md-5", "hmac", "pbkdf2", "digest", "cipher"] + # Everything else: patch bumps only (minor/major of other crates get one PR each). + cargo-patch: + update-types: ["patch"] + patterns: ["*"] + open-pull-requests-limit: 10 commit-message: prefix: "chore(deps)" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000..7b3b6bf5b8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,30 @@ +name: CI + +# Quality gates for every push to main and every pull request (`cargo xtask ci`), through the +# suite's shared gate workflow in craft-common-actions. +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +# A newer push to a PR branch cancels its older run; every push to main runs to the end. +concurrency: + group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + gate: + # 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: + # Same craft-fonts commit as release.yml. + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + timeout-minutes: 90 + packages: >- + pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev + libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers + libgl1-mesa-dev diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index 6ee8681521..007fcfec09 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -1,25 +1,19 @@ # FreeBSD build and package check in a QEMU VM. name: FreeBSD +# The VM build is slow, so it runs nightly on main and on pushes to `release`, not on every pull +# request: a drifted dependency still shows up within a day, and always before a release ships. +# PRs that change the FreeBSD workflow or packaging itself still run it. on: push: - branches: [main] - paths: - - ".github/workflows/freebsd.yml" - - "packaging/freebsd/**" - - "packaging/env.sh" - - "Cargo.toml" - - "Cargo.lock" - - "crates/**" + branches: [release] pull_request: - branches: [main] paths: - - ".github/workflows/freebsd.yml" - - "packaging/freebsd/**" - - "packaging/env.sh" - - "Cargo.toml" - - "Cargo.lock" - - "crates/**" + - .github/workflows/freebsd.yml + - packaging/freebsd/** + - packaging/env.sh + schedule: + - cron: "17 4 * * *" workflow_dispatch: concurrency: @@ -35,5 +29,5 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: require-craft-fonts: true - craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 run-package-check: true diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 3869890227..da85536c43 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -23,3 +23,27 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main with: extra-checks-script: packaging/check-app-specific.sh + + windows-install-policy: + timeout-minutes: 10 + name: Windows installation policy (no app build) + runs-on: windows-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install the pinned packaging toolchain + shell: pwsh + run: | + $tools = Join-Path $env:RUNNER_TEMP 'craft-install-policy-wix' + dotnet tool install --tool-path $tools wix --version 5.0.2 + if ($LASTEXITCODE -ne 0) { throw 'WiX installation failed.' } + $tools >> $env:GITHUB_PATH + $policy = Get-Content -Raw -LiteralPath packaging/windows/install-policy.json | ConvertFrom-Json + foreach ($extension in @($policy.extensions)) { + & (Join-Path $tools 'wix.exe') extension add -g "WixToolset.$extension.wixext/5.0.2" + if ($LASTEXITCODE -ne 0) { throw "WiX extension $extension installation failed." } + } + - name: Build and check non-executable installer fixtures + shell: pwsh + run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests') diff --git a/.github/workflows/print.yml b/.github/workflows/print.yml index 344eae0150..400a819442 100644 --- a/.github/workflows/print.yml +++ b/.github/workflows/print.yml @@ -8,7 +8,7 @@ on: - "apps/vectorcraft/src/printing.rs" - "apps/vectorcraft/src/printing/**" - "crates/ui-egui/src/print.rs" - - "crates/ui-egui/src/tests_printps.rs" + - "crates/ui-egui/src/tests/printps.rs" - ".github/workflows/print.yml" workflow_dispatch: permissions: @@ -26,10 +26,14 @@ jobs: with: toolchain: stable components: clippy - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: desktop-print - run: cargo clippy --locked -p vectorcraft --all-targets -- -D warnings - run: cargo test --locked -p vectorcraft - name: Check pending submission and queue refusal feedback - run: cargo test --locked -p vectorcraft-ui-egui tests_printps + shell: bash + # A filter that matches nothing still passes, so fail unless some test ran. + run: | + cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee printps.log + grep -Eq 'test result: ok\. [1-9][0-9]* passed' printps.log || { echo "::error::tests::printps matched no tests"; exit 1; } diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 54a8e53fb8..d1677e538c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,20 +13,62 @@ on: default: "" permissions: - contents: write + contents: read concurrency: group: release-${{ github.ref }} cancel-in-progress: false jobs: + git-sources: + name: Git dependencies come from storytold + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - 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 + permissions: + contents: write # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: app-name: vectorcraft app-title: VectorCraft - craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 web-craft-fonts: true version: ${{ inputs.version }} secrets: diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml new file mode 100644 index 0000000000..e78fe1ea3b --- /dev/null +++ b/.github/workflows/sonarcloud.yml @@ -0,0 +1,21 @@ +name: SonarCloud + +on: + push: + branches: [main] + pull_request: + types: [opened, synchronize, reopened] + +permissions: + contents: read + +concurrency: + group: sonarcloud-${{ github.ref }} + # A push to main is the run that publishes coverage; superseded runs there would never finish. + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +jobs: + sonarcloud: + # Tracked at @main so org-wide CI improvements propagate without PR churn. + uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main + secrets: inherit diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index f3ba1eeaa5..7fc9b59251 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -5,23 +5,17 @@ # on GitHub Actions' native windows-11-arm runner. name: Windows ARM64 +# Nightly on main and on pushes to `release` (dependency and runner-image drift shows up within a +# day, and always before a release ships), and on PRs that change the Windows packaging itself. on: + schedule: + - cron: "3 5 * * *" push: - branches: [main] - paths: - - ".github/workflows/windows-arm64.yml" - - "packaging/windows/**" - - "Cargo.toml" - - "Cargo.lock" - - "crates/**" + branches: [release] pull_request: - branches: [main] paths: - - ".github/workflows/windows-arm64.yml" - - "packaging/windows/**" - - "Cargo.toml" - - "Cargo.lock" - - "crates/**" + - .github/workflows/windows-arm64.yml + - packaging/windows/** workflow_dispatch: concurrency: @@ -33,8 +27,10 @@ permissions: jobs: windows-arm64: - # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. - uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main + # Immutable supporting workflow revision until the new install contract lands upstream. + uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f with: app-name: vectorcraft app-dir: VectorCraft + install-relative-path: Programs/ArtCraft/VectorCraft + install-scope: perUser diff --git a/.github/workflows/windows7.yml b/.github/workflows/windows7.yml index 0d252f11ed..c638bcef57 100644 --- a/.github/workflows/windows7.yml +++ b/.github/workflows/windows7.yml @@ -14,7 +14,7 @@ on: - "apps/vectorcraft/src/printing.rs" - "apps/vectorcraft/src/printing/**" - "crates/ui-egui/src/print.rs" - - "crates/ui-egui/src/tests_printps.rs" + - "crates/ui-egui/src/tests/printps.rs" - "packaging/windows/windows7.ps1" - ".github/workflows/windows7.yml" schedule: @@ -41,7 +41,7 @@ jobs: with: toolchain: nightly-2026-10-01 components: rust-src - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: windows7-x64 - name: Build, check and test the portable package diff --git a/AGENTS.md b/AGENTS.md index 0b6171cd32..61f141079e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,6 +45,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format - **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd. - **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`. - **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). +- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. - **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`). diff --git a/ASSETS.md b/ASSETS.md index f8121c35bd..26d4630911 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -12,6 +12,8 @@ Generated-in-code art is original and has no file to list. This covers the defau | Asset | Author | Source | Licence | Notes | |---|---|---|---|---| +| `epaint_default_fonts/fonts/egui-icons.ttf` (egui dependency) | John Slegers (emoji-icon-font) | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/egui-icons.txt; original https://github.com/jslegers/emoji-icon-font | MIT (full text in NOTICE) | Small special-icon subset embedded by default_fonts | +| `epaint_default_fonts/fonts/emoji-icon-font.ttf` (egui dependency) | John Slegers | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/emoji-icon-font-mit-license.txt; original https://github.com/jslegers/emoji-icon-font | MIT (full text in NOTICE) | Parent face embedded by monochrome_emoji_fonts | | `docs/brand/artcraft-logo-white.png` | ArtCraft team (project owner) | https://getartcraft.com/ | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | Used in README only; not shipped in the app | | `docs/brand/artcraft-logo-white.svg` | ArtCraft team (project owner) | https://getartcraft.com/ | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | Used in README only; not shipped in the app | | `docs/brand/artcraft-logo.png` | ArtCraft team (project owner) | https://getartcraft.com/ | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | Used in README only; not shipped in the app | @@ -169,6 +171,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-new-stroke.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-objects-on-path.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: three small squares along a curve | MIT OR Apache-2.0 | | | `assets/icons/dc-options.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-para-bullets.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: three dots, each before a line | MIT OR Apache-2.0 | | | `assets/icons/dc-para-center.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-para-justify-all.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-para-justify-center.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -176,6 +179,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-para-justify-right.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-para-left.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-para-ltr.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-para-numbers.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: the digits 1, 2 and 3, each before a line | MIT OR Apache-2.0 | | | `assets/icons/dc-para-right.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-para-rtl.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-path-eraser.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -348,20 +352,20 @@ The shared PDF backend keeps the existing standard-font and CMap features. These | Crate / file | Author | Source | Licence | SHA-256 | Use | | --- | --- | --- | --- | --- | --- | -| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | -| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) | -| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://crates.io/crates/hayro-cmap/0.1.0 | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged | -| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged | +| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) | +| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) | +| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged | +| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged | diff --git a/CLAUDE.md b/CLAUDE.md index 899f22e394..cbf9de1298 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -45,6 +45,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format - **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd. - **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`. - **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). +- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. - **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`). diff --git a/Cargo.lock b/Cargo.lock index ffd1b3d45e..d329c26a7d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,76 +4,70 @@ version = 4 [[package]] name = "accesskit" -version = "0.24.1" +version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320" +checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932" dependencies = [ "uuid", ] [[package]] name = "accesskit_atspi_common" -version = "0.18.1" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e8c61bee90b42a772d39d06a740207dc71a4e780004ace1db8d99fb1baaa954" +checksum = "52c182f9c282ac9c5638d876d551d15e5f7d397ec263349a0c6a2b61595dd5e4" dependencies = [ "accesskit", - "accesskit_consumer 0.36.0", + "accesskit_consumer", "atspi-common", - "phf", + "phf 0.14.0", "serde", "zvariant", ] [[package]] name = "accesskit_consumer" -version = "0.35.0" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53cf47daed85312e763fbf85ceca136e0d7abc68e0a7e12abe11f48172bc3b10" +checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344" dependencies = [ "accesskit", - "hashbrown 0.16.1", + "hashbrown 0.17.1", ] [[package]] -name = "accesskit_consumer" -version = "0.36.0" +name = "accesskit_ios" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25e0d7e25d06f4dc21d1774d67146e9e80d6789216cbd4d1e88185b0095dba60" +checksum = "28e539d64b27fd4c14de8f78ada8f7c944c092f52f7e49fb63316507a57f6937" dependencies = [ "accesskit", - "hashbrown 0.16.1", -] - -[[package]] -name = "accesskit_consumer" -version = "0.38.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245" -dependencies = [ - "accesskit", - "hashbrown 0.16.1", + "accesskit_consumer", + "hashbrown 0.17.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", ] [[package]] name = "accesskit_macos" -version = "0.26.3" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076" +checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4" dependencies = [ "accesskit", - "accesskit_consumer 0.38.0", - "hashbrown 0.16.1", - "objc2 0.5.2", + "accesskit_consumer", + "hashbrown 0.17.1", + "objc2 0.5.3", "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", ] [[package]] name = "accesskit_unix" -version = "0.21.1" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b016ca8db0ea0ea2ceff29a9d6240391492d960716aa471967c00e8cc8cb197c" +checksum = "202f24df034a7476d07b7f74284de84f6d62aabd858dbe7ee9cad3b7ad6f8f9d" dependencies = [ "accesskit", "accesskit_atspi_common", @@ -89,13 +83,13 @@ dependencies = [ [[package]] name = "accesskit_windows" -version = "0.32.1" +version = "0.35.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eff7009f1a532e917d66970a1e80c965140c6cfbbabbdde3d64e5431e6c78e21" +checksum = "ce63f35d6bdcf59f26b76b3379063f738e6412cef46999cc772d46aa3de35adb" dependencies = [ "accesskit", - "accesskit_consumer 0.35.0", - "hashbrown 0.16.1", + "accesskit_consumer", + "hashbrown 0.17.1", "static_assertions", "windows", "windows-core", @@ -103,11 +97,12 @@ dependencies = [ [[package]] name = "accesskit_winit" -version = "0.32.2" +version = "0.34.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fe9a94394896352cc4660ca2288bd4ef883d83238853c038b44070c8f134313" +checksum = "ee96dd150375c05912d8a473f98c2fb155fb3234fac88292d396548a2460fa77" dependencies = [ "accesskit", + "accesskit_ios", "accesskit_macos", "accesskit_unix", "accesskit_windows", @@ -129,7 +124,7 @@ checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", "cipher", - "cpufeatures", + "cpufeatures 0.2.17", ] [[package]] @@ -208,21 +203,21 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "arboard" -version = "3.6.1" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" dependencies = [ "clipboard-win", "image", "log", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "wl-clipboard-rs", "x11rb", ] @@ -344,13 +339,13 @@ dependencies = [ [[package]] name = "async-recursion" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -385,7 +380,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -437,6 +432,30 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "aws-lc-rs" +version = "1.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" +dependencies = [ + "aws-lc-sys", + "untrusted 0.7.1", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + [[package]] name = "base64" version = "0.22.1" @@ -450,13 +469,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" [[package]] -name = "bit-set" -version = "0.8.0" +name = "base64ct" +version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" -dependencies = [ - "bit-vec 0.8.0", -] +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" [[package]] name = "bit-set" @@ -468,10 +484,13 @@ dependencies = [ ] [[package]] -name = "bit-vec" -version = "0.8.0" +name = "bit-set" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec 0.10.1", +] [[package]] name = "bit-vec" @@ -479,6 +498,16 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +[[package]] +name = "bit-vec" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +dependencies = [ + "borsh", + "serde", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -506,7 +535,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" dependencies = [ - "objc2 0.5.2", + "objc2 0.5.3", ] [[package]] @@ -515,7 +544,7 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" dependencies = [ - "objc2 0.6.4", + "objc2 0.6.5", ] [[package]] @@ -531,6 +560,30 @@ dependencies = [ "piper", ] +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "brotli" version = "8.0.4" @@ -575,7 +628,7 @@ checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -606,14 +659,13 @@ dependencies = [ [[package]] name = "calloop" -version = "0.14.4" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dbf9978365bac10f54d1d4b04f7ce4427e51f71d61f2fe15e3fed5166474df7" +checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" dependencies = [ "bitflags 2.13.2", "polling", "rustix 1.1.5", - "slab", "tracing", ] @@ -635,7 +687,7 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" dependencies = [ - "calloop 0.14.4", + "calloop 0.14.5", "rustix 1.1.5", "wayland-backend", "wayland-client", @@ -643,9 +695,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.5.1" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040" +checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df" dependencies = [ "find-msvc-tools", "jobserver", @@ -674,6 +726,31 @@ dependencies = [ "libc", ] +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + [[package]] name = "cipher" version = "0.4.4" @@ -693,6 +770,48 @@ dependencies = [ "error-code", ] +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "cmpv2" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "961b955a666e25ee5a1091d219128d6e6401e3dab84efb1a2bf6b4035d797b39" +dependencies = [ + "crmf", + "der", + "spki", + "x509-cert", +] + +[[package]] +name = "cms" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730" +dependencies = [ + "const-oid", + "der", + "spki", + "x509-cert", +] + +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "codespan-reporting" version = "0.13.1" @@ -731,9 +850,9 @@ dependencies = [ [[package]] name = "combine" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ "bytes", "memchr", @@ -748,6 +867,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "core-foundation" version = "0.9.4" @@ -758,6 +883,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -771,7 +906,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "core-graphics-types", "foreign-types", "libc", @@ -784,10 +919,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "core_maths" version = "0.1.1" @@ -806,15 +947,62 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09a67fb9a3fbd17ffe63#82a24b006eefa036b43c09a67fb9a3fbd17ffe63" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" + +[[package]] +name = "craft-fonts-build" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" + +[[package]] +name = "craft-i18n" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +dependencies = [ + "fixed_decimal", + "icu_decimal", + "icu_locale_core", + "icu_locale_fallback", + "icu_normalizer", + "icu_plurals", + "icu_properties", + "icu_provider", + "icu_provider_adapters", + "icu_provider_blob", + "log", + "objc2-foundation 0.3.2", + "sys-locale", + "unicode-bidi", + "windows-registry", + "writeable", +] + +[[package]] +name = "craft-keymap" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +dependencies = [ + "egui", + "serde", + "serde_json", +] [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d#ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -825,29 +1013,102 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d991bf6792f8ade99c51358bf3c1d902c8cd96b5#d991bf6792f8ade99c51358bf3c1d902c8cd96b5" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ + "craft-winprint-gdi", + "miniz_oxide 0.9.1", + "roxmltree 0.21.1", "tempfile", + "winprint", + "winsafe", ] [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5c874d51eeb3de70e735c8ce87a59a7dedd47675#5c874d51eeb3de70e735c8ce87a59a7dedd47675" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +dependencies = [ + "craft-fonts-build", + "craft-i18n", + "egui", + "epaint", + "js-sys", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "serde", + "skrifa 0.44.0", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "craft-update" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +dependencies = [ + "chrono", + "dunce", + "egui", + "flate2", + "getrandom 0.3.4", + "log", + "plist", + "semver", + "serde", + "serde_json", + "sha2", + "tar", + "tempfile", + "ureq", + "verifysign", + "winreg", + "winsafe", + "zip", +] + +[[package]] +name = "craft-window" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ "egui", - "serde", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "wayland-client", +] + +[[package]] +name = "craft-winprint-gdi" +version = "0.1.0" +source = "git+https://github.com/storytold/winprint.rs?rev=417ac3c4d14d3da5485a99c7d5ce8f05664ec312#417ac3c4d14d3da5485a99c7d5ce8f05664ec312" +dependencies = [ + "windows-sys 0.61.2", ] [[package]] name = "crc32fast" -version = "1.5.2" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" dependencies = [ "cfg-if", ] +[[package]] +name = "crmf" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36fe21b96d5b87f5de4b5b7202ec41c00110ac817ce6728fe75fb2fe5962ed92" +dependencies = [ + "cms", + "der", + "spki", + "x509-cert", +] + [[package]] name = "crossbeam-channel" version = "0.5.17" @@ -910,6 +1171,36 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "der_derive", + "flagset", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "der_derive" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "dify" version = "0.8.0" @@ -948,7 +1239,7 @@ dependencies = [ "bitflags 2.13.2", "block2 0.6.2", "libc", - "objc2 0.6.4", + "objc2 0.6.5", ] [[package]] @@ -959,7 +1250,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -993,10 +1284,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" [[package]] -name = "ecolor" -version = "0.36.2" +name = "dunce" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0656a7530b9e2841ee7a5f983965bdd9840c32f4012f759cfd44b912cced6b34" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "ecolor" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "bytemuck", "emath", @@ -1004,9 +1300,8 @@ dependencies = [ [[package]] name = "eframe" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55ad41fac6e3149abb4866e93df37dbd33baa95db525c3368c944584e95a5dc2" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "ahash", "bytemuck", @@ -1021,7 +1316,7 @@ dependencies = [ "image", "js-sys", "log", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "parking_lot", @@ -1029,6 +1324,7 @@ dependencies = [ "pollster 1.0.1", "profiling", "raw-window-handle", + "send_wrapper", "static_assertions", "wasm-bindgen", "web-sys", @@ -1040,9 +1336,8 @@ dependencies = [ [[package]] name = "egui" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc938cc27cd911415e1e4d151bc56ff9df063d8db081374e87aeb805ea74b2ba" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "accesskit", "ahash", @@ -1060,9 +1355,8 @@ dependencies = [ [[package]] name = "egui-wgpu" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cef1f6d1bba40b09a4d0d62cb822b81030922cfbf65c5373398c3a3caafc5bd" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "ahash", "bytemuck", @@ -1080,30 +1374,33 @@ dependencies = [ [[package]] name = "egui-winit" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98466000559d66ba4db786a30448b01483946add4188e7f10f522a27b4fb89cc" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "accesskit_winit", "arboard", + "block2 0.6.2", "bytemuck", "egui", + "image", "log", - "objc2 0.6.4", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "objc2-ui-kit 0.3.2", + "parking_lot", "profiling", "raw-window-handle", "smithay-clipboard", "web-time", + "windows-sys 0.61.2", "winit", ] [[package]] name = "egui_extras" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05cbdc785020861553f230f23d330ba1fb72613b9d8e0e457f3bdc8ba6db6dcf" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "ahash", "egui", @@ -1116,9 +1413,8 @@ dependencies = [ [[package]] name = "egui_glow" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "606ed4167daf341e5753d703285c4c1d562324b2c07aa8f405cd7d066fe58f3b" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "bytemuck", "egui", @@ -1130,9 +1426,8 @@ dependencies = [ [[package]] name = "egui_kittest" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5eb3f3effb2726fee23449293e67acbf6cc6ce35525b1722bd5743bb348114d5" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "dify", "eframe", @@ -1151,19 +1446,32 @@ dependencies = [ [[package]] name = "either" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52c8d4141cf0f60fb2f7aefaf352d3ffa5171ef0ab09731c64391801e95e48f1" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "bytemuck", ] +[[package]] +name = "encoding_rs" +version = "0.8.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "endi" version = "1.1.1" @@ -1172,22 +1480,22 @@ checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" [[package]] name = "enum-map" -version = "2.7.3" +version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6866f3bfdf8207509a033af1a75a7b08abda06bbaaeae6669323fd5a097df2e9" +checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06" dependencies = [ "enum-map-derive", ] [[package]] name = "enum-map-derive" -version = "0.17.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f282cfdfe92516eb26c2af8589c274c7c17681f5ecc03c18255fe741c6aa64eb" +checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -1213,16 +1521,15 @@ dependencies = [ [[package]] name = "epaint" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0ec0308dc23130fc1a7d4623a8534c2ed069c6dc84e258ee4f3de99615aa1a3" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" dependencies = [ "ahash", "bytemuck", "ecolor", "emath", "epaint_default_fonts", - "font-types 0.12.5", + "font-types 0.12.7", "harfrust 0.12.0", "log", "nohash-hasher", @@ -1231,22 +1538,23 @@ dependencies = [ "self_cell", "skrifa 0.44.0", "smallvec", + "unicode-bidi", "unicode-general-category", + "unicode-properties", "unicode-segmentation", - "vello_cpu 0.1.0", + "vello_cpu", ] [[package]] name = "epaint_default_fonts" -version = "0.36.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773fa9c96dd0dbef887e39d0ed6177f141cce4d68e6041df77570aa3702dfa13" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" @@ -1321,10 +1629,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" [[package]] -name = "find-msvc-tools" -version = "0.1.14" +name = "filetime" +version = "0.2.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fixed_decimal" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2214fb00f669ee96bee5bb29dfb1ddabe058b2bc426817efc79afa03c9bc55ae" +dependencies = [ + "displaydoc", + "smallvec", + "writeable", +] [[package]] name = "fixedbitset" @@ -1332,6 +1661,12 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + [[package]] name = "flate2" version = "1.1.10" @@ -1352,6 +1687,28 @@ dependencies = [ "num-traits", ] +[[package]] +name = "fmt-derive" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cb4a4b45c26455885f8b462db12978e51f60cc914337bccb9a36faf93410169" +dependencies = [ + "fmt-derive-proc", +] + +[[package]] +name = "fmt-derive-proc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7704da0760734344ce8753f15b21e97c6be85dc5a8f2c3a963fbd042b3380d23" +dependencies = [ + "proc-macro-crate", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "fnv" version = "1.0.7" @@ -1381,9 +1738,9 @@ dependencies = [ [[package]] name = "font-types" -version = "0.12.5" +version = "0.12.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8eb065f3251655b3c90e22e5e363f310fc5332fb3402e37bbc94752283248f6" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" dependencies = [ "bytemuck", ] @@ -1417,7 +1774,7 @@ checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -1435,6 +1792,22 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -1468,9 +1841,15 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + [[package]] name = "futures-task" version = "0.3.34" @@ -1484,8 +1863,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-io", "futures-macro", + "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] @@ -1519,6 +1901,19 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1538,8 +1933,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -1549,7 +1947,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" dependencies = [ "color_quant", - "weezl", + "weezl 0.1.12", ] [[package]] @@ -1563,22 +1961,6 @@ dependencies = [ "xml-rs", ] -[[package]] -name = "glifo" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed4a1bb24121291d27230c1b1b44e07d6a9b28cefdb32fe1581dfb84e14f940a" -dependencies = [ - "bytemuck", - "foldhash 0.2.0", - "hashbrown 0.17.1", - "log", - "peniko", - "skrifa 0.44.0", - "smallvec", - "vello_common 0.1.0", -] - [[package]] name = "glifo" version = "0.3.0" @@ -1593,7 +1975,7 @@ dependencies = [ "png 0.18.1", "skrifa 0.44.0", "smallvec", - "vello_common 0.2.0", + "vello_common", ] [[package]] @@ -1622,7 +2004,7 @@ dependencies = [ "glutin_glx_sys", "glutin_wgl_sys", "libloading", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-core-foundation", "objc2-foundation 0.3.2", @@ -1697,6 +2079,25 @@ dependencies = [ "euclid", ] +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "half" version = "2.7.1" @@ -1772,8 +2173,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d285dc30731c8485de5fa732fbdf2b3affdf01e4da7c2135022ca6fa664bf6" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ "brotli", "hayro-postscript", @@ -1782,14 +2182,14 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d#ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ "bitflags 2.13.2", "hayro-cmap", "hayro-syntax", "kurbo 0.13.1", "moxcms", - "phf", + "phf 0.13.1", "rustc-hash 2.1.3", "siphasher", "skrifa 0.47.0", @@ -1800,7 +2200,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d#ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -1818,13 +2218,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d#ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ "flate2", "hayro-ccitt", @@ -1837,6 +2236,12 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hermit-abi" version = "0.5.3" @@ -1849,6 +2254,131 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "icu_collections" version = "2.3.0" @@ -1863,6 +2393,23 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_decimal" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb8f655bba2d0c0459e43a5b0e6cd3cd388109898fb3d85d048165e8b0abd08" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_locale_core", + "icu_pattern", + "icu_plurals", + "icu_provider", + "serde", + "writeable", + "zerovec", +] + [[package]] name = "icu_locale_core" version = "2.3.0" @@ -1908,6 +2455,9 @@ dependencies = [ "icu_properties", "icu_provider", "smallvec", + "utf16_iter", + "utf8_iter", + "write16", "zerovec", ] @@ -1917,6 +2467,32 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" +[[package]] +name = "icu_pattern" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b3db611446bd92c246b03e4aa0bafa71ddb194af431ddbb42b9d70e4bfce1a0" +dependencies = [ + "displaydoc", + "either", + "serde", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_plurals" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e475e6766ef87b1d3c1f97be6363995b0bfaeddbc789671615df598a97ff0593" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_provider", + "serde", + "zerovec", +] + [[package]] name = "icu_properties" version = "2.3.0" @@ -1946,6 +2522,7 @@ checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" dependencies = [ "displaydoc", "icu_locale_core", + "postcard", "serde", "stable_deref_trait", "writeable", @@ -1955,6 +2532,30 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_provider_adapters" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df887bc4f55dbc773c7c45a0c7dfa75be886f7b7812830a71ab7271cc1801820" +dependencies = [ + "icu_locale_fallback", + "icu_provider", +] + +[[package]] +name = "icu_provider_blob" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5916b44fac319d3f58e4d8d805a627df19e27937b582cd99fcde3bb6b7ce1b0e" +dependencies = [ + "icu_provider", + "postcard", + "serde", + "writeable", + "zerotrie", + "zerovec", +] + [[package]] name = "icu_segmenter" version = "2.3.0" @@ -2065,6 +2666,12 @@ dependencies = [ "generic-array", ] +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "is-docker" version = "0.2.0" @@ -2213,18 +2820,18 @@ checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" [[package]] name = "kittest" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90ceaa75eb0036a32b6b9833962eb18137449e9817e2e586006471925b727fd5" +checksum = "0bb81a721ba76aa095b7f45deb180504f786904e56ca4b8e141f66eb89a78b75" dependencies = [ "accesskit", - "accesskit_consumer 0.35.0", + "accesskit_consumer", ] [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d#ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ "base64 0.22.1", "bumpalo", @@ -2286,9 +2893,9 @@ checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" [[package]] name = "libc" -version = "0.2.189" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libloading" @@ -2315,7 +2922,7 @@ dependencies = [ "bitflags 2.13.2", "libc", "plain", - "redox_syscall 0.9.4", + "redox_syscall 0.9.5", ] [[package]] @@ -2354,12 +2961,15 @@ name = "litemap" version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +dependencies = [ + "serde_core", +] [[package]] name = "litrs" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" [[package]] name = "lock_api" @@ -2376,6 +2986,12 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "md-5" version = "0.10.6" @@ -2410,6 +3026,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -2430,6 +3052,17 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "moxcms" version = "0.8.1" @@ -2442,14 +3075,14 @@ dependencies = [ [[package]] name = "muda" -version = "0.21.1" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a7b000cca0783af26837fe2ebd9ddf1c42279463c085b97622ee1d2f444b89e" +checksum = "4340e89c178916e62879c5c36b7f699019369be413e496178a6983ce91b8bc03" dependencies = [ "crossbeam-channel", "dpi", "keyboard-types", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-core-foundation", "objc2-foundation 0.3.2", @@ -2458,6 +3091,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "naga" version = "30.0.1" @@ -2526,6 +3165,18 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -2541,6 +3192,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-traits" version = "0.2.19" @@ -2581,9 +3238,9 @@ checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" [[package]] name = "objc2" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" dependencies = [ "objc-sys", "objc2-encode", @@ -2591,9 +3248,9 @@ dependencies = [ [[package]] name = "objc2" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" dependencies = [ "objc2-encode", ] @@ -2607,7 +3264,7 @@ dependencies = [ "bitflags 2.13.2", "block2 0.5.1", "libc", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-core-data", "objc2-core-image", "objc2-foundation 0.2.2", @@ -2622,7 +3279,7 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation 0.3.2", @@ -2636,7 +3293,7 @@ checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" dependencies = [ "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-core-location", "objc2-foundation 0.2.2", ] @@ -2648,7 +3305,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] @@ -2660,7 +3317,7 @@ checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" dependencies = [ "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] @@ -2672,7 +3329,7 @@ checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ "bitflags 2.13.2", "dispatch2", - "objc2 0.6.4", + "objc2 0.6.5", ] [[package]] @@ -2683,7 +3340,7 @@ checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ "bitflags 2.13.2", "dispatch2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-io-surface", ] @@ -2695,7 +3352,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", "objc2-metal 0.2.2", ] @@ -2707,7 +3364,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-contacts", "objc2-foundation 0.2.2", ] @@ -2737,7 +3394,7 @@ dependencies = [ "block2 0.5.1", "dispatch", "libc", - "objc2 0.5.2", + "objc2 0.5.3", ] [[package]] @@ -2748,7 +3405,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", ] @@ -2759,7 +3416,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" dependencies = [ "bitflags 2.13.2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", ] @@ -2770,7 +3427,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", ] @@ -2783,7 +3440,7 @@ checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" dependencies = [ "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] @@ -2795,7 +3452,7 @@ checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-foundation 0.3.2", ] @@ -2807,7 +3464,7 @@ checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" dependencies = [ "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", "objc2-metal 0.2.2", ] @@ -2819,7 +3476,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" dependencies = [ "bitflags 2.13.2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation 0.3.2", @@ -2832,7 +3489,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" dependencies = [ - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] @@ -2844,7 +3501,7 @@ checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" dependencies = [ "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-cloud-kit", "objc2-core-data", "objc2-core-image", @@ -2864,7 +3521,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" dependencies = [ "bitflags 2.13.2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-foundation 0.3.2", ] @@ -2876,7 +3533,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] @@ -2888,7 +3545,7 @@ checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" dependencies = [ "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-core-location", "objc2-foundation 0.2.2", ] @@ -2909,6 +3566,12 @@ dependencies = [ "libc", ] +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + [[package]] name = "orbclient" version = "0.3.55" @@ -2998,6 +3661,25 @@ dependencies = [ "ryu", ] +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "peniko" version = "0.6.1" @@ -3034,8 +3716,18 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ - "phf_macros", - "phf_shared", + "phf_macros 0.13.1", + "phf_shared 0.13.1", +] + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros 0.14.0", + "phf_shared 0.14.0", "serde", ] @@ -3046,7 +3738,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" dependencies = [ "fastrand", - "phf_shared", + "phf_shared 0.13.1", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared 0.14.0", ] [[package]] @@ -3055,8 +3757,21 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" dependencies = [ - "phf_generator", - "phf_shared", + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", "proc-macro2", "quote", "syn 2.0.119", @@ -3071,6 +3786,15 @@ dependencies = [ "siphasher", ] +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + [[package]] name = "pico-args" version = "0.5.0" @@ -3126,6 +3850,19 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "plist" +version = "1.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" +dependencies = [ + "base64 0.23.1", + "indexmap", + "quick-xml 0.42.0", + "serde", + "time", +] + [[package]] name = "png" version = "0.17.16" @@ -3202,6 +3939,16 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "serde", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -3214,13 +3961,10 @@ dependencies = [ ] [[package]] -name = "ppv-lite86" -version = "0.2.21" +name = "powerfmt" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" [[package]] name = "presser" @@ -3237,6 +3981,30 @@ dependencies = [ "toml_edit", ] +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -3254,16 +4022,17 @@ checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" [[package]] name = "proptest" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" dependencies = [ - "bit-set 0.8.0", - "bit-vec 0.8.0", + "bit-set 0.11.1", + "bit-vec 0.10.1", "bitflags 2.13.2", + "chacha20", + "core_detect", "num-traits", "rand", - "rand_chacha", "rand_xorshift", "regex-syntax", "rusty-fork", @@ -3307,6 +4076,72 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash 2.1.3", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash 2.1.3", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "1.0.47" @@ -3330,40 +4165,43 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.9.5" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core", + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", ] [[package]] name = "rand_core" -version = "0.9.5" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" dependencies = [ - "getrandom 0.3.4", + "rand_core 0.10.1", ] [[package]] name = "rand_xorshift" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" dependencies = [ - "rand_core", + "rand_core 0.10.1", ] [[package]] @@ -3384,7 +4222,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" dependencies = [ - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-foundation 0.3.2", "objc2-quartz-core 0.3.2", @@ -3427,7 +4265,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" dependencies = [ "bytemuck", - "font-types 0.12.5", + "font-types 0.12.7", "once_cell", ] @@ -3438,7 +4276,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "005c8acf251756c478b0bf402885bfd88a1476020c4c7e6060edc1aa68da38ea" dependencies = [ "bytemuck", - "font-types 0.12.5", + "font-types 0.12.7", "once_cell", ] @@ -3449,7 +4287,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8" dependencies = [ "bytemuck", - "font-types 0.12.5", + "font-types 0.12.7", "once_cell", ] @@ -3473,9 +4311,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "737970939a87c6fa31e7acad13307bccbb017a073b695b6089a2c484f929e20e" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" dependencies = [ "bitflags 2.13.2", ] @@ -3492,6 +4330,49 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "encoding_rs", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "resvg" version = "0.45.1" @@ -3517,7 +4398,7 @@ dependencies = [ "js-sys", "libc", "log", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-core-foundation", "objc2-foundation 0.3.2", @@ -3542,6 +4423,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted 0.9.0", + "windows-sys 0.52.0", +] + [[package]] name = "roxmltree" version = "0.20.0" @@ -3604,6 +4499,83 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted 0.9.0", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -3655,6 +4627,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "ryu-js" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" + [[package]] name = "same-file" version = "1.0.6" @@ -3664,6 +4642,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -3687,6 +4674,29 @@ dependencies = [ "tiny-skia", ] +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -3698,6 +4708,16 @@ name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "send_wrapper" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" [[package]] name = "serde" @@ -3726,14 +4746,14 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] name = "serde_json" -version = "1.0.151" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -3742,6 +4762,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_json_canonicalizer" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe52319a927259afbfa5180c5157cd8167edfd3e8c254f9558c7fef44c5649f2" +dependencies = [ + "ryu-js", + "serde", + "serde_json", +] + [[package]] name = "serde_repr" version = "0.1.21" @@ -3750,18 +4781,41 @@ checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] name = "serde_spanned" -version = "1.1.1" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + [[package]] name = "sha2" version = "0.10.9" @@ -3769,7 +4823,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] @@ -3789,6 +4843,175 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "sigstore-bundle" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7dc53c8a941858d01479622dbb7650aaa2ee0ca1fb58fb6cdddbfc3064abbb" +dependencies = [ + "base64 0.22.1", + "hex", + "serde", + "serde_json", + "sigstore-crypto", + "sigstore-merkle", + "sigstore-rekor", + "sigstore-tsa", + "sigstore-types", + "thiserror 2.0.21", +] + +[[package]] +name = "sigstore-crypto" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b" +dependencies = [ + "aws-lc-rs", + "base64 0.22.1", + "const-oid", + "der", + "digest", + "pem", + "rand_core 0.10.1", + "sha2", + "signature", + "sigstore-types", + "spki", + "thiserror 2.0.21", + "tracing", + "x509-cert", +] + +[[package]] +name = "sigstore-merkle" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c0d53558825c77716855c13794306fff766854c1bf92948e77d7890da3f2455" +dependencies = [ + "base64 0.22.1", + "hex", + "sigstore-crypto", + "sigstore-types", + "thiserror 2.0.21", +] + +[[package]] +name = "sigstore-rekor" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "641fdaaa40d0cd6e249cf1671c2240beff1a3ece578062cf43e750779e8db2b3" +dependencies = [ + "base64 0.22.1", + "hex", + "reqwest", + "serde", + "serde_json", + "sigstore-crypto", + "sigstore-merkle", + "sigstore-types", + "thiserror 2.0.21", + "url", +] + +[[package]] +name = "sigstore-trust-root" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6b0d2550f05c096400066e858db13d91f9de3b750a7541fb1291c1dc80ca290" +dependencies = [ + "base64 0.22.1", + "chrono", + "hex", + "rustls-pki-types", + "serde", + "serde_json", + "sigstore-crypto", + "sigstore-types", + "thiserror 2.0.21", + "x509-cert", +] + +[[package]] +name = "sigstore-tsa" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bc86c8abc1ece6832236e7e34e9baebb5d4d40490c0332b814a0d8624ca7255" +dependencies = [ + "aws-lc-rs", + "base64 0.22.1", + "chrono", + "cmpv2", + "cms", + "const-oid", + "der", + "hex", + "rand", + "reqwest", + "rustls-pki-types", + "rustls-webpki", + "sigstore-crypto", + "sigstore-types", + "thiserror 2.0.21", + "tracing", + "x509-cert", + "x509-tsp", +] + +[[package]] +name = "sigstore-types" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8d870c9bcfdf83396ac2bd2d6a23c5d09ec02cc9fda50fa1cbb3dd71a9bee53" +dependencies = [ + "base64 0.22.1", + "chrono", + "hex", + "pem", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "sigstore-verify" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d30aff69036e4579b416956e9ba68cec45b793116f78f10842d04c7f8b924bab" +dependencies = [ + "base64 0.22.1", + "chrono", + "cms", + "const-oid", + "hex", + "pem", + "rustls-pki-types", + "rustls-webpki", + "serde", + "serde_json", + "serde_json_canonicalizer", + "sigstore-bundle", + "sigstore-crypto", + "sigstore-merkle", + "sigstore-rekor", + "sigstore-trust-root", + "sigstore-tsa", + "sigstore-types", + "thiserror 2.0.21", + "tls_codec", + "tracing", + "x509-cert", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -3873,9 +5096,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.16.2" +version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" dependencies = [ "serde", ] @@ -3912,7 +5135,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0512da38f5e2b31201a93524adb8d3136276fa4fe4aafab4e1f727a82b534cc0" dependencies = [ "bitflags 2.13.2", - "calloop 0.14.4", + "calloop 0.14.5", "calloop-wayland-source 0.4.1", "cursor-icon", "libc", @@ -3977,6 +5200,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -4019,6 +5252,27 @@ dependencies = [ "unicode-properties", ] +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "subsetter" version = "0.2.6" @@ -4031,6 +5285,12 @@ dependencies = [ "write-fonts", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "svgtypes" version = "0.15.3" @@ -4051,6 +5311,16 @@ dependencies = [ "siphasher", ] +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "unicode-ident", +] + [[package]] name = "syn" version = "2.0.119" @@ -4064,15 +5334,24 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.6" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -4081,7 +5360,51 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", +] + +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "js-sys", + "libc", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", ] [[package]] @@ -4143,7 +5466,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -4165,10 +5488,40 @@ dependencies = [ "flate2", "half", "quick-error 2.0.1", - "weezl", + "weezl 0.1.12", "zune-jpeg", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-skia" version = "0.11.4" @@ -4224,19 +5577,69 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] -name = "tokio" -version = "1.53.1" +name = "tls_codec" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b" dependencies = [ + "tls_codec_derive", + "zeroize", +] + +[[package]] +name = "tls_codec_derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tokio" +version = "1.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc" +dependencies = [ + "bytes", + "libc", + "mio", "pin-project-lite", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", ] [[package]] name = "toml" -version = "1.1.6+spec-1.1.0" +version = "1.1.8+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" dependencies = [ "indexmap", "serde_core", @@ -4249,18 +5652,18 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.1+spec-1.1.0" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" dependencies = [ "serde_core", ] [[package]] name = "toml_edit" -version = "0.25.15+spec-1.1.0" +version = "0.25.17+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" dependencies = [ "indexmap", "toml_datetime", @@ -4270,18 +5673,63 @@ dependencies = [ [[package]] name = "toml_parser" -version = "1.1.3+spec-1.1.0" +version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ "winnow", ] [[package]] name = "toml_writer" -version = "1.1.2+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tracing" @@ -4326,6 +5774,12 @@ dependencies = [ "petgraph", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "ttf-parser" version = "0.25.1" @@ -4350,6 +5804,12 @@ dependencies = [ "rustc-hash 2.1.3", ] +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + [[package]] name = "typenum" version = "1.20.1" @@ -4399,15 +5859,15 @@ checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" [[package]] name = "unicode-ident" -version = "1.0.26" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-normalization" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" dependencies = [ "tinyvec", ] @@ -4442,6 +5902,47 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "ureq-proto", + "utf8-zero", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + [[package]] name = "url" version = "2.5.8" @@ -4504,6 +6005,18 @@ dependencies = [ "xmlwriter", ] +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -4512,9 +6025,9 @@ checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" [[package]] name = "uuid" -version = "1.26.1" +version = "1.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" dependencies = [ "js-sys", "serde_core", @@ -4523,18 +6036,21 @@ dependencies = [ [[package]] name = "vectorcraft" -version = "0.14.0" +version = "0.17.0" dependencies = [ "arboard", "block2 0.6.2", + "chrono", "clipboard-win", "craft-print", + "craft-update", + "craft-window", "eframe", "egui", "image", "log", "muda", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-core-foundation", "objc2-core-text", @@ -4555,12 +6071,13 @@ dependencies = [ "winit", "winresource", "winsafe", + "x11rb", "zbus", ] [[package]] name = "vectorcraft-affinity" -version = "0.14.0" +version = "0.17.0" dependencies = [ "crc32fast", "flate2", @@ -4571,7 +6088,7 @@ dependencies = [ [[package]] name = "vectorcraft-brush" -version = "0.14.0" +version = "0.17.0" dependencies = [ "kurbo 0.13.1", "serde", @@ -4583,7 +6100,7 @@ dependencies = [ [[package]] name = "vectorcraft-cad" -version = "0.14.0" +version = "0.17.0" dependencies = [ "image", "kurbo 0.13.1", @@ -4599,7 +6116,7 @@ dependencies = [ [[package]] name = "vectorcraft-cli" -version = "0.14.0" +version = "0.17.0" dependencies = [ "log", "objc2-core-foundation", @@ -4621,7 +6138,7 @@ dependencies = [ [[package]] name = "vectorcraft-color" -version = "0.14.0" +version = "0.17.0" dependencies = [ "kurbo 0.13.1", "moxcms", @@ -4633,8 +6150,9 @@ dependencies = [ [[package]] name = "vectorcraft-doc" -version = "0.14.0" +version = "0.17.0" dependencies = [ + "chrono", "hayro-ccitt", "image", "jpeg-encoder", @@ -4651,7 +6169,7 @@ dependencies = [ [[package]] name = "vectorcraft-effects" -version = "0.14.0" +version = "0.17.0" dependencies = [ "image", "kurbo 0.13.1", @@ -4667,7 +6185,7 @@ dependencies = [ [[package]] name = "vectorcraft-engine" -version = "0.14.0" +version = "0.17.0" dependencies = [ "craft-docpath", "crc32fast", @@ -4677,6 +6195,7 @@ dependencies = [ "log", "proptest", "roxmltree 0.21.1", + "rustix 1.1.5", "ruzstd", "serde", "serde_json", @@ -4705,13 +6224,14 @@ dependencies = [ [[package]] name = "vectorcraft-eps" -version = "0.14.0" +version = "0.17.0" dependencies = [ "fax", "flate2", "hayro-ccitt", "image", "kurbo 0.13.1", + "memchr", "ruzstd", "serde_json", "vectorcraft-brush", @@ -4728,7 +6248,7 @@ dependencies = [ [[package]] name = "vectorcraft-format" -version = "0.14.0" +version = "0.17.0" dependencies = [ "flate2", "proptest", @@ -4743,7 +6263,7 @@ dependencies = [ [[package]] name = "vectorcraft-geom" -version = "0.14.0" +version = "0.17.0" dependencies = [ "kurbo 0.13.1", "proptest", @@ -4755,7 +6275,7 @@ dependencies = [ [[package]] name = "vectorcraft-mcp" -version = "0.14.0" +version = "0.17.0" dependencies = [ "image", "log", @@ -4774,7 +6294,7 @@ dependencies = [ [[package]] name = "vectorcraft-metafile" -version = "0.14.0" +version = "0.17.0" dependencies = [ "image", "kurbo 0.13.1", @@ -4788,7 +6308,7 @@ dependencies = [ [[package]] name = "vectorcraft-pathops" -version = "0.14.0" +version = "0.17.0" dependencies = [ "kurbo 0.13.1", "linesweeper", @@ -4800,9 +6320,10 @@ dependencies = [ [[package]] name = "vectorcraft-pdf" -version = "0.14.0" +version = "0.17.0" dependencies = [ "aes", + "chrono", "craft-pdf", "flate2", "image", @@ -4825,12 +6346,12 @@ dependencies = [ "vectorcraft-geom", "vectorcraft-testkit", "vectorcraft-text", - "weezl", + "weezl 0.2.1", ] [[package]] name = "vectorcraft-plugins" -version = "0.14.0" +version = "0.17.0" dependencies = [ "serde", "serde_json", @@ -4844,13 +6365,14 @@ dependencies = [ [[package]] name = "vectorcraft-render" -version = "0.14.0" +version = "0.17.0" dependencies = [ "flate2", "gif", "image", "jpeg-encoder", "log", + "png 0.18.1", "proptest", "psd", "serde_json", @@ -4863,22 +6385,23 @@ dependencies = [ "vectorcraft-plugins", "vectorcraft-testkit", "vectorcraft-text", - "vello_common 0.2.0", - "vello_cpu 0.2.0", + "vello_common", + "vello_cpu", "wat", - "weezl", + "weezl 0.2.1", + "winsafe", ] [[package]] name = "vectorcraft-scriptcheck" -version = "0.14.0" +version = "0.17.0" dependencies = [ "proptest", ] [[package]] name = "vectorcraft-svg" -version = "0.14.0" +version = "0.17.0" dependencies = [ "craft-docpath", "flate2", @@ -4903,7 +6426,7 @@ dependencies = [ [[package]] name = "vectorcraft-testkit" -version = "0.14.0" +version = "0.17.0" dependencies = [ "fax", "image", @@ -4921,7 +6444,7 @@ dependencies = [ [[package]] name = "vectorcraft-text" -version = "0.14.0" +version = "0.17.0" dependencies = [ "harfrust 0.13.3", "icu_segmenter", @@ -4935,13 +6458,14 @@ dependencies = [ "unicode-segmentation", "vectorcraft-doc", "vectorcraft-geom", + "vello_cpu", "windows-registry", "write-fonts", ] [[package]] name = "vectorcraft-three-d" -version = "0.14.0" +version = "0.17.0" dependencies = [ "vectorcraft-geom", "vectorcraft-pathops", @@ -4949,7 +6473,7 @@ dependencies = [ [[package]] name = "vectorcraft-tools" -version = "0.14.0" +version = "0.17.0" dependencies = [ "image", "kurbo 0.13.1", @@ -4965,7 +6489,7 @@ dependencies = [ [[package]] name = "vectorcraft-trace" -version = "0.14.0" +version = "0.17.0" dependencies = [ "image", "kurbo 0.13.1", @@ -4977,14 +6501,18 @@ dependencies = [ [[package]] name = "vectorcraft-ui-egui" -version = "0.14.0" +version = "0.17.0" dependencies = [ + "bytemuck", + "craft-keymap", "craft-ui", + "craft-update", "egui", "egui_extras", "egui_kittest", "image", "log", + "rustix 1.1.5", "serde", "serde_json", "toml", @@ -5011,7 +6539,7 @@ dependencies = [ [[package]] name = "vectorcraft-web" -version = "0.14.0" +version = "0.17.0" dependencies = [ "eframe", "egui", @@ -5028,21 +6556,6 @@ dependencies = [ "web-sys", ] -[[package]] -name = "vello_common" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2e9aed918117e8152c9eddfd8362d73c465c23f26c44786aa331707b8a64fa2" -dependencies = [ - "bytemuck", - "fearless_simd", - "guillotiere", - "log", - "peniko", - "smallvec", - "thiserror 2.0.21", -] - [[package]] name = "vello_common" version = "0.2.0" @@ -5059,18 +6572,6 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "vello_cpu" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac7349e1f55f6b801c7c277958df4ea53e7f20f21e8014910ad888b2ecda93ea" -dependencies = [ - "bytemuck", - "glifo 0.2.0", - "hashbrown 0.17.1", - "vello_common 0.1.0", -] - [[package]] name = "vello_cpu" version = "0.2.0" @@ -5079,13 +6580,23 @@ checksum = "ace506ca414548966fcf3c283be94eb1cad8254de488791ee698bf438b0890a9" dependencies = [ "bytemuck", "crossbeam-channel", - "glifo 0.3.0", + "glifo", "hashbrown 0.17.1", "ordered-channel", "png 0.18.1", "rayon", "thread_local", - "vello_common 0.2.0", + "vello_common", +] + +[[package]] +name = "verifysign" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6acfcc42a8d44f340d001193d97ef56bf33210b51ad760ae8308c97d5241ca51" +dependencies = [ + "core-foundation 0.10.1", + "windows-sys 0.61.2", ] [[package]] @@ -5113,6 +6624,21 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -5165,7 +6691,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "wasm-bindgen-shared", ] @@ -5180,12 +6706,12 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.261.0" +version = "0.262.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2608e8bb6d67fd68f5a8d0eb1363d6e7bcbc1f8ded5a0bd3a1e382462b876b22" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" dependencies = [ "leb128fmt", - "wasmparser 0.261.0", + "wasmparser 0.262.0", ] [[package]] @@ -5240,9 +6766,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.261.0" +version = "0.262.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f20f20e44f7e8aeb6744823ea9d869ede51e51be4fdaedede2852282e54d2d8" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" dependencies = [ "bitflags 2.13.2", "indexmap", @@ -5251,9 +6777,9 @@ dependencies = [ [[package]] name = "wast" -version = "261.0.0" +version = "262.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "776443145731a4062e5b0d392892a2005909b6ab72d9fdc3cad53dd1a714e44a" +checksum = "30612a0c29249b5f185888a107e8a519d920226b7d07f9d351fd094e9f75eb23" dependencies = [ "bumpalo", "leb128fmt", @@ -5264,9 +6790,9 @@ dependencies = [ [[package]] name = "wat" -version = "1.261.0" +version = "1.262.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7b4d1a49ea73a8f3326e74e3a05db667001b16bd1035ed3356fc1a0ed05ca7f" +checksum = "e228027f2b07bbaf946980ebbe2437fca73be6f54c40c2a8d4f42f277075f8d1" dependencies = [ "wast", ] @@ -5390,7 +6916,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" dependencies = [ "proc-macro2", - "quick-xml", + "quick-xml 0.41.0", "quote", ] @@ -5428,26 +6954,41 @@ dependencies = [ [[package]] name = "webbrowser" -version = "1.2.4" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62c35be770821a214dbc362fc26908c853e776c0004294d0b10b8a6bad582f94" +checksum = "d2c8ddfbbf66e501434657400268cefe51b95140a0266236415cda7627732df7" dependencies = [ "jni", "log", "ndk-context", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "url", "web-sys", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" +[[package]] +name = "weezl" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2" + [[package]] name = "wgpu" version = "30.0.1" @@ -5576,7 +7117,7 @@ dependencies = [ "naga", "naga-types", "ndk-sys", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation 0.3.2", @@ -5758,7 +7299,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -5767,16 +7308,7 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", + "windows-targets", ] [[package]] @@ -5794,31 +7326,14 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] [[package]] @@ -5836,101 +7351,52 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - [[package]] name = "winit" version = "0.30.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" dependencies = [ "ahash", "android-activity", @@ -5941,7 +7407,7 @@ dependencies = [ "calloop 0.13.0", "cfg_aliases", "concurrent-queue", - "core-foundation", + "core-foundation 0.9.4", "core-graphics", "cursor-icon", "dpi", @@ -5949,7 +7415,7 @@ dependencies = [ "libc", "memmap2", "ndk", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", "objc2-ui-kit 0.2.2", @@ -5988,10 +7454,41 @@ dependencies = [ ] [[package]] -name = "winresource" -version = "0.1.31" +name = "winprint" +version = "0.2.1" +source = "git+https://github.com/storytold/winprint.rs?rev=5f80b9baf6b58937c401656634e42d33f00ddf49#5f80b9baf6b58937c401656634e42d33f00ddf49" +dependencies = [ + "flate2", + "fmt-derive", + "reqwest", + "scopeguard", + "sigstore-trust-root", + "sigstore-types", + "sigstore-verify", + "strum", + "tar", + "thiserror 2.0.21", + "windows", + "windows-core", + "windows-implement", + "xml", +] + +[[package]] +name = "winreg" +version = "0.55.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0986a8b1d586b7d3e4fe3d9ea39fb451ae22869dcea4aa109d287a374d866087" +checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97" +dependencies = [ + "cfg-if", + "windows-sys 0.59.0", +] + +[[package]] +name = "winresource" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b" dependencies = [ "toml", "version_check", @@ -6040,11 +7537,20 @@ dependencies = [ "read-fonts 0.39.2", ] +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + [[package]] name = "writeable" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +dependencies = [ + "either", +] [[package]] name = "x11-dl" @@ -6078,6 +7584,41 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "x509-cert" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" +dependencies = [ + "const-oid", + "der", + "sha1", + "signature", + "spki", + "tls_codec", +] + +[[package]] +name = "x509-tsp" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5ceece934a21607055b7ac5c25adb56a2ff559804b10705dc674d1d838c15e1" +dependencies = [ + "cmpv2", + "cms", + "der", +] + +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix 1.1.5", +] + [[package]] name = "xcursor" version = "0.3.11" @@ -6103,6 +7644,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" +[[package]] +name = "xml" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f45bb2c13fec6a6cb4c0f76a7e94839e110a14ec803ec2940777a94c347bc52" + [[package]] name = "xml-rs" version = "0.8.29" @@ -6123,7 +7670,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.14.0" +version = "0.17.0" dependencies = [ "serde_json", ] @@ -6141,13 +7688,13 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "synstructure", ] @@ -6219,7 +7766,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "zbus_names", "zvariant", "zvariant_utils", @@ -6227,9 +7774,9 @@ dependencies = [ [[package]] name = "zbus_names" -version = "4.3.4" +version = "4.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" dependencies = [ "serde", "winnow", @@ -6259,18 +7806,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.59" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.59" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", @@ -6294,10 +7841,30 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerotrie" version = "0.2.5" @@ -6305,6 +7872,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" dependencies = [ "displaydoc", + "litemap", + "serde_core", "yoke", "zerofrom", "zerovec", @@ -6330,7 +7899,24 @@ checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", +] + +[[package]] +name = "zip" +version = "9.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704" +dependencies = [ + "crc32fast", + "flate2", + "getrandom 0.4.3", + "indexmap", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zopfli", ] [[package]] @@ -6345,6 +7931,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zune-core" version = "0.5.3" @@ -6362,9 +7960,9 @@ dependencies = [ [[package]] name = "zvariant" -version = "5.15.0" +version = "5.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1d34c27cc6cdd1f458427519dd6b8612f7b7e3f7b9a0b2355d041dda9869147" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" dependencies = [ "endi", "enumflags2", @@ -6377,14 +7975,14 @@ dependencies = [ [[package]] name = "zvariant_derive" -version = "5.15.0" +version = "5.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "zvariant_utils", ] @@ -6397,6 +7995,21 @@ dependencies = [ "proc-macro2", "quote", "serde", - "syn 3.0.6", + "syn 3.0.9", "winnow", ] + +[[patch.unused]] +name = "egui_demo_lib" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "egui_inspection" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "egui_system_font_provider" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" diff --git a/Cargo.toml b/Cargo.toml index 30eff51df3..644bffe9d5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,17 +4,22 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"] [workspace.package] -version = "0.14.0" +version = "0.17.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d991bf6792f8ade99c51358bf3c1d902c8cd96b5" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per +# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -22,8 +27,9 @@ vectorcraft-doc = { path = "crates/doc" } vectorcraft-pathops = { path = "crates/pathops" } vectorcraft-brush = { path = "crates/brush" } vectorcraft-trace = { path = "crates/trace" } -# Without its default `bundled-fonts`: the engine turns them on (its own default feature), so a -# library crate never forces them on an embedder that supplies its fonts at run time. +# Without its default `bundled-fonts`: a crate that wants the fonts asks for them (the apps and +# vectorcraft-testkit through the engine's `bundled-fonts`), so a library crate never forces them on +# an embedder that supplies its fonts at run time. vectorcraft-text = { path = "crates/text", default-features = false } vectorcraft-effects = { path = "crates/effects" } vectorcraft-three-d = { path = "crates/three-d" } @@ -32,7 +38,9 @@ vectorcraft-svg = { path = "crates/svg" } vectorcraft-pdf = { path = "crates/pdf" } vectorcraft-format = { path = "crates/format" } vectorcraft-tools = { path = "crates/tools" } -vectorcraft-engine = { path = "crates/engine" } +# Without its default `bundled-fonts`, as vectorcraft-text: each crate that wants the fonts asks for +# them, so an embedder can build without them (docs/development.md › Leaving out the bundled fonts). +vectorcraft-engine = { path = "crates/engine", default-features = false } vectorcraft-ui-egui = { path = "crates/ui-egui" } vectorcraft-mcp = { path = "crates/mcp" } vectorcraft-testkit = { path = "crates/testkit" } @@ -50,6 +58,8 @@ thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = { version = "1", features = ["float_roundtrip"] } log = "0.4" +# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). +chrono = { version = "0.4.45", default-features = false, features = ["std"] } proptest = "1" crc32fast = "1.5" # tests: a TCP port bound without listening (connections to it are refused) @@ -83,6 +93,8 @@ ruzstd = { version = "0.9.1", default-features = false, features = ["std"] } # CCITT Group 3 and Group 4 decoder (ITU-T T.4 and T.6): EPS images read through # `CCITTFaxDecode`. The PDF reader's hayro-syntax uses the same version. hayro-ccitt = "0.3" +# Substring search for the EPS reader's PostScript `search`. +memchr = "2" jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] } gif = { version = "0.14", default-features = false, features = ["std", "raii_no_panic"] } # CMYK image samples (vectorcraft-doc's cmyk module): the image crate's own TIFF and JPEG @@ -91,10 +103,10 @@ tiff = "0.11" zune-jpeg = "0.5" # ui -egui = "0.36" -egui_extras = { version = "0.36", default-features = false, features = ["svg"] } -eframe = { version = "0.36", default-features = false } -egui_kittest = "0.36" +egui = "0.37" +egui_extras = { version = "0.37", default-features = false, features = ["svg"] } +eframe = { version = "0.37", default-features = false } +egui_kittest = "0.37" rfd = "0.17" arboard = { version = "3.6", default-features = false } clipboard-win = "5.4" @@ -114,18 +126,39 @@ todo = "deny" unimplemented = "deny" unreachable = "deny" +# Workspace crates keep line tables, so panics and backtraces name file and line; dependencies +# carry no debug info. Full debug info would make the dev target dir several times larger. [profile.dev.package."*"] opt-level = 2 +debug = false [profile.dev] opt-level = 1 +debug = "line-tables-only" [profile.release] lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } diff --git a/NOTICE b/NOTICE index 5cf3c8952f..8698b2dfee 100644 --- a/NOTICE +++ b/NOTICE @@ -75,12 +75,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Shared PDF backend -The patched hayro-interpret 0.7.0, hayro-syntax 0.7.2 and hayro-jbig2 0.3.0 -are fetched from https://github.com/storytold/craft-libs at revision -ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d. Their upstream project is +The patched hayro-interpret 0.7.0, hayro-syntax 0.7.2, hayro-jbig2 0.3.0, hayro-cmap 0.1.0 +and hayro-postscript 0.1.0 are fetched from https://github.com/storytold/craft-libs at revision +92d392cff132eaf53e13afff77f38b5c11b73aa0. Their upstream project is https://github.com/LaurenzV/hayro, licensed MIT OR Apache-2.0. The snapshot retains each crate's upstream licence files. The patch ledger is at -https://github.com/storytold/craft-libs/blob/ca50d63b773c99f96e75c77ce5a1d21e7c9cda0d/vendor/README.craft-reader.md. +https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/README.craft-reader.md. Assets already bundled through Hayro's default features retain their licences: - Foxit standard-14 substitutes: Copyright 2014 PDFium Authors. All rights reserved. @@ -123,3 +123,21 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Bundled egui font icons + +The pinned egui dependency includes egui-icons.ttf, a small subset of John Slegers' +emoji-icon-font, through default_fonts. The parent emoji-icon-font.ttf face is +included through monochrome_emoji_fonts. Their upstream project is +https://github.com/jslegers/emoji-icon-font; both use the same exact copyright +and permission notice below. + +MIT License + +Copyright (c) 2014 John Slegers + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 294824164f..d85cef156e 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,10 @@

+

+ VectorCraft icon: an engraved dragon on a red tile +

+

VectorCraft

@@ -202,10 +206,10 @@ the app with `WAYLAND_DISPLAY= vectorcraft`: the window then opens through XWayl (see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)). On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft doesn't respond to a drawing tablet's -pen yet (#491, #2028). Open the window through XWayland instead, where the pen works as a mouse: set the same -preference to **X11 (XWayland)**, or to **X11 (XWayland) When a Pen Is Attached** to use XWayland only when a pen is -attached as VectorCraft starts, and restart; or start the app with `WAYLAND_DISPLAY= vectorcraft` (see -[`docs/development.md`](docs/development.md#linux-wayland-and-x11)). +pen yet (#491, #2028). Open the window through XWayland instead, where the pen works as a mouse and the app reads its +pressure: set the same preference to **X11 (XWayland)**, or to **X11 (XWayland) When a Pen Is Attached** to use +XWayland only when a pen is attached as VectorCraft starts, and restart; or start the app with +`WAYLAND_DISPLAY= vectorcraft` (see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)). ### Use it from Claude Code and other agents @@ -238,8 +242,9 @@ Pathfinder and Shape Builder, paint, gradients, appearance and transparency, typ 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, 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 and images, with what didn't come in (effects, adjustments, brushes, master pages…) listed in the -import warning; a file whose native data can't be read opens as its embedded preview, saying why. VectorCraft +and masks, text with each paragraph's indents, spacing and leading, tables (as text frames and lines), master +pages, shadows, glows, outlines and overlays, embedded Affinity documents and images, with what didn't come in +(adjustments, blurs, bevels, brushes…) listed in the import warning; a file whose native data can't be read opens as its embedded preview, saying why. VectorCraft doesn't write Affinity files. Current `.af` validation includes 33 pinned files, native save/reload and every-board SVG/PDF/PSD export, with fixes for Affinity 3 artboards, source-backed JPEGs and text runs. [Scope and limits](crates/affinity/README.md); [source audit and remaining gaps](docs/affinity-validation.md). @@ -253,7 +258,7 @@ The scores are self-assessed from our code against public documentation; - reliable exchange of .ai files (layer structure in real files; proprietary editing data isn't written); - an interaction-fidelity pass covering every tool's modifiers and small behaviours; - 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials); -- most of the raster effects (11 of 57 still missing; Cutout, Film Grain, Neon Glow, Plastic Wrap, Poster Edges, Smudge Stick, Sponge and Watercolor are available under Artistic, Bas Relief, Chalk & Charcoal, Charcoal, Chrome, Graphic Pen, Halftone Pattern, Note Paper, Photocopy, Plaster, Reticulation and Stamp under Sketch) and the Effect Gallery; +- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in); - CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface); - scripting, and the rest of Variables (image and graph kinds, dataset import); - generative AI features. diff --git a/ROADMAP.md b/ROADMAP.md index 8ae1cf14af..28c15f3268 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** minor (about 90 community PRs of 2026-10-19: Objects on Path, the Simplify slider, Pencil Edit Selected Paths in the middle of a path, Georgian, and more; Background Export progress dialog with Cancel, #2564; about 85 community PRs of 2026-10-18: Justification…, Word .docx placed as area type, CCITT Group 3 TIFF, Roman Hanging Punctuation, blend spines edited with the Anchor Point tool, shadows and glows in stack order, coloured 3D lights, a Dutch catalog completed; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; about 145 community PRs of 2026-10-17: image-decode overflow guards, opaque floating panels, MCP export cancel and progress, editable Illustrator EPS import, scoped `doc_inspect`, Dutch, Danish and Indonesian, Simplified Chinese messages, screen-reader names; headline numbers unchanged; about 160 community PRs of 2026-10-15/16: PDF import crash fixes, Dimension tool, legacy `.ai` save, Intertwine, web pen input, Image Trace fixes, `.ai`/EPS/PDF import fidelity, Bulgarian, Greek, Swedish and Finnish catalogs; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (OpenType SVG colour fonts draw and export as vector art; previously: COLR colour fonts (v0 and v1) draw and export as vector art; previously: G2: the Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step; remaining: filter thumbnails and a preview area inside the dialog; G2 estimate 4–6 → 1–2 h; Raster effects 82% → 85% (power-user view 49% → 52%), estimated, a modest move because the named missing dialog landed without thumbnails or an in-dialog preview; previously: colour emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; headline numbers unchanged; previously:; Affinity import AF.5: master pages, tables, paragraph formats, shadows, glows, outlines, overlays and embedded documents; ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); headline numbers unchanged; previously:; 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged; Print: Japanese paper sizes in the Print dialog's Media list — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (which keep their ISO 216 sizes), はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; about 90 community PRs of 2026-10-19: Objects on Path, the Simplify slider, Pencil Edit Selected Paths in the middle of a path, Georgian, and more; Background Export progress dialog with Cancel, #2564; about 85 community PRs of 2026-10-18: Justification…, Word .docx placed as area type, CCITT Group 3 TIFF, Roman Hanging Punctuation, blend spines edited with the Anchor Point tool, shadows and glows in stack order, coloured 3D lights, a Dutch catalog completed; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; about 145 community PRs of 2026-10-17: image-decode overflow guards, opaque floating panels, MCP export cancel and progress, editable Illustrator EPS import, scoped `doc_inspect`, Dutch, Danish and Indonesian, Simplified Chinese messages, screen-reader names; headline numbers unchanged; about 160 community PRs of 2026-10-15/16: PDF import crash fixes, Dimension tool, legacy `.ai` save, Intertwine, web pen input, Image Trace fixes, `.ai`/EPS/PDF import fidelity, Bulgarian, Greek, Swedish and Finnish catalogs; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -29,7 +29,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)). | | Value | Kind | |---|---|---| -| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 46/57, 3D 4/4 (initial types, no materials) | +| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) | | **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated | | **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated | | **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated | @@ -75,8 +75,8 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so | Colour, swatches, gradients, patterns, mesh, recolor | 92% | 4–7 | | Strokes, brushes, width profiles | 88% | 8–15 | | Appearance, transparency, graphic styles, masks | 97% | 1–2 | -| Live vector effects | 85% | 6–10 | -| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 81% | 8–14 | +| Live vector effects | 85% | 4–8 | +| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 85% | 1–2 | | 3D and Materials | ~25% | 30–55 | | Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 | | Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 | @@ -123,21 +123,34 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap 2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h. 3. **Launch and stability on real machines** (G10): 20–35 h. 4. **Core-tool correctness** (G11: Shape Builder regions, Asset Export borders): 8–15 h. -5. **Raster effects** (G2) alongside: the 11 remaining filters (7 Artistic, 3 Sketch, 1 more) and the Effect Gallery, 8–14 h. +5. **Raster effects** (G2) alongside: the Effect Gallery's filter thumbnails and in-dialog preview area (the gallery and every Photoshop-style filter are in), 1–2 h. 6. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). ## Progress log +- 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged. +- 2026-10-23: OpenType SVG colour fonts draw as vector art: each glyph's SVG document is read by the SVG importer, in the text's colours where it asks for them, and draws, exports and outlines as COLR glyphs do; all colour font formats are now drawn. +- 2026-10-23: COLR colour fonts (v0 and v1, as in Noto Color Emoji's vector build, Segoe UI Emoji, Nabla) draw as vector art: their layers' colours, gradients, clips and blend modes on the canvas and in SVG, EPS, legacy `.ai` and PDF, and as editable paths with Create Outlines; glyphs using sweep gradients or compositing modes are drawn as images of the glyph. +- 2026-10-22: The Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step. Filter thumbnails and a preview area inside the dialog remain ([Filter Gallery overview](https://helpx.adobe.com/photoshop/desktop/effects-filters/get-started-with-filters/filter-gallery.html)). Raster effects 82% → 85% (estimated); headline numbers unchanged. +- 2026-10-22: Colour emoji fonts with bitmap glyphs draw and export: `sbix` (Apple Color Emoji, macOS's emoji font) and `CBDT` (bitmap Noto Color Emoji) glyphs show as their pictures on the canvas, whatever the type's fill, scale and turn with the type, and export to PDF (in the font's Type 3 glyphs, or as images), SVG (images when type is outlined; live text leaves emoji to the viewer), EPS and legacy `.ai` (images); Create Outlines turns them into embedded images. Fonts with bitmaps but no outlines, such as Noto Color Emoji, are now found among the installed fonts. COLR and OpenType SVG fonts remain; headline numbers unchanged. + +- 2026-10-22: Effect › Sketch › Conté Crayon: a black crayon in the dark areas and a white one in the light areas, on mid-grey paper whose texture (Brick, Burlap, Canvas, Sandstone; Scaling, Relief, Light Direction, Invert) breaks the strokes, with Foreground Level and Background Level; an original approximation, defaults unverified. Every Photoshop-style filter is now in (57/57); the Effect Gallery remains (4–6 h). +- 2026-10-22: Ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range of the selected type — above it in horizontal type, right of the column in vertical type (or below/left), start/centre/end aligned, at 1–100% of the base size (default half), overhanging or squeezed to the base width. It is saved in the native file, laid out with its line growing (following lines move on), drawn on the canvas, and written in SVG and PDF as outlines where ruby is present. UI panel and type on a path are next. Headline numbers unchanged. +- 2026-10-22: PDF accessibility: titled exports set `/ViewerPreferences << /DisplayDocTitle true >>`, so viewers show the document title rather than the file name and title checks can pass (#3646). Headline numbers unchanged. + - 2026-10-14: Document fonts register every explicitly supplied craft-fonts family after the existing Japanese, Arabic and Thai prefix; optional empty input remains supported. Headline scores and estimates are unchanged. - 2026-10-13: PngSuite downloads use pinned HTTPS files and a SHA-256 manifest; no archive extraction (#1729). | Date | What landed | |---|---| +| 2026-10-21 | 3D lighting: four original lighting presets shared by Revolve, Extrude & Bevel, Inflate and Rotate, with command access and manual Custom settings; scores and estimates unchanged. | +| 2026-10-21 | Print: the Print dialog's Media list has the Japanese papers — JIS B4 (257 × 364 mm), JIS B5 (182 × 257 mm) and JIS B6 next to the ISO B4/B5 (which keep their ISO 216 dimensions for settings saved before them), はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm / 長形4号 90 × 225 mm / 角形2号 240 × 332 mm / 角形3号 216 × 277 mm and 四六判 127 × 188 mm. A paper is named by its JSON id or its dialog label, any case and spacing (`B5 (JIS)` or `b5jis`), and every added size prints as its own PDF page size. Headline numbers unchanged. | | 2026-10-18 | Inch rulers divide the inch in half, not in ten. Zooming in stepped an inch ruler through 0.2, 0.1 and 0.05 of an inch, marks an inch ruler does not carry; below an inch the steps are binary fractions now, 1/2 down to 1/16, with the unlabelled ticks between them binary too (down to 1/128, so the 32nds, 64ths and 128ths appear as the report expects), while the metric units, points, pixels and picas keep their tenths. A label carries the decimals its step needs, so a sixteenth reads 0.0625 rather than the rounded 0.06, with trailing zeros dropped (#2827). Headline numbers unchanged. | | 2026-10-18 | Exported and saved files can repeat their bytes: PNG, PDF, EPS, legacy `.ai`, packaged zips and `.vectorcraft` saves recorded the wall-clock time they were made in, so the same commands run twice gave different bytes though the pixels matched. `SOURCE_DATE_EPOCH` now stands in for the clock in everything a file records, as the reproducible-builds specification defines it; a date a command is given still wins, and a malformed value is ignored rather than refusing the export. The recovery heartbeat and the seed PDF encryption draws on keep the real clock, so a password-protected PDF still differs between runs (#2880). Headline numbers unchanged. | | 2026-10-18 | About 85 community PRs landed in two batches through the full gate, with our fixes on top. New: Word `.docx` files place as area type with their formatting (#2766), CCITT Group 3 TIFF files open (#2770), Paragraph panel menu › Roman Hanging Punctuation (#2775), the Anchor Point tool edits blend spine points and handles (#2643, fixes #2544), shadows and glows each draw from the art with the effects before them, without the old exponential cost (#2395), one to ten coloured lights in 3D effects (#2706), Artboard Options X and Y with a reference point (#2739), more Contextual Task Bar actions (#2471), Optical Margin Alignment for a whole thread (#2773), History panel Step Backward/Forward and Set History Limit (#2764), Edit › Undo and Redo name the step as the History panel does (#2774), bounding-box handles snap to the grid, pixels and guides (#2715), Ctrl/Cmd+A in the Artboards panel (#2761), Tabs panel menu items (#2742), Import Data Sets defines variables from header cells (#2736), a Linux option to use X11 when a pen is attached (#2717). Fidelity and robustness: variable fonts named by their default weight and fallback glyphs keep bold and italic (#2733, #2732), legacy `.ai` layer names in Windows Latin-1 (#2722), WMF window mapping (#2721), Magic Wand inside isolation (#2720), type values out of range in files are clamped (#2728, #2757), raster effects stay responsive in drags (#2745), exports and Save for Web report undecodable images (#2762, #2737, #2684), Windows-safe exported file names (#2738), a marquee skips a Shaper Group's originals (#2772). Second batch: an export progress dialog with Cancel on the shared cancel token (#2564), CMYK gradient meshes drawn several times faster within a 16 MB cap (#2802), Paragraph panel menu › Justification… with file values clamped (#2771), Edit › Clear History (#2843), SVG image links keep their spelling (#2837, fixes main's Windows test failures), the Linux save dialog through the XDG portal (#2783), RGB input stored as CMYK in CMYK documents (#2812), legacy `.ai` export of images and radial highlights (#2801, #2807), `.ai` import notes for damaged editing data, page sizes and variable libraries (#2799, #2800, #2842), PDF and `.ai` keep their creation date (#2838), undecodable images left out of PDF exports with a note (#2790), MCP input waits for queue room (#2776), slice, snapping, selection, type and accessibility fixes (#2794–#2797, #2805, #2806, #2809, #2815, #2844–#2846), dropdowns close after a keyboard pick (#2824), plug-in dialogs scroll (#2840). Languages: the Dutch catalog completed (#2730). Headline numbers unchanged (estimated). | | 2026-10-19 | About 90 community PRs landed in batches through the full gate, with our fixes on top (formatting, catalog rows, small correctness fixes). New: Objects on Path (#3066), Object › Path › Simplify's slider with Auto-Simplify and More Options (#2555), Pencil Edit Selected Paths redraws the middle of a selected path (#2905), Pencil Tool Options' Alt key toggles to Smooth Tool (#2685), 3D solids built from each stroke's outline (#3049), Live Paint Selection Tool Options (#3052), Locate Selected Objects in the Layers panel (#3033), Snap to Unit for tab stops (#3039), DXF circles and arcs as native entities (#2962), Targa files (#2765), a Georgian interface (#2045), Traditional Chinese status and error messages (#2784), the web page's `window.vectorcraft` control channel (#2943), `select.color` (#2939), reproducible export bytes with `SOURCE_DATE_EPOCH` (#2947), Spacing Guides on resizes (#2966) and measurement labels on more tools. Fixed: number fields step to the next whole unit (#2916), a click away from edited type makes no new text (#2922), inch rulers in halves (#2951), Recent cards in New Document (#2904), Japanese W-weights in SVG (#2896), the point-type baseline marker (#2897) and the Reshape tool's falloff (#2900). Headline numbers unchanged. | +| 2026-10-21 | Affinity import (AF.5), brought over from DesignCraft's (storytold/designcraft#291): master pages show on the pages that use them (a locked layer at the bottom); tables open as a text frame per cell and a line per edge; each paragraph keeps its alignment, indents, spacing and leading; frame text takes its text scale, not its frame's; drop shadows and outer glows become live effects, outlines strokes, colour and gradient overlays are baked into the paint; embedded Affinity documents open as editable content, and their artboards no longer become artboards; large pixel layers come in at a reduced resolution; text placed as Affinity places it (lines of differently aligned paragraphs, a frame's first baseline at cap height, last lines whose descenders hang out of the frame), underlines and strikethrough, line breaks inside paragraphs, table cells taller than their row, no stroke on shapes whose stroke style is None, CMYK pixel layers (phone photos in CMYK documents) shown through the document's own CMYK profile instead of the profile-free formula and its blue cast, outlines on stroked shapes. Headline numbers unchanged. Hostile files stay bounded (one budget for the whole read, embedded documents included; overlay work; master page copies), covered by the import fuzzer and limit tests. | | 2026-10-17 | Background Export shows a progress dialog: the file being exported, the artboard count and a bar, Cancel (Esc) and Continue in Background. It runs on the shared cancel token of #2546, so a cancelled export writes no file and keeps no half-drawn pattern tile or effect raster; translated in every language with complete menus (#2564). Headline numbers unchanged. | | 2026-10-17 | About 145 community PRs landed in six batches, each through the full gate, plus our fixes on top. Crashes and hostile input: an image's RGBA size is checked from its header before decoding, without overflowing, in the renderer, sampling, recoloring and Crop Image (#2442, #2468, #2407), PDF Add Around and huge art are clamped (#2440), graph axis labels past i64, `+` in hex colours and XML ids are handled (#2610, #2470, #2447), Document Raster Effects resolutions open in range (#2579), Batch names stay in their folder (#2504). Regressions: floating panel groups are opaque again while the docked card keeps its rounded corners (#2499), the Wayland pointer returns over panels (#2502). New: MCP cancels long exports, answers while one runs and reports progress (#2546), `doc_inspect` takes ids, kind and paging (#2543), raster export of a page rectangle (#2511), `text.create` returns bounds (#2478), PDF presets and ICC profiles persist (#2547), screen-reader names for widgets (#2611), Expand on Intertwine (#2622, fixes #2540), Duplicate/Copy/Cut of several artboards (#2567), print presets by name (#2607), TSV data sets (#2608), planar TIFF (#2598), Alt-click a swatch onto a gradient stop (#2623), Shift-click ranges in Links, Graphic Styles and Libraries (#2612, #2613, #2618), Space+Shift rotates the view (#2601), Presentation Mode keys (#2583), Small Caps and super/subscript buttons (#2508). Fidelity: editable vector art from Illustrator EPS (#2571), `.ai` Drop Shadow Darkness (#2513), overprint preview with Darken (#2514), Generic CMYK black round-trips (#2503), PNG sRGB chunk (#2519), kerning at a caret (#2518), tab widths in justified area type (#2487), Transform copies keep their own gradients (#2486), smooth Zig Zag (#2475), Live Corners round up to their neighbours (#2484), kerning across style runs (#2554), SVG letter spacing on justified lines (#2574), Dimension tool snapping (#2482), gradient chips (#2495), Transform panel flips and percentages (#2400, #2404). Later the same day: PostScript `.ps` and `.epsf` files open (#2461), EPS images with CCITTFax compression draw (#2445), Illustrator 3 EPS without layers (#2436), `.ai` type opacity and blend modes (#2420), envelope meshes and compound holes in `.ai` (#2410, #2444), CMYK image soft masks in PDF export (#2448), Show Transparency Grid saved with the document (#2488), Save Selection in the Layers panel menu (#2483), Character and Paragraph Reset Panel (#2479, #2438), Cmd/Ctrl+Shift double-click releases a guide (#2467), Shift+Enter keeps a field active (#2431), Shift keeps reshaped handles perpendicular (#2425), emptied type keeps its style (#2464), Smart Blur radius (#2443), freeform gradients recolour (#2397), mesh slivers (#2456), Recolor wheel handles in CMYK (#2454), and six Image Trace fixes (#2387, #2584, #2586–#2589). Fifth batch: Optical Margin Alignment (#2563), Window › Blend panel (#2573), graph column designs (#2406), Live Paint Gap Options (#2424), the SVG Interactivity panel (#2437), RTF placed as area type (#2524), the Touch Type tool (#2469), pattern fills expand into clipped tiles (#2616), Save and Export ask before replacing a file an added extension names (#2619), the Artboard tool's Control bar and Contextual Task Bar (#2559, #2556), Alt-click New Artboard for its options (#2496), Shift-click in Brushes (#2562), the Move dialog remembers the last move (#2542), PDF export uses the document's assigned profiles (#2536), Printer Setup opens the selected printer's preferences on Windows (#2577). Sixth batch: Effect › Artistic › Cutout, Neon Glow and Poster Edges (#2453), View › Rulers › Change to Global / Artboard Rulers (#2416), Symbol Options 9-slice guides (#2512), Create Gradient Mesh on an embedded image (#2538), Rotate View cursors and the Mac trackpad rotation gesture (#2594, #2644), choice parameters as dropdowns in the inline effect editor (#2582), Group Selection picks and moves one path of a compound path (part of #2441), Shift-click ranges in the Artboards panel (#2626), Lock Variables (#2631), a layer dropped under the last row goes to the bottom (#2632), and robustness work: huge selections draw bounded overlays (#2635, #2645, part of #2460), values out of range in presets and files are clamped (#2656), whole-number checks for counts (#2638, #2659), exports warn about overset type (#2628), symbol instances measured by their art (#2614), colour-managed Eyedropper in CMYK documents (#2664). Later: Effect › Rasterize (#2409), variable-font axis sliders in the Character panel (#2710), Image Trace Create Strokes on an exact distance transform with Guo–Hall thinning and a skeleton graph (#2703–#2705), Auto Color keeps rare colours (#2702), large images trace with a warning (#2700), a 1e9 pt input bound on Reshape Segment, Convert Anchor Point and the Pencil (#2709), task-bar Connect, Corner and Smooth for selected anchors (#2697), PDF 0 w strokes import as hairlines (#2696), threading text from the out port (#2713, part of #2572), a panel per swatch library with Persistent (#2714, #2603), installed plug-ins kept across restarts (#2695, #2541). Languages: Dutch, Danish and Indonesian complete (#2393), Simplified Chinese status and error messages (#2578), translated file filters and presets (#2590). Headline numbers unchanged (estimated). | | 2026-10-16 | Symbol Options › Export Type (Graphic or Movie Clip, default Movie Clip) with Registration; `symbol.options` / `symbol.list` (G5). @@ -185,6 +198,14 @@ The full pre-standard record of what landed is kept in [docs/roadmap.md](docs/ro | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | Progress log row for Pathfinder › Trap; Live vector effects hours 6–10 → 4–8; headline numbers unchanged. | +| 2026-10-23 | minor | Progress log row for OpenType SVG colour fonts; headline numbers unchanged. | +| 2026-10-23 | minor | Progress log row for COLR colour fonts; headline numbers unchanged. | +| 2026-10-22 | minor | G2: the Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step; remaining: filter thumbnails and a preview area inside the dialog; G2 estimate 4–6 → 1–2 h; Raster effects 82% → 85% (power-user view 49% → 52%), estimated, a modest move because the named missing dialog landed without thumbnails or an in-dialog preview. | +| 2026-10-22 | minor | Progress log row for colour emoji fonts with bitmap glyphs; headline numbers unchanged. | +| 2026-10-22 | minor | Effects: Sketch › Conté Crayon; measured Photoshop-style filters 57/57, the Effect Gallery remains (G2 estimate 4–6 h). | +| 2026-10-21 | minor | 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged | +| 2026-10-21 | minor | Print: Japanese paper sizes in the Print dialog's Media list (JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号, 四六判); ISO B4/B5 keep their sizes, and a paper is named by id or label, any case and spacing. Headline numbers unchanged. | | 2026-10-17 | minor | Colored Inflate: shared membrane normals and smooth RGB vector ramps replace flat polygon bands; channel groups are batched per solid-fill surface. White-light Inflate retains its original polygons, paint composition and seam joins; the 0.05 seam minimum is restored. Scores and hour estimates unchanged. | | 2026-10-16 | minor | 3D lighting: one to ten directional lights, a selectable light list, Add Light and Delete Light, independent settings and artboard gestures; ambient applied once and smooth RGB vector export; scores and hour estimates unchanged | | 2026-10-16 | minor | 3D lighting: opaque RGB Color for the shared directional light, with neutral ambient, preview/reset controls and smooth vector Revolve shading; scores and hour estimates unchanged | diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index c31998d002..82f0b100d0 100644 --- a/apps/vectorcraft-cli/Cargo.toml +++ b/apps/vectorcraft-cli/Cargo.toml @@ -16,7 +16,7 @@ workspace = true [dependencies] vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } -vectorcraft-engine = { workspace = true } +vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] } vectorcraft-format = { workspace = true } vectorcraft-geom = { workspace = true } vectorcraft-svg = { workspace = true } @@ -32,10 +32,11 @@ log = { workspace = true } [target.'cfg(windows)'.dependencies] winsafe = { version = "0.0.29", default-features = false, features = ["kernel", "psapi"] } -# DirectWrite's system font collection (the desktop app's src/system_fonts.rs, shared): fonts that -# font services such as Adobe Fonts load in place (#579). MIT OR Apache-2.0. +# DirectWrite's system font collection and GDI's font list (the desktop app's src/system_fonts.rs, +# shared): fonts that font services such as Adobe Fonts load in place (#579, #1258). MIT OR +# Apache-2.0. [target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies] -windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite"] } +windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi"] } # CoreText's font manager (the desktop app's src/mac_fonts.rs, shared): fonts that apps and font # managers register from their own folders (#579). Zlib OR Apache-2.0 OR MIT. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 96cc2d0fb3..6ec320ea26 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -1,10 +1,10 @@ //! `vectorcraft-cli`: VectorCraft from the command line. //! //! ```text -//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR] [--automation-write-root DIR] -//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}']]... [--export out.svg]... [--scale 2] +//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... +//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] //! vectorcraft-cli commands -//! vectorcraft-cli convert IN OUT [--scale 2] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] +//! vectorcraft-cli convert IN OUT [--scale 2] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] //! vectorcraft-cli info FILE //! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5] //! vectorcraft-cli perf [--paths 50000] [--deep] @@ -68,24 +68,29 @@ const USAGE: &str = "\ vectorcraft-cli — VectorCraft automation USAGE: - vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR] [--automation-write-root DIR] + vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979 (vectorcraft --control 7979), falling back to a headless in-process session. --automation-read-root / --automation-write-root confine the files the agent's commands read (open, place, relink, library loads…) and write (save, export, package, library saves…) to - DIR, links followed; a root left out grants none of its access. They imply --headless: a - running app enforces its own (vectorcraft --control PORT --automation-read-root DIR …). + DIR, links followed; each may be given more than once, a path inside any of its folders being + allowed, and a kind left out grants none of its access. They imply --headless: a running app + enforces its own (vectorcraft --control PORT --automation-read-root DIR …). - vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON]]... [--export FILE]... [--scale N] + vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] Headless batch: open FILE (any readable format) or start a new document, run commands in order, export each FILE in the format its extension picks (see Writable formats; a .ait FILE is a template, written as file.saveAsTemplate writes it). --scale sizes raster exports (pixels per point, default 1); other formats leave it out. Prints one JSON result per step. + --commands reads steps from FILE, or from standard input for -, where it stands among the + --cmd and --export steps: a JSON array of {\"command\": ID, \"params\": {...}} (or \"id\" for + \"command\"), or one such object per line (JSON Lines), at most 64 MiB and 100000 steps. + Errors name the step, counting from 0 as \"$N\" references do. vectorcraft-cli commands Print the command catalogue as JSON. - vectorcraft-cli convert IN OUT [--scale N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] + vectorcraft-cli convert IN OUT [--scale N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] Open IN (any readable format) and export OUT in the format its extension picks (see Writable formats). --scale sizes a raster OUT (pixels per point, default 1); other formats leave it out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard @@ -96,9 +101,13 @@ USAGE: SVG's data-* attributes; --outline-text writes SVG text as paths, --decimals sets SVG's coordinate precision (1–7, default 3). OUT may not be IN when reading IN left things out (hidden text, art or layers it could not read; the notes say which) unless - --replace-lossy is given. --editing-data opens a .ai from its editing copy even where that - draws differently from its PDF part (which can be older), as long as it can be read. The - result has the export's warnings, and importWarnings for what reading IN left out. + --replace-lossy is given. --editing-data opens a .ai or an EPS with editing data from its editing copy + even where that draws differently from its PDF part or page (which can be older), as long as + it can be read. A PDF OUT omits the embedded native document unless --preserve-editing is + given (the app's Save As PDF still defaults to keeping it). With --preserve-editing, when the + attachment is written the result's warnings say so (it is left out, with its own warning, for + --artboard or a --range without every artboard). + The result has the export's warnings, and importWarnings for what reading IN left out. --ai-version 7 writes a .ai as the legacy version 7 (layers, groups and type kept; one file per artboard, OUT-.ai when there are several; default pdf, PDF-compatible), with --hidden-objects (default layer: a hidden layer above each layer's hidden objects; omit; @@ -128,6 +137,29 @@ fn usage() -> String { format!("{USAGE}\nReadable formats: .{}\nWritable formats: .{}\n", OPEN_EXTS.join(", ."), export_extensions().join(", .")) } +/// Does a subcommand's `args` ask for the usage? `--help` or `-h` counts where an option goes, not as +/// the value of one of the `valued` options before it, so `run --cmd -h` keeps `-h` for `--cmd`. The +/// subcommands check this before they parse or read anything else. +fn help_requested(args: &[String], valued: &[&str]) -> bool { + let mut it = args.iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--help" | "-h" => return true, + a if valued.contains(&a) => { + it.next(); + } + _ => {} + } + } + false +} + +/// Prints the usage, for `help`, `--help` and `-h`. +fn help() -> Result<(), String> { + out!("{}", usage()); + Ok(()) +} + fn main() -> ExitCode { // Before any font lookup: the fonts font services load (#579). #[cfg(all(windows, not(target_vendor = "win7")))] @@ -137,6 +169,9 @@ fn main() -> ExitCode { prefs_dir::install_fonts(); let args: Vec = std::env::args().skip(1).collect(); let r = match args.first().map(String::as_str) { + // `commands` and `info` take no options, so `--help` or `-h` anywhere after them prints the + // usage. The other subcommands check for it themselves. + Some("commands" | "info") if help_requested(&args[1..], &[]) => help(), Some("mcp") => mcp(&args[1..]), Some("run") => run(&args[1..]), Some("commands") => commands(), @@ -144,10 +179,7 @@ fn main() -> ExitCode { Some("info") => info(&args[1..]), Some("bench") => bench(&args[1..]), Some("perf") => perf::run(&args[1..]), - Some("-h" | "--help" | "help") | None => { - out!("{}", usage()); - Ok(()) - } + Some("-h" | "--help" | "help") | None => help(), Some("-V" | "--version") => { outln!("vectorcraft-cli {}", env!("CARGO_PKG_VERSION")); Ok(()) @@ -174,9 +206,12 @@ fn with_stores(mut h: Headless) -> Headless { } fn mcp(args: &[String]) -> Result<(), String> { + if help_requested(args, &["--connect", "--automation-read-root", "--automation-write-root"]) { + return help(); + } let mut connect: Option = None; let mut headless = false; - let (mut read_root, mut write_root): (Option, Option) = (None, None); + let (mut read_roots, mut write_roots): (Vec, Vec) = (vec![], vec![]); let mut it = args.iter(); while let Some(a) = it.next() { // The roots also come as `--flag=DIR`, as the other Craft apps take them. @@ -189,10 +224,7 @@ fn mcp(args: &[String]) -> Result<(), String> { "--headless" => headless = true, "--automation-read-root" | "--automation-write-root" => { let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?; - let slot = if flag == "--automation-read-root" { &mut read_root } else { &mut write_root }; - if slot.replace(dir).is_some() { - return Err(format!("{flag} is given twice: it takes one folder")); - } + if flag == "--automation-read-root" { read_roots.push(dir) } else { write_roots.push(dir) } } other => return Err(format!("unknown mcp option `{other}`")), } @@ -200,16 +232,17 @@ fn mcp(args: &[String]) -> Result<(), String> { if headless && connect.is_some() { return Err("use either --connect or --headless".into()); } - let roots = AutomationRoots::new(read_root.as_deref().map(Path::new), write_root.as_deref().map(Path::new))?; + let read: Vec<&Path> = read_roots.iter().map(Path::new).collect(); + let write: Vec<&Path> = write_roots.iter().map(Path::new).collect(); + let roots = AutomationRoots::new(&read, &write)?; if roots.is_some() && connect.is_some() { - return Err("--automation-read-root and --automation-write-root confine the headless server; a running app enforces its own roots: start it with `vectorcraft --control --automation-read-root

--automation-write-root `" + return Err("--automation-read-root and --automation-write-root confine the headless server; a running app enforces its own roots: start it with `vectorcraft --control --automation-read-root --automation-write-root `" .into()); } let backend: Box = if let Some(roots) = roots { // Every thread of this process, not only the server's: nothing reaches past the roots. file_access::confine_process(roots.clone()); - let show = |root: Option<&Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string()); - eprintln!("vectorcraft-cli: files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root())); + eprintln!("vectorcraft-cli: files confined: {}", roots.describe()); Box::new(Headless::with_document().with_automation_roots(Some(roots))) } else if headless { Box::new(with_stores(Headless::with_document())) @@ -239,9 +272,13 @@ fn commands() -> Result<(), String> { } fn convert(args: &[String]) -> Result<(), String> { + let valued = ["--scale", "-s", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"]; + if help_requested(args, &valued) { + return help(); + } let mut files = vec![]; - let (mut scale, mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data) = - (1.0f64, None::, None::, false, false, false); + let (mut scale, mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) = + (1.0f64, None::, None::, false, false, false, false); let mut decimals = None::; // Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`, // `transparentImages`); the engine checks their values. @@ -256,6 +293,7 @@ fn convert(args: &[String]) -> Result<(), String> { "--decimals" => decimals = Some(it.next().and_then(|v| v.parse::().ok()).ok_or("--decimals needs a number")?), "--replace-lossy" => replace_lossy = true, "--editing-data" => editing_data = true, + "--preserve-editing" => preserve_editing = true, "--ai-version" => legacy.push(("aiVersion", it.next().cloned().ok_or("--ai-version needs 7 or pdf")?)), "--hidden-objects" => legacy.push(("hiddenObjects", it.next().cloned().ok_or("--hidden-objects needs layer, omit or visible")?)), "--transparent-images" => legacy.push(("transparentImages", it.next().cloned().ok_or("--transparent-images needs flatten or omit")?)), @@ -285,6 +323,9 @@ fn convert(args: &[String]) -> Result<(), String> { if let Some(decimals) = decimals { params["decimals"] = json!(decimals); } + if vectorcraft_engine::cmd::fileio::format_for_name(&output).is_some_and(|f| f.id == "pdf") { + params["preserveEditing"] = json!(preserve_editing); + } ("document.export", params) }; for (key, value) in legacy { @@ -296,6 +337,25 @@ fn convert(args: &[String]) -> Result<(), String> { if let (Some(w), Some(out)) = (opened.get("warnings").filter(|w| w.as_array().is_some_and(|a| !a.is_empty())), r.as_object_mut()) { out.insert("importWarnings".into(), w.clone()); } + if preserve_editing + && vectorcraft_engine::cmd::fileio::format_for_name(&output).is_some_and(|f| f.id == "pdf") + && let Some(obj) = r.as_object_mut() + { + // The export leaves the attachment out (with this warning) for --artboard or a --range + // without every artboard; otherwise it writes it. Read that from the result, not the file. + let skipped = vectorcraft_engine::cmd::fileio::pdf::EDITING_NEEDS_EVERY_ARTBOARD; + let embedded = !obj.get("warnings").and_then(Value::as_array).is_some_and(|w| w.iter().any(|w| w.as_str() == Some(skipped))); + if embedded { + let note = "The PDF embeds the native VectorCraft document as an attachment (preserveEditing)."; + if let Some(Value::Array(w)) = obj.get_mut("warnings") { + if !w.iter().any(|w| w.as_str() == Some(note)) { + w.push(json!(note)); + } + } else { + obj.insert("warnings".into(), json!([note])); + } + } + } outln!("{r}"); Ok(()) } @@ -337,28 +397,131 @@ enum Step { Export(String), } +/// Most bytes `run --commands` reads from a file or standard input: the steps are untrusted input. +const MAX_COMMANDS_BYTES: u64 = 64 * 1024 * 1024; +/// Most steps one `run --commands` takes. +const MAX_COMMANDS_STEPS: usize = 100_000; + +/// The text of `--commands source`: the file `source`, or standard input for `-`, refused past +/// [`MAX_COMMANDS_BYTES`]. +fn read_commands(source: &str) -> Result { + use std::io::Read; + let mut bytes = vec![]; + let read = if source == "-" { + std::io::stdin().lock().take(MAX_COMMANDS_BYTES + 1).read_to_end(&mut bytes) + } else { + std::fs::File::open(source).and_then(|f| f.take(MAX_COMMANDS_BYTES + 1).read_to_end(&mut bytes)) + }; + read.map_err(|e| format!("--commands {source}: {e}"))?; + if bytes.len() as u64 > MAX_COMMANDS_BYTES { + return Err(format!("--commands {source}: more than {} MiB of steps", MAX_COMMANDS_BYTES / (1024 * 1024))); + } + String::from_utf8(bytes).map_err(|_| format!("--commands {source}: not UTF-8 text")) +} + +/// The steps of `--commands source` from its `text`: a JSON array of `{"command": ID, "params": +/// {…}}` objects (`"id"` may stand for `"command"`, as in MCP's `command_batch`), or one such object +/// per line (JSON Lines, blank lines skipped). `first` is the run's index of the first of them +/// (the `N` of `"$N"`), which an error names with the entry's place in the text. +fn parse_commands(source: &str, text: &str, first: usize) -> Result, String> { + // Notepad on Windows starts UTF-8 files with a byte order mark. + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let too_many = || format!("--commands {source}: more than {MAX_COMMANDS_STEPS} steps"); + // Each entry with where it is in the text: its line for JSON Lines. + let mut entries: Vec<(Option, Value)> = vec![]; + if text.trim_start().starts_with('[') { + let v: Value = serde_json::from_str(text).map_err(|e| format!("--commands {source}: {e}"))?; + let Value::Array(items) = v else { return Err(format!("--commands {source}: not a JSON array")) }; + if items.len() > MAX_COMMANDS_STEPS { + return Err(too_many()); + } + entries.extend(items.into_iter().map(|v| (None, v))); + } else { + for (n, line) in text.lines().enumerate().filter(|(_, l)| !l.trim().is_empty()) { + if entries.len() == MAX_COMMANDS_STEPS { + return Err(too_many()); + } + let v = serde_json::from_str(line).map_err(|e| format!("--commands {source}: step {} (line {}): {e}", first + entries.len(), n + 1))?; + entries.push((Some(n + 1), v)); + } + } + entries + .into_iter() + .enumerate() + .map(|(k, (line, v))| { + command_step(v).map_err(|e| { + let place = line.map_or_else(|| format!("entry {}", k + 1), |l| format!("line {l}")); + format!("--commands {source}: step {} ({place}): {e}", first + k) + }) + }) + .collect() +} + +/// The step of one `--commands` entry, `{"command": ID, "params": {…}}`. +fn command_step(v: Value) -> Result { + let Value::Object(mut o) = v else { return Err("a step must be an object such as {\"command\": \"select.all\", \"params\": {}}".into()) }; + let id = match (o.remove("command"), o.remove("id")) { + (Some(Value::String(id)), None) | (None, Some(Value::String(id))) => id, + (Some(_), Some(_)) => return Err("give `command` or `id`, not both".into()), + (None, None) => return Err("no `command`".into()), + _ => return Err("`command` must be a string, a command id".into()), + }; + let params = match o.remove("params") { + None | Some(Value::Null) => json!({}), + Some(p @ Value::Object(_)) => p, + Some(_) => return Err(format!("`params` of {id} must be a JSON object")), + }; + if let Some(key) = o.keys().next() { + return Err(format!("unknown key `{key}`: a step has `command` (or `id`) and `params`")); + } + Ok(Step::Cmd(id, params)) +} + fn run(args: &[String]) -> Result<(), String> { + let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s"]; + if help_requested(args, &valued) { + return help(); + } let mut input: Option = None; let mut steps: Vec = vec![]; + // The step of the `--cmd` just given, which a `--params` sets. + let mut params_for: Option = None; + let mut stdin_read = false; let mut scale = 1.0; let mut it = args.iter(); while let Some(a) = it.next() { let mut val = |what: &str| it.next().cloned().ok_or_else(|| format!("{a} needs {what}")); match a.as_str() { "--in" | "-i" => input = Some(val("a file")?), - "--cmd" | "-c" => steps.push(Step::Cmd(val("a command id")?, json!({}))), + "--cmd" | "-c" => { + steps.push(Step::Cmd(val("a command id")?, json!({}))); + params_for = Some(steps.len() - 1); + } "--params" | "-p" => { let raw = val("JSON")?; let p: Value = serde_json::from_str(&raw).map_err(|e| format!("--params {raw}: {e}"))?; if !p.is_object() { return Err(format!("--params must be a JSON object, got {raw}")); } - match steps.last_mut() { + match params_for.and_then(|i| steps.get_mut(i)) { Some(Step::Cmd(_, params)) => *params = p, _ => return Err("--params must follow a --cmd".into()), } } - "--export" | "-o" => steps.push(Step::Export(val("a file")?)), + "--commands" => { + let source = val("a file, or - for standard input")?; + if source == "-" && std::mem::replace(&mut stdin_read, true) { + return Err("--commands - is given twice: standard input is read once".into()); + } + let text = read_commands(&source)?; + let read = parse_commands(&source, &text, steps.len())?; + steps.extend(read); + params_for = None; + } + "--export" | "-o" => { + steps.push(Step::Export(val("a file")?)); + params_for = None; + } "--scale" | "-s" => { let raw = val("a number")?; scale = raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?; @@ -393,10 +556,12 @@ fn run(args: &[String]) -> Result<(), String> { // Each step's result, for later steps to refer to (`"$1.id"`, see `vectorcraft_engine::steps`). let mut results = vec![]; for step in steps { + // The step's index, as `"$N"` names its result. + let n = results.len(); let r = match step { Step::Cmd(id, params) => { - let params = vectorcraft_engine::steps::resolve(¶ms, &results).map_err(|e| format!("{id}: {e}"))?; - let r = h.call("engine.execute", json!({"command": id, "params": params})).map_err(|e| format!("{id}: {e}"))?; + let params = vectorcraft_engine::steps::resolve(¶ms, &results).map_err(|e| format!("step {n} ({id}): {e}"))?; + let r = h.call("engine.execute", json!({"command": id, "params": params})).map_err(|e| format!("step {n} ({id}): {e}"))?; emit(json!({"step": "cmd", "command": id, "result": r}))?; r } @@ -406,7 +571,7 @@ fn run(args: &[String]) -> Result<(), String> { } else { h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale)) }; - let r = r.map_err(|e| format!("export {path}: {e}"))?; + let r = r.map_err(|e| format!("step {n}: export {path}: {e}"))?; emit(json!({"step": "export", "result": r}))?; r } @@ -417,6 +582,9 @@ fn run(args: &[String]) -> Result<(), String> { } fn bench(args: &[String]) -> Result<(), String> { + if help_requested(args, &["--size", "--iters"]) { + return help(); + } let mut file = None; let (mut w, mut h, mut iters) = (2880u32, 1800u32, 5u32); let mut it = args.iter(); diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs index 3aa1db6a44..8fe3d23b74 100644 --- a/apps/vectorcraft-cli/src/perf.rs +++ b/apps/vectorcraft-cli/src/perf.rs @@ -23,13 +23,16 @@ impl Rng { } } +/// The synthetic document's page, in points. +const SYNTHETIC_PAGE: (f64, f64) = (1600.0, 1200.0); + /// `n` mixed paths (ellipses with strokes, translucent rectangles, stroked stars) on a 1600×1200 page. pub fn synthetic(n: usize) -> Result { - let mut d = Document::new(1600.0, 1200.0); + let mut d = Document::new(SYNTHETIC_PAGE.0, SYNTHETIC_PAGE.1); let l = d.layers.first().map(|l| l.id); let mut r = Rng(42); for i in 0..n { - let (x, y, s) = (r.next() * 1600.0, r.next() * 1200.0, 3.0 + r.next() * 22.0); + let (x, y, s) = (r.next() * SYNTHETIC_PAGE.0, r.next() * SYNTHETIC_PAGE.1, 3.0 + r.next() * 22.0); let c = Color::rgb(r.next() as f32, r.next() as f32, r.next() as f32); let id = d.alloc_id(); let mut node = match i % 3 { @@ -282,7 +285,7 @@ fn deep(n: usize) -> Result<(), String> { let key = format!("photo {i}"); d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", photo)); let xf = Affine::translate((f64::from(i % 2) * 800.0, f64::from(i / 2) * 600.0)) * Affine::scale(800.0 / 6000.0); - let image = vectorcraft_doc::ImageObject { key, width: 6000, height: 4000, xf, link: None, placement: Default::default() }; + let image = vectorcraft_doc::ImageObject { key, width: 6000, height: 4000, xf, link: None, placement: Default::default(), pixels: None }; let id = d.alloc_id(); d.insert(l, usize::MAX, Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(image)))).map_err(|e| e.to_string())?; } @@ -296,6 +299,27 @@ fn deep(n: usize) -> Result<(), String> { rows.push(("render 4 embedded 24 MP photos with 3 renderers (cold)".into(), ms)); note("after rendering the photos with 3 renderers"); } + // An SVG with one embedded picture opened from its text, as picture-heavy SVGs come: the + // importer's passes over the text before usvg reads it, most of which is the data URL. The + // picture is the synthetic page drawn at 1.25x (about 2 MB as a PNG; the row names its size); + // the hidden rectangle is a marker, so the prepass walks the tree as it does for a file that + // has one, instead of returning at its first check. + { + let k = 1.25; + let (w, h) = ((SYNTHETIC_PAGE.0 * k).round() as u32, (SYNTHETIC_PAGE.1 * k).round() as u32); + let photo = Renderer::new().render(&synthetic(3000)?, w, h, Affine::scale(k), &opts).to_png()?; + let data = vectorcraft_svg::base64_encode(&photo); + let svg = format!( + r#""# + ); + // One import checked first, so a failure is reported rather than timed; the same text + // imports the same way each time. Its document is kept for the memory reading. + let imported = vectorcraft_svg::import_with_report(&svg).map_err(|e| e.to_string())?; + let ms = median_ms(5, || drop(vectorcraft_svg::import_with_report(&svg))); + rows.push((format!("import SVG, one embedded {} KB PNG", photo.len() / 1024), ms)); + note("after the import of an embedded picture"); + drop(imported); + } // Output hashes, to compare builds: the SVG export and a save → open → save round trip. let fnv = |b: &[u8]| b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| (h ^ u64::from(x)).wrapping_mul(0x100_0000_01b3)); let doc = synthetic(n)?; @@ -317,6 +341,9 @@ fn deep(n: usize) -> Result<(), String> { } pub fn run(args: &[String]) -> Result<(), String> { + if crate::help_requested(args, &["--paths"]) { + return crate::help(); + } let mut n = 50_000usize; let mut want_deep = false; let mut it = args.iter(); diff --git a/apps/vectorcraft-cli/tests/cli.rs b/apps/vectorcraft-cli/tests/it/cli.rs similarity index 66% rename from apps/vectorcraft-cli/tests/cli.rs rename to apps/vectorcraft-cli/tests/it/cli.rs index b376a139fd..c45c5d8676 100644 --- a/apps/vectorcraft-cli/tests/cli.rs +++ b/apps/vectorcraft-cli/tests/it/cli.rs @@ -1,5 +1,3 @@ -// 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::io::Write; use std::process::{Command, Stdio}; @@ -84,11 +82,183 @@ fn scale_sizes_raster_exports_only() { fn run_reports_errors() { let out = Command::new(BIN).args(["run", "--cmd", "nope.nothing"]).output().unwrap(); assert!(!out.status.success()); - assert!(String::from_utf8_lossy(&out.stderr).contains("nope.nothing")); + 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(); assert!(!out.status.success()); } +/// The JSON lines `run` printed. +fn json_lines(stdout: &[u8]) -> Vec { + String::from_utf8_lossy(stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect() +} + +/// #3147: `run --commands FILE` reads its steps from a JSON array (`command` or `id`), runs them +/// where the option stands among `--cmd` and `--export`, and they count with those for `"$N"`; a +/// placed file's `dataBase64` longer than a Windows command line holds fits. +#[test] +fn run_reads_steps_from_a_commands_file() { + let steps = tmp("steps.json"); + let svg = tmp("steps.svg"); + // Base64 of an SVG well past 32,767 characters, the most a Windows command line holds. + let padding = "x".repeat(40_000); + let placed = format!( + r##""## + ); + let data = vectorcraft_format::base64_encode(placed.as_bytes()); + assert!(data.len() > 32_767); + let file = json!([ + {"command": "shape.rectangle", "params": {"x": 10, "y": 10, "width": 50, "height": 30}}, + {"command": "file.place", "params": {"name": "code.svg", "dataBase64": data}}, + {"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) + .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() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let lines = json_lines(&out.stdout); + let ran: Vec<&str> = lines.iter().map(|l| l["command"].as_str().unwrap_or("export")).collect(); + assert_eq!(ran, ["file.new", "shape.rectangle", "file.place", "object.setProps", "document.node", "export"]); + // `$2` in the file and in the `--cmd` after it is the placed art. + assert_eq!(lines[4]["result"]["name"], "barcode", "{}", lines[4]); + let written = std::fs::read_to_string(&svg).unwrap(); + assert!(written.contains("118833") && written.contains("barcode"), "{written}"); +} + +/// `run --commands -` reads JSON Lines from standard input: a byte order mark, blank lines and +/// CRLF line ends are fine, and the first step may be `file.new`. +#[test] +fn run_reads_json_lines_from_standard_input() { + let svg = tmp("stdin.svg"); + let mut child = Command::new(BIN) + .args(["run", "--commands", "-", "--export", svg.to_str().unwrap()]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let text = "\u{feff}{\"command\":\"file.new\",\"params\":{\"width\":120,\"height\":80}}\n\n{\"command\":\"shape.ellipse\",\"params\":{\"x\":10,\"y\":10,\"width\":40,\"height\":30}}\r\n{\"id\":\"paint.setFill\",\"params\":{\"color\":\"#3366ff\"}}\n"; + child.stdin.take().unwrap().write_all(text.as_bytes()).unwrap(); + let out = child.wait_with_output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let lines = json_lines(&out.stdout); + assert_eq!(lines.len(), 4); + assert_eq!(lines[0]["command"], "file.new"); + assert!(std::fs::read_to_string(&svg).unwrap().contains("3366ff")); +} + +/// Malformed `--commands` input stops the run before any step runs, naming the step (counted from +/// 0 with the `--cmd` before it) and the entry or line; input past the size and step limits is +/// refused; a step that fails names its number. +#[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(); + assert!(!out.status.success(), "{args:?}"); + (String::from_utf8_lossy(&out.stderr).to_string(), json_lines(&out.stdout).len()) + }; + let bad = |name: &str, text: &[u8], wanted: &[&str]| { + let path = tmp(name); + std::fs::write(&path, text).unwrap(); + let (e, printed) = fails(&["run", "--cmd", "file.new", "--commands", path.to_str().unwrap()]); + assert!(wanted.iter().all(|w| e.contains(w)), "{name}: {e}"); + assert_eq!(printed, 0, "{name}: nothing runs"); + }; + bad("number.json", b"[1]", &["step 1 (entry 1)", "must be an object"]); + bad("both.json", br#"[{"command":"select.all"},{"command":"select.all","id":"select.none"}]"#, &["step 2 (entry 2)", "not both"]); + bad("no-command.json", br#"[{"params":{}}]"#, &["step 1 (entry 1)", "no `command`"]); + bad("id-number.json", br#"[{"command":3}]"#, &["`command` must be a string"]); + bad("params-array.json", br#"[{"command":"select.all","params":[1]}]"#, &["`params` of select.all must be a JSON object"]); + bad("typo.json", br#"[{"command":"select.all","param":{}}]"#, &["unknown key `param`"]); + bad("broken.json", b"[{\"command\":", &["--commands", "broken.json"]); + bad("lines.jsonl", b"{\"command\":\"select.all\"}\n\n{oops}\n", &["step 2 (line 3)"]); + bad("line-array.jsonl", b"{\"command\":\"select.all\"}\n[1]\n", &["step 2 (line 2)"]); + bad("latin1.json", b"[{\"command\":\"select.all\",\"params\":{\"name\":\"\xe9\"}}]", &["not UTF-8"]); + let many = "{\"command\":\"select.all\"}\n".repeat(100_001); + bad("many.jsonl", many.as_bytes(), &["more than 100000 steps"]); + // Past 64 MiB (a sparse file: nothing is written). + let huge = tmp("huge.json"); + std::fs::File::create(&huge).unwrap().set_len(64 * 1024 * 1024 + 1).unwrap(); + let (e, _) = fails(&["run", "--commands", huge.to_str().unwrap()]); + assert!(e.contains("more than 64 MiB"), "{e}"); + let (e, _) = fails(&["run", "--commands", tmp("missing.json").to_str().unwrap()]); + assert!(e.contains("missing.json"), "{e}"); + // `--params` sets the `--cmd` just before it, never a step of the file. + let ok = tmp("ok.json"); + std::fs::write(&ok, br#"[{"command":"select.all"}]"#).unwrap(); + let (e, _) = fails(&["run", "--cmd", "select.all", "--commands", ok.to_str().unwrap(), "--params", "{}"]); + assert!(e.contains("--params must follow a --cmd"), "{e}"); + let (e, _) = fails(&["run", "--commands", "-", "--commands", "-"]); + assert!(e.contains("standard input is read once"), "{e}"); + // A step that fails is named by its number, after the steps before it ran. + let failing = tmp("failing.json"); + std::fs::write(&failing, br#"[{"command":"select.all"},{"command":"nope.nothing"}]"#).unwrap(); + let (e, printed) = fails(&["run", "--cmd", "file.new", "--commands", failing.to_str().unwrap()]); + assert!(e.contains("step 2 (nope.nothing)"), "{e}"); + assert_eq!(printed, 2); +} + +/// `--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(); + 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(); + 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)); + } + } +} + +/// `--help` and `-h` after other arguments print the usage too, before the subcommand does anything +/// with them. +#[test] +fn help_later_in_the_line_prints_the_usage() { + let usage = Command::new(BIN).arg("help").output().unwrap(); + let mut wrong = vec![]; + for args in [ + &["mcp", "--headless", "--help"][..], + &["mcp", "--headless", "-h"], + &["mcp", "--connect", "127.0.0.1:1", "--help"], + &["run", "--cmd", "file.new", "--help"], + &["run", "--in", "missing.svg", "-h"], + &["run", "--commands", "missing.json", "--help"], + &["run", "--cmd", "file.new", "--params", "not json", "-h"], + &["commands", "x", "-h"], + &["convert", "missing.svg", "out.png", "--help"], + &["convert", "missing.svg", "--scale", "2", "-h"], + &["info", "missing.svg", "--help"], + &["bench", "missing.svg", "-h"], + &["bench", "--size", "10x10", "--help"], + &["bench", "--size", "bad", "-h"], + &["perf", "--paths", "10", "--help"], + &["perf", "--paths", "many", "-h"], + &["convert", "--decimals", "many", "--help"], + ] { + let out = Command::new(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))); + } + } + assert!(wrong.is_empty(), "{}", wrong.join("\n")); +} + +/// 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 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 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(); @@ -130,6 +300,58 @@ fn mcp_automation_roots_in_a_folder_an_earlier_run_left() { automation_roots(&empty_dir(dir).join("roots")); } +/// #3546: each root flag may be given more than once: a path inside any of the read roots opens, +/// one inside any of the write roots is written, and everything else, a write root's sibling read +/// root included, is refused. +#[test] +fn mcp_automation_roots_take_several_folders() { + let base = tmp("several-roots"); + for d in ["in", "in2", "out", "out2", "outside"] { + std::fs::create_dir_all(base.join(d)).unwrap(); + } + let svg = r#""#; + for f in ["in/a.svg", "in2/b.svg", "outside/c.svg"] { + std::fs::write(base.join(f), svg).unwrap(); + } + 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) + .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()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let call = |id: u64, name: &str, args: Value| json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":name,"arguments":args}}); + let calls = [ + (call(1, "open_file", json!({"path": file("in", "a.svg")})), false), + (call(2, "open_file", json!({"path": file("in2", "b.svg")})), false), + (call(3, "open_file", json!({"path": file("outside", "c.svg")})), true), + (call(4, "export", json!({"path": file("out", "a.png")})), false), + (call(5, "export", json!({"path": file("out2", "b.png")})), false), + (call(6, "export", json!({"path": file("outside", "c.png")})), true), + (call(7, "export", json!({"path": file("in2", "d.png")})), true), + (call(8, "open_file", json!({"path": file("out2", "b.png")})), true), + ]; + { + let mut stdin = child.stdin.take().unwrap(); + for (m, _) in &calls { + writeln!(stdin, "{m}").unwrap(); + } + } + let out = child.wait_with_output().unwrap(); + assert!(out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("files confined: read ") && stderr.contains("; write "), "{stderr}"); + let replies: Vec = String::from_utf8(out.stdout).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + let errors: Vec = replies.iter().map(|r| r["result"]["isError"] == true).collect(); + assert_eq!(errors, calls.iter().map(|(_, e)| *e).collect::>(), "{replies:?}"); + assert!(replies[2]["result"]["content"][0]["text"].as_str().unwrap().contains("outside the read roots"), "{}", replies[2]); + assert!(base.join("out/a.png").is_file() && base.join("out2/b.png").is_file()); + assert!(!base.join("outside/c.png").exists() && !base.join("in2/d.png").exists()); +} + fn automation_roots(base: &std::path::Path) { for d in ["in", "out", "outside"] { std::fs::create_dir_all(base.join(d)).unwrap(); @@ -153,9 +375,12 @@ fn automation_roots(base: &std::path::Path) { assert!(!out.status.success() && err.contains(why), "{args:?}: {err}"); }; fails(&["mcp", "--automation-read-root", &dir("missing")], "cannot open the automation read root"); - fails(&["mcp", "--automation-read-root", &dir("in"), "--automation-read-root", &dir("out")], "given twice"); + fails(&["mcp", "--automation-read-root", &dir("in"), "--automation-read-root", &dir("missing")], "cannot open the automation read root"); fails(&["mcp", "--automation-write-root"], "needs a folder"); - fails(&["mcp", "--connect", "127.0.0.1:1", &format!("--automation-write-root={}", dir("out"))], "a running app enforces its own roots"); + fails( + &["mcp", "--connect", "127.0.0.1:1", &format!("--automation-write-root={}", dir("out"))], + "a running app enforces its own roots: start it with `vectorcraft --control ", + ); let mut child = Command::new(BIN) .args(["mcp", "--automation-read-root", &dir("in"), &format!("--automation-write-root={}", dir("out"))]) diff --git a/apps/vectorcraft-cli/tests/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs similarity index 84% rename from apps/vectorcraft-cli/tests/fileio.rs rename to apps/vectorcraft-cli/tests/it/fileio.rs index 4de10d932d..1423b78b42 100644 --- a/apps/vectorcraft-cli/tests/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -1,6 +1,4 @@ //! The CLI opens every readable format (PDF, .ai, images) through the engine's `document.open`. -// 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::process::Command; @@ -48,6 +46,29 @@ fn info(file: &str) -> Value { serde_json::from_str(&ok(&["info", file])).unwrap() } +/// #3627: `convert` to PDF omits the embedded native document unless asked. +#[test] +fn convert_pdf_omits_editing_data_unless_preserve_editing() { + let pdf = tmp("flyer.pdf"); + make(&pdf, 120, 80); + let plain = tmp("plain.pdf"); + ok(&["convert", &pdf, &plain]); + let bytes = std::fs::read(&plain).unwrap(); + assert!(!bytes.windows(b"vectorcraft-editing.vectorcraft".len()).any(|w| w == b"vectorcraft-editing.vectorcraft")); + let kept = tmp("kept.pdf"); + let r: Value = serde_json::from_str(&ok(&["convert", &pdf, &kept, "--preserve-editing"])).unwrap(); + let bytes = std::fs::read(&kept).unwrap(); + assert!(bytes.windows(b"vectorcraft-editing.vectorcraft".len()).any(|w| w == b"vectorcraft-editing.vectorcraft"), "{r}"); + assert!(r["warnings"].as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|s| s.contains("preserveEditing")))), "{r}"); + // A --range without every artboard leaves the attachment out: no "embeds" note, even when the + // output's own name contains the attachment's name. + let part = tmp("vectorcraft-editing.vectorcraft.pdf"); + let r: Value = serde_json::from_str(&ok(&["convert", &pdf, &part, "--preserve-editing", "--range", "2"])).unwrap(); + let warnings = r["warnings"].as_array().cloned().unwrap_or_default(); + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|s| s.contains("every artboard"))), "{r}"); + assert!(!warnings.iter().any(|w| w.as_str().is_some_and(|s| s.contains("preserveEditing"))), "{r}"); +} + #[test] fn convert_pdf_to_svg_and_info_on_ai() { let pdf = tmp("in.pdf"); diff --git a/apps/vectorcraft-cli/tests/it/main.rs b/apps/vectorcraft-cli/tests/it/main.rs new file mode 100644 index 0000000000..6918ea19b6 --- /dev/null +++ b/apps/vectorcraft-cli/tests/it/main.rs @@ -0,0 +1,7 @@ +//! Integration tests: one test binary for the crate, one module per area. +// 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 cli; +mod fileio; +mod mcp_e2e; diff --git a/apps/vectorcraft-cli/tests/mcp_e2e.rs b/apps/vectorcraft-cli/tests/it/mcp_e2e.rs similarity index 98% rename from apps/vectorcraft-cli/tests/mcp_e2e.rs rename to apps/vectorcraft-cli/tests/it/mcp_e2e.rs index e75ef09403..5a353070ae 100644 --- a/apps/vectorcraft-cli/tests/mcp_e2e.rs +++ b/apps/vectorcraft-cli/tests/it/mcp_e2e.rs @@ -1,6 +1,4 @@ //! End-to-end MCP over stdio against the built `vectorcraft-cli mcp --headless` binary. -// 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::io::{BufRead, BufReader, Write}; use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index f67a377efc..8decb13d85 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -14,7 +14,7 @@ name = "vectorcraft-web" path = "src/main.rs" [dependencies] -vectorcraft-engine = { workspace = true } +vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] } vectorcraft-ui-egui = { workspace = true } vectorcraft-format = { workspace = true } vectorcraft-text = { workspace = true } @@ -29,4 +29,4 @@ wasm-bindgen = "0.2" serde_json = { workspace = true } wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal"] } diff --git a/apps/vectorcraft-web/src/keys.rs b/apps/vectorcraft-web/src/keys.rs new file mode 100644 index 0000000000..8cb27096b4 --- /dev/null +++ b/apps/vectorcraft-web/src/keys.rs @@ -0,0 +1,118 @@ +//! Shortcuts the browser would also act on. Many of the app's Cmd and Ctrl chords are the +//! browser's too: the View menu's `Cmd+=`, `Cmd+-` and `Cmd+0` zoom the page, Edit's `Cmd+Z` and +//! `Cmd+Shift+Z` undo and redo in the browser (in Safari, Undo Close Tab when the page has nothing +//! to undo), `Cmd+[` and `Cmd+]` go back and forward, `Cmd+F` finds. eframe lets them through, so +//! the browser acted on them as well. For a press the keymap in effect binds (the user's shortcuts +//! included), the page's default action is cancelled; the key still reaches egui, which runs the +//! command (or a text field its own undo). A few chords never reach a page at all (Safari's +//! `Cmd+L`, Chrome's `Cmd+T`, `Cmd+W` and `Cmd+N`): the browser keeps those. + +use egui::{Key, Modifiers}; + +/// Whether the browser's own action for a key press is cancelled. `key` is the event's `key` (the +/// character typed), `code` its `code` (the key's position), `modifiers` as eframe reports them, +/// and `alt_graph` whether AltGr is held. +/// +/// Only Cmd and Ctrl presses: a plain or Shift press types (cancelling it would drop the +/// character it types), and so does AltGr, which Windows reports as Ctrl and Alt held. Cut, Copy +/// and Paste (with any other modifiers) are left to the browser, whose clipboard events carry +/// their text, and Reload too, as eframe leaves them. +pub(crate) fn kept_from_browser(key: &str, code: &str, modifiers: Modifiers, alt_graph: bool) -> bool { + if !(modifiers.ctrl || modifiers.mac_cmd) || alt_graph { + return false; + } + if matches!(Key::from_name(key).or(Key::from_name(code)), Some(Key::C | Key::V | Key::X | Key::R)) { + return false; + } + vectorcraft_ui_egui::shortcuts::runs_a_shortcut(key, code, modifiers) +} + +/// The modifiers of a key event as eframe reports them to egui (its `modifiers_from_kb_event`). +#[cfg(target_arch = "wasm32")] +fn modifiers(e: &web_sys::KeyboardEvent) -> Modifiers { + Modifiers { alt: e.alt_key(), ctrl: e.ctrl_key(), shift: e.shift_key(), mac_cmd: e.meta_key(), command: e.ctrl_key() || e.meta_key() } +} + +/// Whether the app has the keyboard for this event: it went to the canvas, or to the text input +/// eframe places right after it while a text field has the focus. Elsewhere (the page's body, a +/// file input) eframe ignores the key, so the browser keeps it. +#[cfg(target_arch = "wasm32")] +fn to_the_app(e: &web_sys::KeyboardEvent) -> bool { + use wasm_bindgen::JsCast as _; + let Some(target) = e.target() else { return false }; + if target.has_type::() { + return true; + } + target + .dyn_ref::() + .and_then(|input| input.previous_element_sibling()) + .is_some_and(|before| before.has_type::()) +} + +/// Cancel the page's default action for [`kept_from_browser`] presses, before eframe's listener +/// sees the event (it doesn't stop it). +#[cfg(target_arch = "wasm32")] +pub(crate) fn keep_app_keys() { + use wasm_bindgen::JsCast as _; + let Some(window) = web_sys::window() else { return }; + let on_key = wasm_bindgen::closure::Closure::::new(|e: web_sys::KeyboardEvent| { + // An IME's keys are its own until it commits. + if e.is_composing() || !to_the_app(&e) { + return; + } + if kept_from_browser(&e.key(), &e.code(), modifiers(&e), e.get_modifier_state("AltGraph")) { + e.prevent_default(); + } + }); + if let Err(e) = window.add_event_listener_with_callback_and_bool("keydown", on_key.as_ref().unchecked_ref(), true) { + log::error!("couldn't follow keydown events: {e:?}"); + } + // The listener lives as long as the page. + on_key.forget(); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Cmd as egui reports it on this platform: the Command key on macOS, Ctrl elsewhere. + fn cmd() -> Modifiers { + if cfg!(target_os = "macos") { Modifiers::MAC_CMD | Modifiers::COMMAND } else { Modifiers::CTRL | Modifiers::COMMAND } + } + + #[test] + fn the_keymaps_chords_are_kept_from_the_browser() { + for (key, code, mods) in [ + ("=", "Equal", cmd()), + ("-", "Minus", cmd()), + ("0", "Digit0", cmd()), + ("z", "KeyZ", cmd()), + ("Z", "KeyZ", cmd() | Modifiers::SHIFT), + ("[", "BracketLeft", cmd()), + ] { + assert!(kept_from_browser(key, code, mods, false), "{key} ({code}) {mods:?}"); + } + } + + #[test] + fn typing_the_clipboard_and_reload_stay_with_the_browser() { + for (key, code, mods) in [ + // Typing: plain and Shift presses. + ("z", "KeyZ", Modifiers::NONE), + ("Z", "KeyZ", Modifiers::SHIFT), + ("=", "Equal", Modifiers::NONE), + // The clipboard's events carry the text; Paste and Match Style is Shift+Cmd+V. + ("c", "KeyC", cmd()), + ("x", "KeyX", cmd()), + ("v", "KeyV", cmd()), + ("V", "KeyV", cmd() | Modifiers::SHIFT), + ("r", "KeyR", cmd()), + ] { + assert!(!kept_from_browser(key, code, mods, false), "{key} ({code}) {mods:?}"); + } + // AltGr+Z types ż on a Polish layout, reported as Ctrl and Alt held on Windows. + let ctrl_alt = Modifiers::CTRL | Modifiers::COMMAND | Modifiers::ALT; + assert!(!kept_from_browser("ż", "KeyZ", ctrl_alt, true)); + assert!(!kept_from_browser("}", "Digit0", ctrl_alt, true)); + } +} diff --git a/apps/vectorcraft-web/src/main.rs b/apps/vectorcraft-web/src/main.rs index f76e54786f..f7dd201af2 100644 --- a/apps/vectorcraft-web/src/main.rs +++ b/apps/vectorcraft-web/src/main.rs @@ -11,7 +11,10 @@ //! - 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 -//! hover, palm rejection, fingers navigate once a pen has been seen). +//! hover, palm rejection, fingers navigate once a pen has been seen, the pen's eraser end +//! selects the Eraser tool); +//! - a Cmd or Ctrl chord the keymap binds runs its command, not the browser's own action as well +//! (`Cmd+=` zooms the canvas, not the page; `Cmd+Z` undoes in the document) (`keys`). //! //! URL query flags: `?webgl` forces the WebGL2 backend instead of WebGPU; `?lang=es` (any //! language code) stands in for the browser's languages when the interface language is Automatic. @@ -20,6 +23,8 @@ mod api; #[cfg(target_arch = "wasm32")] mod fonts; +#[cfg(any(target_arch = "wasm32", test))] +mod keys; #[cfg(target_arch = "wasm32")] mod locks; #[cfg(any(target_arch = "wasm32", test))] diff --git a/apps/vectorcraft-web/src/pencil.rs b/apps/vectorcraft-web/src/pencil.rs index 42f6294f21..b7140d7e58 100644 --- a/apps/vectorcraft-web/src/pencil.rs +++ b/apps/vectorcraft-web/src/pencil.rs @@ -5,6 +5,9 @@ //! - A pen drives egui's pointer and is a touch contact with the pen's pressure as its force (the //! canvas reads it), so holding it still opens the context menu (egui's long touch). It hovers //! where the pen can (Apple Pencil hover). +//! - A press of the pen's eraser end (the eraser button, `button` 5 in Pointer Events) presses +//! like the tip, and the pen's samples go into a [`StylusFeed`] with that end, so the canvas +//! selects the Eraser tool for the press. A press of the tip turns the pen back. //! - Fingers are touch contacts: two pinch and pan the canvas, and tap to undo or redo. The first //! finger also drives the pointer, so it taps the panels and menus; on the canvas it navigates //! only once a pen has been seen ([`touch::set_source`]), for this page session only. @@ -20,6 +23,7 @@ use std::cell::RefCell; use std::rc::Rc; use egui::{Event, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase}; +use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed}; use vectorcraft_ui_egui::touch::{self, Source}; #[cfg(target_arch = "wasm32")] use wasm_bindgen::JsCast as _; @@ -28,8 +32,11 @@ use wasm_bindgen::JsCast as _; const PEN_DEVICE: TouchDeviceId = TouchDeviceId(1); const FINGER_DEVICE: TouchDeviceId = TouchDeviceId(2); +/// The Pointer Events `button` of a pen's eraser button, which is how a pen's eraser end presses +/// (). +const ERASER_BUTTON: i16 = 5; + /// The pen and finger contacts followed, and the egui events they made since the last frame. -#[derive(Default)] pub struct Pointers { events: Vec, /// The pen pressing, by pointer id. @@ -39,6 +46,16 @@ pub struct Pointers { /// The contact driving egui's pointer. primary: Option, button: Option, + /// The pen last pressed with its eraser end. + eraser: bool, + /// The pen's pressure and end for the canvas (`Services::stylus`). + stylus: StylusFeed, +} + +impl Default for Pointers { + fn default() -> Self { + Self { events: vec![], pen: None, fingers: vec![], primary: None, button: None, eraser: false, stylus: StylusFeed::on_ui_thread() } + } } #[cfg(target_arch = "wasm32")] @@ -71,6 +88,16 @@ impl Pointers { std::mem::take(&mut self.events) } + /// The feed the pen's samples go into, for `Services::stylus`. + pub fn stylus(&self) -> StylusFeed { + self.stylus.clone() + } + + /// A pen moved or pressed with `pressure`, with the end it last pressed with. + fn pen_sample(&self, pressure: f32) { + self.stylus.set_sample(Some(PenSample { pressure, eraser: self.eraser })); + } + fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option) { self.events.push(Event::Touch { device_id: device, id: TouchId::from(id as u64), phase, pos, force }); } @@ -110,6 +137,11 @@ impl Pointers { /// Follow one pointer event; `true` if it was the pen's or a finger's (taken from eframe). fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32)], on_canvas: bool) -> bool { let id = e.id; + if e.pointer_type != "pen" && self.pen.is_none() && matches!(kind, "pointerdown" | "pointermove") { + // Another pointer moved while no pen presses (a palm under a pen pressing is + // rejected): the canvas takes no pen pressure or pen end for it. + self.stylus.set(None); + } match e.pointer_type { "pen" => { let force = Some(e.pressure.clamp(0.0, 1.0)); @@ -118,14 +150,27 @@ impl Pointers { if !on_canvas && self.pen.is_none() { return false; } - let Some(button) = button(e.button) else { return false }; + // The eraser end presses like the tip; the tip and the eraser end each + // set the end the pen is turned to. + let (button, end) = match e.button { + ERASER_BUTTON => (PointerButton::Primary, Some(true)), + number => match button(number) { + Some(button) => (button, (number == 0).then_some(false)), + None => return false, + }, + }; touch::set_source(Source::Pen); self.cancel_fingers(pos, e.modifiers); + if let Some(end) = end { + self.eraser = end; + } + self.pen_sample(e.pressure); self.pen = Some(id); self.touch(PEN_DEVICE, id, TouchPhase::Start, pos, force); self.press(id, pos, button, e.modifiers); } "pointermove" if self.pen == Some(id) => { + self.pen_sample(e.pressure); // The positions the pen reported between two events (up to 240 a second // on an iPad), each with its pressure, so fast strokes keep their curve. for c in coalesced.iter().take(coalesced.len().saturating_sub(1)) { @@ -143,10 +188,14 @@ impl Pointers { if !on_canvas { return false; } + // Pointer Events report no end while a pen hovers: it keeps the end it + // last pressed with. + self.pen_sample(e.pressure); self.events.push(Event::PointerMoved(pos)); } "pointerup" | "pointercancel" if self.pen == Some(id) => { let phase = if kind == "pointerup" { TouchPhase::End } else { TouchPhase::Cancel }; + self.pen_sample(0.0); self.pen = None; self.touch(PEN_DEVICE, id, phase, pos, None); self.release(pos, e.modifiers); @@ -388,8 +437,85 @@ mod tests { fn unknown_pen_buttons_are_not_reinterpreted_as_primary() { reset(); let mut p = Pointers::default(); - assert!(!p.feed("pointerdown", &input("pen", 5), Pos2::ZERO, &[], true)); + assert!(!p.feed("pointerdown", &input("pen", 6), Pos2::ZERO, &[], true)); assert!(p.take().is_empty()); assert!(!touch::pen_seen()); + assert_eq!(p.stylus().eraser(), None); + } + + fn presses(p: &mut Pointers) -> Vec<(PointerButton, bool)> { + p.take() + .into_iter() + .filter_map(|e| match e { + Event::PointerButton { button, pressed, .. } => Some((button, pressed)), + _ => None, + }) + .collect() + } + + /// The eraser end presses as Pointer Events' eraser button (`button` 5): a primary press whose + /// samples carry the eraser end, kept while the pen hovers, until the tip presses. + #[test] + fn the_eraser_button_presses_with_the_eraser_end() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + let pos = Pos2::new(30.0, 40.0); + let eraser = input("pen", ERASER_BUTTON); + assert!(p.feed("pointerdown", &eraser, pos, &[], true)); + assert_eq!(presses(&mut p), [(PointerButton::Primary, true)]); + assert!(touch::pen_seen()); + assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(0.6))); + assert!(p.feed("pointermove", &input("pen", -1), pos, &[], true)); + assert_eq!(feed.eraser(), Some(true)); + assert!(p.feed("pointerup", &eraser, pos, &[], true)); + assert_eq!(presses(&mut p), [(PointerButton::Primary, false)]); + let mut hover = input("pen", -1); + hover.pressure = 0.0; + assert!(p.feed("pointermove", &hover, pos, &[], true)); + assert_eq!(feed.eraser(), Some(true), "a hovering pen keeps the end it pressed with"); + // The barrel button leaves the end as it was. + assert!(p.feed("pointerdown", &input("pen", 2), pos, &[], true)); + assert!(p.feed("pointerup", &input("pen", 2), pos, &[], true)); + assert_eq!(feed.eraser(), Some(true)); + assert!(p.feed("pointerdown", &input("pen", 0), pos, &[], true)); + assert_eq!(feed.eraser(), Some(false), "the tip"); + reset(); + } + + /// A mouse or a finger that moves takes the pen out of the feed, so the canvas gives it no + /// pen pressure and does not switch tools for it. + #[test] + fn other_pointers_clear_the_pen_feed() { + for (pointer_type, kind) in [("mouse", "pointermove"), ("mouse", "pointerdown"), ("touch", "pointerdown"), ("touch", "pointermove")] { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + assert!(p.feed("pointerdown", &input("pen", ERASER_BUTTON), Pos2::ZERO, &[], true)); + assert!(p.feed("pointerup", &input("pen", ERASER_BUTTON), Pos2::ZERO, &[], true)); + let mut other = input(pointer_type, 0); + other.id = 10; + p.feed(kind, &other, Pos2::ZERO, &[], true); + assert_eq!((feed.eraser(), feed.held()), (None, None), "{pointer_type} {kind}"); + } + reset(); + } + + /// A palm that lands or moves while the eraser end presses is rejected, and the feed keeps the + /// eraser end for the canvas's next frame. + #[test] + fn a_rejected_palm_keeps_the_pen_end() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + assert!(p.feed("pointerdown", &input("pen", ERASER_BUTTON), Pos2::ZERO, &[], true)); + let mut palm = input("touch", 0); + palm.id = 10; + for (pointer_type, kind) in [("touch", "pointerdown"), ("touch", "pointermove"), ("mouse", "pointermove")] { + palm.pointer_type = pointer_type; + p.feed(kind, &palm, Pos2::ZERO, &[], true); + assert_eq!(feed.eraser(), Some(true), "{pointer_type} {kind}"); + } + reset(); } } diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index c307994753..859d41ef79 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -13,6 +13,7 @@ use vectorcraft_ui_egui::graphics::GraphicsLoss; 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 wasm_bindgen::JsCast as _; @@ -81,6 +82,7 @@ pub fn start() { restarts: 0, }; track_paste(&host.pasted); + crate::keys::keep_app_keys(); run(host, canvas, None).await; }); } @@ -106,6 +108,7 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option { // The old services asked the old context for frames. @@ -365,55 +369,63 @@ impl eframe::App for WebShell { self.restart(&why); } let Some(app) = &mut self.app else { return }; - let pasted = self.host.pasted.borrow_mut().flavour.take(); - if let Some((f, held)) = pasted { - app.paste_from_host(ctx, f, held); - } - let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files)); - if !dropped.is_empty() { - let at = self.host.drag.take(); - let z = ctx.zoom_factor(); - let (pos, shift) = (at.map(|(x, y, _)| egui::pos2(x / z, y / z)), at.is_some_and(|a| a.2)); - 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, ctx) = (self.host.inbox.clone(), self.host.place_inbox.clone(), ctx.clone()); - wasm_bindgen_futures::spawn_local(async move { - match f.bytes_async().await { - Ok(bytes) => { - match target { - DropTarget::Place(d) => { - place_inbox.lock().unwrap_or_else(|e| e.into_inner()).push(PlaceArrival { name, bytes, drop: Some(d) }) - } - DropTarget::Open => inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes)), - } - ctx.request_repaint(); - } - Err(e) => log::error!("couldn't read dropped file {name}: {e}"), - } - }); - } - } - app.logic(ctx); + app.tick(ctx); crate::api::poll_replies(); + app.finish_ime_logic(ctx); } - fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) { + /// Forward host-gathered pointer events into this frame's raw input, then let the app apply its + /// shared input hook before egui runs. + fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { raw.events.extend(self.host.pointers.borrow_mut().take()); if let Some(app) = &mut self.app { - app.raw_input_hook(raw); + app.raw_input_hook(ctx, raw); } } + /// Read host paste and drop input once in the UI phase, hand files to the app's drop targets, run + /// the app UI, then poll control replies. fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + let ctx = ui.ctx().clone(); if let Some(app) = &mut self.app { + // DOM paste and drop are host input: read them in the UI phase, once per pass, not in + // `logic` where a hidden tab replays the last shown frame's input. + let pasted = self.host.pasted.borrow_mut().flavour.take(); + if let Some((f, held)) = pasted { + app.paste_from_host(&ctx, f, held); + } + let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files)); + if !dropped.is_empty() { + let at = self.host.drag.take(); + let z = ctx.zoom_factor(); + let (pos, shift) = (at.map(|(x, y, _)| egui::pos2(x / z, y / z)), at.is_some_and(|a| a.2)); + 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()); + wasm_bindgen_futures::spawn_local(async move { + match f.bytes_async().await { + Ok(bytes) => { + match target { + DropTarget::Place(d) => { + place_inbox.lock().unwrap_or_else(|e| e.into_inner()).push(PlaceArrival { name, bytes, drop: Some(d) }) + } + DropTarget::Open => inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes)), + } + repaint.request_repaint(); + } + Err(e) => log::error!("couldn't read dropped file {name}: {e}"), + } + }); + } + } app.ui(ui); } crate::api::poll_replies(); } } -fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Option) -> Services { +fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Option, stylus: StylusFeed) -> Services { let open_inbox = inbox.clone(); let picked = place_inbox.clone(); let place_ctx = ctx.clone(); @@ -463,6 +475,8 @@ fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Op recovery_store: Some(Arc::new(BrowserStore { locks })), // File → Print: the browser's print dialog. print: Some(Box::new(BrowserPrint)), + // The pen's end, from the page's Pointer Events (`crate::pencil`). + stylus: Some(stylus), ..Default::default() } } diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 3459689111..561fd0e845 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -17,13 +17,17 @@ accessibility = ["eframe/accesskit"] windows7 = ["eframe/glow"] [dependencies] -vectorcraft-engine = { workspace = true } +vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] } vectorcraft-ui-egui = { workspace = true } vectorcraft-text = { workspace = true } -eframe = { workspace = true, features = ["default_fonts", "wayland", "x11"] } +# Shared across the Craft suite: decides who draws the window frame per desktop (compositor vs app) +# so VectorCraft matches the rest on Linux. `egui` adds `craft_window::decorate`. See #217. +craft-window = { workspace = true } +eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] } egui = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +chrono = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rfd = { workspace = true } @@ -39,25 +43,30 @@ winit = { version = "0.30", default-features = false } craft-print = { workspace = true } [target.'cfg(windows)'.dependencies] +craft-update = { workspace = true } clipboard-win = { workspace = true } # Which GPU drives which display (EnumDisplayDevices, src/gpu.rs), so the window is drawn on the # GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over # Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter. winsafe = { version = "0.0.29", default-features = false, features = ["user"], optional = true } -# DirectWrite's system font collection (src/system_fonts.rs): fonts that font services such as -# Adobe Fonts load in place (#579). MIT OR Apache-2.0, already in the build through accesskit. +# DirectWrite's system font collection and GDI's font list (src/system_fonts.rs): fonts that font +# services such as Adobe Fonts load in place (#579, #1258). MIT OR Apache-2.0, already in the build +# through accesskit. +# Win32_UI_WindowsAndMessaging has `MSG` and `WM_POINTERDOWN`, which src/windows_stylus.rs uses to +# read a pen's barrel button from its pointer messages. Win32_UI_Input_Pointer has +# `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down. [target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies] -windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite"] } +windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] } [target.'cfg(target_os = "macos")'.dependencies] # The macOS menu bar (src/mac_menu.rs): Tauri's menu crate, AppKit menus behind a safe API (no GTK # with default features off). Pinned exactly: review the diff before bumping. -muda = { version = "=0.21.1", default-features = false } +muda = { version = "=0.21.2", default-features = false } objc2 = "0.6" objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "NSApplication", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] } -# Files opened from Finder and the Dock (src/open_documents.rs) and pasted bitmaps (src/clipboard.rs); both already come with winit, muda and rfd. -objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSString", "NSURL"] } +# Files opened from Finder and the Dock (src/open_documents.rs), pasted bitmaps (src/clipboard.rs) and the control channel's App Nap activity (src/control_server.rs); both already come with winit, muda and rfd. +objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] } block2 = "0.6" # The window's AppKit view, to centre its buttons on the app bar (src/mac_window.rs). MIT OR # Apache-2.0 OR Zlib, already in the build through eframe and winit. @@ -74,6 +83,10 @@ pollster = "1" [target.'cfg(target_os = "linux")'.dependencies] # GNOME/Wayland needs client-side window controls without a bundled title font. winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] } +# A drawing tablet's pen pressure under X11 and XWayland (src/tablet.rs): XInput2 raw events on a +# second X connection, x11rb's pure-Rust `RustConnection`. MIT OR Apache-2.0, already in the build +# through winit with the `xinput` feature. +x11rb = { version = "0.13", default-features = false, features = ["xinput"] } # 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. diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs new file mode 100644 index 0000000000..c7d6ada32d --- /dev/null +++ b/apps/vectorcraft/src/app.rs @@ -0,0 +1,166 @@ +use super::prefs::save_prefs; +use super::*; + +/// 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 +/// button's secondary click on Windows. The control channel's input and the native menu's keys +/// go to the main window only. +#[cfg(target_os = "macos")] +pub(crate) fn native_input_hook(app: &VectorcraftApp) -> Option { + app.services.native_menu.is_some().then(|| std::sync::Arc::new(mac_menu::raw_input_hook) as vectorcraft_ui_egui::NativeInputHook) +} + +#[cfg(all(windows, not(target_vendor = "win7")))] +pub(crate) fn native_input_hook(_: &VectorcraftApp) -> Option { + Some(std::sync::Arc::new(windows_stylus::raw_input_hook)) +} + +#[cfg(not(any(target_os = "macos", all(windows, not(target_vendor = "win7")))))] +pub(crate) fn native_input_hook(_: &VectorcraftApp) -> Option { + None +} + +impl eframe::App for App { + // Each frame runs unconfined: it is the person at the keyboard's. The app confines what the + // 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) { + file_access::unconfined(|| self.logic_frame(ctx, frame)); + self.app.finish_ime_logic(ctx); + } + /// 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) { + // 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() { + window_frame(); + } + #[cfg(target_os = "macos")] + if self.app.services.native_menu.is_some() { + mac_menu::raw_input_hook(raw); + } + // A pen contact with the barrel button held presses the secondary button (Windows Ink). + #[cfg(all(windows, not(target_vendor = "win7")))] + windows_stylus::raw_input_hook(raw); + file_access::unconfined(|| self.app.raw_input_hook(ctx, raw)); + } + #[cfg_attr(not(target_os = "macos"), allow(unused_variables))] + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + #[cfg(target_os = "macos")] + { + let bar = vectorcraft_ui_egui::chrome::APP_BAR_HEIGHT; + let inset = mac_window::center_buttons(frame, ui.ctx().zoom_factor(), bar); + self.app.titlebar_inset = inset.unwrap_or(mac_window::DEFAULT_INSET); + } + file_access::unconfined(|| self.app.ui(ui)); + // Preferences are written when confirmed, not only at exit: a session ended any other way + // (the system shutting down, the process ended or crashing) used to lose them (#1747). + if self.app.take_prefs_changed() { + file_access::unconfined(|| save_prefs(&self.app)); + } + // Not while a file dialog's sheet has the keyboard: its name field's composition would go. + #[cfg(target_os = "macos")] + if !self.app.file_dialog_open() && self.app.take_ime_discard() { + discard_marked_text(); + } + } + #[cfg(not(feature = "windows7"))] + fn on_exit(&mut self) { + file_access::unconfined(|| save_prefs(&self.app)); + end_before_teardown(self.frames); + } + #[cfg(feature = "windows7")] + fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) { + file_access::unconfined(|| save_prefs(&self.app)); + } +} + +impl App { + fn logic_frame(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + self.frames = ctx.cumulative_frame_nr(); + if let Some(why) = self.graphics_loss.take() { + // eframe can't give a window a new device: the user saves and starts again. + self.graphics_lost = self.app.graphics_lost(&why); + self.app.status(if self.graphics_lost { + "The graphics device was lost: unsaved changes are kept for Data Recovery. Save your documents and restart VectorCraft" + } else { + "The graphics device was lost: save your documents and restart VectorCraft" + }); + } + if self.graphics_lost && ctx.input(|i| i.viewport().close_requested()) { + // The window can't show the Save Changes question: it closes, and the next launch + // offers the changes back. + vectorcraft_ui_egui::background::wait_all(&mut self.app); + return; + } + // Files from the Finder and the Dock wait while a file dialog is open: what asked for it runs + // again on its document when it answers. + #[cfg(target_os = "macos")] + if !self.app.file_dialog_open() { + let files = open_documents::take(); + if !files.is_empty() { + bring_window_forward(ctx); + } + open_files(&mut self.app, files); + } + self.app.tick(ctx); + if self.pending_maximize { + if let Some(w) = &self.winit_window { + self.pending_maximize = window::apply_pending_maximize(w, true, &mut self.maximize_tries); + } else { + self.pending_maximize = false; + } + } + let host_maximized = self.winit_window.as_ref().map(|w| w.is_maximized()); + window::track(ctx, &mut self.app.ui.window, host_maximized); + if self.app.ui.status == "quit" { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + } +} + +/// On macOS with accessibility, end the process once the app has saved what it keeps on quitting, +/// before eframe tears the window down (#661). AccessKit then gives the window's content view back +/// its own class, which AppKit's Touch Bar support was observing it under, and AppKit aborts the +/// app as it quits on Macs with a Touch Bar. Nothing after the window is needed on a normal quit. +/// Not while the window is still starting up (`frames` below [`gpu::STARTUP_FRAMES`]): a graphics +/// failure then starts the app again on another adapter (#651). +#[allow(unused_variables)] +fn end_before_teardown(frames: u64) { + #[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))] + if frames >= gpu::STARTUP_FRAMES { + log::info!("quitting"); + log::logger().flush(); + std::process::exit(0); + } +} + +/// Show the window when files are opened from the Finder or the Dock: a minimized window comes back +/// out of the Dock and the app takes focus, as a document-based Mac app does (#3769). +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +pub(crate) fn bring_window_forward(ctx: &egui::Context) { + ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); +} + +/// Open files handed to the app (command line, macOS Finder and Dock) as documents. A file that +/// can't be opened is reported to the user and on stderr; the others still open. +pub(crate) fn open_files(app: &mut VectorcraftApp, files: Vec) { + for f in files { + if let Err(e) = vectorcraft_ui_egui::io::open_reporting(app, &f) { + eprintln!("vectorcraft: {f}: {e}"); + } + } +} + +/// Tell the macOS input method to drop its composition (the Type tool kept the marked text as +/// typed). winit's IME toggle only clears its own copy, so the IME would type it again. +#[cfg(target_os = "macos")] +fn discard_marked_text() { + if let Some(mtm) = objc2::MainThreadMarker::new() + && let Some(ic) = objc2_app_kit::NSTextInputContext::currentInputContext(mtm) + { + ic.discardMarkedText(); + } +} diff --git a/apps/vectorcraft/src/automation_args.rs b/apps/vectorcraft/src/automation_args.rs index 26157b76d2..979f42e7bd 100644 --- a/apps/vectorcraft/src/automation_args.rs +++ b/apps/vectorcraft/src/automation_args.rs @@ -6,29 +6,29 @@ use std::ffi::OsString; use std::path::PathBuf; pub struct AutomationArgs { - pub read_root: Option, - pub write_root: Option, + pub read_roots: Vec, + pub write_roots: Vec, read_given: bool, write_given: bool, } impl AutomationArgs { + /// The roots the environment gives (`VECTORCRAFT_AUTOMATION_READ_ROOT` / `_WRITE_ROOT`), until + /// the command line gives its own. pub fn new(read_root: Option, write_root: Option) -> Self { - Self { read_root, write_root, read_given: false, write_given: false } + Self { read_roots: read_root.into_iter().collect(), write_roots: write_root.into_iter().collect(), read_given: false, write_given: false } } - /// Returns whether this argument is a root flag. CLI values override environment defaults - /// once; a second occurrence is an error, including when the two spellings are mixed. + /// Returns whether this argument is a root flag. Each flag may be given more than once (#3546), + /// in either spelling: the first replaces the environment's root of its kind, the others add + /// folders. pub fn consume(&mut self, arg: &str, args: &mut impl Iterator) -> Result { let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value))); - let (root, given) = match flag { - "--automation-read-root" => (&mut self.read_root, &mut self.read_given), - "--automation-write-root" => (&mut self.write_root, &mut self.write_given), + let (roots, given) = match flag { + "--automation-read-root" => (&mut self.read_roots, &mut self.read_given), + "--automation-write-root" => (&mut self.write_roots, &mut self.write_given), _ => return Ok(false), }; - if *given { - return Err(format!("{flag} given twice")); - } let value = match inline { Some(value) => value.to_owned(), None => { @@ -42,8 +42,10 @@ impl AutomationArgs { if value.is_empty() { return Err(format!("{flag} needs a non-empty folder")); } - *root = Some(value.into()); - *given = true; + if !std::mem::replace(given, true) { + roots.clear(); + } + roots.push(value.into()); Ok(true) } } @@ -97,17 +99,24 @@ mod tests { use super::*; #[test] - fn roots_override_environment_once_and_leave_other_arguments() { - let mut roots = AutomationArgs::new(Some("environment".into()), None); + fn roots_override_environment_and_add_up() { + let mut roots = AutomationArgs::new(Some("environment".into()), Some("environment out".into())); let mut args = ["a folder".to_owned(), "drawing.svg".to_owned()].into_iter(); assert!(roots.consume("--automation-read-root", &mut args).unwrap()); assert!(roots.consume("--automation-write-root=out", &mut args).unwrap()); assert!(!roots.consume("--in-window-menus", &mut args).unwrap()); - assert_eq!(roots.read_root, Some("a folder".into())); - assert_eq!(roots.write_root, Some("out".into())); + assert_eq!(roots.read_roots, [PathBuf::from("a folder")]); + assert_eq!(roots.write_roots, [PathBuf::from("out")]); assert_eq!(args.next().as_deref(), Some("drawing.svg")); - assert!(roots.consume("--automation-read-root=other", &mut args).is_err()); - assert_eq!(roots.read_root, Some("a folder".into())); + // #3546: a flag given again adds a folder, in either spelling. + assert!(roots.consume("--automation-read-root=other", &mut args).unwrap()); + assert!(roots.consume("--automation-write-root", &mut ["out2".to_owned()].into_iter()).unwrap()); + assert_eq!(roots.read_roots, [PathBuf::from("a folder"), PathBuf::from("other")]); + assert_eq!(roots.write_roots, [PathBuf::from("out"), PathBuf::from("out2")]); + // A kind the command line leaves alone keeps the environment's root. + let mut roots = AutomationArgs::new(Some("environment".into()), Some("environment out".into())); + assert!(roots.consume("--automation-read-root=a", &mut std::iter::empty()).unwrap()); + assert_eq!(roots.write_roots, [PathBuf::from("environment out")]); } #[test] @@ -117,11 +126,15 @@ mod tests { let mut roots = AutomationArgs::new(Some("read".into()), Some("write".into())); let mut args = operand.map(str::to_owned).into_iter(); assert!(roots.consume(flag, &mut args).is_err(), "{flag} {operand:?}"); - assert_eq!(roots.read_root, Some("read".into())); - assert_eq!(roots.write_root, Some("write".into())); + assert_eq!(roots.read_roots, [PathBuf::from("read")]); + assert_eq!(roots.write_roots, [PathBuf::from("write")]); } let mut roots = AutomationArgs::new(None, None); assert!(roots.consume(&format!("{flag}="), &mut std::iter::empty()).is_err()); + // A bad second folder is an error too, and keeps the first. + assert!(roots.consume(&format!("{flag}=first"), &mut std::iter::empty()).unwrap()); + assert!(roots.consume(flag, &mut std::iter::empty()).is_err()); + assert_eq!([roots.read_roots.len(), roots.write_roots.len()].iter().sum::(), 1); } } @@ -130,8 +143,8 @@ mod tests { let mut roots = AutomationArgs::new(None, None); assert!(roots.consume("--automation-read-root=-folder", &mut std::iter::empty()).unwrap()); assert!(roots.consume("--automation-write-root", &mut ["./-folder".to_owned()].into_iter()).unwrap()); - assert_eq!(roots.read_root, Some("-folder".into())); - assert_eq!(roots.write_root, Some("./-folder".into())); + assert_eq!(roots.read_roots, [PathBuf::from("-folder")]); + assert_eq!(roots.write_roots, [PathBuf::from("./-folder")]); } fn control(args: &[&str]) -> Result, String> { diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index 165c0a81d2..957d302d59 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -143,6 +143,13 @@ fn copied_file(paths: Vec, mimes: &[&'static str]) -> Option { Some(p) if p.ends_with('\r') => PathBuf::from(p.trim_end_matches('\r')), _ => path, }; + // A paste sent by automation reads only what its roots allow. + match path.to_str() { + Some(p) => vectorcraft_engine::file_access::check_read(p).ok()?, + // A lossy name would check another file than the one opened. + None if vectorcraft_engine::file_access::current().is_none() => {} + None => return None, + } let mut head = Vec::with_capacity(FILE_HEAD); std::fs::File::open(&path).ok()?.take(FILE_HEAD as u64).read_to_end(&mut head).ok()?; let mime = file_flavour(&path.to_string_lossy(), &head, mimes)?; diff --git a/apps/vectorcraft/src/control_server.rs b/apps/vectorcraft/src/control_server.rs index 5291005133..508ab0daf2 100644 --- a/apps/vectorcraft/src/control_server.rs +++ b/apps/vectorcraft/src/control_server.rs @@ -67,10 +67,31 @@ pub fn start(port: u16, ctx: egui::Context) -> Receiver { } }; eprintln!("vectorcraft: control server listening on 127.0.0.1:{port}"); + #[cfg(target_os = "macos")] + keep_answering(); std::thread::spawn(move || accept_loop(listener, tx, ctx)); rx } +/// The activity the control channel holds on macOS: work the user asked for, which may let the +/// system sleep when idle, with full timer precision. Without it, App Nap lowers every thread to +/// the lowest priority within about a minute of the window no longer being visible. +#[cfg(target_os = "macos")] +fn activity_options() -> objc2_foundation::NSActivityOptions { + use objc2_foundation::NSActivityOptions; + NSActivityOptions::UserInitiatedAllowingIdleSystemSleep | NSActivityOptions::LatencyCritical +} + +/// Begins the control channel's activity. It lasts until the process ends. +#[cfg(target_os = "macos")] +fn keep_answering() { + use objc2_foundation::{NSProcessInfo, NSString}; + let reason = NSString::from_str("Answering control requests"); + let activity = NSProcessInfo::processInfo().beginActivityWithOptions_reason(activity_options(), &reason); + // The token is never released or passed to `endActivity`, so the activity lasts for the process's lifetime. + std::mem::forget(activity); +} + fn accept_loop(listener: TcpListener, tx: Sender, ctx: egui::Context) { let open = Arc::new(AtomicUsize::new(0)); for stream in listener.incoming().flatten() { @@ -268,378 +289,4 @@ fn serve_lines_with( } #[cfg(test)] -mod tests { - use super::*; - - fn short_timeouts() -> ConnectionTimeouts { - ConnectionTimeouts { idle: Duration::from_millis(150), line: Duration::from_millis(120), write: Duration::from_millis(150) } - } - - fn socket_fixture( - timeouts: ConnectionTimeouts, - handle: impl FnMut(String, Value) -> Option + Send + 'static, - ) -> (TcpStream, Receiver<()>, std::thread::JoinHandle<()>) { - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let addr = listener.local_addr().unwrap(); - let (finished, done) = channel(); - let worker = std::thread::spawn(move || { - let (stream, _) = listener.accept().unwrap(); - socket2::SockRef::from(&stream).set_send_buffer_size(4096).unwrap(); - serve_socket(stream, timeouts, handle); - finished.send(()).unwrap(); - }); - let client = TcpStream::connect(addr).unwrap(); - socket2::SockRef::from(&client).set_recv_buffer_size(4096).unwrap(); - client.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); - (client, done, worker) - } - - fn expect_socket_deadline(client: TcpStream, done: Receiver<()>, worker: std::thread::JoinHandle<()>) { - let stopped = done.recv_timeout(Duration::from_secs(3)).is_ok(); - // Always unblock the old implementation too, so a failed regression leaves no worker behind. - let _ = client.shutdown(std::net::Shutdown::Both); - drop(client); - worker.join().unwrap(); - assert!(stopped, "the server retained a stalled connection beyond its transport deadline"); - } - - #[test] - fn idle_control_socket_releases_its_worker() { - let (client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected")); - expect_socket_deadline(client, done, worker); - } - - /// An idle connection is closed without a line: a client that sends its next request late - /// must not find an error waiting where its reply should be. - #[test] - fn idle_expiry_closes_without_writing_a_line() { - let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected")); - let mut got = Vec::new(); - client.read_to_end(&mut got).unwrap(); - assert_eq!(String::from_utf8_lossy(&got), "", "the app wrote to an idle connection"); - expect_socket_deadline(client, done, worker); - } - - /// A line that stalls is refused in words a client's author can act on, not the system's. - #[test] - fn stalled_control_line_is_refused_with_the_reason() { - let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute")); - client.write_all(b"{\"method\":").unwrap(); - let mut line = String::new(); - BufReader::new(client.try_clone().unwrap()).read_line(&mut line).unwrap(); - assert_eq!( - serde_json::from_str::(&line).unwrap(), - json!({"ok": false, "error": "request line not completed in time; closing the connection"}) - ); - expect_socket_deadline(client, done, worker); - } - - #[test] - fn partial_control_line_releases_its_worker() { - let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute")); - client.write_all(b"{\"method\":").unwrap(); - expect_socket_deadline(client, done, worker); - } - - #[test] - fn trickled_control_line_has_an_absolute_deadline() { - let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute")); - client.write_all(b"{").unwrap(); - let mut writer = client.try_clone().unwrap(); - let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let writing = Arc::clone(&stop); - let trickle = std::thread::spawn(move || { - while !writing.load(Ordering::SeqCst) { - if writer.write_all(b" ").is_err() { - break; - } - std::thread::sleep(Duration::from_millis(20)); - } - }); - let stopped = done.recv_timeout(Duration::from_secs(3)).is_ok(); - stop.store(true, Ordering::SeqCst); - // Both socket copies belong to this fixture; shutdown cleans up the baseline failure as well. - let _ = client.shutdown(std::net::Shutdown::Both); - trickle.join().unwrap(); - worker.join().unwrap(); - assert!(stopped, "trickled bytes restarted the line's deadline"); - } - - #[test] - fn a_nonreading_control_peer_cannot_retain_the_writer() { - let payload = "x".repeat(2 * 1024 * 1024); - let (mut client, done, worker) = socket_fixture(short_timeouts(), move |_, _| Some(json!({"ok": true, "result": payload}))); - client.write_all(b"{\"method\":\"large\"}\n").unwrap(); - expect_socket_deadline(client, done, worker); - } - - #[test] - fn persistent_control_requests_get_fresh_transport_deadlines() { - let timeouts = ConnectionTimeouts { idle: Duration::from_secs(2), ..short_timeouts() }; - let (mut client, done, worker) = socket_fixture(timeouts, |_, _| { - // Application processing is not transport time; begin the reply budget afterwards. - std::thread::sleep(Duration::from_millis(200)); - Some(json!({"ok": true})) - }); - let mut reader = BufReader::new(client.try_clone().unwrap()); - for id in [1, 2] { - // The client sends each line in one write. `writeln!` on the socket sends the JSON in many - // small writes, and when the machine is busy, a pause of more than the 120 ms line deadline - // between two of them closes the connection. - client.write_all(format!("{}\n", json!({"id": id, "method": "inspect"})).as_bytes()).unwrap(); - let mut line = String::new(); - reader.read_line(&mut line).unwrap(); - assert_eq!(serde_json::from_str::(&line).unwrap(), json!({"id": id, "ok": true})); - } - client.shutdown(std::net::Shutdown::Write).unwrap(); - done.recv_timeout(Duration::from_secs(3)).unwrap(); - worker.join().unwrap(); - } - - #[test] - fn buffered_partial_control_line_also_expires() { - let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| Some(json!({"ok": true}))); - client.write_all(b"{\"id\":1,\"method\":\"inspect\"}\n{").unwrap(); - let mut line = String::new(); - BufReader::new(client.try_clone().unwrap()).read_line(&mut line).unwrap(); - assert_eq!(serde_json::from_str::(&line).unwrap()["id"], 1); - expect_socket_deadline(client, done, worker); - } - - #[test] - fn timed_out_worker_returns_its_connection_slot() { - let open = Arc::new(AtomicUsize::new(0)); - let held: Vec<_> = (0..MAX_CONNECTIONS - 1).map(|_| acquire_slot(&open).unwrap()).collect(); - let slot = acquire_slot(&open).unwrap(); - assert!(acquire_slot(&open).is_none()); - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); - let (stream, _) = listener.accept().unwrap(); - let (tx, _rx) = channel(); - let worker = spawn_connection(stream, tx, egui::Context::default(), slot, short_timeouts()).unwrap(); - let start = std::time::Instant::now(); - while open.load(Ordering::SeqCst) == MAX_CONNECTIONS && start.elapsed() < Duration::from_secs(3) { - std::thread::sleep(Duration::from_millis(10)); - } - let released = open.load(Ordering::SeqCst) < MAX_CONNECTIONS; - // Clean up an old implementation that never returned its slot as well. - let _ = client.shutdown(std::net::Shutdown::Both); - worker.join().unwrap(); - assert!(released, "the deadline did not free capacity for the next client"); - let replacement = acquire_slot(&open).expect("a new client can reserve the freed slot"); - drop(replacement); - drop(held); - assert_eq!(open.load(Ordering::SeqCst), 0); - } - - fn run(input: &[u8]) -> (Vec, Vec) { - let mut out = Vec::new(); - let mut calls = Vec::new(); - serve_lines(input, &mut out, |m, _p| { - calls.push(m); - Some(json!({"ok": true, "result": null})) - }); - let replies = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str::(l).unwrap()).collect(); - (replies, calls) - } - - /// Counts the `write` calls made on it and keeps the bytes they write. - #[derive(Default)] - struct Writes { - calls: usize, - bytes: Vec, - } - - impl Write for Writes { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.calls += 1; - self.bytes.extend_from_slice(buf); - Ok(buf.len()) - } - - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - - /// A reply shaped like `document.inspect`'s for a layer of `n` squares in rows of 200. - fn inspect_reply(n: u64) -> Value { - let paths: Vec = (0..n) - .map(|k| { - let (x, y) = ((k % 200) as f64 * 20.0, (k / 200) as f64 * 20.0); - json!({"anchors": 4, "bounds": {"height": 10.0, "width": 10.0, "x": x, "y": y}, "closed": true, "fill": "#f4a261", - "id": k + 2, "kind": "Path", "locked": false, "name": "", "stroke": "None", "strokeWidth": 0.0, "visible": true}) - }) - .collect(); - json!({"ok": true, "result": {"layers": [{"children": paths, "id": 1, "kind": "Layer", "name": "Layer 1"}]}}) - } - - /// #1725: a request its caller gave up before the app took it never runs; one the app took - /// first can't be withdrawn, and the timeout says so. - #[test] - fn a_timed_out_request_is_withdrawn_unless_it_started() { - let (waiting, _rx) = ControlRequest::new("engine.execute", json!({})); - assert!(timed_out(&waiting.ticket())["error"].as_str().unwrap().contains("will not run")); - assert!(!waiting.claim(), "the app skips a withdrawn request"); - let (running, _rx) = ControlRequest::new("engine.execute", json!({})); - assert!(running.claim()); - assert!(timed_out(&running.ticket())["error"].as_str().unwrap().contains("still running")); - assert!(!running.claim(), "a request is taken once"); - } - - #[test] - fn requests_are_answered_in_order_with_ids() { - let (r, calls) = run(b"{\"id\":1,\"method\":\"a\"}\n\n{\"id\":2,\"method\":\"b\",\"params\":{}}\r\n{\"method\":\"c\"}"); - assert_eq!(calls, ["a", "b", "c"]); - assert_eq!(r.len(), 3); - assert_eq!(r[0]["id"], 1); - assert_eq!(r[1]["id"], 2); - assert_eq!(r[2]["id"], Value::Null); - } - - #[test] - fn replies_are_written_in_few_large_writes() { - for reply in [json!({"ok": true, "result": null}), inspect_reply(2_000)] { - let mut out = Writes::default(); - let mut once = Some(reply.clone()); - serve_lines(&b"{\"id\":1,\"method\":\"document.inspect\"}\n"[..], &mut out, |_, _| once.take()); - let mut want = reply; - want["id"] = json!(1); - let text = String::from_utf8(out.bytes).unwrap(); - // The writer receives the bytes that `writeln!(out, "{want}")` writes, in at most one write per 4 KiB. - assert_eq!(text, format!("{want}\n")); - assert!(out.calls <= text.len().div_ceil(4096), "{} writes for {} bytes", out.calls, text.len()); - } - // A refusal is one write as well. - let mut out = Writes::default(); - serve_lines(&b"hello\n"[..], &mut out, |_, _| None); - assert_eq!(out.calls, 1); - } - - #[test] - fn http_request_closes_before_the_body_runs() { - // A browser's cross-origin `fetch` POST: the request line is rejected and the - // connection closed, so the JSON body is never executed. - let http = b"POST / HTTP/1.1\r\nHost: 127.0.0.1:7979\r\nOrigin: https://attacker.example\r\nContent-Type: text/plain\r\n\r\n\ - {\"id\":7,\"method\":\"engine.execute\",\"params\":{\"command\":\"file.new\",\"params\":{}}}\n"; - let (r, calls) = run(http); - assert!(calls.is_empty(), "nothing may run: {calls:?}"); - assert_eq!(r.len(), 1); - assert_eq!(r[0]["ok"], false); - assert!(r[0]["error"].as_str().unwrap().contains("closing the connection")); - } - - #[test] - fn non_request_json_closes_the_connection() { - for junk in [ - &b"[1,2]\n{\"method\":\"a\"}\n"[..], - b"{\"id\":1}\n{\"method\":\"a\"}\n", - b"{\"method\":5}\n{\"method\":\"a\"}\n", - b"\xff\xfe\n{\"method\":\"a\"}\n", - ] { - let (r, calls) = run(junk); - assert!(calls.is_empty(), "{calls:?}"); - assert_eq!(r.len(), 1); - assert_eq!(r[0]["ok"], false); - } - } - - #[test] - fn a_request_before_junk_still_runs() { - let (r, calls) = run(b"{\"method\":\"a\"}\nGET / HTTP/1.1\n{\"method\":\"b\"}\n"); - assert_eq!(calls, ["a"]); - assert_eq!(r.len(), 2); - assert_eq!(r[1]["ok"], false); - } - - #[test] - fn overlong_line_is_refused() { - // One byte over the limit, then a valid request: neither runs. - let mut input = vec![b'x'; MAX_LINE + 1]; - input.extend_from_slice(b"\n{\"method\":\"a\"}\n"); - let (r, calls) = run(&input); - assert!(calls.is_empty(), "{calls:?}"); - assert_eq!(r.len(), 1); - assert!(r[0]["error"].as_str().unwrap().contains("longer than")); - } - - #[test] - fn line_at_the_limit_is_accepted() { - let mut buf = Vec::new(); - let line = vec![b'a'; 10]; - let mut input = line.clone(); - input.push(b'\n'); - assert_eq!(read_bounded_line(&mut &input[..], &mut buf, 10), Ok(true)); - assert_eq!(buf, line); - assert!(read_bounded_line(&mut &[b'a'; 11][..], &mut buf, 10).is_err()); - } - - #[test] - fn tcp_connection_is_closed_after_junk() { - // End to end over a real loopback socket (the transport the app uses). - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let addr = listener.local_addr().unwrap(); - let server = std::thread::spawn(move || { - let (s, _) = listener.accept().unwrap(); - let read = s.try_clone().unwrap(); - serve_lines(read, s, |_, _| Some(json!({"ok": true}))); - }); - let mut c = TcpStream::connect(addr).unwrap(); - c.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); - c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n{\"method\":\"y\"}\n").unwrap(); - let mut text = String::new(); - c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection - server.join().unwrap(); - let lines: Vec<&str> = text.lines().collect(); - assert_eq!(lines.len(), 2, "{text}"); - assert!(lines[0].contains("\"id\":7")); - assert!(lines[1].contains("closing the connection")); - } - - #[test] - fn ten_inspect_replies_for_10000_objects_arrive_within_20_s() { - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let addr = listener.local_addr().unwrap(); - let reply = inspect_reply(10_000); - let mut want = reply.clone(); - want["id"] = json!(1); - let want = format!("{want}\n"); - std::thread::spawn(move || { - let (s, _) = listener.accept().unwrap(); - let read = s.try_clone().unwrap(); - serve_lines(read, s, |_, _| Some(reply.clone())); - }); - // The client sends each request line and reads its reply line through a `BufReader`, as `vectorcraft_mcp::Remote` does. - let (tx, rx) = channel(); - std::thread::spawn(move || { - let mut c = TcpStream::connect(addr).unwrap(); - let mut read = BufReader::new(c.try_clone().unwrap()); - let mut lines = vec![]; - for _ in 0..10 { - c.write_all(b"{\"id\":1,\"method\":\"document.inspect\"}\n").unwrap(); - let mut line = String::new(); - read.read_line(&mut line).unwrap(); - lines.push(line); - } - tx.send(lines).ok(); - }); - let lines = rx.recv_timeout(Duration::from_secs(20)).unwrap_or_else(|_| panic!("ten replies did not arrive within 20 s")); - assert!(lines.iter().all(|l| *l == want), "a reply differs from the bytes `writeln!` writes"); - } - - #[test] - fn extra_connections_are_refused() { - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let addr = listener.local_addr().unwrap(); - let (tx, _rx) = channel::(); - std::thread::spawn(move || accept_loop(listener, tx, egui::Context::default())); - // Idle connections are accepted in order and held open. - let held: Vec = (0..16).map(|_| TcpStream::connect(addr).unwrap()).collect(); - let mut extra = TcpStream::connect(addr).unwrap(); - extra.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); - let mut line = String::new(); - BufReader::new(&mut extra).read_line(&mut line).unwrap(); - assert!(line.contains("too many control connections"), "{line}"); - drop(held); - } -} +mod tests; diff --git a/apps/vectorcraft/src/control_server/tests.rs b/apps/vectorcraft/src/control_server/tests.rs new file mode 100644 index 0000000000..7fa3f27e7e --- /dev/null +++ b/apps/vectorcraft/src/control_server/tests.rs @@ -0,0 +1,394 @@ +use super::*; + +fn short_timeouts() -> ConnectionTimeouts { + ConnectionTimeouts { idle: Duration::from_millis(150), line: Duration::from_millis(120), write: Duration::from_millis(150) } +} + +/// The short line deadline, with idle and reply budgets longer than the tests' 3 s waits. On a +/// busy machine either thread can pause for more than 150 ms between connecting and sending, or +/// between starting a reply and writing it, and a short budget then closes the connection with no +/// reply. +fn line_timeouts() -> ConnectionTimeouts { + ConnectionTimeouts { idle: Duration::from_secs(10), write: Duration::from_secs(10), ..short_timeouts() } +} + +fn socket_fixture( + timeouts: ConnectionTimeouts, + handle: impl FnMut(String, Value) -> Option + Send + 'static, +) -> (TcpStream, Receiver<()>, std::thread::JoinHandle<()>) { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let (finished, done) = channel(); + let worker = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + socket2::SockRef::from(&stream).set_send_buffer_size(4096).unwrap(); + serve_socket(stream, timeouts, handle); + finished.send(()).unwrap(); + }); + let client = TcpStream::connect(addr).unwrap(); + socket2::SockRef::from(&client).set_recv_buffer_size(4096).unwrap(); + client.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); + (client, done, worker) +} + +fn expect_socket_deadline(client: TcpStream, done: Receiver<()>, worker: std::thread::JoinHandle<()>) { + let stopped = done.recv_timeout(Duration::from_secs(3)).is_ok(); + // Always unblock the old implementation too, so a failed regression leaves no worker behind. + let _ = client.shutdown(std::net::Shutdown::Both); + drop(client); + worker.join().unwrap(); + assert!(stopped, "the server retained a stalled connection beyond its transport deadline"); +} + +#[test] +fn idle_control_socket_releases_its_worker() { + let (client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected")); + expect_socket_deadline(client, done, worker); +} + +/// An idle connection is closed without a line: a client that sends its next request late +/// must not find an error waiting where its reply should be. +#[test] +fn idle_expiry_closes_without_writing_a_line() { + let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected")); + let mut got = Vec::new(); + client.read_to_end(&mut got).unwrap(); + assert_eq!(String::from_utf8_lossy(&got), "", "the app wrote to an idle connection"); + expect_socket_deadline(client, done, worker); +} + +/// A line that stalls is refused in words a client's author can act on, not the system's. +#[test] +fn stalled_control_line_is_refused_with_the_reason() { + let (mut client, done, worker) = socket_fixture(line_timeouts(), |_, _| panic!("incomplete requests must not execute")); + client.write_all(b"{\"method\":").unwrap(); + let mut line = String::new(); + BufReader::new(client.try_clone().unwrap()).read_line(&mut line).unwrap(); + assert_eq!( + serde_json::from_str::(&line).unwrap(), + json!({"ok": false, "error": "request line not completed in time; closing the connection"}) + ); + expect_socket_deadline(client, done, worker); +} + +#[test] +fn partial_control_line_releases_its_worker() { + let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute")); + client.write_all(b"{\"method\":").unwrap(); + expect_socket_deadline(client, done, worker); +} + +#[test] +fn trickled_control_line_has_an_absolute_deadline() { + let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute")); + client.write_all(b"{").unwrap(); + let mut writer = client.try_clone().unwrap(); + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let writing = Arc::clone(&stop); + let trickle = std::thread::spawn(move || { + while !writing.load(Ordering::SeqCst) { + if writer.write_all(b" ").is_err() { + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + }); + let stopped = done.recv_timeout(Duration::from_secs(3)).is_ok(); + stop.store(true, Ordering::SeqCst); + // Both socket copies belong to this fixture; shutdown cleans up the baseline failure as well. + let _ = client.shutdown(std::net::Shutdown::Both); + trickle.join().unwrap(); + worker.join().unwrap(); + assert!(stopped, "trickled bytes restarted the line's deadline"); +} + +#[test] +fn a_nonreading_control_peer_cannot_retain_the_writer() { + let payload = "x".repeat(2 * 1024 * 1024); + let (mut client, done, worker) = socket_fixture(short_timeouts(), move |_, _| Some(json!({"ok": true, "result": payload}))); + client.write_all(b"{\"method\":\"large\"}\n").unwrap(); + expect_socket_deadline(client, done, worker); +} + +#[test] +fn persistent_control_requests_get_fresh_transport_deadlines() { + let timeouts = ConnectionTimeouts { idle: Duration::from_secs(2), ..short_timeouts() }; + let (mut client, done, worker) = socket_fixture(timeouts, |_, _| { + // Application processing is not transport time; begin the reply budget afterwards. + std::thread::sleep(Duration::from_millis(200)); + Some(json!({"ok": true})) + }); + let mut reader = BufReader::new(client.try_clone().unwrap()); + for id in [1, 2] { + // The client sends each line in one write. `writeln!` on the socket sends the JSON in many + // small writes, and when the machine is busy, a pause of more than the 120 ms line deadline + // between two of them closes the connection. + client.write_all(format!("{}\n", json!({"id": id, "method": "inspect"})).as_bytes()).unwrap(); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap(), json!({"id": id, "ok": true})); + } + client.shutdown(std::net::Shutdown::Write).unwrap(); + done.recv_timeout(Duration::from_secs(3)).unwrap(); + worker.join().unwrap(); +} + +#[test] +fn buffered_partial_control_line_also_expires() { + let (mut client, done, worker) = socket_fixture(line_timeouts(), |_, _| Some(json!({"ok": true}))); + client.write_all(b"{\"id\":1,\"method\":\"inspect\"}\n{").unwrap(); + let mut line = String::new(); + BufReader::new(client.try_clone().unwrap()).read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["id"], 1); + expect_socket_deadline(client, done, worker); +} + +#[test] +fn timed_out_worker_returns_its_connection_slot() { + let open = Arc::new(AtomicUsize::new(0)); + let held: Vec<_> = (0..MAX_CONNECTIONS - 1).map(|_| acquire_slot(&open).unwrap()).collect(); + let slot = acquire_slot(&open).unwrap(); + assert!(acquire_slot(&open).is_none()); + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let (stream, _) = listener.accept().unwrap(); + let (tx, _rx) = channel(); + let worker = spawn_connection(stream, tx, egui::Context::default(), slot, short_timeouts()).unwrap(); + let start = std::time::Instant::now(); + while open.load(Ordering::SeqCst) == MAX_CONNECTIONS && start.elapsed() < Duration::from_secs(3) { + std::thread::sleep(Duration::from_millis(10)); + } + let released = open.load(Ordering::SeqCst) < MAX_CONNECTIONS; + // Clean up an old implementation that never returned its slot as well. + let _ = client.shutdown(std::net::Shutdown::Both); + worker.join().unwrap(); + assert!(released, "the deadline did not free capacity for the next client"); + let replacement = acquire_slot(&open).expect("a new client can reserve the freed slot"); + drop(replacement); + drop(held); + assert_eq!(open.load(Ordering::SeqCst), 0); +} + +fn run(input: &[u8]) -> (Vec, Vec) { + let mut out = Vec::new(); + let mut calls = Vec::new(); + serve_lines(input, &mut out, |m, _p| { + calls.push(m); + Some(json!({"ok": true, "result": null})) + }); + let replies = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str::(l).unwrap()).collect(); + (replies, calls) +} + +/// Counts the `write` calls made on it and keeps the bytes they write. +#[derive(Default)] +struct Writes { + calls: usize, + bytes: Vec, +} + +impl Write for Writes { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.calls += 1; + self.bytes.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// A reply shaped like `document.inspect`'s for a layer of `n` squares in rows of 200. +fn inspect_reply(n: u64) -> Value { + let paths: Vec = (0..n) + .map(|k| { + let (x, y) = ((k % 200) as f64 * 20.0, (k / 200) as f64 * 20.0); + json!({"anchors": 4, "bounds": {"height": 10.0, "width": 10.0, "x": x, "y": y}, "closed": true, "fill": "#f4a261", + "id": k + 2, "kind": "Path", "locked": false, "name": "", "stroke": "None", "strokeWidth": 0.0, "visible": true}) + }) + .collect(); + json!({"ok": true, "result": {"layers": [{"children": paths, "id": 1, "kind": "Layer", "name": "Layer 1"}]}}) +} + +/// #1725: a request its caller gave up before the app took it never runs; one the app took +/// first can't be withdrawn, and the timeout says so. +#[test] +fn a_timed_out_request_is_withdrawn_unless_it_started() { + let (waiting, _rx) = ControlRequest::new("engine.execute", json!({})); + assert!(timed_out(&waiting.ticket())["error"].as_str().unwrap().contains("will not run")); + assert!(!waiting.claim(), "the app skips a withdrawn request"); + let (running, _rx) = ControlRequest::new("engine.execute", json!({})); + assert!(running.claim()); + assert!(timed_out(&running.ticket())["error"].as_str().unwrap().contains("still running")); + assert!(!running.claim(), "a request is taken once"); +} + +#[test] +fn requests_are_answered_in_order_with_ids() { + let (r, calls) = run(b"{\"id\":1,\"method\":\"a\"}\n\n{\"id\":2,\"method\":\"b\",\"params\":{}}\r\n{\"method\":\"c\"}"); + assert_eq!(calls, ["a", "b", "c"]); + assert_eq!(r.len(), 3); + assert_eq!(r[0]["id"], 1); + assert_eq!(r[1]["id"], 2); + assert_eq!(r[2]["id"], Value::Null); +} + +#[test] +fn replies_are_written_in_few_large_writes() { + for reply in [json!({"ok": true, "result": null}), inspect_reply(2_000)] { + let mut out = Writes::default(); + let mut once = Some(reply.clone()); + serve_lines(&b"{\"id\":1,\"method\":\"document.inspect\"}\n"[..], &mut out, |_, _| once.take()); + let mut want = reply; + want["id"] = json!(1); + let text = String::from_utf8(out.bytes).unwrap(); + // The writer receives the bytes that `writeln!(out, "{want}")` writes, in at most one write per 4 KiB. + assert_eq!(text, format!("{want}\n")); + assert!(out.calls <= text.len().div_ceil(4096), "{} writes for {} bytes", out.calls, text.len()); + } + // A refusal is one write as well. + let mut out = Writes::default(); + serve_lines(&b"hello\n"[..], &mut out, |_, _| None); + assert_eq!(out.calls, 1); +} + +#[test] +fn http_request_closes_before_the_body_runs() { + // A browser's cross-origin `fetch` POST: the request line is rejected and the + // connection closed, so the JSON body is never executed. + let http = b"POST / HTTP/1.1\r\nHost: 127.0.0.1:7979\r\nOrigin: https://attacker.example\r\nContent-Type: text/plain\r\n\r\n\ + {\"id\":7,\"method\":\"engine.execute\",\"params\":{\"command\":\"file.new\",\"params\":{}}}\n"; + let (r, calls) = run(http); + assert!(calls.is_empty(), "nothing may run: {calls:?}"); + assert_eq!(r.len(), 1); + assert_eq!(r[0]["ok"], false); + assert!(r[0]["error"].as_str().unwrap().contains("closing the connection")); +} + +#[test] +fn non_request_json_closes_the_connection() { + for junk in [ + &b"[1,2]\n{\"method\":\"a\"}\n"[..], + b"{\"id\":1}\n{\"method\":\"a\"}\n", + b"{\"method\":5}\n{\"method\":\"a\"}\n", + b"\xff\xfe\n{\"method\":\"a\"}\n", + ] { + let (r, calls) = run(junk); + assert!(calls.is_empty(), "{calls:?}"); + assert_eq!(r.len(), 1); + assert_eq!(r[0]["ok"], false); + } +} + +#[test] +fn a_request_before_junk_still_runs() { + let (r, calls) = run(b"{\"method\":\"a\"}\nGET / HTTP/1.1\n{\"method\":\"b\"}\n"); + assert_eq!(calls, ["a"]); + assert_eq!(r.len(), 2); + assert_eq!(r[1]["ok"], false); +} + +#[test] +fn overlong_line_is_refused() { + // One byte over the limit, then a valid request: neither runs. + let mut input = vec![b'x'; MAX_LINE + 1]; + input.extend_from_slice(b"\n{\"method\":\"a\"}\n"); + let (r, calls) = run(&input); + assert!(calls.is_empty(), "{calls:?}"); + assert_eq!(r.len(), 1); + assert!(r[0]["error"].as_str().unwrap().contains("longer than")); +} + +#[test] +fn line_at_the_limit_is_accepted() { + let mut buf = Vec::new(); + let line = vec![b'a'; 10]; + let mut input = line.clone(); + input.push(b'\n'); + assert_eq!(read_bounded_line(&mut &input[..], &mut buf, 10), Ok(true)); + assert_eq!(buf, line); + assert!(read_bounded_line(&mut &[b'a'; 11][..], &mut buf, 10).is_err()); +} + +#[test] +fn tcp_connection_is_closed_after_junk() { + // End to end over a real loopback socket (the transport the app uses). + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let (s, _) = listener.accept().unwrap(); + let read = s.try_clone().unwrap(); + serve_lines(read, s, |_, _| Some(json!({"ok": true}))); + }); + let mut c = TcpStream::connect(addr).unwrap(); + c.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n{\"method\":\"y\"}\n").unwrap(); + let mut text = String::new(); + c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection + server.join().unwrap(); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines.len(), 2, "{text}"); + assert!(lines[0].contains("\"id\":7")); + assert!(lines[1].contains("closing the connection")); +} + +#[test] +fn ten_inspect_replies_for_10000_objects_arrive_within_20_s() { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let reply = inspect_reply(10_000); + let mut want = reply.clone(); + want["id"] = json!(1); + let want = format!("{want}\n"); + std::thread::spawn(move || { + let (s, _) = listener.accept().unwrap(); + let read = s.try_clone().unwrap(); + serve_lines(read, s, |_, _| Some(reply.clone())); + }); + // The client sends each request line and reads its reply line through a `BufReader`, as `vectorcraft_mcp::Remote` does. + let (tx, rx) = channel(); + std::thread::spawn(move || { + let mut c = TcpStream::connect(addr).unwrap(); + let mut read = BufReader::new(c.try_clone().unwrap()); + let mut lines = vec![]; + for _ in 0..10 { + c.write_all(b"{\"id\":1,\"method\":\"document.inspect\"}\n").unwrap(); + let mut line = String::new(); + read.read_line(&mut line).unwrap(); + lines.push(line); + } + tx.send(lines).ok(); + }); + let lines = rx.recv_timeout(Duration::from_secs(20)).unwrap_or_else(|_| panic!("ten replies did not arrive within 20 s")); + assert!(lines.iter().all(|l| *l == want), "a reply differs from the bytes `writeln!` writes"); +} + +#[test] +fn extra_connections_are_refused() { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, _rx) = channel::(); + std::thread::spawn(move || accept_loop(listener, tx, egui::Context::default())); + // Idle connections are accepted in order and held open. + let held: Vec = (0..16).map(|_| TcpStream::connect(addr).unwrap()).collect(); + let mut extra = TcpStream::connect(addr).unwrap(); + extra.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut line = String::new(); + BufReader::new(&mut extra).read_line(&mut line).unwrap(); + assert!(line.contains("too many control connections"), "{line}"); + drop(held); +} + +// A test process is not an app that App Nap applies to, so this checks the activity the +// channel asks for; the throttling itself shows only in a running app with its window hidden. +#[cfg(target_os = "macos")] +#[test] +fn the_control_channel_keeps_the_app_at_full_priority_on_macos() { + use objc2_foundation::NSActivityOptions; + let options = activity_options(); + assert!(options.contains(NSActivityOptions::LatencyCritical), "without it App Nap still lowers the priority to 20"); + assert!(options.contains(NSActivityOptions::UserInitiatedAllowingIdleSystemSleep)); + assert!(!options.contains(NSActivityOptions::IdleSystemSleepDisabled), "the channel must not keep the Mac awake"); + keep_answering(); +} diff --git a/apps/vectorcraft/src/gpu.rs b/apps/vectorcraft/src/gpu.rs index 93ca920688..f683f03b4a 100644 --- a/apps/vectorcraft/src/gpu.rs +++ b/apps/vectorcraft/src/gpu.rs @@ -878,753 +878,4 @@ fn restart(skip: &str) -> std::io::Result<()> { } #[cfg(test)] -mod tests { - use super::*; - - fn gpu(name: &str, backend: Backend, device_type: DeviceType) -> Candidate { - Candidate { key: format!("{backend:?}:{name}"), name: name.into(), backend, device_type, pci: (0, 0), presents: true } - } - - /// #1459: a 9048 px wide window (two display scales' ratio past 8192) fits an adapter that - /// takes 16384 px textures; an adapter with less than eframe asks for changes nothing. - #[test] - fn the_surface_may_be_as_large_as_the_adapter_allows() { - assert_eq!(surface_limit(8192, 16384), 16384); - assert_eq!(surface_limit(8192, 4096), 8192); - } - - fn names(c: &[Candidate], order: &[usize]) -> Vec { - order.iter().map(|&i| c[i].name.clone()).collect() - } - - const NVIDIA_3090: (u32, u32) = (0x10de, 0x2204); - const AMD_IGPU: (u32, u32) = (0x1002, 0x164e); - const INTEL_IGPU: (u32, u32) = (0x8086, 0xa780); - const WARP: (u32, u32) = (0x1414, 0x008c); - - fn pci_gpu(name: &str, backend: Backend, device_type: DeviceType, pci: (u32, u32)) -> Candidate { - Candidate { key: key(backend, pci.0, pci.1, name), name: name.into(), backend, device_type, pci, presents: true } - } - - fn monitor(pci: (u32, u32)) -> DisplayGpu { - DisplayGpu { pci, primary: false } - } - - fn primary(pci: (u32, u32)) -> DisplayGpu { - DisplayGpu { pci, primary: true } - } - - /// The desktop of pdfcraft#378 as wgpu lists it on Windows: a Ryzen's integrated GPU without a - /// monitor and an RTX 3090 driving both monitors, each under Vulkan and DX12, then WARP and - /// OpenGL (which reports no device id). - fn ryzen_desktop() -> Vec { - vec![ - pci_gpu("NVIDIA GeForce RTX 3090", Backend::Vulkan, DeviceType::DiscreteGpu, NVIDIA_3090), - pci_gpu("AMD Radeon(TM) Graphics", Backend::Vulkan, DeviceType::IntegratedGpu, AMD_IGPU), - pci_gpu("NVIDIA GeForce RTX 3090", Backend::Dx12, DeviceType::DiscreteGpu, NVIDIA_3090), - pci_gpu("AMD Radeon(TM) Graphics", Backend::Dx12, DeviceType::IntegratedGpu, AMD_IGPU), - pci_gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu, WARP), - pci_gpu("NVIDIA GeForce RTX 3090/PCIe/SSE2", Backend::Gl, DeviceType::Other, (NVIDIA_3090.0, 0)), - ] - } - - /// pdfcraft#378: power saving picked the integrated GPU, whose driver reset when Windows had to - /// present its frames on the monitors of the NVIDIA card. The GPU that drives the displays now - /// comes first, through DX12 (#545); the integrated GPU stays the fallback a restart reaches. - #[test] - fn a_desktop_draws_on_the_gpu_that_drives_its_monitors() { - let c = ryzen_desktop(); - for displays in [vec![primary(NVIDIA_3090)], vec![monitor(NVIDIA_3090)]] { - assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), [2, 0, 3, 1, 5, 4], "{displays:?}"); - assert_eq!(adapter_order(&c, PowerPreference::None, &displays, None, None, &[]), [2, 0, 3, 1, 5, 4], "{displays:?}"); - } - // Without the display information the order is power saving's, as before. - assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]), [3, 1, 2, 0, 5, 4]); - // After the NVIDIA adapters failed, the integrated GPU is next. - let skip = vec![c[2].key.clone(), c[0].key.clone()]; - assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[primary(NVIDIA_3090)], None, None, &skip), [3, 1, 5, 4]); - } - - /// A hybrid laptop: the panel (primary) on the integrated GPU, an external monitor on the - /// discrete one. Power saving and the display agree, in either enumeration order. - #[test] - fn a_hybrid_laptop_draws_on_the_integrated_gpu_that_drives_its_panel() { - let c = ryzen_desktop(); - for displays in [vec![primary(AMD_IGPU), monitor(NVIDIA_3090)], vec![monitor(NVIDIA_3090), primary(AMD_IGPU)], vec![primary(AMD_IGPU)]] { - assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), [3, 1, 2, 0, 5, 4], "{displays:?}"); - } - // Linux names no primary unless there is a built-in panel: a monitor on each GPU keeps the - // system's order among them (Mesa puts the compositor's GPU first), and a GPU without one - // comes after both. - let linux = vec![ - pci_gpu("AMD Radeon Graphics (RADV RAPHAEL_MENDOCINO)", Backend::Vulkan, DeviceType::IntegratedGpu, AMD_IGPU), - pci_gpu("NVIDIA GeForce RTX 3090", Backend::Vulkan, DeviceType::DiscreteGpu, NVIDIA_3090), - pci_gpu("Intel(R) Arc(TM) A380", Backend::Vulkan, DeviceType::DiscreteGpu, INTEL_IGPU), - pci_gpu("llvmpipe (LLVM 20.1.8, 256 bits)", Backend::Vulkan, DeviceType::Cpu, (0x10005, 0)), - ]; - let both = [monitor(AMD_IGPU), monitor(NVIDIA_3090)]; - assert_eq!(adapter_order(&linux, PowerPreference::None, &both, None, None, &[]), [0, 1, 2, 3]); - assert_eq!(adapter_order(&linux, PowerPreference::None, &[monitor(INTEL_IGPU)], None, None, &[]), [2, 0, 1, 3]); - assert_eq!(adapter_order(&linux, PowerPreference::None, &[monitor(NVIDIA_3090), primary(AMD_IGPU)], None, None, &[]), [0, 1, 2, 3]); - } - - /// A hybrid laptop whose Wayland compositor runs on the discrete GPU (Hyprland with - /// `AQ_DRM_DEVICES` naming it first), as Vulkan lists it there: the integrated GPU drives the - /// built-in panel, yet the compositor shows nothing it draws, and reports no error. The GPU the - /// compositor draws with comes first; without it, the panel's, as before. - #[test] - fn the_gpu_the_compositor_draws_with_comes_before_the_panels() { - const RTX_3050: (u32, u32) = (0x10de, 0x25ac); - const INTEL_RPL: (u32, u32) = (0x8086, 0xa7a8); - let mut c = vec![ - pci_gpu("NVIDIA GeForce RTX 3050 6GB Laptop GPU", Backend::Vulkan, DeviceType::DiscreteGpu, RTX_3050), - pci_gpu("Intel(R) Graphics (RPL-P)", Backend::Vulkan, DeviceType::IntegratedGpu, INTEL_RPL), - pci_gpu("NVIDIA GeForce RTX 3050 6GB Laptop GPU/PCIe/SSE2", Backend::Gl, DeviceType::Other, (RTX_3050.0, 0)), - ]; - c[2].presents = false; - let panel = [primary(INTEL_RPL)]; - assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some(RTX_3050), None, &[]), [0, 1]); - assert_eq!(adapter_order(&c, PowerPreference::None, &panel, None, None, &[]), [1, 0]); - // The usual hybrid laptop, with the compositor on the integrated GPU: the panel's GPU. - assert_eq!(adapter_order(&c, PowerPreference::None, &[primary(INTEL_RPL), monitor(RTX_3050)], Some(INTEL_RPL), None, &[]), [1, 0]); - // `WGPU_ADAPTER_NAME` still comes first, and a restart after a failure still moves on. - assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some(RTX_3050), Some("intel"), &[]), [1, 0]); - assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some(RTX_3050), None, &[c[0].key.clone()]), [1]); - // A compositor GPU no adapter matches (a virtual one) leaves the displays in charge. - assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some((0x1af4, 0x1050)), None, &[]), [1, 0]); - } - - /// A Windows desktop with a monitor on each GPU: the window opens on the primary display, so - /// its GPU draws, whichever kind it is. - #[test] - fn the_primary_display_decides_between_gpus_that_both_drive_a_monitor() { - let c = ryzen_desktop(); - assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[monitor(AMD_IGPU), primary(NVIDIA_3090)], None, None, &[]), [2, 0, 3, 1, 5, 4]); - assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[primary(AMD_IGPU), monitor(NVIDIA_3090)], None, None, &[]), [3, 1, 2, 0, 5, 4]); - // The displays only matter among adapters that can show the window; a GPU driving no - // display still loses to one that does. - assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[monitor(AMD_IGPU), monitor(INTEL_IGPU)], None, None, &[]), [3, 1, 2, 0, 5, 4]); - } - - /// Display GPUs none of the adapters match (another driver's ids, OpenGL's missing device id, - /// Metal's zeros) change nothing: power saving's order, the old behaviour. - #[test] - fn displays_no_adapter_matches_leave_the_power_preference_in_charge() { - let c = ryzen_desktop(); - let low = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]); - for displays in [vec![monitor(INTEL_IGPU)], vec![primary((0x8086, 0x1234)), monitor((0x8086, 0x5678))], vec![primary((0, 0))]] { - assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), low, "{displays:?}"); - } - assert_eq!( - names(&c, &adapter_order(&c, PowerPreference::HighPerformance, &[monitor(INTEL_IGPU)], None, None, &[]))[0], - "NVIDIA GeForce RTX 3090" - ); - // The #502 machine's adapters report no ids in these tests: the primary display never matches. - let c = issue_502(); - assert_eq!( - adapter_order(&c, PowerPreference::None, &[primary(NVIDIA_3090)], None, None, &[]), - adapter_order(&c, PowerPreference::None, &[], None, None, &[]) - ); - assert!(adapter_order(&[], PowerPreference::LowPower, &[primary(NVIDIA_3090)], None, None, &[]).is_empty()); - } - - /// `WGPU_ADAPTER_NAME` and "can't present" still come before the displays. - #[test] - fn a_named_adapter_comes_before_the_one_driving_the_display() { - let mut c = ryzen_desktop(); - let displays = [primary(NVIDIA_3090)]; - assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, Some("radeon"), &[]), [3, 1, 2, 0, 5, 4]); - c[2].presents = false; - c[0].presents = false; - assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), [3, 1, 5, 4]); - } - - /// A user's own choice (Preferences or `WGPU_POWER_PREF`) is kept as it is; only Automatic - /// looks at the displays. - #[test] - fn only_automatic_considers_which_gpu_drives_the_display() { - assert!(automatic(None, None)); - assert!(automatic(Some("automatic"), None)); - assert!(automatic(Some("powerSaving"), None)); - assert!(!automatic(Some("lowPower"), None)); - assert!(!automatic(Some("highPerformance"), None)); - assert!(!automatic(None, Some(PowerPreference::None))); - assert!(!automatic(Some("automatic"), Some(PowerPreference::LowPower))); - assert!(preferred_displays(Some("lowPower"), None).is_empty()); - assert!(preferred_displays(None, Some(PowerPreference::HighPerformance)).is_empty()); - // Automatic reports whatever this machine has (nothing on macOS, in CI, or under Remote Desktop). - assert_eq!(preferred_displays(None, None), display_gpus()); - assert_eq!(preferred_compositor(Some("lowPower"), None), None); - assert_eq!(preferred_compositor(None, Some(PowerPreference::HighPerformance)), None); - assert_eq!(preferred_compositor(None, None), crate::compositor_gpu::compositor_gpu()); - } - - #[test] - fn pci_ids_come_from_windows_device_ids() { - assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_2204&SUBSYS_40421458&REV_A1"), Some(NVIDIA_3090)); - assert_eq!(pci_ids("PCI\\VEN_1002&DEV_164E&SUBSYS_88771043&REV_C1"), Some(AMD_IGPU)); - assert_eq!(pci_ids("pci\\ven_1002&dev_164e"), Some(AMD_IGPU)); - // Remote Desktop and other non-PCI display devices, and malformed ids. - assert_eq!(pci_ids("ROOT\\BasicDisplay\\0000"), None); - assert_eq!(pci_ids("PCI\\VEN_10DE&SUBSYS_40421458"), None); - assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_ZZZZ"), None); - assert_eq!(pci_ids("VEN_&DEV_"), None); - assert_eq!(pci_ids(""), None); - } - - /// Whatever this machine has: every GPU listed is a PCI device, at most one drives the primary - /// display, and none is listed twice. (A headless CI runner may list none.) - #[cfg(windows)] - #[test] - fn windows_lists_each_gpu_with_a_monitor_once() { - let gpus = windows_display_gpus(); - assert!(gpus.iter().filter(|g| g.primary).count() <= 1, "{gpus:?}"); - for (i, g) in gpus.iter().enumerate() { - assert_ne!(g.pci.0, 0, "{gpus:?}"); - assert!(!gpus[..i].iter().any(|h| h.pci == g.pci), "{gpus:?}"); - } - } - - #[test] - fn internal_panels_are_edp_lvds_and_dsi_connectors() { - for name in ["eDP-1", "LVDS-1", "DSI-1"] { - assert!(is_internal_panel(name), "{name}"); - } - for name in ["DP-3", "HDMI-A-1", "DVI-D-1", "VGA-1", "Writeback-1", ""] { - assert!(!is_internal_panel(name), "{name}"); - } - } - - /// A sysfs like a hybrid laptop's with an external monitor: the panel and a disconnected port - /// on the integrated GPU (card0), the monitor on the discrete one (card1), and a card without - /// PCI ids. Each GPU is listed once, the one with the panel as primary. - #[test] - fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()> { - let dir = std::env::temp_dir().join(format!("vectorcraft-drm-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let card = |name: &str, (vendor, device): (u32, u32)| -> std::io::Result<()> { - std::fs::create_dir_all(dir.join(name).join("device"))?; - std::fs::write(dir.join(name).join("device/vendor"), format!("{vendor:#06x}\n"))?; - std::fs::write(dir.join(name).join("device/device"), format!("{device:#06x}\n")) - }; - let connector = |name: &str, status: &str| -> std::io::Result<()> { - std::fs::create_dir_all(dir.join(name))?; - std::fs::write(dir.join(name).join("status"), format!("{status}\n")) - }; - card("card0", AMD_IGPU)?; - card("card1", NVIDIA_3090)?; - std::fs::create_dir_all(dir.join("card2"))?; - connector("card0-eDP-1", "connected")?; - connector("card0-HDMI-A-1", "disconnected")?; - connector("card1-DP-1", "connected")?; - connector("card1-DP-2", "connected")?; - connector("card2-Virtual-1", "connected")?; - std::fs::write(dir.join("renderD128"), "")?; - let mut gpus = linux_display_gpus(&dir); - gpus.sort_by_key(|g| g.pci); - assert_eq!(gpus, [primary(AMD_IGPU), monitor(NVIDIA_3090)]); - assert!(linux_display_gpus(&dir.join("no such dir")).is_empty()); - std::fs::remove_dir_all(&dir) - } - - #[test] - fn display_gpus_are_logged_as_pci_ids() { - assert_eq!(primary(NVIDIA_3090).to_string(), "10de:2204 (primary)"); - assert_eq!(monitor(AMD_IGPU).to_string(), "1002:164e"); - let mut gpus = vec![]; - add_display_gpu(&mut gpus, NVIDIA_3090, false); - add_display_gpu(&mut gpus, NVIDIA_3090, true); - add_display_gpu(&mut gpus, AMD_IGPU, false); - assert_eq!(gpus, [primary(NVIDIA_3090), monitor(AMD_IGPU)]); - } - - /// The machine of #502 as Vulkan lists it with Mesa's device-select layer: the GPU KDE's - /// compositor runs on (NVIDIA) first, then the Ryzen's integrated GPU, Mesa's software - /// renderer, and OpenGL. - fn issue_502() -> Vec { - vec![ - gpu("NVIDIA GeForce RTX 5070", Backend::Vulkan, DeviceType::DiscreteGpu), - gpu("AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)", Backend::Vulkan, DeviceType::IntegratedGpu), - gpu("llvmpipe (LLVM 20.1.8, 256 bits)", Backend::Vulkan, DeviceType::Cpu), - gpu("NVIDIA GeForce RTX 5070/PCIe/SSE2", Backend::Gl, DeviceType::Other), - ] - } - - #[test] - fn automatic_keeps_the_systems_order_on_linux_and_saves_power_elsewhere() { - let c = issue_502(); - let order = adapter_order(&c, power_preference(None, None), &[], None, None, &[]); - let first = &c[order[0]].name; - if cfg!(any(windows, target_os = "macos")) { - assert_eq!(first, "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)"); - } else { - // #502: the integrated GPU couldn't show frames to a compositor on the NVIDIA GPU. - assert_eq!(first, "NVIDIA GeForce RTX 5070"); - } - } - - #[test] - fn each_preference_orders_the_adapters_then_falls_back_to_opengl_and_software() { - let c = issue_502(); - let order = |power| names(&c, &adapter_order(&c, power, &[], None, None, &[])); - assert_eq!( - order(PowerPreference::None), - [ - "NVIDIA GeForce RTX 5070", - "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)", - "NVIDIA GeForce RTX 5070/PCIe/SSE2", - "llvmpipe (LLVM 20.1.8, 256 bits)" - ] - ); - assert_eq!( - order(PowerPreference::LowPower), - [ - "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)", - "NVIDIA GeForce RTX 5070", - "NVIDIA GeForce RTX 5070/PCIe/SSE2", - "llvmpipe (LLVM 20.1.8, 256 bits)" - ] - ); - assert_eq!( - order(PowerPreference::HighPerformance), - [ - "NVIDIA GeForce RTX 5070", - "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)", - "NVIDIA GeForce RTX 5070/PCIe/SSE2", - "llvmpipe (LLVM 20.1.8, 256 bits)" - ] - ); - } - - /// A restart leaves out the adapter the window failed on, so Power Saving on the machine of - /// #502 ends up on the NVIDIA GPU, and once every adapter failed there is nothing to try. - /// A dual-GPU Mac reports both GPUs under Metal with no PCI ids (#651): their keys still - /// differ, so when the integrated GPU fails, the restart renders on the discrete one. - #[test] - fn gpus_without_pci_ids_are_told_apart_by_name() { - let mac = |name: &str, device_type| Candidate { - key: key(Backend::Metal, 0, 0, name), - name: name.into(), - backend: Backend::Metal, - device_type, - pci: (0, 0), - presents: true, - }; - let c = vec![mac("NVIDIA GeForce GT 750M", DeviceType::DiscreteGpu), mac("Intel Iris Pro Graphics", DeviceType::IntegratedGpu)]; - assert_eq!((c[0].key.as_str(), c[1].key.as_str()), ("Metal:NVIDIA GeForce GT 750M", "Metal:Intel Iris Pro Graphics")); - let first = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]); - assert_eq!(names(&c, &first)[0], "Intel Iris Pro Graphics"); - let skip = parse_skip(&c[first[0]].key); - assert_eq!(names(&c, &adapter_order(&c, PowerPreference::LowPower, &[], None, None, &skip)), ["NVIDIA GeForce GT 750M"]); - // A comma in a name can't split the list. - assert_eq!(parse_skip(&key(Backend::Gl, 0, 0, "Mesa, llvmpipe")), ["Gl:Mesa llvmpipe"]); - } - - #[test] - fn a_first_frame_that_never_reaches_the_screen_hangs_its_adapter() { - let s = Duration::from_secs; - // The second frame began: the first was presented. - assert_eq!(first_frame(2, s(60), false), FirstFrame::Shown); - // Still drawing (or presenting) the first frame: waited for, then given up on (#964). - for frames in [0, 1] { - assert_eq!(first_frame(frames, s(3), false), FirstFrame::Wait); - assert_eq!(first_frame(frames, FIRST_FRAME_TIMEOUT, false), FirstFrame::Hung); - } - // A window minimized at the start may not draw again until restored. - assert_eq!(first_frame(1, s(60), true), FirstFrame::Shown); - // A hung adapter is left out once, like one that failed. - let skip = vec!["Dx12:10de:28a0".to_string()]; - assert_eq!(restart_without(true, 1, Some("Dx12:10de:28a0"), &skip), None); - assert_eq!(restart_without(true, 1, Some("Dx12:8086:a7a8"), &skip), Some("Dx12:8086:a7a8")); - } - - #[test] - fn a_restart_tries_the_next_adapter() { - let c = issue_502(); - let mut skip = vec![]; - let mut tried = vec![]; - while let Some(&i) = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &skip).first() { - tried.push(c[i].name.clone()); - skip.push(c[i].key.clone()); - } - assert_eq!( - tried, - [ - "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)", - "NVIDIA GeForce RTX 5070", - "NVIDIA GeForce RTX 5070/PCIe/SSE2", - "llvmpipe (LLVM 20.1.8, 256 bits)" - ] - ); - } - - #[test] - fn adapters_that_cannot_present_to_the_window_are_never_tried() { - let mut c = issue_502(); - c[0].presents = false; - c[3].presents = false; - for power in [PowerPreference::None, PowerPreference::LowPower, PowerPreference::HighPerformance] { - let order = adapter_order(&c, power, &[], None, None, &[]); - assert!(!order.contains(&0) && !order.contains(&3), "{power:?}: {order:?}"); - assert_eq!(order.len(), 2); - } - for p in &mut c { - p.presents = false; - } - assert!(adapter_order(&c, PowerPreference::None, &[], None, None, &[]).is_empty()); - assert!(adapter_order(&[], PowerPreference::HighPerformance, &[], None, None, &[]).is_empty()); - } - - #[test] - fn wgpu_adapter_name_picks_an_adapter_first_and_the_rest_stay_as_fallbacks() { - let c = issue_502(); - let order = adapter_order(&c, PowerPreference::HighPerformance, &[], None, Some("radv"), &[]); - assert_eq!(c[order[0]].name, "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)"); - assert_eq!(order.len(), 4); - // Any case; every match comes before the rest, natively first. - let order = adapter_order(&c, PowerPreference::LowPower, &[], None, Some("GeForce"), &[]); - assert_eq!(names(&c, &order[..2]), ["NVIDIA GeForce RTX 5070", "NVIDIA GeForce RTX 5070/PCIe/SSE2"]); - // An empty name or one nothing matches changes nothing. - for named in ["", "no such gpu"] { - assert_eq!( - adapter_order(&c, PowerPreference::LowPower, &[], None, Some(named), &[]), - adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]) - ); - } - // A named adapter that failed is left out like any other. - let skip = vec![c[1].key.clone()]; - assert_eq!(adapter_order(&c, PowerPreference::None, &[], None, Some("radv"), &skip)[0], 0); - } - - /// A Windows machine lists every GPU twice (Vulkan and DX12): power saving still takes the - /// integrated GPU first, as wgpu's own choice did (#306), each GPU through DX12 first (#545). - #[test] - fn hybrid_laptop_on_windows_renders_on_the_integrated_gpu_with_power_saving() { - let c = vec![ - gpu("Intel(R) Arc(TM) A370M", Backend::Vulkan, DeviceType::DiscreteGpu), - gpu("Intel(R) Iris(R) Xe Graphics", Backend::Vulkan, DeviceType::IntegratedGpu), - gpu("Intel(R) Arc(TM) A370M", Backend::Dx12, DeviceType::DiscreteGpu), - gpu("Intel(R) Iris(R) Xe Graphics", Backend::Dx12, DeviceType::IntegratedGpu), - gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu), - ]; - let order = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]); - assert_eq!(order, [3, 1, 2, 0, 4]); - assert_eq!(adapter_order(&c, PowerPreference::HighPerformance, &[], None, None, &[]), [2, 0, 3, 1, 4]); - } - - /// The machine of #545: one Intel GPU, whose Vulkan driver made the window flicker black. - /// DX12 comes first whatever the preference; Vulkan stays a fallback, and `WGPU_ADAPTER_NAME` - /// or a restart leaving DX12 out still reach it. - #[test] - fn a_windows_gpu_renders_through_dx12_before_vulkan() { - let c = vec![ - gpu("Intel(R) Graphics", Backend::Vulkan, DeviceType::IntegratedGpu), - gpu("Intel(R) Graphics", Backend::Dx12, DeviceType::IntegratedGpu), - gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu), - gpu("Intel(R) Graphics", Backend::Gl, DeviceType::Other), - ]; - for power in [PowerPreference::LowPower, PowerPreference::HighPerformance, PowerPreference::None] { - assert_eq!(adapter_order(&c, power, &[], None, None, &[]), [1, 0, 3, 2], "{power:?}"); - } - assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[c[1].key.clone()]), [0, 3, 2], "DX12 failed: Vulkan next"); - } - - #[test] - fn windows_never_loads_vulkan_drivers_unless_asked() { - let all = Backends::all(); - let start = backends(all, false); - if cfg!(windows) { - assert_eq!(start, Backends::DX12 | Backends::GL, "#806"); - } else { - assert_eq!(start, all); - } - assert_eq!(backends(Backends::VULKAN, true), Backends::VULKAN, "WGPU_BACKEND=vulkan still picks it"); - } - - #[test] - fn power_preference_follows_the_environment_then_the_preference() { - assert_eq!(power_preference(None, None), AUTOMATIC); - assert_eq!(power_preference(Some("automatic"), None), AUTOMATIC); - assert_eq!(power_preference(Some("lowPower"), None), PowerPreference::LowPower); - assert_eq!(power_preference(Some("highPerformance"), None), PowerPreference::HighPerformance); - // 0.5.0's default, and values this version doesn't know (a newer or damaged file). - for old in ["powerSaving", "turbo", ""] { - assert_eq!(power_preference(Some(old), None), AUTOMATIC, "{old}"); - } - // WGPU_POWER_PREF wins over the preference, either way. - assert_eq!(power_preference(Some("lowPower"), Some(PowerPreference::HighPerformance)), PowerPreference::HighPerformance); - assert_eq!(power_preference(Some("highPerformance"), Some(PowerPreference::LowPower)), PowerPreference::LowPower); - assert_eq!(power_preference(Some("lowPower"), Some(PowerPreference::None)), PowerPreference::None); - assert_eq!(AUTOMATIC, if cfg!(any(windows, target_os = "macos")) { PowerPreference::LowPower } else { PowerPreference::None }); - } - - /// The preference the engine saves is the one the app reads back before the window opens. - #[test] - fn the_saved_engine_preference_is_found() { - let mut prefs = vectorcraft_engine::Prefs::default(); - let saved = prefs.to_json(); - assert_eq!(saved.get("gpuPreference").and_then(serde_json::Value::as_str), Some("automatic")); - for (value, power) in [("lowPower", PowerPreference::LowPower), ("highPerformance", PowerPreference::HighPerformance)] { - prefs.gpu_preference = value.into(); - let saved = prefs.to_json(); - assert_eq!(power_preference(saved.get("gpuPreference").and_then(serde_json::Value::as_str), None), power); - } - // Every choice Preferences offer means something here. - for (value, _) in vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES { - assert!(["automatic", "lowPower", "highPerformance"].contains(value), "{value}"); - } - } - - #[test] - fn skipped_adapters_parse_from_a_comma_separated_list() { - assert_eq!(parse_skip("Vulkan:1002:164e, Gl:10de:2f04,,"), ["Vulkan:1002:164e", "Gl:10de:2f04"]); - assert!(parse_skip("").is_empty()); - assert_eq!(key(Backend::Vulkan, 0x1002, 0x164e, "AMD Radeon"), "Vulkan:1002:164e"); - assert_eq!(key(Backend::Gl, 0x10de, 0x2f04, "NVIDIA"), "Gl:10de:2f04"); - } - - #[test] - fn panics_in_wgpu_egui_wgpu_and_naga_are_graphics_failures() { - for file in [ - "/home/u/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/egui-wgpu-0.36.2/src/winit.rs", - r"C:\Users\u\.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\wgpu-core-30.0.1\src\device\mod.rs", - "/rustc/deps/wgpu-hal-30.0.1/src/vulkan/adapter.rs", - "naga-30.0.0/src/back/spv/writer.rs", - ] { - assert!(in_graphics_stack(file), "{file}"); - } - for file in [ - "apps/vectorcraft/src/main.rs", - "/home/wgpu/vectorcraft/crates/ui-egui/src/lib.rs", - "egui-0.36.2/src/context.rs", - "winit-0.30.12/src/x.rs", - ] { - assert!(!in_graphics_stack(file), "{file}"); - } - } - - #[test] - fn only_a_graphics_failure_while_starting_up_restarts_without_the_adapter() { - let amd = Some("Vulkan:1002:164e"); - assert_eq!(restart_without(true, 0, amd, &[]), amd); - assert_eq!(restart_without(true, STARTUP_FRAMES - 1, amd, &[]), amd); - // After start-up the adapter has shown frames; a lost window is something else. - assert_eq!(restart_without(true, STARTUP_FRAMES, amd, &[]), None); - // A bug outside the graphics, or no adapter picked: nothing another adapter would change. - assert_eq!(restart_without(false, 0, amd, &[]), None); - assert_eq!(restart_without(true, 0, None, &[]), None); - // Never the same adapter twice, so restarts end. - assert_eq!(restart_without(true, 0, amd, &["Vulkan:1002:164e".into()]), None); - } - - #[test] - fn a_normal_exit_or_another_failure_does_not_restart() { - let startup = Startup::default(); - assert_eq!(finish(Ok(Ok(())), &startup), Ok(())); - // No adapter was picked (none can show the window): the error is returned, nothing restarts. - let none = - eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no graphics adapter can show the window".into())); - assert_eq!( - finish(Ok(Err(none)), &startup), - Err(format!("WGPU error: Adapter selection failed: no graphics adapter can show the window ({HELP})")) - ); - let _ = startup.adapter.set("Vulkan:1002:164e".into()); - GRAPHICS_PANIC.store(false, Ordering::Relaxed); - assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into())); - } - - /// A log folder of its own for each test. - fn start_dir(tag: &str) -> std::path::PathBuf { - let d = std::env::temp_dir().join(format!("vectorcraft-gpu-start-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - d - } - - /// What a start in `dir` leaves out; it then ends without crashing. - fn next_start(dir: &std::path::Path, explicit: bool) -> LeftOut { - let s = Startup::default(); - let left_out = s.track(dir, None, explicit); - s.ended(); - left_out - } - - /// The machine of #2243: one Intel UHD Graphics 605, listed through DX12 and OpenGL, and - /// Windows' software adapter. - fn issue_2243() -> Vec { - vec![ - pci_gpu("Intel(R) UHD Graphics 605", Backend::Dx12, DeviceType::IntegratedGpu, (0x8086, 0x3184)), - pci_gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu, (0x1414, 0x008c)), - pci_gpu("Intel(R) UHD Graphics 605", Backend::Gl, DeviceType::Other, (0x8086, 0)), - ] - } - - /// #2243: the driver ends the process after the adapter was picked, before the first frame. - /// The next start leaves that adapter out and draws through OpenGL, and so do the starts after - /// it, without a status-bar note. - #[test] - fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() { - let dir = start_dir("crash"); - let c = issue_2243(); - let first = Startup::default(); - assert_eq!(first.track(&dir, None, false), LeftOut::default()); - first.picked(&c[0].key, &c[0].name, true); - // The process ends here: its file is closed and unlocked, and the start is still recorded. - drop(first); - - let second = Startup::default(); - let left_out = second.track(&dir, Some("automatic"), false); - assert_eq!(left_out.adapters, ["Dx12:8086:3184"]); - assert_eq!(left_out.crash, Some(Crash::Adapter { key: "Dx12:8086:3184".into(), name: "Intel(R) UHD Graphics 605".into() })); - assert!(!left_out.opengl_only); - assert_eq!(left_out.backends(Backends::DX12 | Backends::GL), Backends::DX12 | Backends::GL); - let order = adapter_order(&c, AUTOMATIC, &[], None, None, &left_out.adapters); - assert_eq!(order, [2, 1], "OpenGL on the same GPU before the software adapter"); - second.picked(&c[2].key, &c[2].name, true); - second.presented(); - - let third = Startup::default(); - let left_out = third.track(&dir, None, false); - assert_eq!(left_out.adapters, ["Dx12:8086:3184"], "kept"); - assert_eq!(left_out.crash, None, "the note is shown once"); - third.ended(); - let _ = std::fs::remove_dir_all(&dir); - } - - /// A start whose first frame reached the screen, or that ended without crashing (a normal exit, - /// an error, a restart on another adapter), leaves nothing out of the next. - #[test] - fn a_start_that_showed_its_first_frame_or_ended_is_cleared() { - let dir = start_dir("shown"); - let c = issue_2243(); - for end in [Startup::presented as fn(&Startup), Startup::ended] { - let first = Startup::default(); - first.track(&dir, None, false); - first.picked(&c[0].key, &c[0].name, true); - end(&first); - drop(first); - assert_eq!(next_start(&dir, false), LeftOut::default()); - } - // So does a start that ended before it picked an adapter. - let first = Startup::default(); - first.track(&dir, None, false); - assert!(finish(Ok(Ok(())), &first).is_ok()); - drop(first); - assert_eq!(next_start(&dir, false), LeftOut::default()); - let _ = std::fs::remove_dir_all(&dir); - } - - /// The process ended while the adapters were being listed (wgpu's DX12 backend creates a - /// device on each GPU to list it): the next starts list OpenGL's adapters alone, except on - /// macOS, where wgpu has none. - #[test] - fn a_crash_while_listing_lists_opengl_alone() { - let dir = start_dir("listing"); - let first = Startup::default(); - first.track(&dir, None, false); - drop(first); - let second = Startup::default(); - let left_out = second.track(&dir, None, false); - assert!(left_out.adapters.is_empty()); - if cfg!(target_os = "macos") { - assert_eq!(left_out, LeftOut::default()); - } else { - assert_eq!(left_out.crash, Some(Crash::Listing)); - assert_eq!(left_out.backends(Backends::DX12 | Backends::GL), Backends::GL); - assert_eq!(left_out.backends(Backends::PRIMARY | Backends::GL), Backends::GL); - assert_eq!(left_out.backends(Backends::METAL), Backends::METAL, "no OpenGL to fall back to"); - } - // Listing OpenGL alone found nothing that can show the window: the next start lists every - // backend again. - second.none_left(); - second.ended(); - assert_eq!(next_start(&dir, false), LeftOut::default()); - let _ = std::fs::remove_dir_all(&dir); - } - - /// `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` choose for a start whatever crashed before; when that - /// start shows its first frame on the adapter that crashed, the adapter counts again. - #[test] - fn wgpu_backend_or_adapter_name_ignores_the_crashes() { - let dir = start_dir("explicit"); - let c = issue_2243(); - let first = Startup::default(); - first.track(&dir, None, false); - first.picked(&c[0].key, &c[0].name, true); - drop(first); - assert_eq!(next_start(&dir, true), LeftOut::default()); - assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"], "still left out without them"); - - let explicit = Startup::default(); - explicit.track(&dir, None, true); - explicit.picked(&c[0].key, &c[0].name, true); - explicit.presented(); - assert_eq!(next_start(&dir, false), LeftOut::default(), "a new driver shows the window"); - let _ = std::fs::remove_dir_all(&dir); - } - - /// A damaged record, a file that can't be opened and one another starting copy of the app holds - /// are ignored: the start goes on with nothing left out. - #[test] - fn a_damaged_or_unreadable_start_file_is_ignored() { - let dir = start_dir("damaged"); - std::fs::create_dir_all(&dir).unwrap(); - let damaged: [&[u8]; 9] = [ - b"", - b"{", - b"[]", - b"null", - b"{\"version\":1}", - b"{\"starting\":{}}", - b"\xef\xbb\xbf\0", - b"\xff\xfe{", - &[b' '; START_FILE_LIMIT as usize + 1], - ]; - for text in damaged { - std::fs::write(dir.join(START_FILE), text).unwrap(); - assert_eq!(next_start(&dir, false), LeftOut::default(), "{:?}", String::from_utf8_lossy(&text[..text.len().min(20)])); - } - - // Another copy of the app is starting: this start neither reads nor writes the file. - let c = issue_2243(); - let starting = Startup::default(); - starting.track(&dir, None, false); - starting.picked(&c[0].key, &c[0].name, true); - assert_eq!(next_start(&dir, false), LeftOut::default()); - drop(starting); - assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"]); - - // A folder in the file's place. - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(dir.join(START_FILE)).unwrap(); - assert_eq!(next_start(&dir, false), LeftOut::default()); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn crashes_are_forgotten_in_another_version_or_under_another_preference() { - let starting = |key: &str| Starting { adapter: Some(Recorded { key: key.into(), name: "GPU".into() }), native: true }; - let (mut record, crash) = StartRecord::begin(None, "0.9.0", "automatic"); - assert_eq!(crash, None); - record.starting = Some(starting("Dx12:8086:3184")); - let (record, crash) = StartRecord::begin(Some(record), "0.9.0", "automatic"); - assert_eq!(crash, Some(Crash::Adapter { key: "Dx12:8086:3184".into(), name: "GPU".into() })); - assert_eq!(record.left_out(None, false).adapters, ["Dx12:8086:3184"]); - // Written and read back. - assert_eq!(StartRecord::parse(&record.to_json()), Some(record.clone())); - assert!(StartRecord::begin(Some(record.clone()), "0.9.1", "automatic").0.crashed.is_empty()); - assert!(StartRecord::begin(Some(record.clone()), "0.9.0", "highPerformance").0.crashed.is_empty()); - assert_eq!(preference_name(None), "automatic"); - assert_eq!(preference_name(Some("powerSaving")), "automatic"); - assert_eq!(preference_name(Some("lowPower")), "lowPower"); - // An adapter is listed once, and the list is bounded. - let mut record = record; - for n in 0..CRASHED_LIMIT + 4 { - for _ in 0..2 { - record.starting = Some(starting(&format!("Dx12:10de:{n:04x}"))); - record = StartRecord::begin(Some(record), "0.9.0", "automatic").0; - } - } - assert_eq!(record.crashed.len(), CRASHED_LIMIT); - assert_eq!(record.crashed.last().map(|c| c.key.as_str()), Some("Dx12:10de:0013")); - } -} +mod tests; diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs new file mode 100644 index 0000000000..906e35fb61 --- /dev/null +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -0,0 +1,744 @@ +use super::*; + +fn gpu(name: &str, backend: Backend, device_type: DeviceType) -> Candidate { + Candidate { key: format!("{backend:?}:{name}"), name: name.into(), backend, device_type, pci: (0, 0), presents: true } +} + +/// #1459: a 9048 px wide window (two display scales' ratio past 8192) fits an adapter that +/// takes 16384 px textures; an adapter with less than eframe asks for changes nothing. +#[test] +fn the_surface_may_be_as_large_as_the_adapter_allows() { + assert_eq!(surface_limit(8192, 16384), 16384); + assert_eq!(surface_limit(8192, 4096), 8192); +} + +fn names(c: &[Candidate], order: &[usize]) -> Vec { + order.iter().map(|&i| c[i].name.clone()).collect() +} + +const NVIDIA_3090: (u32, u32) = (0x10de, 0x2204); +const AMD_IGPU: (u32, u32) = (0x1002, 0x164e); +const INTEL_IGPU: (u32, u32) = (0x8086, 0xa780); +const WARP: (u32, u32) = (0x1414, 0x008c); + +fn pci_gpu(name: &str, backend: Backend, device_type: DeviceType, pci: (u32, u32)) -> Candidate { + Candidate { key: key(backend, pci.0, pci.1, name), name: name.into(), backend, device_type, pci, presents: true } +} + +fn monitor(pci: (u32, u32)) -> DisplayGpu { + DisplayGpu { pci, primary: false } +} + +fn primary(pci: (u32, u32)) -> DisplayGpu { + DisplayGpu { pci, primary: true } +} + +/// The desktop of pdfcraft#378 as wgpu lists it on Windows: a Ryzen's integrated GPU without a +/// monitor and an RTX 3090 driving both monitors, each under Vulkan and DX12, then WARP and +/// OpenGL (which reports no device id). +fn ryzen_desktop() -> Vec { + vec![ + pci_gpu("NVIDIA GeForce RTX 3090", Backend::Vulkan, DeviceType::DiscreteGpu, NVIDIA_3090), + pci_gpu("AMD Radeon(TM) Graphics", Backend::Vulkan, DeviceType::IntegratedGpu, AMD_IGPU), + pci_gpu("NVIDIA GeForce RTX 3090", Backend::Dx12, DeviceType::DiscreteGpu, NVIDIA_3090), + pci_gpu("AMD Radeon(TM) Graphics", Backend::Dx12, DeviceType::IntegratedGpu, AMD_IGPU), + pci_gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu, WARP), + pci_gpu("NVIDIA GeForce RTX 3090/PCIe/SSE2", Backend::Gl, DeviceType::Other, (NVIDIA_3090.0, 0)), + ] +} + +/// pdfcraft#378: power saving picked the integrated GPU, whose driver reset when Windows had to +/// present its frames on the monitors of the NVIDIA card. The GPU that drives the displays now +/// comes first, through DX12 (#545); the integrated GPU stays the fallback a restart reaches. +#[test] +fn a_desktop_draws_on_the_gpu_that_drives_its_monitors() { + let c = ryzen_desktop(); + for displays in [vec![primary(NVIDIA_3090)], vec![monitor(NVIDIA_3090)]] { + assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), [2, 0, 3, 1, 5, 4], "{displays:?}"); + assert_eq!(adapter_order(&c, PowerPreference::None, &displays, None, None, &[]), [2, 0, 3, 1, 5, 4], "{displays:?}"); + } + // Without the display information the order is power saving's, as before. + assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]), [3, 1, 2, 0, 5, 4]); + // After the NVIDIA adapters failed, the integrated GPU is next. + let skip = vec![c[2].key.clone(), c[0].key.clone()]; + assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[primary(NVIDIA_3090)], None, None, &skip), [3, 1, 5, 4]); +} + +/// A hybrid laptop: the panel (primary) on the integrated GPU, an external monitor on the +/// discrete one. Power saving and the display agree, in either enumeration order. +#[test] +fn a_hybrid_laptop_draws_on_the_integrated_gpu_that_drives_its_panel() { + let c = ryzen_desktop(); + for displays in [vec![primary(AMD_IGPU), monitor(NVIDIA_3090)], vec![monitor(NVIDIA_3090), primary(AMD_IGPU)], vec![primary(AMD_IGPU)]] { + assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), [3, 1, 2, 0, 5, 4], "{displays:?}"); + } + // Linux names no primary unless there is a built-in panel: a monitor on each GPU keeps the + // system's order among them (Mesa puts the compositor's GPU first), and a GPU without one + // comes after both. + let linux = vec![ + pci_gpu("AMD Radeon Graphics (RADV RAPHAEL_MENDOCINO)", Backend::Vulkan, DeviceType::IntegratedGpu, AMD_IGPU), + pci_gpu("NVIDIA GeForce RTX 3090", Backend::Vulkan, DeviceType::DiscreteGpu, NVIDIA_3090), + pci_gpu("Intel(R) Arc(TM) A380", Backend::Vulkan, DeviceType::DiscreteGpu, INTEL_IGPU), + pci_gpu("llvmpipe (LLVM 20.1.8, 256 bits)", Backend::Vulkan, DeviceType::Cpu, (0x10005, 0)), + ]; + let both = [monitor(AMD_IGPU), monitor(NVIDIA_3090)]; + assert_eq!(adapter_order(&linux, PowerPreference::None, &both, None, None, &[]), [0, 1, 2, 3]); + assert_eq!(adapter_order(&linux, PowerPreference::None, &[monitor(INTEL_IGPU)], None, None, &[]), [2, 0, 1, 3]); + assert_eq!(adapter_order(&linux, PowerPreference::None, &[monitor(NVIDIA_3090), primary(AMD_IGPU)], None, None, &[]), [0, 1, 2, 3]); +} + +/// A hybrid laptop whose Wayland compositor runs on the discrete GPU (Hyprland with +/// `AQ_DRM_DEVICES` naming it first), as Vulkan lists it there: the integrated GPU drives the +/// built-in panel, yet the compositor shows nothing it draws, and reports no error. The GPU the +/// compositor draws with comes first; without it, the panel's, as before. +#[test] +fn the_gpu_the_compositor_draws_with_comes_before_the_panels() { + const RTX_3050: (u32, u32) = (0x10de, 0x25ac); + const INTEL_RPL: (u32, u32) = (0x8086, 0xa7a8); + let mut c = vec![ + pci_gpu("NVIDIA GeForce RTX 3050 6GB Laptop GPU", Backend::Vulkan, DeviceType::DiscreteGpu, RTX_3050), + pci_gpu("Intel(R) Graphics (RPL-P)", Backend::Vulkan, DeviceType::IntegratedGpu, INTEL_RPL), + pci_gpu("NVIDIA GeForce RTX 3050 6GB Laptop GPU/PCIe/SSE2", Backend::Gl, DeviceType::Other, (RTX_3050.0, 0)), + ]; + c[2].presents = false; + let panel = [primary(INTEL_RPL)]; + assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some(RTX_3050), None, &[]), [0, 1]); + assert_eq!(adapter_order(&c, PowerPreference::None, &panel, None, None, &[]), [1, 0]); + // The usual hybrid laptop, with the compositor on the integrated GPU: the panel's GPU. + assert_eq!(adapter_order(&c, PowerPreference::None, &[primary(INTEL_RPL), monitor(RTX_3050)], Some(INTEL_RPL), None, &[]), [1, 0]); + // `WGPU_ADAPTER_NAME` still comes first, and a restart after a failure still moves on. + assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some(RTX_3050), Some("intel"), &[]), [1, 0]); + assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some(RTX_3050), None, &[c[0].key.clone()]), [1]); + // A compositor GPU no adapter matches (a virtual one) leaves the displays in charge. + assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some((0x1af4, 0x1050)), None, &[]), [1, 0]); +} + +/// A Windows desktop with a monitor on each GPU: the window opens on the primary display, so +/// its GPU draws, whichever kind it is. +#[test] +fn the_primary_display_decides_between_gpus_that_both_drive_a_monitor() { + let c = ryzen_desktop(); + assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[monitor(AMD_IGPU), primary(NVIDIA_3090)], None, None, &[]), [2, 0, 3, 1, 5, 4]); + assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[primary(AMD_IGPU), monitor(NVIDIA_3090)], None, None, &[]), [3, 1, 2, 0, 5, 4]); + // The displays only matter among adapters that can show the window; a GPU driving no + // display still loses to one that does. + assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[monitor(AMD_IGPU), monitor(INTEL_IGPU)], None, None, &[]), [3, 1, 2, 0, 5, 4]); +} + +/// Display GPUs none of the adapters match (another driver's ids, OpenGL's missing device id, +/// Metal's zeros) change nothing: power saving's order, the old behaviour. +#[test] +fn displays_no_adapter_matches_leave_the_power_preference_in_charge() { + let c = ryzen_desktop(); + let low = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]); + for displays in [vec![monitor(INTEL_IGPU)], vec![primary((0x8086, 0x1234)), monitor((0x8086, 0x5678))], vec![primary((0, 0))]] { + assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), low, "{displays:?}"); + } + assert_eq!( + names(&c, &adapter_order(&c, PowerPreference::HighPerformance, &[monitor(INTEL_IGPU)], None, None, &[]))[0], + "NVIDIA GeForce RTX 3090" + ); + // The #502 machine's adapters report no ids in these tests: the primary display never matches. + let c = issue_502(); + assert_eq!( + adapter_order(&c, PowerPreference::None, &[primary(NVIDIA_3090)], None, None, &[]), + adapter_order(&c, PowerPreference::None, &[], None, None, &[]) + ); + assert!(adapter_order(&[], PowerPreference::LowPower, &[primary(NVIDIA_3090)], None, None, &[]).is_empty()); +} + +/// `WGPU_ADAPTER_NAME` and "can't present" still come before the displays. +#[test] +fn a_named_adapter_comes_before_the_one_driving_the_display() { + let mut c = ryzen_desktop(); + let displays = [primary(NVIDIA_3090)]; + assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, Some("radeon"), &[]), [3, 1, 2, 0, 5, 4]); + c[2].presents = false; + c[0].presents = false; + assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), [3, 1, 5, 4]); +} + +/// A user's own choice (Preferences or `WGPU_POWER_PREF`) is kept as it is; only Automatic +/// looks at the displays. +#[test] +fn only_automatic_considers_which_gpu_drives_the_display() { + assert!(automatic(None, None)); + assert!(automatic(Some("automatic"), None)); + assert!(automatic(Some("powerSaving"), None)); + assert!(!automatic(Some("lowPower"), None)); + assert!(!automatic(Some("highPerformance"), None)); + assert!(!automatic(None, Some(PowerPreference::None))); + assert!(!automatic(Some("automatic"), Some(PowerPreference::LowPower))); + assert!(preferred_displays(Some("lowPower"), None).is_empty()); + assert!(preferred_displays(None, Some(PowerPreference::HighPerformance)).is_empty()); + // Automatic reports whatever this machine has (nothing on macOS, in CI, or under Remote Desktop). + assert_eq!(preferred_displays(None, None), display_gpus()); + assert_eq!(preferred_compositor(Some("lowPower"), None), None); + assert_eq!(preferred_compositor(None, Some(PowerPreference::HighPerformance)), None); + assert_eq!(preferred_compositor(None, None), crate::compositor_gpu::compositor_gpu()); +} + +#[test] +fn pci_ids_come_from_windows_device_ids() { + assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_2204&SUBSYS_40421458&REV_A1"), Some(NVIDIA_3090)); + assert_eq!(pci_ids("PCI\\VEN_1002&DEV_164E&SUBSYS_88771043&REV_C1"), Some(AMD_IGPU)); + assert_eq!(pci_ids("pci\\ven_1002&dev_164e"), Some(AMD_IGPU)); + // Remote Desktop and other non-PCI display devices, and malformed ids. + assert_eq!(pci_ids("ROOT\\BasicDisplay\\0000"), None); + assert_eq!(pci_ids("PCI\\VEN_10DE&SUBSYS_40421458"), None); + assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_ZZZZ"), None); + assert_eq!(pci_ids("VEN_&DEV_"), None); + assert_eq!(pci_ids(""), None); +} + +/// Whatever this machine has: every GPU listed is a PCI device, at most one drives the primary +/// display, and none is listed twice. (A headless CI runner may list none.) +#[cfg(windows)] +#[test] +fn windows_lists_each_gpu_with_a_monitor_once() { + let gpus = windows_display_gpus(); + assert!(gpus.iter().filter(|g| g.primary).count() <= 1, "{gpus:?}"); + for (i, g) in gpus.iter().enumerate() { + assert_ne!(g.pci.0, 0, "{gpus:?}"); + assert!(!gpus[..i].iter().any(|h| h.pci == g.pci), "{gpus:?}"); + } +} + +#[test] +fn internal_panels_are_edp_lvds_and_dsi_connectors() { + for name in ["eDP-1", "LVDS-1", "DSI-1"] { + assert!(is_internal_panel(name), "{name}"); + } + for name in ["DP-3", "HDMI-A-1", "DVI-D-1", "VGA-1", "Writeback-1", ""] { + assert!(!is_internal_panel(name), "{name}"); + } +} + +/// A sysfs like a hybrid laptop's with an external monitor: the panel and a disconnected port +/// on the integrated GPU (card0), the monitor on the discrete one (card1), and a card without +/// PCI ids. Each GPU is listed once, the one with the panel as primary. +#[test] +fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()> { + let dir = std::env::temp_dir().join(format!("vectorcraft-drm-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let card = |name: &str, (vendor, device): (u32, u32)| -> std::io::Result<()> { + std::fs::create_dir_all(dir.join(name).join("device"))?; + std::fs::write(dir.join(name).join("device/vendor"), format!("{vendor:#06x}\n"))?; + std::fs::write(dir.join(name).join("device/device"), format!("{device:#06x}\n")) + }; + let connector = |name: &str, status: &str| -> std::io::Result<()> { + std::fs::create_dir_all(dir.join(name))?; + std::fs::write(dir.join(name).join("status"), format!("{status}\n")) + }; + card("card0", AMD_IGPU)?; + card("card1", NVIDIA_3090)?; + std::fs::create_dir_all(dir.join("card2"))?; + connector("card0-eDP-1", "connected")?; + connector("card0-HDMI-A-1", "disconnected")?; + connector("card1-DP-1", "connected")?; + connector("card1-DP-2", "connected")?; + connector("card2-Virtual-1", "connected")?; + std::fs::write(dir.join("renderD128"), "")?; + let mut gpus = linux_display_gpus(&dir); + gpus.sort_by_key(|g| g.pci); + assert_eq!(gpus, [primary(AMD_IGPU), monitor(NVIDIA_3090)]); + assert!(linux_display_gpus(&dir.join("no such dir")).is_empty()); + std::fs::remove_dir_all(&dir) +} + +#[test] +fn display_gpus_are_logged_as_pci_ids() { + assert_eq!(primary(NVIDIA_3090).to_string(), "10de:2204 (primary)"); + assert_eq!(monitor(AMD_IGPU).to_string(), "1002:164e"); + let mut gpus = vec![]; + add_display_gpu(&mut gpus, NVIDIA_3090, false); + add_display_gpu(&mut gpus, NVIDIA_3090, true); + add_display_gpu(&mut gpus, AMD_IGPU, false); + assert_eq!(gpus, [primary(NVIDIA_3090), monitor(AMD_IGPU)]); +} + +/// The machine of #502 as Vulkan lists it with Mesa's device-select layer: the GPU KDE's +/// compositor runs on (NVIDIA) first, then the Ryzen's integrated GPU, Mesa's software +/// renderer, and OpenGL. +fn issue_502() -> Vec { + vec![ + gpu("NVIDIA GeForce RTX 5070", Backend::Vulkan, DeviceType::DiscreteGpu), + gpu("AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)", Backend::Vulkan, DeviceType::IntegratedGpu), + gpu("llvmpipe (LLVM 20.1.8, 256 bits)", Backend::Vulkan, DeviceType::Cpu), + gpu("NVIDIA GeForce RTX 5070/PCIe/SSE2", Backend::Gl, DeviceType::Other), + ] +} + +#[test] +fn automatic_keeps_the_systems_order_on_linux_and_saves_power_elsewhere() { + let c = issue_502(); + let order = adapter_order(&c, power_preference(None, None), &[], None, None, &[]); + let first = &c[order[0]].name; + if cfg!(any(windows, target_os = "macos")) { + assert_eq!(first, "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)"); + } else { + // #502: the integrated GPU couldn't show frames to a compositor on the NVIDIA GPU. + assert_eq!(first, "NVIDIA GeForce RTX 5070"); + } +} + +#[test] +fn each_preference_orders_the_adapters_then_falls_back_to_opengl_and_software() { + let c = issue_502(); + let order = |power| names(&c, &adapter_order(&c, power, &[], None, None, &[])); + assert_eq!( + order(PowerPreference::None), + [ + "NVIDIA GeForce RTX 5070", + "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)", + "NVIDIA GeForce RTX 5070/PCIe/SSE2", + "llvmpipe (LLVM 20.1.8, 256 bits)" + ] + ); + assert_eq!( + order(PowerPreference::LowPower), + [ + "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)", + "NVIDIA GeForce RTX 5070", + "NVIDIA GeForce RTX 5070/PCIe/SSE2", + "llvmpipe (LLVM 20.1.8, 256 bits)" + ] + ); + assert_eq!( + order(PowerPreference::HighPerformance), + [ + "NVIDIA GeForce RTX 5070", + "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)", + "NVIDIA GeForce RTX 5070/PCIe/SSE2", + "llvmpipe (LLVM 20.1.8, 256 bits)" + ] + ); +} + +/// A restart leaves out the adapter the window failed on, so Power Saving on the machine of +/// #502 ends up on the NVIDIA GPU, and once every adapter failed there is nothing to try. +/// A dual-GPU Mac reports both GPUs under Metal with no PCI ids (#651): their keys still +/// differ, so when the integrated GPU fails, the restart renders on the discrete one. +#[test] +fn gpus_without_pci_ids_are_told_apart_by_name() { + let mac = |name: &str, device_type| Candidate { + key: key(Backend::Metal, 0, 0, name), + name: name.into(), + backend: Backend::Metal, + device_type, + pci: (0, 0), + presents: true, + }; + let c = vec![mac("NVIDIA GeForce GT 750M", DeviceType::DiscreteGpu), mac("Intel Iris Pro Graphics", DeviceType::IntegratedGpu)]; + assert_eq!((c[0].key.as_str(), c[1].key.as_str()), ("Metal:NVIDIA GeForce GT 750M", "Metal:Intel Iris Pro Graphics")); + let first = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]); + assert_eq!(names(&c, &first)[0], "Intel Iris Pro Graphics"); + let skip = parse_skip(&c[first[0]].key); + assert_eq!(names(&c, &adapter_order(&c, PowerPreference::LowPower, &[], None, None, &skip)), ["NVIDIA GeForce GT 750M"]); + // A comma in a name can't split the list. + assert_eq!(parse_skip(&key(Backend::Gl, 0, 0, "Mesa, llvmpipe")), ["Gl:Mesa llvmpipe"]); +} + +#[test] +fn a_first_frame_that_never_reaches_the_screen_hangs_its_adapter() { + let s = Duration::from_secs; + // The second frame began: the first was presented. + assert_eq!(first_frame(2, s(60), false), FirstFrame::Shown); + // Still drawing (or presenting) the first frame: waited for, then given up on (#964). + for frames in [0, 1] { + assert_eq!(first_frame(frames, s(3), false), FirstFrame::Wait); + assert_eq!(first_frame(frames, FIRST_FRAME_TIMEOUT, false), FirstFrame::Hung); + } + // A window minimized at the start may not draw again until restored. + assert_eq!(first_frame(1, s(60), true), FirstFrame::Shown); + // A hung adapter is left out once, like one that failed. + let skip = vec!["Dx12:10de:28a0".to_string()]; + assert_eq!(restart_without(true, 1, Some("Dx12:10de:28a0"), &skip), None); + assert_eq!(restart_without(true, 1, Some("Dx12:8086:a7a8"), &skip), Some("Dx12:8086:a7a8")); +} + +#[test] +fn a_restart_tries_the_next_adapter() { + let c = issue_502(); + let mut skip = vec![]; + let mut tried = vec![]; + while let Some(&i) = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &skip).first() { + tried.push(c[i].name.clone()); + skip.push(c[i].key.clone()); + } + assert_eq!( + tried, + [ + "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)", + "NVIDIA GeForce RTX 5070", + "NVIDIA GeForce RTX 5070/PCIe/SSE2", + "llvmpipe (LLVM 20.1.8, 256 bits)" + ] + ); +} + +#[test] +fn adapters_that_cannot_present_to_the_window_are_never_tried() { + let mut c = issue_502(); + c[0].presents = false; + c[3].presents = false; + for power in [PowerPreference::None, PowerPreference::LowPower, PowerPreference::HighPerformance] { + let order = adapter_order(&c, power, &[], None, None, &[]); + assert!(!order.contains(&0) && !order.contains(&3), "{power:?}: {order:?}"); + assert_eq!(order.len(), 2); + } + for p in &mut c { + p.presents = false; + } + assert!(adapter_order(&c, PowerPreference::None, &[], None, None, &[]).is_empty()); + assert!(adapter_order(&[], PowerPreference::HighPerformance, &[], None, None, &[]).is_empty()); +} + +#[test] +fn wgpu_adapter_name_picks_an_adapter_first_and_the_rest_stay_as_fallbacks() { + let c = issue_502(); + let order = adapter_order(&c, PowerPreference::HighPerformance, &[], None, Some("radv"), &[]); + assert_eq!(c[order[0]].name, "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)"); + assert_eq!(order.len(), 4); + // Any case; every match comes before the rest, natively first. + let order = adapter_order(&c, PowerPreference::LowPower, &[], None, Some("GeForce"), &[]); + assert_eq!(names(&c, &order[..2]), ["NVIDIA GeForce RTX 5070", "NVIDIA GeForce RTX 5070/PCIe/SSE2"]); + // An empty name or one nothing matches changes nothing. + for named in ["", "no such gpu"] { + assert_eq!( + adapter_order(&c, PowerPreference::LowPower, &[], None, Some(named), &[]), + adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]) + ); + } + // A named adapter that failed is left out like any other. + let skip = vec![c[1].key.clone()]; + assert_eq!(adapter_order(&c, PowerPreference::None, &[], None, Some("radv"), &skip)[0], 0); +} + +/// A Windows machine lists every GPU twice (Vulkan and DX12): power saving still takes the +/// integrated GPU first, as wgpu's own choice did (#306), each GPU through DX12 first (#545). +#[test] +fn hybrid_laptop_on_windows_renders_on_the_integrated_gpu_with_power_saving() { + let c = vec![ + gpu("Intel(R) Arc(TM) A370M", Backend::Vulkan, DeviceType::DiscreteGpu), + gpu("Intel(R) Iris(R) Xe Graphics", Backend::Vulkan, DeviceType::IntegratedGpu), + gpu("Intel(R) Arc(TM) A370M", Backend::Dx12, DeviceType::DiscreteGpu), + gpu("Intel(R) Iris(R) Xe Graphics", Backend::Dx12, DeviceType::IntegratedGpu), + gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu), + ]; + let order = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]); + assert_eq!(order, [3, 1, 2, 0, 4]); + assert_eq!(adapter_order(&c, PowerPreference::HighPerformance, &[], None, None, &[]), [2, 0, 3, 1, 4]); +} + +/// The machine of #545: one Intel GPU, whose Vulkan driver made the window flicker black. +/// DX12 comes first whatever the preference; Vulkan stays a fallback, and `WGPU_ADAPTER_NAME` +/// or a restart leaving DX12 out still reach it. +#[test] +fn a_windows_gpu_renders_through_dx12_before_vulkan() { + let c = vec![ + gpu("Intel(R) Graphics", Backend::Vulkan, DeviceType::IntegratedGpu), + gpu("Intel(R) Graphics", Backend::Dx12, DeviceType::IntegratedGpu), + gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu), + gpu("Intel(R) Graphics", Backend::Gl, DeviceType::Other), + ]; + for power in [PowerPreference::LowPower, PowerPreference::HighPerformance, PowerPreference::None] { + assert_eq!(adapter_order(&c, power, &[], None, None, &[]), [1, 0, 3, 2], "{power:?}"); + } + assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[c[1].key.clone()]), [0, 3, 2], "DX12 failed: Vulkan next"); +} + +#[test] +fn windows_never_loads_vulkan_drivers_unless_asked() { + let all = Backends::all(); + let start = backends(all, false); + if cfg!(windows) { + assert_eq!(start, Backends::DX12 | Backends::GL, "#806"); + } else { + assert_eq!(start, all); + } + assert_eq!(backends(Backends::VULKAN, true), Backends::VULKAN, "WGPU_BACKEND=vulkan still picks it"); +} + +#[test] +fn power_preference_follows_the_environment_then_the_preference() { + assert_eq!(power_preference(None, None), AUTOMATIC); + assert_eq!(power_preference(Some("automatic"), None), AUTOMATIC); + assert_eq!(power_preference(Some("lowPower"), None), PowerPreference::LowPower); + assert_eq!(power_preference(Some("highPerformance"), None), PowerPreference::HighPerformance); + // 0.5.0's default, and values this version doesn't know (a newer or damaged file). + for old in ["powerSaving", "turbo", ""] { + assert_eq!(power_preference(Some(old), None), AUTOMATIC, "{old}"); + } + // WGPU_POWER_PREF wins over the preference, either way. + assert_eq!(power_preference(Some("lowPower"), Some(PowerPreference::HighPerformance)), PowerPreference::HighPerformance); + assert_eq!(power_preference(Some("highPerformance"), Some(PowerPreference::LowPower)), PowerPreference::LowPower); + assert_eq!(power_preference(Some("lowPower"), Some(PowerPreference::None)), PowerPreference::None); + assert_eq!(AUTOMATIC, if cfg!(any(windows, target_os = "macos")) { PowerPreference::LowPower } else { PowerPreference::None }); +} + +/// The preference the engine saves is the one the app reads back before the window opens. +#[test] +fn the_saved_engine_preference_is_found() { + let mut prefs = vectorcraft_engine::Prefs::default(); + let saved = prefs.to_json(); + assert_eq!(saved.get("gpuPreference").and_then(serde_json::Value::as_str), Some("automatic")); + for (value, power) in [("lowPower", PowerPreference::LowPower), ("highPerformance", PowerPreference::HighPerformance)] { + prefs.gpu_preference = value.into(); + let saved = prefs.to_json(); + assert_eq!(power_preference(saved.get("gpuPreference").and_then(serde_json::Value::as_str), None), power); + } + // Every choice Preferences offer means something here. + for (value, _) in vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES { + assert!(["automatic", "lowPower", "highPerformance"].contains(value), "{value}"); + } +} + +#[test] +fn skipped_adapters_parse_from_a_comma_separated_list() { + assert_eq!(parse_skip("Vulkan:1002:164e, Gl:10de:2f04,,"), ["Vulkan:1002:164e", "Gl:10de:2f04"]); + assert!(parse_skip("").is_empty()); + assert_eq!(key(Backend::Vulkan, 0x1002, 0x164e, "AMD Radeon"), "Vulkan:1002:164e"); + assert_eq!(key(Backend::Gl, 0x10de, 0x2f04, "NVIDIA"), "Gl:10de:2f04"); +} + +#[test] +fn panics_in_wgpu_egui_wgpu_and_naga_are_graphics_failures() { + for file in [ + "/home/u/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/egui-wgpu-0.36.2/src/winit.rs", + r"C:\Users\u\.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\wgpu-core-30.0.1\src\device\mod.rs", + "/rustc/deps/wgpu-hal-30.0.1/src/vulkan/adapter.rs", + "naga-30.0.0/src/back/spv/writer.rs", + ] { + assert!(in_graphics_stack(file), "{file}"); + } + for file in + ["apps/vectorcraft/src/main.rs", "/home/wgpu/vectorcraft/crates/ui-egui/src/lib.rs", "egui-0.36.2/src/context.rs", "winit-0.30.12/src/x.rs"] + { + assert!(!in_graphics_stack(file), "{file}"); + } +} + +#[test] +fn only_a_graphics_failure_while_starting_up_restarts_without_the_adapter() { + let amd = Some("Vulkan:1002:164e"); + assert_eq!(restart_without(true, 0, amd, &[]), amd); + assert_eq!(restart_without(true, STARTUP_FRAMES - 1, amd, &[]), amd); + // After start-up the adapter has shown frames; a lost window is something else. + assert_eq!(restart_without(true, STARTUP_FRAMES, amd, &[]), None); + // A bug outside the graphics, or no adapter picked: nothing another adapter would change. + assert_eq!(restart_without(false, 0, amd, &[]), None); + assert_eq!(restart_without(true, 0, None, &[]), None); + // Never the same adapter twice, so restarts end. + assert_eq!(restart_without(true, 0, amd, &["Vulkan:1002:164e".into()]), None); +} + +#[test] +fn a_normal_exit_or_another_failure_does_not_restart() { + let startup = Startup::default(); + assert_eq!(finish(Ok(Ok(())), &startup), Ok(())); + // No adapter was picked (none can show the window): the error is returned, nothing restarts. + let none = eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no graphics adapter can show the window".into())); + assert_eq!( + finish(Ok(Err(none)), &startup), + Err(format!("WGPU error: Adapter selection failed: no graphics adapter can show the window ({HELP})")) + ); + let _ = startup.adapter.set("Vulkan:1002:164e".into()); + GRAPHICS_PANIC.store(false, Ordering::Relaxed); + assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into())); +} + +/// A log folder of its own for each test. +fn start_dir(tag: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("vectorcraft-gpu-start-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d +} + +/// What a start in `dir` leaves out; it then ends without crashing. +fn next_start(dir: &std::path::Path, explicit: bool) -> LeftOut { + let s = Startup::default(); + let left_out = s.track(dir, None, explicit); + s.ended(); + left_out +} + +/// The machine of #2243: one Intel UHD Graphics 605, listed through DX12 and OpenGL, and +/// Windows' software adapter. +fn issue_2243() -> Vec { + vec![ + pci_gpu("Intel(R) UHD Graphics 605", Backend::Dx12, DeviceType::IntegratedGpu, (0x8086, 0x3184)), + pci_gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu, (0x1414, 0x008c)), + pci_gpu("Intel(R) UHD Graphics 605", Backend::Gl, DeviceType::Other, (0x8086, 0)), + ] +} + +/// #2243: the driver ends the process after the adapter was picked, before the first frame. +/// The next start leaves that adapter out and draws through OpenGL, and so do the starts after +/// it, without a status-bar note. +#[test] +fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() { + let dir = start_dir("crash"); + let c = issue_2243(); + let first = Startup::default(); + assert_eq!(first.track(&dir, None, false), LeftOut::default()); + first.picked(&c[0].key, &c[0].name, true); + // The process ends here: its file is closed and unlocked, and the start is still recorded. + drop(first); + + let second = Startup::default(); + let left_out = second.track(&dir, Some("automatic"), false); + assert_eq!(left_out.adapters, ["Dx12:8086:3184"]); + assert_eq!(left_out.crash, Some(Crash::Adapter { key: "Dx12:8086:3184".into(), name: "Intel(R) UHD Graphics 605".into() })); + assert!(!left_out.opengl_only); + assert_eq!(left_out.backends(Backends::DX12 | Backends::GL), Backends::DX12 | Backends::GL); + let order = adapter_order(&c, AUTOMATIC, &[], None, None, &left_out.adapters); + assert_eq!(order, [2, 1], "OpenGL on the same GPU before the software adapter"); + second.picked(&c[2].key, &c[2].name, true); + second.presented(); + + let third = Startup::default(); + let left_out = third.track(&dir, None, false); + assert_eq!(left_out.adapters, ["Dx12:8086:3184"], "kept"); + assert_eq!(left_out.crash, None, "the note is shown once"); + third.ended(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A start whose first frame reached the screen, or that ended without crashing (a normal exit, +/// an error, a restart on another adapter), leaves nothing out of the next. +#[test] +fn a_start_that_showed_its_first_frame_or_ended_is_cleared() { + let dir = start_dir("shown"); + let c = issue_2243(); + for end in [Startup::presented as fn(&Startup), Startup::ended] { + let first = Startup::default(); + first.track(&dir, None, false); + first.picked(&c[0].key, &c[0].name, true); + end(&first); + drop(first); + assert_eq!(next_start(&dir, false), LeftOut::default()); + } + // So does a start that ended before it picked an adapter. + let first = Startup::default(); + first.track(&dir, None, false); + assert!(finish(Ok(Ok(())), &first).is_ok()); + drop(first); + assert_eq!(next_start(&dir, false), LeftOut::default()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The process ended while the adapters were being listed (wgpu's DX12 backend creates a +/// device on each GPU to list it): the next starts list OpenGL's adapters alone, except on +/// macOS, where wgpu has none. +#[test] +fn a_crash_while_listing_lists_opengl_alone() { + let dir = start_dir("listing"); + let first = Startup::default(); + first.track(&dir, None, false); + drop(first); + let second = Startup::default(); + let left_out = second.track(&dir, None, false); + assert!(left_out.adapters.is_empty()); + if cfg!(target_os = "macos") { + assert_eq!(left_out, LeftOut::default()); + } else { + assert_eq!(left_out.crash, Some(Crash::Listing)); + assert_eq!(left_out.backends(Backends::DX12 | Backends::GL), Backends::GL); + assert_eq!(left_out.backends(Backends::PRIMARY | Backends::GL), Backends::GL); + assert_eq!(left_out.backends(Backends::METAL), Backends::METAL, "no OpenGL to fall back to"); + } + // Listing OpenGL alone found nothing that can show the window: the next start lists every + // backend again. + second.none_left(); + second.ended(); + assert_eq!(next_start(&dir, false), LeftOut::default()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` choose for a start whatever crashed before; when that +/// start shows its first frame on the adapter that crashed, the adapter counts again. +#[test] +fn wgpu_backend_or_adapter_name_ignores_the_crashes() { + let dir = start_dir("explicit"); + let c = issue_2243(); + let first = Startup::default(); + first.track(&dir, None, false); + first.picked(&c[0].key, &c[0].name, true); + drop(first); + assert_eq!(next_start(&dir, true), LeftOut::default()); + assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"], "still left out without them"); + + let explicit = Startup::default(); + explicit.track(&dir, None, true); + explicit.picked(&c[0].key, &c[0].name, true); + explicit.presented(); + assert_eq!(next_start(&dir, false), LeftOut::default(), "a new driver shows the window"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A damaged record, a file that can't be opened and one another starting copy of the app holds +/// are ignored: the start goes on with nothing left out. +#[test] +fn a_damaged_or_unreadable_start_file_is_ignored() { + let dir = start_dir("damaged"); + std::fs::create_dir_all(&dir).unwrap(); + let damaged: [&[u8]; 9] = [ + b"", + b"{", + b"[]", + b"null", + b"{\"version\":1}", + b"{\"starting\":{}}", + b"\xef\xbb\xbf\0", + b"\xff\xfe{", + &[b' '; START_FILE_LIMIT as usize + 1], + ]; + for text in damaged { + std::fs::write(dir.join(START_FILE), text).unwrap(); + assert_eq!(next_start(&dir, false), LeftOut::default(), "{:?}", String::from_utf8_lossy(&text[..text.len().min(20)])); + } + + // Another copy of the app is starting: this start neither reads nor writes the file. + let c = issue_2243(); + let starting = Startup::default(); + starting.track(&dir, None, false); + starting.picked(&c[0].key, &c[0].name, true); + assert_eq!(next_start(&dir, false), LeftOut::default()); + drop(starting); + assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"]); + + // A folder in the file's place. + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join(START_FILE)).unwrap(); + assert_eq!(next_start(&dir, false), LeftOut::default()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn crashes_are_forgotten_in_another_version_or_under_another_preference() { + let starting = |key: &str| Starting { adapter: Some(Recorded { key: key.into(), name: "GPU".into() }), native: true }; + let (mut record, crash) = StartRecord::begin(None, "0.9.0", "automatic"); + assert_eq!(crash, None); + record.starting = Some(starting("Dx12:8086:3184")); + let (record, crash) = StartRecord::begin(Some(record), "0.9.0", "automatic"); + assert_eq!(crash, Some(Crash::Adapter { key: "Dx12:8086:3184".into(), name: "GPU".into() })); + assert_eq!(record.left_out(None, false).adapters, ["Dx12:8086:3184"]); + // Written and read back. + assert_eq!(StartRecord::parse(&record.to_json()), Some(record.clone())); + assert!(StartRecord::begin(Some(record.clone()), "0.9.1", "automatic").0.crashed.is_empty()); + assert!(StartRecord::begin(Some(record.clone()), "0.9.0", "highPerformance").0.crashed.is_empty()); + assert_eq!(preference_name(None), "automatic"); + assert_eq!(preference_name(Some("powerSaving")), "automatic"); + assert_eq!(preference_name(Some("lowPower")), "lowPower"); + // An adapter is listed once, and the list is bounded. + let mut record = record; + for n in 0..CRASHED_LIMIT + 4 { + for _ in 0..2 { + record.starting = Some(starting(&format!("Dx12:10de:{n:04x}"))); + record = StartRecord::begin(Some(record), "0.9.0", "automatic").0; + } + } + assert_eq!(record.crashed.len(), CRASHED_LIMIT); + assert_eq!(record.crashed.last().map(|c| c.key.as_str()), Some("Dx12:10de:0013")); +} diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs new file mode 100644 index 0000000000..aa7d7f42c2 --- /dev/null +++ b/apps/vectorcraft/src/host_services.rs @@ -0,0 +1,326 @@ +use super::*; + +/// The window file dialogs belong to. +pub(crate) type Parent = Option>; + +/// What rfd's blocking and asynchronous file dialogs are both set up with. +trait DialogSettings: Sized { + fn parent(self, window: &winit::window::Window) -> Self; + fn title(self, title: &str) -> Self; + fn filter(self, name: &str, exts: &[impl ToString]) -> Self; + fn folder(self, folder: &str) -> Self; + fn file_name(self, name: &str) -> Self; +} + +macro_rules! dialog_settings { + ($($dialog:ty),*) => {$( + impl DialogSettings for $dialog { + fn parent(self, window: &winit::window::Window) -> Self { + self.set_parent(window) + } + fn title(self, title: &str) -> Self { + self.set_title(title) + } + fn filter(self, name: &str, exts: &[impl ToString]) -> Self { + self.add_filter(name, exts) + } + fn folder(self, folder: &str) -> Self { + self.set_directory(folder) + } + fn file_name(self, name: &str) -> Self { + self.set_file_name(name) + } + } + )*}; +} + +dialog_settings!(rfd::FileDialog, rfd::AsyncFileDialog); + +/// `d` set up for `request`: its title, file types, folder and suggested name. +fn dialog_for(d: D, request: &PickRequest) -> D { + let pick = match request { + PickRequest::Open(pick) | PickRequest::Save(pick) => pick, + PickRequest::OpenMany => { + return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { + d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts) + }); + } + PickRequest::Folder => return d, + }; + let d = pick.filters.iter().fold(d, |d, (name, exts)| { + d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), exts) + }); + let d = match &pick.folder { + Some(folder) => d.folder(folder), + None => d, + }; + if pick.name.is_empty() { d } else { d.file_name(&pick.name) } +} + +/// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the +/// window and keeps it in front). +#[cfg(not(target_os = "macos"))] +fn file_dialog(request: &PickRequest, parent: &Parent) -> rfd::FileDialog { + match parent { + Some(w) => dialog_for(rfd::FileDialog::new().parent(w), request), + None => dialog_for(rfd::FileDialog::new(), request), + } +} + +/// Before `request`'s dialog shows: a save dialog's folder (the Templates folder) may not exist yet. +fn make_folder(request: &PickRequest) { + if let PickRequest::Save(FilePick { folder: Some(folder), .. }) = request { + let _ = std::fs::create_dir_all(folder); + } +} + +/// Show `dialog` for `request` (on the calling thread, until it closes) → the paths picked. On +/// Linux and the BSDs a save dialog with two or more file types is the desktop portal's, over +/// `parent`, and its answer also names the file type picked ([`portal_save`]); `dialog` shows when +/// the portal can't. +#[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()) + { + return answer; + } + let paths = match request { + PickRequest::Open(_) => dialog.pick_file().into_iter().collect(), + PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(), + PickRequest::Save(_) => dialog.save_file().into_iter().collect(), + PickRequest::Folder => dialog.pick_folder().into_iter().collect(), + }; + paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect() +} + +/// 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) +} + +/// macOS shows no dialog in line: its modal loop would run inside winit's event handler, and an +/// event winit held back meanwhile aborts the app (#867). Dialogs are sheets there ([`start_pick`]); +/// one asked for any other way (a bug: outside a command, a dialog's OK or a button) picks nothing. +#[cfg(target_os = "macos")] +fn pick_now(request: PickRequest, _parent: &Parent) -> Vec { + log::error!("no file dialog shown for {request:?}: macOS shows them as sheets, from commands, dialogs' OK and buttons only"); + Vec::new() +} + +/// File → Show in Folder: select `path` in Finder / Explorer, or open its folder elsewhere. +fn reveal(path: &str) -> Result<(), String> { + explorer_safe(path)?; + reveal_command(path).spawn().map(|_| ()).map_err(|e| format!("can't show {path}: {e}")) +} + +#[cfg(target_os = "macos")] +fn reveal_command(path: &str) -> std::process::Command { + let mut c = std::process::Command::new("open"); + c.args(["-R", path]); + c +} + +#[cfg(windows)] +fn reveal_command(path: &str) -> std::process::Command { + use std::os::windows::process::CommandExt as _; + // Explorer reads `/select,"path"` itself (the usual argument quoting breaks paths with spaces) + // and needs backslashes. + let mut c = std::process::Command::new("explorer"); + c.raw_arg(format!("/select,\"{}\"", path.replace('/', "\\"))); + c +} + +#[cfg(not(any(target_os = "macos", windows)))] +fn reveal_command(path: &str) -> std::process::Command { + let folder = std::path::Path::new(path).parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(std::path::Path::new(".")); + let mut c = std::process::Command::new("xdg-open"); + c.arg(folder); + c +} + +/// Write a file the safe way: a failed write keeps the old file ([`fileio::write_atomic`]). +fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> { + fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string()) +} + +/// Linux: show the dialog for `request` over `parent` on a thread of its own, answering on the +/// receiver. Shown on the UI thread, nothing would answer the compositor meanwhile, which then +/// offers to kill the window as not responding (#592). +#[cfg(not(target_os = "macos"))] +fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Option>> { + let dialog = file_dialog(&request, parent); + let (tx, rx) = std::sync::mpsc::channel(); + let ui = ui.clone(); + let parent = parent.clone(); + std::thread::Builder::new() + .name("file-dialog".into()) + .spawn(move || { + // The app gone meanwhile has no use for the answer. + let _ = tx.send(show_dialog(dialog, &request, &parent)); + ui.request_repaint(); + }) + .ok()?; + Some(rx) +} + +/// The paths a dialog shown as a sheet picks, once it closes. +#[cfg(target_os = "macos")] +type SheetAnswer = std::pin::Pin> + Send>>; + +/// macOS: show the dialog for `request` as a sheet on `parent`'s window, answering on the receiver +/// (#867). Shown in line, the panel ran AppKit's modal event loop inside winit's event handler: an +/// event winit had held back meanwhile (one came as a resize of the panel ended) then re-entered +/// the handler, and winit's panic there, inside an AppKit callback, aborted the app. The sheet +/// returns at once and the window keeps running; a thread of its own waits for the answer. +#[cfg(target_os = "macos")] +fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Option>> { + use winit::raw_window_handle::HasWindowHandle as _; + // rfd runs the panel modally after all unless it has the running app's window to hold the + // sheet (and from another thread it can't reach the window): no dialog then (`pick_now`). + let mtm = objc2::MainThreadMarker::new(); + let running = mtm.is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isRunning()); + let Some(window) = parent.as_ref().filter(|w| running && w.window_handle().is_ok()) else { + log::error!("no window to show the file dialog on (main thread: {}, running: {running})", mtm.is_some()); + return None; + }; + // The thread first, so the answer of a sheet once shown always has somewhere to go. + let (sheet_tx, sheet_rx) = std::sync::mpsc::channel::(); + let (tx, rx) = std::sync::mpsc::channel(); + let ui = ui.clone(); + std::thread::Builder::new() + .name("file-dialog".into()) + .spawn(move || { + if let Ok(answer) = sheet_rx.recv() { + // The app gone meanwhile has no use for the answer. + let _ = tx.send(pollster::block_on(answer)); + ui.request_repaint(); + } + }) + .ok()?; + make_folder(&request); + // The panel is built and the sheet is begun below, on the main thread (as it must). + let dialog = dialog_for(rfd::AsyncFileDialog::new().parent(window), &request); + let path = |f: &rfd::FileHandle| f.path().to_string_lossy().to_string(); + let answer: SheetAnswer = match request { + PickRequest::Open(_) => { + let picked = dialog.pick_file(); + Box::pin(async move { picked.await.iter().map(path).collect() }) + } + PickRequest::OpenMany => { + let picked = dialog.pick_files(); + Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() }) + } + // A save panel with two or more named file types is built by `mac_save_format`, which sets + // up its Format menu before the sheet begins (#866); rfd shows the others. + PickRequest::Save(pick) => match mac_save_format::begin(window, &pick) { + // The dialog thread blocks here until the sheet answers. + Some(picked) => Box::pin(async move { picked.recv().unwrap_or_default() }), + None => { + // Nothing is added to the sheet once rfd has begun it: an accessory view set then + // made recent macOS versions dismiss the sheet at once (#1800). + let picked = dialog.save_file(); + Box::pin(async move { picked.await.iter().map(path).collect() }) + } + }, + PickRequest::Folder => { + let picked = dialog.pick_folder(); + Box::pin(async move { picked.await.iter().map(path).collect() }) + } + }; + // The thread can't be gone: it waits for this. If it were, its receiver answers as cancelled. + let _ = sheet_tx.send(answer); + Some(rx) +} + +/// The host's services; `ui` is woken when a file dialog answers. +pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { + use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; + let wayland = parent.as_ref().and_then(|w| w.window_handle().ok()).is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Wayland(_))); + // A window on X11 (XWayland included) reads a tablet pen's pressure itself (#764). + #[cfg(target_os = "linux")] + let x11 = parent + .as_ref() + .and_then(|w| w.window_handle().ok()) + .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); + let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); + #[cfg(target_os = "macos")] + let sampled_ui = ui.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))), + pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())), + // Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows + // dialogs run the window's events while they are open. + start_pick: cfg!(unix).then(|| Box::new(move |request: PickRequest| start_pick(request, &p5, &ui)) as vectorcraft_ui_egui::picks::StartPick), + dialogs_are_sheets: cfg!(target_os = "macos"), + wayland, + no_cursor_theme: wayland && cursor_theme::theme_missing(), + #[cfg(target_os = "linux")] + stylus: if x11 { tablet::start() } else { None }, + // macOS reads it from AppKit's events (#852). + #[cfg(target_os = "macos")] + stylus: mac_tablet::start(), + // Windows reads it from the pen's pointer messages (`windows_stylus`). + #[cfg(all(windows, not(target_vendor = "win7")))] + stylus: Some(windows_stylus::start()), + read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), + write: Some(Box::new(write_file)), + exists: Some(Box::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)), + // 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()), + // Linux checks whether Paste has something to take on a background thread: an X11 clipboard + // owner that never answers holds a read for up to 4 s. Windows only asks which formats the + // clipboard holds and macOS asks the pasteboard server, so they check in line. + clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(clipboard::system_clipboard) as ClipboardProbeFactory), + // Help → Discord / website / GitHub, the Discord button, About and Home links. + open_url: Some(Box::new(|url: &str| { + let _ = webbrowser::open(url); + })), + reveal: Some(Box::new(reveal)), + // Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders. + open_file: Some(Box::new(open_file)), + pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), + // Sample Color from Screen: the system's color sampler. + #[cfg(target_os = "macos")] + screen_color: Some(mac_screen_color::sampler(sampled_ui)), + // File → Print: the system's printers and print queue. + print: Some(Box::new(printing::SystemPrint)), + ..Default::default() + } +} + +/// Windows passes `path` to Explorer inside quotes it adds itself, so a path holding a quote (which +/// no Windows file name has) is refused rather than split into other arguments. +fn explorer_safe(path: &str) -> Result<(), String> { + if cfg!(windows) && path.contains('"') { Err(format!("can't open {path}: the path contains a quotation mark")) } else { Ok(()) } +} + +/// Edit Original, Show Package: open `path` (a file or a folder) in the system's default app for it. +fn open_file(path: &str) -> Result<(), String> { + explorer_safe(path)?; + #[cfg(windows)] + let mut c = { + use std::os::windows::process::CommandExt as _; + let mut c = std::process::Command::new("explorer"); + c.raw_arg(format!("\"{}\"", path.replace('/', "\\"))); + c + }; + #[cfg(target_os = "macos")] + let mut c = std::process::Command::new("open"); + #[cfg(not(any(target_os = "macos", windows)))] + let mut c = std::process::Command::new("xdg-open"); + #[cfg(not(windows))] + c.arg(path); + c.spawn().map(|_| ()).map_err(|e| format!("can't open {path}: {e}")) +} diff --git a/apps/vectorcraft/src/linux_stylus.rs b/apps/vectorcraft/src/linux_stylus.rs new file mode 100644 index 0000000000..f86a9cc536 --- /dev/null +++ b/apps/vectorcraft/src/linux_stylus.rs @@ -0,0 +1,116 @@ +//! Linux pen tablets: winit reports barrel buttons as [`winit::event::MouseButton::Other`] +//! (for example `BTN_STYLUS`), and egui-winit drops those before they reach the UI (#3632). + +use eframe::AppCreator; +use winit::application::ApplicationHandler; +use winit::event::{DeviceEvent, DeviceId, StartCause, WindowEvent}; +use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; +use winit::window::WindowId; + +use eframe::UserEvent; + +/// `BTN_STYLUS` and neighbours (`linux/input-event-codes.h`): pen barrel buttons Wayland passes +/// through the pointer protocol as non-standard mouse buttons. +const BTN_STYLUS: u16 = 0x014b; +const BTN_STYLUS2: u16 = 0x014c; +const BTN_STYLUS3: u16 = 0x014d; + +/// Like [`eframe::run_native`], but turns pen barrel buttons into mouse buttons egui understands. +pub fn run_native(app_name: &str, mut native_options: eframe::NativeOptions, app_creator: AppCreator<'_>) -> eframe::Result { + let mut builder = EventLoop::::with_user_event(); + if let Some(hook) = native_options.event_loop_builder.take() { + hook(&mut builder); + } + let event_loop = builder.build().map_err(eframe::Error::WinitEventLoop)?; + event_loop.set_control_flow(ControlFlow::Poll); + let inner = eframe::create_native(app_name, native_options, app_creator, &event_loop); + let mut app = Forwarder { inner }; + event_loop.run_app(&mut app).map_err(eframe::Error::WinitEventLoop)?; + Ok(()) +} + +struct Forwarder<'a> { + inner: eframe::EframeWinitApplication<'a>, +} + +impl ApplicationHandler for Forwarder<'_> { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + self.inner.resumed(event_loop); + } + + fn window_event(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: WindowEvent) { + self.inner.window_event(event_loop, window_id, map_window_event(event)); + } + + fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) { + self.inner.new_events(event_loop, cause); + } + + fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) { + self.inner.user_event(event_loop, event); + } + + fn device_event(&mut self, event_loop: &ActiveEventLoop, device_id: DeviceId, event: DeviceEvent) { + self.inner.device_event(event_loop, device_id, event); + } + + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + self.inner.about_to_wait(event_loop); + } + + fn suspended(&mut self, event_loop: &ActiveEventLoop) { + self.inner.suspended(event_loop); + } + + fn exiting(&mut self, event_loop: &ActiveEventLoop) { + self.inner.exiting(event_loop); + } + + fn memory_warning(&mut self, event_loop: &ActiveEventLoop) { + self.inner.memory_warning(event_loop); + } +} + +/// Map a tablet button code winit labels `MouseButton::Other` to a standard mouse button. +pub(crate) fn map_tablet_button(code: u16) -> Option { + use winit::event::MouseButton; + match code { + BTN_STYLUS | BTN_STYLUS2 => Some(MouseButton::Right), + BTN_STYLUS3 => Some(MouseButton::Middle), + _ => None, + } +} + +fn map_window_event(event: WindowEvent) -> WindowEvent { + if let WindowEvent::MouseInput { device_id, state, button: winit::event::MouseButton::Other(code), .. } = event + && let Some(button) = map_tablet_button(code) + { + WindowEvent::MouseInput { device_id, state, button } + } else { + event + } +} + +#[cfg(test)] +mod tests { + use super::*; + use winit::event::{ElementState, MouseButton}; + + #[test] + fn stylus_barrel_buttons_become_secondary_clicks() { + assert_eq!(map_tablet_button(BTN_STYLUS), Some(MouseButton::Right)); + assert_eq!(map_tablet_button(BTN_STYLUS2), Some(MouseButton::Right)); + assert_eq!(map_tablet_button(BTN_STYLUS3), Some(MouseButton::Middle)); + assert_eq!(map_tablet_button(0x110), None); + } + + #[test] + fn window_mouse_input_is_remapped_before_eframe() { + let device_id = winit::event::DeviceId::dummy(); + let press = WindowEvent::MouseInput { device_id, state: ElementState::Pressed, button: MouseButton::Other(BTN_STYLUS) }; + let mapped = map_window_event(press); + assert!(matches!(mapped, WindowEvent::MouseInput { button: MouseButton::Right, state: ElementState::Pressed, .. })); + let release = map_window_event(WindowEvent::MouseInput { device_id, state: ElementState::Released, button: MouseButton::Other(BTN_STYLUS2) }); + assert!(matches!(release, WindowEvent::MouseInput { button: MouseButton::Right, state: ElementState::Released, .. })); + } +} diff --git a/apps/vectorcraft/src/logging.rs b/apps/vectorcraft/src/logging.rs index cd2ea1eba5..e005d702df 100644 --- a/apps/vectorcraft/src/logging.rs +++ b/apps/vectorcraft/src/logging.rs @@ -93,28 +93,36 @@ fn matches(name: &str, target: &str) -> bool { } /// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch. +/// A clock far past chrono's year range still converts (the calendar repeats every 400 years), so +/// logging never panics and never silently resets to the epoch for a convertible instant. pub fn timestamp(t: SystemTime) -> String { let since = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default(); - let secs = since.as_secs(); - let (days, rem) = (secs / 86_400, secs % 86_400); - let (y, m, d) = civil_from_days(days); - format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{:03}Z", rem / 3600, rem % 3600 / 60, rem % 60, since.subsec_millis()) + // Pre-1970 is clamped to the epoch by `unwrap_or_default` above. `as_secs` is `u64`; a value + // past `i64::MAX` seconds saturates rather than falling back to the epoch. + let secs = i64::try_from(since.as_secs()).unwrap_or(i64::MAX); + let (y, t) = utc_parts(secs, since.subsec_nanos()); + // `{:04}` rather than `%Y`, which writes a `+` before years past 9999. + format!("{y:04}-{}", t.format("%m-%dT%H:%M:%S%.3fZ")) } -/// Days since 1970-01-01 to a proleptic Gregorian (year, month, day) (Howard Hinnant's -/// `civil_from_days`, unsigned because `timestamp` clamps at the epoch). Saturating, so no clock -/// value can overflow it. -fn civil_from_days(days: u64) -> (u64, u64, u64) { - let z = days.saturating_add(719_468); - let era = z / 146_097; - let doe = z % 146_097; - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = era.saturating_mul(400).saturating_add(yoe).saturating_add(u64::from(m <= 2)); - (y, m, d) +/// Unix seconds (+ nanos) → (proleptic Gregorian year, the same wall-clock instant moved into +/// chrono's range by whole 400-year cycles). The calendar repeats every 400 years (146_097 days), +/// so month, day and time of day come from chrono and only the year is carried, which keeps every +/// `i64` exact. Replaces the old hand-rolled `civil_from_days`; chrono is the only calendar logic. +fn utc_parts(secs: i64, nanos: u32) -> (i64, chrono::NaiveDateTime) { + use chrono::Datelike; + let (days, sod) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); + let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097)); + // `rest + 719_163` (1970-01-01 is CE day 719_163) is always a valid CE day, and `sod` < 86_400. + let date = i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt); + let time = u32::try_from(sod).ok().and_then(|s| chrono::NaiveTime::from_num_seconds_from_midnight_opt(s, nanos.min(999_999_999))); + match (date, time) { + (Some(d), Some(t)) => { + let y = i128::from(d.year()) + i128::from(cycles) * 400; + (i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX }), d.and_time(t)) + } + _ => (1970, chrono::NaiveDateTime::default()), // unreachable + } } fn numbered(dir: &Path, n: usize) -> PathBuf { @@ -288,295 +296,4 @@ pub fn install() -> Option<&'static AppLogger> { } #[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::time::{Duration, UNIX_EPOCH}; - - fn temp_dir(tag: &str) -> PathBuf { - static N: AtomicUsize = AtomicUsize::new(0); - let d = std::env::temp_dir().join(format!("vectorcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); - let _ = std::fs::remove_dir_all(&d); - d - } - - fn read(path: &Path) -> String { - std::fs::read_to_string(path).expect("read log") - } - - #[test] - fn the_default_filter_shows_vectorcraft_info_and_other_crates_warnings() { - let f = Filter::parse(DEFAULT_FILTER); - assert_eq!(f.level_for("vectorcraft"), LevelFilter::Info); - assert_eq!(f.level_for("vectorcraft::window"), LevelFilter::Info); - assert_eq!(f.level_for("vectorcraft_engine::guard"), LevelFilter::Info); - assert_eq!(f.level_for("vectorcraft_ui_egui::io"), LevelFilter::Info); - assert_eq!(f.level_for("wgpu_core::device"), LevelFilter::Warn); - assert_eq!(f.level_for("naga"), LevelFilter::Warn); - assert_eq!(f.max(), LevelFilter::Info); - } - - #[test] - fn directives_follow_env_logger_and_the_most_specific_one_wins() { - let f = Filter::parse("info,wgpu_core=error,vectorcraft_render=trace,vectorcraft_render::tiles=off"); - assert_eq!(f.level_for("eframe"), LevelFilter::Info); - assert_eq!(f.level_for("wgpu_core::instance"), LevelFilter::Error); - assert_eq!(f.level_for("vectorcraft_render::canvas"), LevelFilter::Trace); - assert_eq!(f.level_for("vectorcraft_render::tiles"), LevelFilter::Off); - assert_eq!(f.max(), LevelFilter::Trace); - // A module name is matched at `::` boundaries, not as a bare prefix. - assert_eq!(f.level_for("wgpu_core_extra"), LevelFilter::Info); - // A trailing `*` is a prefix. - assert_eq!(Filter::parse("vectorcraft*=debug").level_for("vectorcraft_text::shape"), LevelFilter::Debug); - assert_eq!(Filter::parse("vectorcraft*=debug").level_for("eframe"), LevelFilter::Error); - // A bare target name sets that target to the most verbose level, as env_logger does. - assert_eq!(Filter::parse("naga").level_for("naga::front"), LevelFilter::Trace); - assert_eq!(Filter::parse("naga").level_for("eframe"), LevelFilter::Error); - // Levels are case-insensitive and surrounding blanks are ignored. - assert_eq!(Filter::parse(" WARN , vectorcraft = Debug ").level_for("vectorcraft"), LevelFilter::Debug); - assert_eq!(Filter::parse(" WARN , vectorcraft = Debug ").level_for("eframe"), LevelFilter::Warn); - } - - #[test] - fn hostile_specs_never_panic_and_fall_back_sensibly() { - let long = "x".repeat(100_000); - let many = "a=info,".repeat(10_000); - for spec in [ - "", - ",,,", - "=", - "==", - "=debug", - "vectorcraft=", - "nonsense=loud", - "🦀=info", - "*", - "*=", - "=*", - "a=b=c", - "warn,,vectorcraft=DEBUG", - "\0", - "é::ü=trace", - &long, - &many, - ] { - let f = Filter::parse(spec); - for target in ["", "vectorcraft", "🦀", "a::b", "*"] { - let _ = f.level_for(target); - } - let _ = f.max(); - } - assert_eq!(Filter::parse("warn,,vectorcraft=DEBUG").level_for("vectorcraft"), LevelFilter::Debug); - // An unknown level is skipped: that target keeps the default. - assert_eq!(Filter::parse("nonsense=loud").level_for("nonsense"), LevelFilter::Error); - assert_eq!(Filter::parse("vectorcraft=").level_for("vectorcraft"), LevelFilter::Error); - assert_eq!(Filter::parse("=debug").max(), LevelFilter::Error); - assert_eq!(Filter::parse("🦀=info").level_for("🦀::claw"), LevelFilter::Info); - } - - #[test] - fn timestamps_are_utc_with_milliseconds() { - assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z"); - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_791_446_357_728)), "2026-10-08T07:59:17.728Z"); - // Leap day, and the day after it. - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z"); - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_199)), "2024-02-29T23:59:59.000Z"); - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_200)), "2024-03-01T00:00:00.000Z"); - // 2000 is a leap year (divisible by 400), 2100 is not. - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z"); - assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z"); - // Before the epoch (a clock set wrong) clamps instead of panicking. - assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z"); - } - - #[test] - fn a_line_carries_time_level_thread_target_and_message() { - assert_eq!( - format_line("2026-10-08T07:59:17.728Z", log::Level::Info, "main", "vectorcraft", "rendering with Mesa (Vulkan, IntegratedGpu)"), - "2026-10-08T07:59:17.728Z INFO [main] vectorcraft: rendering with Mesa (Vulkan, IntegratedGpu)\n" - ); - // A multi-line message keeps its lines; the record still ends in one newline. - assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n")); - } - - #[test] - fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() { - let dir = temp_dir("rotate"); - for run in 1..=4 { - let (path, _file) = rotate(&dir).expect("rotate"); - assert_eq!(path, dir.join(LOG_FILE)); - assert_eq!(read(&path), ""); - std::fs::write(&path, format!("run {run}")).expect("write"); - } - assert_eq!(read(&dir.join(LOG_FILE)), "run 4"); - assert_eq!(read(&dir.join("vectorcraft.1.log")), "run 3"); - assert_eq!(read(&dir.join("vectorcraft.2.log")), "run 2"); - assert!(!dir.join("vectorcraft.3.log").exists(), "only {KEEP} old logs are kept"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() { - let dir = temp_dir("blocked"); - std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp"); - std::fs::write(&dir, "a file where the directory should be").expect("block"); - assert!(rotate(&dir).is_err()); - let _ = std::fs::remove_file(&dir); - } - - #[test] - fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() { - let dir = temp_dir("pending"); - let (path, file) = rotate(&dir).expect("rotate"); - let mut sink = Sink::new(MAX_FILE_BYTES); - sink.write("early 1\n"); - sink.write("early 2\n"); - sink.attach(file); - sink.write("late\n"); - assert_eq!(read(&path), "early 1\nearly 2\nlate\n"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() { - let dir = temp_dir("bounded"); - let (path, file) = rotate(&dir).expect("rotate"); - let mut sink = Sink::new(MAX_FILE_BYTES); - for i in 0..MAX_PENDING + 5 { - sink.write(&format!("line {i}\n")); - } - sink.attach(file); - let text = read(&path); - assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), MAX_PENDING); - assert!(text.contains("5 earlier log lines were dropped"), "{text}"); - assert!(text.contains("line 0\n") && !text.contains(&format!("line {MAX_PENDING}\n"))); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn exactly_a_full_pending_buffer_drops_nothing() { - let dir = temp_dir("full"); - let (path, file) = rotate(&dir).expect("rotate"); - let mut sink = Sink::new(MAX_FILE_BYTES); - for i in 0..MAX_PENDING { - sink.write(&format!("line {i}\n")); - } - sink.attach(file); - let text = read(&path); - assert_eq!(text.lines().count(), MAX_PENDING); - assert!(!text.contains("dropped"), "{text}"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn without_a_file_nothing_is_kept_in_memory() { - let mut sink = Sink::new(MAX_FILE_BYTES); - sink.write("early\n"); - sink.no_file(); - sink.write("late\n"); - assert!(sink.pending.is_empty() && sink.dropped == 0); - } - - #[test] - fn the_file_stops_at_its_size_cap_with_one_note() { - let dir = temp_dir("cap"); - let (path, file) = rotate(&dir).expect("rotate"); - let mut sink = Sink::new(100); - sink.attach(file); - for i in 0..50 { - sink.write(&format!("line {i:02} with some padding\n")); - } - let text = read(&path); - assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), 3, "{text}"); - assert_eq!(text.matches("log file reached").count(), 1, "{text}"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn the_logger_filters_records_and_writes_them_to_the_attached_file() { - use log::Log; - let dir = temp_dir("logger"); - let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false); - let record = |level, target: &'static str, msg: &'static str| { - logger.log(&log::Record::builder().level(level).target(target).args(format_args!("{msg}")).build()); - }; - record(log::Level::Info, "vectorcraft", "before the settings directory"); - record(log::Level::Info, "wgpu_core::device", "too chatty"); - let path = logger.attach_dir(&dir).expect("attach"); - assert_eq!(path, dir.join(LOG_FILE)); - record(log::Level::Warn, "wgpu_hal::vulkan", "a real warning"); - record(log::Level::Error, "vectorcraft_engine::guard", "recovered from a panic: boom"); - record(log::Level::Debug, "vectorcraft", "below info"); - let text = read(&path); - let lines: Vec<&str> = text.lines().collect(); - assert_eq!(lines.len(), 3, "{text}"); - assert!(lines[0].contains(" INFO [") && lines[0].ends_with("vectorcraft: before the settings directory"), "{text}"); - assert!(lines[1].ends_with("wgpu_hal::vulkan: a real warning"), "{text}"); - assert!(lines[2].contains(" ERROR [") && lines[2].ends_with("vectorcraft_engine::guard: recovered from a panic: boom"), "{text}"); - assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("vectorcraft_ui_egui").build())); - assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build())); - // Attaching again rotates: the first log becomes `.1`. - logger.attach_dir(&dir).expect("attach again"); - assert_eq!(read(&dir.join("vectorcraft.1.log")), text); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn records_from_many_threads_are_whole_lines() { - use log::Log; - let dir = temp_dir("threads"); - let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false)); - let path = logger.attach_dir(&dir).expect("attach"); - let workers: Vec<_> = (0..8) - .map(|t| { - let l = std::sync::Arc::clone(&logger); - std::thread::spawn(move || { - for i in 0..100 { - l.log( - &log::Record::builder().level(log::Level::Info).target("vectorcraft").args(format_args!("thread {t} record {i}")).build(), - ); - } - }) - }) - .collect(); - for w in workers { - w.join().expect("worker"); - } - let text = read(&path); - assert_eq!(text.lines().count(), 800); - assert!(text.lines().all(|l| l.contains(" vectorcraft: thread ")), "{text}"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn attaching_to_an_unusable_directory_reports_an_error_and_keeps_logging() { - use log::Log; - let dir = temp_dir("unusable"); - std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp"); - std::fs::write(&dir, "not a directory").expect("block"); - let logger = AppLogger::new(Filter::parse("info"), false); - assert!(logger.attach_dir(&dir).is_err()); - logger.log(&log::Record::builder().level(log::Level::Error).target("x").args(format_args!("still fine")).build()); - // Nothing waits in memory for a file that won't come. - assert!(logger.sink.lock().expect("sink").pending.is_empty()); - let _ = std::fs::remove_file(&dir); - } - - #[test] - fn a_poisoned_sink_still_logs() { - use log::Log; - let dir = temp_dir("poison"); - let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false)); - let l = std::sync::Arc::clone(&logger); - let _ = std::thread::spawn(move || { - let _guard = l.sink.lock().expect("lock"); - panic!("poison the sink"); - }) - .join(); - assert!(logger.sink.is_poisoned()); - let path = logger.attach_dir(&dir).expect("attach"); - logger.log(&log::Record::builder().level(log::Level::Warn).target("vectorcraft").args(format_args!("after the poison")).build()); - assert!(read(&path).contains("vectorcraft: after the poison")); - let _ = std::fs::remove_dir_all(&dir); - } -} +mod tests; diff --git a/apps/vectorcraft/src/logging/tests.rs b/apps/vectorcraft/src/logging/tests.rs new file mode 100644 index 0000000000..a1b54b353a --- /dev/null +++ b/apps/vectorcraft/src/logging/tests.rs @@ -0,0 +1,302 @@ +use super::*; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, UNIX_EPOCH}; + +fn temp_dir(tag: &str) -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("vectorcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + d +} + +fn read(path: &Path) -> String { + std::fs::read_to_string(path).expect("read log") +} + +#[test] +fn the_default_filter_shows_vectorcraft_info_and_other_crates_warnings() { + let f = Filter::parse(DEFAULT_FILTER); + assert_eq!(f.level_for("vectorcraft"), LevelFilter::Info); + assert_eq!(f.level_for("vectorcraft::window"), LevelFilter::Info); + assert_eq!(f.level_for("vectorcraft_engine::guard"), LevelFilter::Info); + assert_eq!(f.level_for("vectorcraft_ui_egui::io"), LevelFilter::Info); + assert_eq!(f.level_for("wgpu_core::device"), LevelFilter::Warn); + assert_eq!(f.level_for("naga"), LevelFilter::Warn); + assert_eq!(f.max(), LevelFilter::Info); +} + +#[test] +fn directives_follow_env_logger_and_the_most_specific_one_wins() { + let f = Filter::parse("info,wgpu_core=error,vectorcraft_render=trace,vectorcraft_render::tiles=off"); + assert_eq!(f.level_for("eframe"), LevelFilter::Info); + assert_eq!(f.level_for("wgpu_core::instance"), LevelFilter::Error); + assert_eq!(f.level_for("vectorcraft_render::canvas"), LevelFilter::Trace); + assert_eq!(f.level_for("vectorcraft_render::tiles"), LevelFilter::Off); + assert_eq!(f.max(), LevelFilter::Trace); + // A module name is matched at `::` boundaries, not as a bare prefix. + assert_eq!(f.level_for("wgpu_core_extra"), LevelFilter::Info); + // A trailing `*` is a prefix. + assert_eq!(Filter::parse("vectorcraft*=debug").level_for("vectorcraft_text::shape"), LevelFilter::Debug); + assert_eq!(Filter::parse("vectorcraft*=debug").level_for("eframe"), LevelFilter::Error); + // A bare target name sets that target to the most verbose level, as env_logger does. + assert_eq!(Filter::parse("naga").level_for("naga::front"), LevelFilter::Trace); + assert_eq!(Filter::parse("naga").level_for("eframe"), LevelFilter::Error); + // Levels are case-insensitive and surrounding blanks are ignored. + assert_eq!(Filter::parse(" WARN , vectorcraft = Debug ").level_for("vectorcraft"), LevelFilter::Debug); + assert_eq!(Filter::parse(" WARN , vectorcraft = Debug ").level_for("eframe"), LevelFilter::Warn); +} + +#[test] +fn hostile_specs_never_panic_and_fall_back_sensibly() { + let long = "x".repeat(100_000); + let many = "a=info,".repeat(10_000); + for spec in [ + "", + ",,,", + "=", + "==", + "=debug", + "vectorcraft=", + "nonsense=loud", + "🦀=info", + "*", + "*=", + "=*", + "a=b=c", + "warn,,vectorcraft=DEBUG", + "\0", + "é::ü=trace", + &long, + &many, + ] { + let f = Filter::parse(spec); + for target in ["", "vectorcraft", "🦀", "a::b", "*"] { + let _ = f.level_for(target); + } + let _ = f.max(); + } + assert_eq!(Filter::parse("warn,,vectorcraft=DEBUG").level_for("vectorcraft"), LevelFilter::Debug); + // An unknown level is skipped: that target keeps the default. + assert_eq!(Filter::parse("nonsense=loud").level_for("nonsense"), LevelFilter::Error); + assert_eq!(Filter::parse("vectorcraft=").level_for("vectorcraft"), LevelFilter::Error); + assert_eq!(Filter::parse("=debug").max(), LevelFilter::Error); + assert_eq!(Filter::parse("🦀=info").level_for("🦀::claw"), LevelFilter::Info); +} + +#[test] +fn timestamps_are_utc_with_milliseconds() { + assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_791_446_357_728)), "2026-10-08T07:59:17.728Z"); + // Leap day, and the day after it. + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_199)), "2024-02-29T23:59:59.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_200)), "2024-03-01T00:00:00.000Z"); + // 2000 is a leap year (divisible by 400), 2100 is not. + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z"); + // Before the epoch (a clock set wrong) clamps instead of panicking. + assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z"); + // Past chrono's year range still converts via the 400-year cycle (the old code did too, + // through `civil_from_days`): never a silent reset to the epoch. Platform-safe: Windows' + // SystemTime can't hold this instant, so it is only checked where it exists. + // `u64::MAX / 2` seconds == `i64::MAX` seconds → year 292277026596 (old output). + if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) { + assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z"); + } + // Years past 9999 keep the plain zero-padded year (no `+`). + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z"); + // 10_000_000_000_000 s is far beyond chrono's range; old output is year 318857. + // Windows' SystemTime holds only up to about year 30828, so this is checked where it fits. + if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) { + assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z"); + } +} + +#[test] +fn a_line_carries_time_level_thread_target_and_message() { + assert_eq!( + format_line("2026-10-08T07:59:17.728Z", log::Level::Info, "main", "vectorcraft", "rendering with Mesa (Vulkan, IntegratedGpu)"), + "2026-10-08T07:59:17.728Z INFO [main] vectorcraft: rendering with Mesa (Vulkan, IntegratedGpu)\n" + ); + // A multi-line message keeps its lines; the record still ends in one newline. + assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n")); +} + +#[test] +fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() { + let dir = temp_dir("rotate"); + for run in 1..=4 { + let (path, _file) = rotate(&dir).expect("rotate"); + assert_eq!(path, dir.join(LOG_FILE)); + assert_eq!(read(&path), ""); + std::fs::write(&path, format!("run {run}")).expect("write"); + } + assert_eq!(read(&dir.join(LOG_FILE)), "run 4"); + assert_eq!(read(&dir.join("vectorcraft.1.log")), "run 3"); + assert_eq!(read(&dir.join("vectorcraft.2.log")), "run 2"); + assert!(!dir.join("vectorcraft.3.log").exists(), "only {KEEP} old logs are kept"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() { + let dir = temp_dir("blocked"); + std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp"); + std::fs::write(&dir, "a file where the directory should be").expect("block"); + assert!(rotate(&dir).is_err()); + let _ = std::fs::remove_file(&dir); +} + +#[test] +fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() { + let dir = temp_dir("pending"); + let (path, file) = rotate(&dir).expect("rotate"); + let mut sink = Sink::new(MAX_FILE_BYTES); + sink.write("early 1\n"); + sink.write("early 2\n"); + sink.attach(file); + sink.write("late\n"); + assert_eq!(read(&path), "early 1\nearly 2\nlate\n"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() { + let dir = temp_dir("bounded"); + let (path, file) = rotate(&dir).expect("rotate"); + let mut sink = Sink::new(MAX_FILE_BYTES); + for i in 0..MAX_PENDING + 5 { + sink.write(&format!("line {i}\n")); + } + sink.attach(file); + let text = read(&path); + assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), MAX_PENDING); + assert!(text.contains("5 earlier log lines were dropped"), "{text}"); + assert!(text.contains("line 0\n") && !text.contains(&format!("line {MAX_PENDING}\n"))); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn exactly_a_full_pending_buffer_drops_nothing() { + let dir = temp_dir("full"); + let (path, file) = rotate(&dir).expect("rotate"); + let mut sink = Sink::new(MAX_FILE_BYTES); + for i in 0..MAX_PENDING { + sink.write(&format!("line {i}\n")); + } + sink.attach(file); + let text = read(&path); + assert_eq!(text.lines().count(), MAX_PENDING); + assert!(!text.contains("dropped"), "{text}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn without_a_file_nothing_is_kept_in_memory() { + let mut sink = Sink::new(MAX_FILE_BYTES); + sink.write("early\n"); + sink.no_file(); + sink.write("late\n"); + assert!(sink.pending.is_empty() && sink.dropped == 0); +} + +#[test] +fn the_file_stops_at_its_size_cap_with_one_note() { + let dir = temp_dir("cap"); + let (path, file) = rotate(&dir).expect("rotate"); + let mut sink = Sink::new(100); + sink.attach(file); + for i in 0..50 { + sink.write(&format!("line {i:02} with some padding\n")); + } + let text = read(&path); + assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), 3, "{text}"); + assert_eq!(text.matches("log file reached").count(), 1, "{text}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_logger_filters_records_and_writes_them_to_the_attached_file() { + use log::Log; + let dir = temp_dir("logger"); + let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false); + let record = |level, target: &'static str, msg: &'static str| { + logger.log(&log::Record::builder().level(level).target(target).args(format_args!("{msg}")).build()); + }; + record(log::Level::Info, "vectorcraft", "before the settings directory"); + record(log::Level::Info, "wgpu_core::device", "too chatty"); + let path = logger.attach_dir(&dir).expect("attach"); + assert_eq!(path, dir.join(LOG_FILE)); + record(log::Level::Warn, "wgpu_hal::vulkan", "a real warning"); + record(log::Level::Error, "vectorcraft_engine::guard", "recovered from a panic: boom"); + record(log::Level::Debug, "vectorcraft", "below info"); + let text = read(&path); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines.len(), 3, "{text}"); + assert!(lines[0].contains(" INFO [") && lines[0].ends_with("vectorcraft: before the settings directory"), "{text}"); + assert!(lines[1].ends_with("wgpu_hal::vulkan: a real warning"), "{text}"); + assert!(lines[2].contains(" ERROR [") && lines[2].ends_with("vectorcraft_engine::guard: recovered from a panic: boom"), "{text}"); + assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("vectorcraft_ui_egui").build())); + assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build())); + // Attaching again rotates: the first log becomes `.1`. + logger.attach_dir(&dir).expect("attach again"); + assert_eq!(read(&dir.join("vectorcraft.1.log")), text); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn records_from_many_threads_are_whole_lines() { + use log::Log; + let dir = temp_dir("threads"); + let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false)); + let path = logger.attach_dir(&dir).expect("attach"); + let workers: Vec<_> = (0..8) + .map(|t| { + let l = std::sync::Arc::clone(&logger); + std::thread::spawn(move || { + for i in 0..100 { + l.log(&log::Record::builder().level(log::Level::Info).target("vectorcraft").args(format_args!("thread {t} record {i}")).build()); + } + }) + }) + .collect(); + for w in workers { + w.join().expect("worker"); + } + let text = read(&path); + assert_eq!(text.lines().count(), 800); + assert!(text.lines().all(|l| l.contains(" vectorcraft: thread ")), "{text}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn attaching_to_an_unusable_directory_reports_an_error_and_keeps_logging() { + use log::Log; + let dir = temp_dir("unusable"); + std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp"); + std::fs::write(&dir, "not a directory").expect("block"); + let logger = AppLogger::new(Filter::parse("info"), false); + assert!(logger.attach_dir(&dir).is_err()); + logger.log(&log::Record::builder().level(log::Level::Error).target("x").args(format_args!("still fine")).build()); + // Nothing waits in memory for a file that won't come. + assert!(logger.sink.lock().expect("sink").pending.is_empty()); + let _ = std::fs::remove_file(&dir); +} + +#[test] +fn a_poisoned_sink_still_logs() { + use log::Log; + let dir = temp_dir("poison"); + let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false)); + let l = std::sync::Arc::clone(&logger); + let _ = std::thread::spawn(move || { + let _guard = l.sink.lock().expect("lock"); + panic!("poison the sink"); + }) + .join(); + assert!(logger.sink.is_poisoned()); + let path = logger.attach_dir(&dir).expect("attach"); + logger.log(&log::Record::builder().level(log::Level::Warn).target("vectorcraft").args(format_args!("after the poison")).build()); + assert!(read(&path).contains("vectorcraft: after the poison")); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/apps/vectorcraft/src/mac_save_format.rs b/apps/vectorcraft/src/mac_save_format.rs index 519c980972..fe20971574 100644 --- a/apps/vectorcraft/src/mac_save_format.rs +++ b/apps/vectorcraft/src/mac_save_format.rs @@ -26,9 +26,7 @@ use objc2_app_kit::{NSModalResponse, NSModalResponseOK, NSPopUpButton, NSSavePan use objc2_foundation::{NSArray, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString, NSURL}; use raw_window_handle::{HasWindowHandle, RawWindowHandle}; use vectorcraft_engine::cmd::fileio; -use vectorcraft_ui_egui::{FilePick, i18n}; - -type Filter = (&'static str, &'static [&'static str]); +use vectorcraft_ui_egui::{FileFilter as Filter, FilePick, i18n}; /// The accessory's height and the room around and between its label and menu, in points. const HEIGHT: f64 = 38.0; @@ -70,7 +68,8 @@ define_class!( /// The file types a Format menu lists: `filters` without "every file" ones. Empty when fewer than /// two remain, and the panel is then left to rfd. fn menu_formats(filters: &[Filter]) -> Vec { - let named: Vec = filters.iter().copied().filter(|(_, extensions)| !extensions.is_empty() && !extensions.contains(&"*")).collect(); + let named: Vec = + filters.iter().filter(|(_, extensions)| !extensions.is_empty() && !extensions.iter().any(|x| x == "*")).cloned().collect(); if named.len() < 2 { Vec::new() } else { named } } @@ -95,10 +94,10 @@ fn filename(name: &str, extension: &str, filters: &[Filter]) -> String { /// The extensions a panel with menu `filters` allows, those of entry `selected` first. AppKit adds /// the first one to a name typed without an extension, and a name typed with another of them is /// saved in that format. -fn allowed_types(filters: &[Filter], selected: usize) -> Vec<&'static str> { - let first = filters.get(selected).map_or(&[][..], |(_, extensions)| *extensions); +fn allowed_types(filters: &[Filter], selected: usize) -> Vec<&str> { + let first = filters.get(selected).map_or(&[][..], |(_, extensions)| extensions.as_slice()); let others = filters.iter().enumerate().filter(|(i, _)| *i != selected).flat_map(|(_, (_, extensions))| extensions.iter()); - first.iter().chain(others).copied().collect() + first.iter().chain(others).map(String::as_str).collect() } /// Set `panel`'s allowed file types ([`allowed_types`]). @@ -184,26 +183,28 @@ fn accessory(mtm: MainThreadMarker, panel: &NSSavePanel, filters: Vec, s mod tests { use super::*; - const FILTERS: &[Filter] = &[("VectorCraft", &["vectorcraft"]), ("SVG", &["svg"]), ("PDF", &["pdf"])]; + fn filters() -> Vec { + FilePick::filters([("VectorCraft", &["vectorcraft"][..]), ("SVG", &["svg"]), ("PDF", &["pdf"])]) + } /// Save, Save As and Save a Copy list every save format with the default first; a panel with one /// named type, or one for every file, gets no menu, and rfd shows it. #[test] fn save_panels_with_several_formats_get_the_menu() { - let save = menu_formats(&fileio::save_filters("vectorcraft")); + let save = menu_formats(&FilePick::filters(fileio::save_filters("vectorcraft"))); assert!(save.len() >= 2, "{save:?}"); - assert_eq!(save.first().map(|(_, e)| *e), Some(&["vectorcraft"][..])); - assert!(menu_formats(&fileio::save_filters("svg")).first().is_some_and(|(_, e)| e.contains(&"svg"))); - assert!(menu_formats(&fileio::template_filters("template")).len() >= 2); - assert!(menu_formats(&[("PDF", &["pdf"])]).is_empty()); - assert!(menu_formats(&[("PDF", &["pdf"]), ("All files", &["*"]), ("Any", &[])]).is_empty()); - assert_eq!(menu_formats(&[("PDF", &["pdf"]), ("All files", &["*"]), ("SVG", &["svg"])]).len(), 2); + assert_eq!(save.first().map(|(_, e)| e.as_slice()), Some(&["vectorcraft".to_owned()][..])); + assert!(menu_formats(&FilePick::filters(fileio::save_filters("svg"))).first().is_some_and(|(_, e)| e.iter().any(|e| e == "svg"))); + assert!(menu_formats(&FilePick::filters(fileio::template_filters("template"))).len() >= 2); + assert!(menu_formats(&FilePick::filters([("PDF", &["pdf"][..])])).is_empty()); + assert!(menu_formats(&FilePick::filters([("PDF", &["pdf"][..]), ("All files", &["*"]), ("Any", &[])])).is_empty()); + assert_eq!(menu_formats(&FilePick::filters([("PDF", &["pdf"][..]), ("All files", &["*"]), ("SVG", &["svg"])])).len(), 2); } #[test] fn the_suggested_name_selects_its_format_and_an_unknown_one_the_default() { for (name, index) in [("Untitled-1", 0), ("a b.SVG", 1), ("art.pdf", 2), ("version.2", 0), ("", 0)] { - assert_eq!(initial_format(name, FILTERS), index, "{name}"); + assert_eq!(initial_format(name, &filters()), index, "{name}"); } } @@ -219,7 +220,7 @@ mod tests { ("photo.png", "photo.svg"), ("", ""), ] { - assert_eq!(filename(name, "svg", FILTERS), expected, "{name}"); + assert_eq!(filename(name, "svg", &filters()), expected, "{name}"); } } @@ -227,27 +228,19 @@ mod tests { /// type. The others stay allowed. #[test] fn the_chosen_format_is_the_first_allowed_type() { - assert_eq!(allowed_types(FILTERS, 0), ["vectorcraft", "svg", "pdf"]); - assert_eq!(allowed_types(FILTERS, 1), ["svg", "vectorcraft", "pdf"]); - assert_eq!(allowed_types(FILTERS, 2), ["pdf", "vectorcraft", "svg"]); - assert_eq!(allowed_types(FILTERS, 9), ["vectorcraft", "svg", "pdf"]); + assert_eq!(allowed_types(&filters(), 0), ["vectorcraft", "svg", "pdf"]); + assert_eq!(allowed_types(&filters(), 1), ["svg", "vectorcraft", "pdf"]); + assert_eq!(allowed_types(&filters(), 2), ["pdf", "vectorcraft", "svg"]); + assert_eq!(allowed_types(&filters(), 9), ["vectorcraft", "svg", "pdf"]); } /// Each entry of the Save As menu gives a name the save command reads as that entry's format. #[test] fn each_menu_entry_names_a_file_the_save_command_writes_in_that_format() { - let filters = menu_formats(&fileio::save_filters("vectorcraft")); + let filters = menu_formats(&FilePick::filters(fileio::save_filters("vectorcraft"))); for (label, extensions) in &filters { - let name = filename("Untitled-1.vectorcraft", extensions[0], &filters); - assert_eq!(fileio::format_for_name(&name).map(|f| f.label), Some(*label), "{name}"); - } - } - - /// The menu's label is translated in every language with complete menus. - #[test] - fn the_label_is_translated() { - for lang in i18n::Lang::all().filter(|l| l.complete_menus()) { - assert!(i18n::has(lang, "Format:"), "{}", lang.code()); + let name = filename("Untitled-1.vectorcraft", &extensions[0], &filters); + assert_eq!(fileio::format_for_name(&name).map(|f| f.label), Some(label.as_str()), "{name}"); } } } diff --git a/apps/vectorcraft/src/mac_tablet.rs b/apps/vectorcraft/src/mac_tablet.rs new file mode 100644 index 0000000000..b624262aa4 --- /dev/null +++ b/apps/vectorcraft/src/mac_tablet.rs @@ -0,0 +1,275 @@ +//! macOS: a drawing tablet's pen pressure (#852). winit 0.30 hands a pen to the window there as a +//! mouse, without its pressure, so the app reads it from AppKit itself and writes it into the UI's +//! [`StylusFeed`] (`Services::stylus`), which the canvas reads, as on X11 ([`crate::tablet`]). +//! +//! A local event monitor (`addLocalMonitorForEventsMatchingMask:handler:`, which AppKit calls "with +//! each event it is about to dispatch" in this app: +//! ) +//! reads each mouse and tablet event on the main thread before winit's view handles it, and passes +//! it on unchanged: +//! - A mouse event whose `subtype` is `NSEventSubtypeTabletPoint` comes from a pen: its `pressure` +//! (0..1) goes into the feed, kept for the pointer move winit makes of the event +//! ([`StylusFeed::set_move`]), so each move of a fast stroke has its own pressure. A mouse event +//! of any other subtype is a mouse's or a trackpad's: the feed is set to `None`. +//! - An `NSEventTypeTabletPoint` event carries the same pressure without a move. +//! - A tablet proximity event (`NSEventTypeTabletProximity`, or a mouse event of that subtype) says +//! which end of the pen came near (`pointingDeviceType`): the eraser end's samples are marked so, +//! and the canvas switches to the Eraser tool ([`vectorcraft_ui_egui::stylus`]). A puck +//! (`NSPointingDeviceTypeCursor`) is a mouse. +//! +//! The monitor also turns off mouse event coalescing (`NSEvent.mouseCoalescingEnabled`), which +//! merges the drags that queue up between two reads into one: every report of the pen arrives. +//! +//! The mapping comes from PhotoCraft's `crates/tablet` (`appkit.rs` and `macos.rs`), with the +//! pressure and the pen's end only. It is plain values, tested on every platform; the monitor +//! reads them. +#![cfg_attr(not(target_os = "macos"), allow(dead_code))] + +use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed}; + +/// `NSEventType` values (AppKit headers). +mod event_type { + pub const TABLET_POINT: usize = 23; + pub const TABLET_PROXIMITY: usize = 24; + /// Left, right and other mouse down, up, moved and dragged: winit makes a pointer move of each. + pub const MOUSE: [usize; 10] = [1, 2, 3, 4, 5, 6, 7, 25, 26, 27]; +} + +/// `NSEventSubtype` values of mouse events. +mod subtype { + pub const TABLET_POINT: i16 = 1; + pub const TABLET_PROXIMITY: i16 = 2; +} + +/// `NSPointingDeviceType` values. +mod device { + pub const CURSOR: usize = 2; + pub const ERASER: usize = 3; +} + +/// The tablet fields of one `NSEvent`, as plain values. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct RawEvent { + /// `type`. + kind: usize, + /// `subtype` (mouse events only). + subtype: i16, + /// `pressure` (tablet point events and mouse events of that subtype only). + pressure: f32, + /// `pointingDeviceType` (proximity events only). + device: usize, + /// `isEnteringProximity` (proximity events only). + entering: bool, +} + +impl RawEvent { + fn mouse(&self) -> bool { + event_type::MOUSE.contains(&self.kind) + } + + fn proximity(&self) -> bool { + self.kind == event_type::TABLET_PROXIMITY || (self.mouse() && self.subtype == subtype::TABLET_PROXIMITY) + } + + fn point(&self) -> bool { + self.kind == event_type::TABLET_POINT || (self.mouse() && self.subtype == subtype::TABLET_POINT) + } +} + +/// The events the monitor reads (`NSEventMask` bits are `1 << type`). +fn event_mask() -> u64 { + event_type::MOUSE.iter().chain(&[event_type::TABLET_POINT, event_type::TABLET_PROXIMITY]).fold(0, |m, t| m | 1u64 << t) +} + +/// What an event means for the feed. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Update { + /// Nothing: an event the monitor doesn't map. + Keep, + /// The pressure and end of a pen, or `None` for a mouse. + Set(Option), + /// A pen's sample that comes with a pointer move. + Move(PenSample), +} + +impl Update { + fn apply(self, feed: &StylusFeed) { + match self { + Update::Keep => {} + Update::Set(sample) => feed.set_sample(sample), + Update::Move(sample) => feed.set_move(sample), + } + } +} + +/// Which end of the pen is near the tablet. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Pen { + eraser: bool, +} + +impl Pen { + fn handle(&mut self, e: &RawEvent) -> Update { + if e.proximity() { + // Entering with the tip or the eraser end: it hovers. A puck, or leaving, is a mouse. + self.eraser = e.entering && e.device == device::ERASER; + let pen = e.entering && e.device != device::CURSOR; + return Update::Set(pen.then_some(PenSample { pressure: 0.0, eraser: self.eraser })); + } + let sample = PenSample { pressure: e.pressure, eraser: self.eraser }; + match (e.point(), e.mouse()) { + (true, true) => Update::Move(sample), + (true, false) => Update::Set(Some(sample)), + (false, true) => Update::Set(None), + (false, false) => Update::Keep, + } + } +} + +/// Start reading pen pressure: the feed the monitor writes into, or `None` (logged) when AppKit +/// refuses the monitor or this isn't the main thread. +#[cfg(target_os = "macos")] +pub fn start() -> Option { + // The monitor writes on the main thread before winit hands the event on: a press never waits. + let feed = StylusFeed::on_ui_thread(); + match monitor::install(feed.clone()) { + Ok(()) => Some(feed), + Err(e) => { + log::warn!("tablet pressure: {e}"); + None + } + } +} + +#[cfg(target_os = "macos")] +mod monitor { + use std::cell::Cell; + use std::ptr::NonNull; + + use block2::RcBlock; + use objc2::MainThreadMarker; + use objc2_app_kit::{NSEvent, NSEventMask}; + use vectorcraft_ui_egui::stylus::StylusFeed; + + use super::{Pen, RawEvent, event_mask}; + + /// Install the monitor for the life of the app. Main thread only. + pub(super) fn install(feed: StylusFeed) -> Result<(), &'static str> { + MainThreadMarker::new().ok_or("the event monitor can only be installed from the main thread")?; + let pen = Cell::new(Pen::default()); + let handler = RcBlock::new(move |event: NonNull| -> *mut NSEvent { + // SAFETY: AppKit calls the handler with the event it is about to dispatch, which it + // keeps alive while the handler runs. + #[allow(unsafe_code)] + let e = unsafe { event.as_ref() }; + let mut p = pen.get(); + p.handle(&read(e)).apply(&feed); + pen.set(p); + event.as_ptr() + }); + // SAFETY: the handler returns the event it was given, a valid pointer ("the block's return + // must be a valid pointer or null"). AppKit copies the block and keeps it while the monitor + // is installed. + #[allow(unsafe_code)] + let token = unsafe { NSEvent::addLocalMonitorForEventsMatchingMask_handler(NSEventMask(event_mask()), &handler) }; + // The monitor stays until the app quits: its token is never handed to `removeMonitor:`. + std::mem::forget(token.ok_or("AppKit refused the event monitor")?); + NSEvent::setMouseCoalescingEnabled(false); + Ok(()) + } + + /// The tablet fields of `e`. `subtype` raises an exception for events without one, and the + /// pressure and proximity fields are read only for the events that define them. + fn read(e: &NSEvent) -> RawEvent { + let mut raw = RawEvent { kind: e.r#type().0, ..Default::default() }; + if raw.mouse() { + raw.subtype = e.subtype().0; + } + if raw.point() { + raw.pressure = e.pressure(); + } + if raw.proximity() { + raw.device = e.pointingDeviceType().0; + raw.entering = e.isEnteringProximity(); + } + raw + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const DRAG: usize = 6; + const KEY_DOWN: usize = 10; + + fn pen(kind: usize, pressure: f32) -> RawEvent { + RawEvent { kind, subtype: subtype::TABLET_POINT, pressure, ..Default::default() } + } + + fn proximity(device: usize, entering: bool) -> RawEvent { + RawEvent { kind: event_type::TABLET_PROXIMITY, device, entering, ..Default::default() } + } + + fn tip(pressure: f32) -> PenSample { + PenSample { pressure, eraser: false } + } + + #[test] + fn a_pens_mouse_events_are_moves_with_its_pressure() { + let mut p = Pen::default(); + assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Move(tip(0.5))); + assert_eq!(p.handle(&pen(1, 0.25)), Update::Move(tip(0.25)), "a press"); + assert_eq!(p.handle(&pen(event_type::TABLET_POINT, 0.8)), Update::Set(Some(tip(0.8))), "no move"); + } + + #[test] + fn other_mouse_events_are_a_mouse_and_other_events_are_kept() { + let mut p = Pen::default(); + for subtype in [0, 3, 99, -1] { + let e = RawEvent { kind: DRAG, subtype, pressure: 1.0, ..Default::default() }; + assert_eq!(p.handle(&e), Update::Set(None), "subtype {subtype}"); + } + for kind in [0, KEY_DOWN, 22, 29, 34, usize::MAX] { + // Other events' subtypes don't make them a pen's. + let e = RawEvent { kind, subtype: subtype::TABLET_POINT, ..Default::default() }; + assert_eq!(p.handle(&e), Update::Keep, "type {kind}"); + } + } + + #[test] + fn proximity_says_which_end_is_near() { + let mut p = Pen::default(); + let eraser = |pressure| PenSample { pressure, eraser: true }; + assert_eq!(p.handle(&proximity(device::ERASER, true)), Update::Set(Some(eraser(0.0)))); + assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Move(eraser(0.4))); + assert_eq!(p.handle(&proximity(device::ERASER, false)), Update::Set(None), "it left"); + assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Move(tip(0.4))); + assert_eq!(p.handle(&proximity(1, true)), Update::Set(Some(tip(0.0))), "the tip"); + assert_eq!(p.handle(&proximity(0, true)), Update::Set(Some(tip(0.0))), "an unknown tool draws as the tip"); + assert_eq!(p.handle(&proximity(device::CURSOR, true)), Update::Set(None), "a puck is a mouse"); + let e = RawEvent { kind: 5, subtype: subtype::TABLET_PROXIMITY, device: device::ERASER, entering: true, ..Default::default() }; + assert_eq!(p.handle(&e), Update::Set(Some(eraser(0.0))), "as a mouse event's subtype"); + } + + #[test] + fn the_feed_gets_each_moves_pressure_within_0_to_1() { + let feed = StylusFeed::default(); + let mut p = Pen::default(); + for e in [pen(DRAG, f32::NAN), pen(DRAG, 4.0), pen(DRAG, -1.0), pen(event_type::TABLET_POINT, 0.3)] { + p.handle(&e).apply(&feed); + } + assert_eq!((feed.take_moves(), feed.held()), (vec![1.0, 1.0, 0.0], Some(0.3))); + p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed); + assert_eq!(feed.held(), None, "a mouse moved"); + } + + #[test] + fn the_mask_covers_the_mapped_events() { + let m = event_mask(); + for t in [1, 2, 3, 4, 5, 6, 7, 23, 24, 25, 26, 27] { + assert!(m & (1 << t) != 0, "{t}"); + } + assert_eq!(m & (1 << KEY_DOWN), 0, "keys are not read"); + } +} diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index a457d98089..2cdf80b428 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -1,6 +1,6 @@ //! VectorCraft desktop app. //! -//! Usage: `vectorcraft [--control [--automation-read-root ] [--automation-write-root ]] +//! Usage: `vectorcraft [--control [--automation-read-root ]... [--automation-write-root ]...] //! [--in-window-menus] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`) //! //! `--in-window-menus` (or `VECTORCRAFT_IN_WINDOW_MENUS=1`) keeps the menus inside the window on @@ -30,6 +30,8 @@ mod control_server; mod cursor_theme; #[cfg(feature = "wgpu")] mod gpu; +#[cfg(target_os = "linux")] +mod linux_stylus; mod logging; #[cfg(target_os = "macos")] mod mac_fonts; @@ -39,6 +41,7 @@ mod mac_menu; mod mac_save_format; #[cfg(target_os = "macos")] mod mac_screen_color; +mod mac_tablet; #[cfg(target_os = "macos")] mod mac_window; #[cfg(target_os = "macos")] @@ -49,8 +52,10 @@ mod prefs_dir; mod printing; #[cfg(all(windows, not(target_vendor = "win7")))] mod system_fonts; +mod tablet; mod window; mod window_frame; +mod windows_stylus; mod xwayland; use vectorcraft_engine::Session; @@ -60,6 +65,31 @@ use vectorcraft_ui_egui::graphics::GraphicsLoss; use vectorcraft_ui_egui::picks::PickRequest; use vectorcraft_ui_egui::{ClipboardProbeFactory, FilePick, Services, VectorcraftApp}; +mod app; +mod host_services; +mod prefs; +mod titlebar; + +#[cfg(all(test, feature = "wgpu"))] +use app::bring_window_forward; +use app::native_input_hook; +use app::open_files; +use host_services::services; +#[cfg(all(test, feature = "wgpu"))] +use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes}; +use prefs::{load_prefs, log_dir, prefs_enabled, prefs_path, read_prefs}; +#[cfg(all(test, feature = "wgpu", any(target_os = "macos", target_os = "windows")))] +use titlebar::CUSTOM_TITLEBAR; +#[cfg(feature = "wgpu")] +use titlebar::adapter_summary; +#[cfg(all(test, feature = "wgpu"))] +use titlebar::custom_titlebar_from; +#[cfg(all(test, feature = "wgpu"))] +use titlebar::opted_into_system_title_bar; +#[cfg(windows)] +use titlebar::set_taskbar_icon; +use titlebar::{custom_titlebar, native_options}; + struct App { app: VectorcraftApp, /// Reported by wgpu when the window's graphics device is lost (a driver reset). @@ -70,591 +100,12 @@ struct App { frames: u64, /// Keeps the custom title bar's window borderless (Windows, #1758). window_frame: Option, -} - -impl eframe::App for App { - // Each frame runs unconfined: it is the person at the keyboard's. The app confines what the - // 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) { - file_access::unconfined(|| self.logic_frame(ctx, frame)); - } - fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) { - // 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() { - window_frame(); - } - #[cfg(target_os = "macos")] - if self.app.services.native_menu.is_some() { - mac_menu::raw_input_hook(raw); - } - file_access::unconfined(|| self.app.raw_input_hook(raw)); - } - #[cfg_attr(not(target_os = "macos"), allow(unused_variables))] - fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { - #[cfg(target_os = "macos")] - { - let bar = vectorcraft_ui_egui::chrome::APP_BAR_HEIGHT; - let inset = mac_window::center_buttons(frame, ui.ctx().zoom_factor(), bar); - self.app.titlebar_inset = inset.unwrap_or(mac_window::DEFAULT_INSET); - } - file_access::unconfined(|| self.app.ui(ui)); - // Preferences are written when confirmed, not only at exit: a session ended any other way - // (the system shutting down, the process ended or crashing) used to lose them (#1747). - if self.app.take_prefs_changed() { - file_access::unconfined(|| save_prefs(&self.app)); - } - // Not while a file dialog's sheet has the keyboard: its name field's composition would go. - #[cfg(target_os = "macos")] - if !self.app.file_dialog_open() && self.app.take_ime_discard() { - discard_marked_text(); - } - } - #[cfg(not(feature = "windows7"))] - fn on_exit(&mut self) { - file_access::unconfined(|| save_prefs(&self.app)); - end_before_teardown(self.frames); - } - #[cfg(feature = "windows7")] - fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) { - file_access::unconfined(|| save_prefs(&self.app)); - } -} - -impl App { - fn logic_frame(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { - self.frames = ctx.cumulative_frame_nr(); - if let Some(why) = self.graphics_loss.take() { - // eframe can't give a window a new device: the user saves and starts again. - self.graphics_lost = self.app.graphics_lost(&why); - self.app.status(if self.graphics_lost { - "The graphics device was lost: unsaved changes are kept for Data Recovery. Save your documents and restart VectorCraft" - } else { - "The graphics device was lost: save your documents and restart VectorCraft" - }); - } - if self.graphics_lost && ctx.input(|i| i.viewport().close_requested()) { - // The window can't show the Save Changes question: it closes, and the next launch - // offers the changes back. - vectorcraft_ui_egui::background::wait_all(&mut self.app); - return; - } - // Files from the Finder and the Dock wait while a file dialog is open: what asked for it runs - // again on its document when it answers. - #[cfg(target_os = "macos")] - if !self.app.file_dialog_open() { - // Files from the Finder and the Dock wait while a file dialog is open: what asked for it runs - // again on its document when it answers. - if !self.app.file_dialog_open() { - open_files(&mut self.app, open_documents::take()); - } - } - self.app.logic(ctx); - window::track(ctx, &mut self.app.ui.window); - if self.app.ui.status == "quit" { - ctx.send_viewport_cmd(egui::ViewportCommand::Close); - } - } -} - -/// On macOS with accessibility, end the process once the app has saved what it keeps on quitting, -/// before eframe tears the window down (#661). AccessKit then gives the window's content view back -/// its own class, which AppKit's Touch Bar support was observing it under, and AppKit aborts the -/// app as it quits on Macs with a Touch Bar. Nothing after the window is needed on a normal quit. -/// Not while the window is still starting up (`frames` below [`gpu::STARTUP_FRAMES`]): a graphics -/// failure then starts the app again on another adapter (#651). -#[allow(unused_variables)] -fn end_before_teardown(frames: u64) { - #[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))] - if frames >= gpu::STARTUP_FRAMES { - log::info!("quitting"); - log::logger().flush(); - std::process::exit(0); - } -} - -/// Open files handed to the app (command line, macOS Finder and Dock) as documents. A file that -/// can't be opened is reported to the user and on stderr; the others still open. -fn open_files(app: &mut VectorcraftApp, files: Vec) { - for f in files { - if let Err(e) = vectorcraft_ui_egui::io::open_reporting(app, &f) { - eprintln!("vectorcraft: {f}: {e}"); - } - } -} - -/// Tell the macOS input method to drop its composition (the Type tool kept the marked text as -/// typed). winit's IME toggle only clears its own copy, so the IME would type it again. -#[cfg(target_os = "macos")] -fn discard_marked_text() { - if let Some(mtm) = objc2::MainThreadMarker::new() - && let Some(ic) = objc2_app_kit::NSTextInputContext::currentInputContext(mtm) - { - ic.discardMarkedText(); - } -} - -/// Where UI preferences live: ~/Library/Application Support/VectorCraft (macOS), -/// %APPDATA%\VectorCraft (Windows), $XDG_CONFIG_HOME or ~/.config/vectorcraft (Linux). -fn prefs_path() -> Option { - prefs_dir::prefs_path_for("VectorCraft", "vectorcraft") -} - -/// The same place under the project's former name (DrawCraft): read once if there are no -/// VectorCraft preferences yet, so settings survive the rename. -fn legacy_prefs_path() -> Option { - prefs_dir::prefs_path_for("DrawCraft", "drawcraft") -} - -/// Where the log files live: `logs` in the preferences folder (see `logging`). -fn log_dir() -> Option { - Some(prefs_path()?.parent()?.join("logs")) -} - -/// Runs without preferences (`VECTORCRAFT_NO_PREFS`, agents' test runs) neither read nor write them. -fn prefs_enabled() -> bool { - std::env::var_os("VECTORCRAFT_NO_PREFS").is_none() -} - -/// The saved UI preferences, read before the window opens (they hold its size and position). -fn read_prefs() -> Option { - if !prefs_enabled() { - return None; - } - let bytes = prefs_path().and_then(|p| std::fs::read(p).ok()).or_else(|| legacy_prefs_path().and_then(|p| std::fs::read(p).ok()))?; - decode_saved_prefs(&bytes) -} - -/// Recover only optional persisted docking metadata. Runtime UiState and command decoding -/// remains strict, and an unreadable workspace layout cannot discard unrelated preferences. -fn decode_saved_prefs(bytes: &[u8]) -> Option { - use serde_json::{Map, Value, json}; - - fn recover(object: &mut Map, hidden_key: &str) { - if let Some(layout) = object.get("docking") - && serde_json::from_value::(json!({"docking": layout})).is_err() - { - object.remove("docking"); - } - if let Some(hidden) = object.get_mut(hidden_key) { - if let Value::Object(entries) = hidden { - entries.retain(|panel, location| { - serde_json::from_value::(json!({"docking_hidden": {panel: location}})).is_ok() - }); - } else { - object.remove(hidden_key); - } - } - } - - let mut value: Value = serde_json::from_slice(bytes).ok()?; - let object = value.as_object_mut()?; - recover(object, "docking_hidden"); - if let Some(Value::Array(workspaces)) = object.get_mut("custom_workspaces") { - for workspace in workspaces { - if let Some(object) = workspace.as_object_mut() { - recover(object, "dockingHidden"); - } - } - } - serde_json::from_value(value).ok() -} - -fn load_prefs(app: &mut VectorcraftApp, saved: Option) { - if !prefs_enabled() { - return; - } - if let Some(ui) = saved { - app.ui = ui.sanitized(); - } - vectorcraft_ui_egui::prefs_dialog::restore(app); -} - -fn save_prefs(app: &VectorcraftApp) { - if !prefs_enabled() { - return; - } - if let Some(p) = prefs_path() { - let _ = std::fs::create_dir_all(p.parent().unwrap_or(std::path::Path::new("."))); - let mut ui = app.ui.clone(); - ui.engine_prefs = app.session.prefs.to_json(); - if let Ok(bytes) = serde_json::to_vec_pretty(&ui) { - // Preferences are best effort: a failed write keeps the previous file. - let _ = fileio::write_atomic(&p, &bytes); - } - } -} - -/// The window file dialogs belong to. -type Parent = Option>; - -/// What rfd's blocking and asynchronous file dialogs are both set up with. -trait DialogSettings: Sized { - fn parent(self, window: &winit::window::Window) -> Self; - fn title(self, title: &str) -> Self; - fn filter(self, name: &str, exts: &[&str]) -> Self; - fn folder(self, folder: &str) -> Self; - fn file_name(self, name: &str) -> Self; -} - -macro_rules! dialog_settings { - ($($dialog:ty),*) => {$( - impl DialogSettings for $dialog { - fn parent(self, window: &winit::window::Window) -> Self { - self.set_parent(window) - } - fn title(self, title: &str) -> Self { - self.set_title(title) - } - fn filter(self, name: &str, exts: &[&str]) -> Self { - self.add_filter(name, exts) - } - fn folder(self, folder: &str) -> Self { - self.set_directory(folder) - } - fn file_name(self, name: &str) -> Self { - self.set_file_name(name) - } - } - )*}; -} - -dialog_settings!(rfd::FileDialog, rfd::AsyncFileDialog); - -/// `d` set up for `request`: its title, file types, folder and suggested name. -fn dialog_for(d: D, request: &PickRequest) -> D { - let pick = match request { - PickRequest::Open(pick) | PickRequest::Save(pick) => pick, - PickRequest::OpenMany => { - return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { - d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts) - }); - } - PickRequest::Folder => return d, - }; - let d = pick - .filters - .iter() - .fold(d, |d, (name, exts)| d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts)); - let d = match &pick.folder { - Some(folder) => d.folder(folder), - None => d, - }; - if pick.name.is_empty() { d } else { d.file_name(&pick.name) } -} - -/// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the -/// window and keeps it in front). -#[cfg(not(target_os = "macos"))] -fn file_dialog(request: &PickRequest, parent: &Parent) -> rfd::FileDialog { - match parent { - Some(w) => dialog_for(rfd::FileDialog::new().parent(w), request), - None => dialog_for(rfd::FileDialog::new(), request), - } -} - -/// Before `request`'s dialog shows: a save dialog's folder (the Templates folder) may not exist yet. -fn make_folder(request: &PickRequest) { - if let PickRequest::Save(FilePick { folder: Some(folder), .. }) = request { - let _ = std::fs::create_dir_all(folder); - } -} - -/// Show `dialog` for `request` (on the calling thread, until it closes) → the paths picked. On -/// Linux and the BSDs a save dialog with two or more file types is the desktop portal's, over -/// `parent`, and its answer also names the file type picked ([`portal_save`]); `dialog` shows when -/// the portal can't. -#[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()) - { - return answer; - } - let paths = match request { - PickRequest::Open(_) => dialog.pick_file().into_iter().collect(), - PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(), - PickRequest::Save(_) => dialog.save_file().into_iter().collect(), - PickRequest::Folder => dialog.pick_folder().into_iter().collect(), - }; - paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect() -} - -/// 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) -} - -/// macOS shows no dialog in line: its modal loop would run inside winit's event handler, and an -/// event winit held back meanwhile aborts the app (#867). Dialogs are sheets there ([`start_pick`]); -/// one asked for any other way (a bug: outside a command, a dialog's OK or a button) picks nothing. -#[cfg(target_os = "macos")] -fn pick_now(request: PickRequest, _parent: &Parent) -> Vec { - log::error!("no file dialog shown for {request:?}: macOS shows them as sheets, from commands, dialogs' OK and buttons only"); - Vec::new() -} - -/// File → Show in Folder: select `path` in Finder / Explorer, or open its folder elsewhere. -fn reveal(path: &str) -> Result<(), String> { - explorer_safe(path)?; - reveal_command(path).spawn().map(|_| ()).map_err(|e| format!("can't show {path}: {e}")) -} - -#[cfg(target_os = "macos")] -fn reveal_command(path: &str) -> std::process::Command { - let mut c = std::process::Command::new("open"); - c.args(["-R", path]); - c -} - -#[cfg(windows)] -fn reveal_command(path: &str) -> std::process::Command { - use std::os::windows::process::CommandExt as _; - // Explorer reads `/select,"path"` itself (the usual argument quoting breaks paths with spaces) - // and needs backslashes. - let mut c = std::process::Command::new("explorer"); - c.raw_arg(format!("/select,\"{}\"", path.replace('/', "\\"))); - c -} - -#[cfg(not(any(target_os = "macos", windows)))] -fn reveal_command(path: &str) -> std::process::Command { - let folder = std::path::Path::new(path).parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(std::path::Path::new(".")); - let mut c = std::process::Command::new("xdg-open"); - c.arg(folder); - c -} - -/// Write a file the safe way: a failed write keeps the old file ([`fileio::write_atomic`]). -fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> { - fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string()) -} - -/// Linux: show the dialog for `request` over `parent` on a thread of its own, answering on the -/// receiver. Shown on the UI thread, nothing would answer the compositor meanwhile, which then -/// offers to kill the window as not responding (#592). -#[cfg(not(target_os = "macos"))] -fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Option>> { - let dialog = file_dialog(&request, parent); - let (tx, rx) = std::sync::mpsc::channel(); - let ui = ui.clone(); - let parent = parent.clone(); - std::thread::Builder::new() - .name("file-dialog".into()) - .spawn(move || { - // The app gone meanwhile has no use for the answer. - let _ = tx.send(show_dialog(dialog, &request, &parent)); - ui.request_repaint(); - }) - .ok()?; - Some(rx) -} - -/// The paths a dialog shown as a sheet picks, once it closes. -#[cfg(target_os = "macos")] -type SheetAnswer = std::pin::Pin> + Send>>; - -/// macOS: show the dialog for `request` as a sheet on `parent`'s window, answering on the receiver -/// (#867). Shown in line, the panel ran AppKit's modal event loop inside winit's event handler: an -/// event winit had held back meanwhile (one came as a resize of the panel ended) then re-entered -/// the handler, and winit's panic there, inside an AppKit callback, aborted the app. The sheet -/// returns at once and the window keeps running; a thread of its own waits for the answer. -#[cfg(target_os = "macos")] -fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Option>> { - use winit::raw_window_handle::HasWindowHandle as _; - // rfd runs the panel modally after all unless it has the running app's window to hold the - // sheet (and from another thread it can't reach the window): no dialog then (`pick_now`). - let mtm = objc2::MainThreadMarker::new(); - let running = mtm.is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isRunning()); - let Some(window) = parent.as_ref().filter(|w| running && w.window_handle().is_ok()) else { - log::error!("no window to show the file dialog on (main thread: {}, running: {running})", mtm.is_some()); - return None; - }; - // The thread first, so the answer of a sheet once shown always has somewhere to go. - let (sheet_tx, sheet_rx) = std::sync::mpsc::channel::(); - let (tx, rx) = std::sync::mpsc::channel(); - let ui = ui.clone(); - std::thread::Builder::new() - .name("file-dialog".into()) - .spawn(move || { - if let Ok(answer) = sheet_rx.recv() { - // The app gone meanwhile has no use for the answer. - let _ = tx.send(pollster::block_on(answer)); - ui.request_repaint(); - } - }) - .ok()?; - make_folder(&request); - // The panel is built and the sheet is begun below, on the main thread (as it must). - let dialog = dialog_for(rfd::AsyncFileDialog::new().parent(window), &request); - let path = |f: &rfd::FileHandle| f.path().to_string_lossy().to_string(); - let answer: SheetAnswer = match request { - PickRequest::Open(_) => { - let picked = dialog.pick_file(); - Box::pin(async move { picked.await.iter().map(path).collect() }) - } - PickRequest::OpenMany => { - let picked = dialog.pick_files(); - Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() }) - } - // A save panel with two or more named file types is built by `mac_save_format`, which sets - // up its Format menu before the sheet begins (#866); rfd shows the others. - PickRequest::Save(pick) => match mac_save_format::begin(window, &pick) { - // The dialog thread blocks here until the sheet answers. - Some(picked) => Box::pin(async move { picked.recv().unwrap_or_default() }), - None => { - // Nothing is added to the sheet once rfd has begun it: an accessory view set then - // made recent macOS versions dismiss the sheet at once (#1800). - let picked = dialog.save_file(); - Box::pin(async move { picked.await.iter().map(path).collect() }) - } - }, - PickRequest::Folder => { - let picked = dialog.pick_folder(); - Box::pin(async move { picked.await.iter().map(path).collect() }) - } - }; - // The thread can't be gone: it waits for this. If it were, its receiver answers as cancelled. - let _ = sheet_tx.send(answer); - Some(rx) -} - -/// The host's services; `ui` is woken when a file dialog answers. -fn services(parent: Parent, ui: egui::Context) -> Services { - use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; - let wayland = parent.as_ref().and_then(|w| w.window_handle().ok()).is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Wayland(_))); - let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); - #[cfg(target_os = "macos")] - let sampled_ui = ui.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))), - pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())), - // Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows - // dialogs run the window's events while they are open. - start_pick: cfg!(unix).then(|| Box::new(move |request: PickRequest| start_pick(request, &p5, &ui)) as vectorcraft_ui_egui::picks::StartPick), - dialogs_are_sheets: cfg!(target_os = "macos"), - wayland, - no_cursor_theme: wayland && cursor_theme::theme_missing(), - read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), - write: Some(Box::new(write_file)), - exists: Some(Box::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)), - // 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()), - // Linux checks whether Paste has something to take on a background thread: an X11 clipboard - // owner that never answers holds a read for up to 4 s. Windows only asks which formats the - // clipboard holds and macOS asks the pasteboard server, so they check in line. - clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(clipboard::system_clipboard) as ClipboardProbeFactory), - // Help → Discord / website / GitHub, the Discord button, About and Home links. - open_url: Some(Box::new(|url: &str| { - let _ = webbrowser::open(url); - })), - reveal: Some(Box::new(reveal)), - // Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders. - open_file: Some(Box::new(open_file)), - pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), - // Sample Color from Screen: the system's color sampler. - #[cfg(target_os = "macos")] - screen_color: Some(mac_screen_color::sampler(sampled_ui)), - // File → Print: the system's printers and print queue. - print: Some(Box::new(printing::SystemPrint)), - ..Default::default() - } -} - -/// Windows passes `path` to Explorer inside quotes it adds itself, so a path holding a quote (which -/// no Windows file name has) is refused rather than split into other arguments. -fn explorer_safe(path: &str) -> Result<(), String> { - if cfg!(windows) && path.contains('"') { Err(format!("can't open {path}: the path contains a quotation mark")) } else { Ok(()) } -} - -/// Edit Original, Show Package: open `path` (a file or a folder) in the system's default app for it. -fn open_file(path: &str) -> Result<(), String> { - explorer_safe(path)?; - #[cfg(windows)] - let mut c = { - use std::os::windows::process::CommandExt as _; - let mut c = std::process::Command::new("explorer"); - c.raw_arg(format!("\"{}\"", path.replace('/', "\\"))); - c - }; - #[cfg(target_os = "macos")] - let mut c = std::process::Command::new("open"); - #[cfg(not(any(target_os = "macos", windows)))] - let mut c = std::process::Command::new("xdg-open"); - #[cfg(not(windows))] - c.arg(path); - c.spawn().map(|_| ()).map_err(|e| format!("can't open {path}: {e}")) -} - -/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets -/// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches -/// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon. -fn app_icon() -> egui::IconData { - #[cfg(target_os = "macos")] - let png: &[u8] = include_bytes!("../../../assets/app-icon/vectorcraft-macos-512.png"); - #[cfg(not(target_os = "macos"))] - let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.vectorcraft.png"); - eframe::icon_data::from_png_bytes(png).unwrap_or_default() -} - -/// Windows shows a window's big icon (`ICON_BIG`) in the taskbar and Alt+Tab; eframe sets only the -/// small one (the title bar's), so the taskbar showed a generic icon. Set the big one too. -#[cfg(windows)] -fn set_taskbar_icon(w: &winit::window::Window) { - use winit::platform::windows::WindowExtWindows as _; - let icon = app_icon(); - // An icon that can't be made leaves the generic one: nothing else depends on it. - if let Ok(i) = winit::window::Icon::from_rgba(icon.rgba, icon.width, icon.height) { - w.set_taskbar_icon(Some(i)); - } -} - -/// "name (backend, kind)" of the adapter the window renders with, for Help › About and bug reports. -#[cfg(feature = "wgpu")] -fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String { - format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type) -} - -/// Windows and Linux: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`). -/// macOS keeps its traffic lights over the integrated title strip. -const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos"); - -/// Whether this start draws its own title bar: Windows and Linux do, unless Preferences › -/// User Interface › System Title Bar asks for the system's. Read from the saved preferences -/// before the window opens; a missing or unreadable value keeps the default. -fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool { - CUSTOM_TITLEBAR && !saved.map(|ui| ui.engine_prefs.get("systemTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false) -} - -fn native_options(custom_titlebar: bool) -> eframe::NativeOptions { - eframe::NativeOptions { - viewport: egui::ViewportBuilder::default() - .with_title("VectorCraft") - .with_inner_size(window::DEFAULT_SIZE) - .with_min_inner_size(window::MIN_SIZE) - .with_drag_and_drop(true) - .with_decorations(!custom_titlebar) - .with_fullsize_content_view(true) - .with_titlebar_shown(false) - .with_title_shown(false) - .with_icon(app_icon()) - .with_app_id("ai.storyteller.vectorcraft"), - #[cfg(feature = "windows7")] - renderer: eframe::Renderer::Glow, - ..Default::default() - } + /// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635). + winit_window: Option>, + /// A saved or fitted geometry asked for maximize once the window is mapped (Linux). + pending_maximize: bool, + /// Frames left to retry [`window::apply_pending_maximize`]. + maximize_tries: u8, } /// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s. @@ -667,7 +118,9 @@ Options: --control Start the localhost JSON-lines control server on (or VECTORCRAFT_CONTROL_PORT) --automation-read-root Confine the files control requests read to + (may be given more than once) --automation-write-root Confine the files control requests write to + (may be given more than once) --in-window-menus Keep the menus inside the window on macOS (or VECTORCRAFT_IN_WINDOW_MENUS=1) --version Print the version and exit @@ -678,6 +131,11 @@ Without a window (converting, scripting, the MCP server), use vectorcraft-cli: "; fn main() -> std::process::ExitCode { + // Windows: the update helper is a copy of this program started with `--finish-update`. + #[cfg(windows)] + if let Some(result) = craft_update::self_update::finish(&craft_update::suite::VECTORCRAFT, &std::env::args_os().skip(1).collect::>()) { + std::process::exit(i32::from(result.is_err())); + } // Before any thread starts: the pointer must find a cursor theme on Wayland (#2450). #[cfg(target_os = "linux")] cursor_theme::apply(); @@ -716,7 +174,7 @@ fn main() -> std::process::ExitCode { _ => files.push(a), } } - let automation_args::AutomationArgs { read_root, write_root, .. } = roots_args; + let automation_args::AutomationArgs { read_roots, write_roots, .. } = roots_args; // After the arguments: `--control` and `--version` win over a bad environment value. let control_port = match control.port { Some(port) => Some(port), @@ -755,12 +213,14 @@ fn main() -> std::process::ExitCode { // 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() { - if read_root.is_some() || write_root.is_some() { + if !read_roots.is_empty() || !write_roots.is_empty() { log::warn!("--automation-read-root and --automation-write-root confine the control channel: ignored without --control"); } None } else { - match AutomationRoots::new(read_root.as_deref(), write_root.as_deref()) { + let read: Vec<&std::path::Path> = read_roots.iter().map(std::path::PathBuf::as_path).collect(); + let write: Vec<&std::path::Path> = write_roots.iter().map(std::path::PathBuf::as_path).collect(); + match AutomationRoots::new(&read, &write) { Ok(roots) => roots, Err(e) => { log::error!("{e}"); @@ -832,6 +292,18 @@ fn main() -> std::process::ExitCode { } options }; + // With Windows Ink, winit reports a pen as a touch and drops its barrel button and which end + // is down; the message hook notes each pointer contact and whether it starts with the barrel + // button held, and writes the pen's end into the pen feed (`windows_stylus`). + #[cfg(all(windows, not(target_vendor = "win7")))] + let options = { + use winit::platform::windows::EventLoopBuilderExtWindows as _; + let mut options = options; + options.event_loop_builder = Some(Box::new(|builder| { + builder.with_msg_hook(windows_stylus::msg_hook); + })); + options + }; #[cfg(feature = "wgpu")] let options = { let mut options = options; @@ -876,31 +348,50 @@ fn main() -> std::process::ExitCode { #[cfg(feature = "wgpu")] let created = startup.clone(); // 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")] + { + linux_stylus::run_native("VectorCraft", options, app_creator) + } + #[cfg(not(target_os = "linux"))] + { + eframe::run_native("VectorCraft", options, app_creator) + } + }; let outcome = vectorcraft_engine::guard::catch_panic(|| { - eframe::run_native( - "VectorCraft", + run( options, Box::new(move |cc| { + VectorcraftApp::install_ime_reset_hooks(&cc.egui_ctx); let mut session = Session::new(); // The profiles loaded before come back before the preferences name any of them. prefs_dir::attach_profile_store(&mut session); prefs_dir::attach_plugin_store(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); + app.set_startup_update_check(true); load_prefs(&mut app, saved); // The saved PDF presets live in their own folder (also read by vectorcraft-cli), // which takes over from the copy the preferences file used to hold. prefs_dir::attach_pdf_preset_store(&mut app.session); // Fit the window to its monitor, or put it back where it was (still hidden). - if let Some(w) = cc.winit_window() { - app.ui.window = Some(window::restore(w, saved_window)); + let winit_window = cc.winit_window().cloned(); + if let Some(w) = &winit_window { + let g = window::restore(w, saved_window); + app.ui.window = Some(g); #[cfg(windows)] set_taskbar_icon(w); } - // User Defined swatch and graphic style libraries live next to the preferences. + // Linux may not map the window before the first frames, so a saved maximize is retried then (#3635). + let pending_maximize = cfg!(target_os = "linux") && app.ui.window.as_ref().is_some_and(|g| g.maximized); + // User Defined swatch, graphic style, symbol and brush libraries live next to the preferences. let swatches = prefs_path().and_then(|p| Some(p.parent()?.join("Swatches").to_string_lossy().to_string())); app.session.swatch_libraries.set_user_dir(swatches); let styles = prefs_path().and_then(|p| Some(p.parent()?.join("Graphic Styles").to_string_lossy().to_string())); app.session.style_libraries.set_user_dir(styles); + let symbols = prefs_path().and_then(|p| Some(p.parent()?.join("Symbols").to_string_lossy().to_string())); + app.session.symbol_libraries.set_user_dir(symbols); + let brushes = prefs_path().and_then(|p| Some(p.parent()?.join("Brushes").to_string_lossy().to_string())); + app.session.brush_libraries.set_user_dir(brushes); // With the User Defined libraries listed, the persistent library panels reopen. vectorcraft_ui_egui::panels::library_panel::restore(&mut app); // So do the Libraries panel's libraries; runs without preferences (agents' test @@ -957,7 +448,7 @@ fn main() -> std::process::ExitCode { // Everywhere the app doesn't say whose work it is (worker threads), the // roots hold: unconfined is only what the person at the keyboard does. file_access::confine_process(roots.clone()); - log::info!("control channel confined to the automation roots: read {:?}, write {:?}", roots.read_root(), roots.write_root()); + log::info!("control channel confined to the automation roots: {}", roots.describe()); } } #[cfg(target_os = "macos")] @@ -970,13 +461,23 @@ fn main() -> std::process::ExitCode { } #[cfg(not(target_os = "macos"))] let _ = in_window_menus; + app.services.native_input_hook = native_input_hook(&app); file_access::unconfined(|| open_files(&mut app, files)); // The first frame is due from now (`gpu::watch_first_frame`). #[cfg(feature = "wgpu")] created.ready(); // The content and the pointer stay aligned on Windows (#1758). let window_frame = window_frame::service(cc, custom_titlebar); - Ok(Box::new(App { app, graphics_loss, graphics_lost: false, frames: 0, window_frame })) + Ok(Box::new(App { + app, + graphics_loss, + graphics_lost: false, + frames: 0, + window_frame, + winit_window, + pending_maximize, + maximize_tries: 8, + })) }), ) }); @@ -994,212 +495,4 @@ fn main() -> std::process::ExitCode { } #[cfg(all(test, feature = "wgpu"))] -mod tests { - use super::*; - - fn ui_state_with_prefs(engine_prefs: serde_json::Value) -> vectorcraft_ui_egui::UiState { - vectorcraft_ui_egui::UiState { engine_prefs, ..Default::default() } - } - - #[test] - fn unreadable_saved_docking_keeps_preferences_and_every_workspace() { - use serde_json::json; - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - app.run("window.panel.float", json!({"panel":"layers"})).unwrap(); - app.ui.toolbar = false; - app.ui.engine_prefs = json!({"interfaceLanguage":"fr", "uiBrightness":"light"}); - app.ui.custom_workspaces = - vec![vectorcraft_ui_egui::workspaces::capture(&app.ui, "Future"), vectorcraft_ui_egui::workspaces::capture(&app.ui, "Valid")]; - let original = serde_json::to_value(&app.ui).unwrap(); - let valid_location = original["docking_hidden"]["layers"].clone(); - assert!(valid_location.is_object()); - for invalid_layout in [json!({"root":{"FutureNode":{}},"floating":[]}), json!(false)] { - for invalid_hidden in [json!({"layers":{"placement":{"FuturePlacement":{}}},"swatches":valid_location}), json!(["malformed"])] { - let mut raw = original.clone(); - raw["docking"] = invalid_layout.clone(); - raw["docking_hidden"] = invalid_hidden.clone(); - raw["custom_workspaces"][0]["docking"] = invalid_layout.clone(); - raw["custom_workspaces"][0]["dockingHidden"] = invalid_hidden.clone(); - assert!(serde_json::from_value::(raw.clone()).is_err(), "runtime serde stays strict"); - let loaded = decode_saved_prefs(&serde_json::to_vec(&raw).unwrap()).unwrap(); - assert_eq!(loaded.engine_prefs, app.ui.engine_prefs); - assert!(!loaded.toolbar); - assert!(loaded.docking.is_none()); - assert!(!loaded.docking_hidden.contains_key("layers")); - if invalid_hidden.is_object() { - assert_eq!(serde_json::to_value(loaded.docking_hidden.get("swatches")).unwrap(), valid_location); - } else { - assert!(loaded.docking_hidden.is_empty()); - } - assert_eq!(loaded.custom_workspaces.len(), 2); - assert_eq!(loaded.custom_workspaces[0].name, "Future"); - assert!(loaded.custom_workspaces[0].docking.is_none()); - assert!(!loaded.custom_workspaces[0].docking_hidden.contains_key("layers")); - assert_eq!(serde_json::to_value(&loaded.custom_workspaces[1]).unwrap(), original["custom_workspaces"][1]); - } - } - let roundtrip = decode_saved_prefs(&serde_json::to_vec(&original).unwrap()).unwrap(); - assert_eq!(serde_json::to_value(roundtrip).unwrap(), original); - assert!( - decode_saved_prefs(&serde_json::to_vec(&json!({"toolbar":"invalid"})).unwrap()).is_none(), - "unrelated fields retain normal strict parsing" - ); - } - - #[test] - fn the_system_title_bar_preference_keeps_the_window_decorations() { - // Preferences › User Interface › System Title Bar gives the window back its system - // decorations on Windows and Linux; macOS always has them. - assert_eq!(super::custom_titlebar(None), super::CUSTOM_TITLEBAR, "no preferences: the default"); - let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false})); - assert_eq!(super::custom_titlebar(Some(&off)), super::CUSTOM_TITLEBAR); - let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true})); - assert!(!super::custom_titlebar(Some(&on))); - assert_eq!(super::native_options(false).viewport.decorations, Some(true)); - if super::CUSTOM_TITLEBAR { - assert_eq!(super::native_options(true).viewport.decorations, Some(false)); - } - } - - /// The file extensions the macOS bundle declares: its document types and its own exported type. - fn plist_extensions(plist: &str) -> Vec<&str> { - ["CFBundleTypeExtensions", "public.filename-extension"] - .iter() - .flat_map(|key| plist.split(key).skip(1)) - .filter_map(|rest| rest.split("").next()) - .flat_map(|array| array.split("").skip(1)) - .filter_map(|s| s.split("").next()) - .collect() - } - - /// Finder offers the app for every file File › Open reads (#295, #354) but those with an - /// extension in `UNASSOCIATED_EXTS`, takes over no other app's files, and hands them to the app - /// rather than to AppKit's document machinery. - #[test] - fn the_macos_bundle_opens_every_readable_format() { - let plist = include_str!("../../../packaging/macos/Info.plist.in"); - let declared = plist_extensions(plist); - for e in fileio::OPEN_EXTS.iter().filter(|e| !fileio::UNASSOCIATED_EXTS.contains(e)) { - assert!(declared.contains(e), "Info.plist.in doesn't declare .{e}"); - } - for e in &declared { - assert!(fileio::OPEN_EXTS.contains(e), "Info.plist.in declares .{e}, which the app doesn't open"); - } - assert!(!plist.contains("NSDocumentClass"), "not an NSDocument app: AppKit would refuse the files"); - let types = plist.matches("CFBundleTypeName").count(); - assert!(types > 1 && plist.matches("LSHandlerRank").count() == types, "every document type has a rank"); - assert_eq!(plist.matches("Owner").count(), 2, "only VectorCraft documents and templates are owned"); - } - - /// The MIME types a Linux desktop gives each extension in `OPEN_EXTS` but `UNASSOCIATED_EXTS` - /// (one row per type): shared-mime-info's, or one that `ai.storyteller.vectorcraft.mime.xml` - /// declares. - const LINUX_TYPES: &[(&str, &str)] = &[ - ("vectorcraft", "application/x-vectorcraft"), - ("drawcraft", "application/x-vectorcraft"), - ("svg", "image/svg+xml"), - ("svgz", "image/svg+xml-compressed"), - ("pdf", "application/pdf"), - ("ai", "application/illustrator"), // brand-ok: shared-mime-info's type - ("ait", "application/x-ai-template"), - ("png", "image/png"), - ("jpg", "image/jpeg"), - ("jpeg", "image/jpeg"), - ("gif", "image/gif"), - ("webp", "image/webp"), - ("tif", "image/tiff"), - ("tiff", "image/tiff"), - ("bmp", "image/bmp"), - ("vctemplate", "application/x-vectorcraft-template"), - ("dxf", "image/vnd.dxf"), - ("emf", "image/emf"), - ("wmf", "image/wmf"), - ("eps", "image/x-eps"), - ("af", "application/x-affinity"), - ("afdesign", "application/x-affinity"), - ("afpub", "application/x-affinity"), - ]; - - /// The types in `LINUX_TYPES` that shared-mime-info defines. The MIME package declares every - /// other one. - const LINUX_SHARED_TYPES: &[&str] = &[ - "image/svg+xml", - "image/svg+xml-compressed", - "application/pdf", - "application/illustrator", // brand-ok: shared-mime-info's type - "image/png", - "image/jpeg", - "image/gif", - "image/webp", - "image/tiff", - "image/bmp", - "image/vnd.dxf", - "image/emf", - "image/wmf", - "image/x-eps", - ]; - - /// Extensions in `LINUX_TYPES` whose type the MIME package matches by file content and not by a - /// glob, with the package's `` rule for that type (its lines joined, indentation removed). - const LINUX_BY_CONTENT: &[(&str, &str)] = &[( - "af", - // `MAGIC` at offset 0 and `DOCUMENT_KIND` at offset 8 (crates/affinity/src/container.rs). - r#""#, - )]; - - /// The desktop entry lists a MIME type for every extension in `OPEN_EXTS` but - /// `UNASSOCIATED_EXTS`, and the app's MIME package declares the types shared-mime-info doesn't - /// have. - #[test] - fn the_linux_desktop_entry_opens_every_readable_format() { - let desktop = include_str!("../../../packaging/linux/ai.storyteller.vectorcraft.desktop"); - let mime = include_str!("../../../packaging/linux/ai.storyteller.vectorcraft.mime.xml"); - let listed: Vec<&str> = - desktop.lines().find_map(|l| l.strip_prefix("MimeType=")).unwrap_or_default().split(';').filter(|t| !t.is_empty()).collect(); - // Each type the MIME package declares, with the extensions of its globs and its `` - // rule (empty when it has none) in the form `LINUX_BY_CONTENT` gives. - let declared: Vec<(&str, Vec<&str>, String)> = mime - .split("").next().unwrap_or_default(); - let globs = body.split("")) { - (Some(start), Some(end)) => body[start..end + "".len()].lines().map(str::trim).collect(), - _ => String::new(), - }; - (block.split('"').next().unwrap_or_default(), globs, magic) - }) - .collect(); - let mut associated: Vec<&str> = fileio::OPEN_EXTS.iter().copied().filter(|e| !fileio::UNASSOCIATED_EXTS.contains(e)).collect(); - let mut typed: Vec<&str> = LINUX_TYPES.iter().map(|(e, _)| *e).collect(); - associated.sort_unstable(); - typed.sort_unstable(); - typed.dedup(); - assert_eq!(typed, associated, "a MIME type for each extension the packaging associates with the app"); - for (e, t) in LINUX_TYPES { - assert!(listed.contains(t), "the desktop entry doesn't list {t} (.{e})"); - let package = declared.iter().find(|(name, ..)| name == t); - if LINUX_SHARED_TYPES.contains(t) { - assert!(package.is_none(), "{t} is shared-mime-info's, and the MIME package declares it again"); - continue; - } - let Some((_, globs, magic)) = package else { panic!("the MIME package doesn't declare {t} (.{e})") }; - if let Some((_, rule)) = LINUX_BY_CONTENT.iter().find(|(content, _)| content == e) { - assert!(!globs.contains(e), "{t} matches .{e} files by content only"); - assert_eq!(magic, rule, "{t}'s magic rule for .{e} files"); - } else { - assert!(globs.contains(e), "{t} has no *.{e} glob"); - } - } - for t in &listed { - assert!(LINUX_TYPES.iter().any(|(_, known)| known == t), "the desktop entry lists {t}, which the app doesn't open"); - } - for (t, globs, _) in &declared { - assert!(listed.contains(t), "the desktop entry doesn't list the declared {t}"); - for g in globs { - assert!(LINUX_TYPES.contains(&(*g, *t)), "{t}'s *.{g} isn't a file the app opens as {t}"); - } - } - } -} +mod tests; diff --git a/apps/vectorcraft/src/portal_save.rs b/apps/vectorcraft/src/portal_save.rs index c374c8949f..b6362107e5 100644 --- a/apps/vectorcraft/src/portal_save.rs +++ b/apps/vectorcraft/src/portal_save.rs @@ -326,7 +326,11 @@ mod tests { let pick = FilePick { name: "Untitled-1.vectorcraft".into(), folder: Some("/home/me/Art".into()), - filters: vec![("VectorCraft", &["vectorcraft"]), ("SVG", &["svg"]), ("PDF-compatible .ai", &["ai"])], + filters: vec![ + FilePick::filter("VectorCraft", &["vectorcraft"]), + FilePick::filter("SVG", &["svg"]), + FilePick::filter("PDF-compatible .ai", &["ai"]), + ], }; SaveRequest::new(&pick, "x11:3a0000f".into()) } diff --git a/apps/vectorcraft/src/prefs.rs b/apps/vectorcraft/src/prefs.rs new file mode 100644 index 0000000000..67a5a4a083 --- /dev/null +++ b/apps/vectorcraft/src/prefs.rs @@ -0,0 +1,107 @@ +use super::*; + +/// Where UI preferences live: ~/Library/Application Support/VectorCraft (macOS), +/// %APPDATA%\VectorCraft (Windows), $XDG_CONFIG_HOME or ~/.config/vectorcraft (Linux). +pub(crate) fn prefs_path() -> Option { + prefs_dir::prefs_path_for("VectorCraft", "vectorcraft") +} + +/// The same place under the project's former name (DrawCraft): read once if there are no +/// VectorCraft preferences yet, so settings survive the rename. +fn legacy_prefs_path() -> Option { + prefs_dir::prefs_path_for("DrawCraft", "drawcraft") +} + +/// Where the log files live: `logs` in the preferences folder (see `logging`). +pub(crate) fn log_dir() -> Option { + Some(prefs_path()?.parent()?.join("logs")) +} + +/// Runs without preferences (`VECTORCRAFT_NO_PREFS`, agents' test runs) neither read nor write them. +pub(crate) fn prefs_enabled() -> bool { + std::env::var_os("VECTORCRAFT_NO_PREFS").is_none() +} + +/// The saved UI preferences, read before the window opens (they hold its size and position). +/// A file read only in part, or with layouts converted from an older version, is copied beside +/// itself before anything saves over it. +pub(crate) fn read_prefs() -> Option { + if !prefs_enabled() { + return None; + } + if let Some(p) = prefs_path() + && let Ok(bytes) = std::fs::read(&p) + { + let read = vectorcraft_ui_egui::UiState::read_preferences(&bytes); + if read.as_ref().is_none_or(|read| !read.intact) { + keep_prefs_copy(&p, &bytes, "ui.unreadable"); + } + if read.as_ref().is_some_and(|read| read.converted) { + keep_prefs_copy(&p, &bytes, "ui.before-layout-migration"); + } + return read.map(|read| read.ui); + } + let bytes = legacy_prefs_path().and_then(|p| std::fs::read(p).ok())?; + decode_saved_prefs(&bytes) +} + +/// Saved preferences, with what this version cannot read of their docking data dropped and +/// older layouts converted (`vectorcraft_ui_egui::layout_migration`). +pub(crate) fn decode_saved_prefs(bytes: &[u8]) -> Option { + vectorcraft_ui_egui::UiState::read_preferences(bytes).map(|read| read.ui) +} + +/// Set when `ui.json` needed a copy kept ([`keep_prefs_copy`]) and none could be: the file is +/// then left as it is rather than overwritten. +pub(crate) static KEEP_UI_PREFS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Copy `ui.json` beside it as `.json` or the first free `-N.json`, before the next +/// save replaces it: `ui.unreadable` when it could not be read in full (a newer VectorCraft may +/// have written it), `ui.before-layout-migration` when its layouts were converted. +pub(crate) fn keep_prefs_copy(path: &std::path::Path, bytes: &[u8], stem: &str) { + use std::io::Write as _; + for n in 1..100u32 { + let name = if n == 1 { format!("{stem}.json") } else { format!("{stem}-{n}.json") }; + match std::fs::OpenOptions::new().write(true).create_new(true).open(path.with_file_name(name)) { + Ok(mut file) => { + if file.write_all(bytes).is_ok() { + return; + } + break; + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(_) => break, + } + } + KEEP_UI_PREFS.store(true, std::sync::atomic::Ordering::Relaxed); +} + +pub(crate) fn load_prefs(app: &mut VectorcraftApp, saved: Option) { + if !prefs_enabled() { + return; + } + if let Some(ui) = saved { + app.ui = ui.sanitized(); + } + vectorcraft_ui_egui::prefs_dialog::restore(app); +} + +pub(crate) fn save_prefs(app: &VectorcraftApp) { + if !prefs_enabled() || KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + if let Some(p) = prefs_path() { + let _ = std::fs::create_dir_all(p.parent().unwrap_or(std::path::Path::new("."))); + if let Ok(bytes) = prefs_bytes(app) { + // Preferences are best effort: a failed write keeps the previous file. + let _ = fileio::write_atomic(&p, &bytes); + } + } +} + +/// The preferences file's contents: the UI state with the engine preferences. +pub(crate) fn prefs_bytes(app: &VectorcraftApp) -> serde_json::Result> { + let mut ui = app.ui.clone(); + ui.engine_prefs = app.session.prefs.to_json(); + serde_json::to_vec_pretty(&ui) +} diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 643e64c694..c9e6539a26 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -23,6 +23,11 @@ impl PrintService for SystemPrint { fn shared_print(&self) -> Option { Some(std::sync::Arc::new(|job| SystemPrint.print(job))) } + fn turns_landscape(&self) -> bool { + // macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright + // paper. craft-print turns each sheet to its own orientation on Windows. + !cfg!(target_os = "macos") + } fn has_setup(&self) -> bool { true } @@ -127,3 +132,14 @@ mod tests { assert_eq!(args, ["ms-settings:printers"]); } } + +#[cfg(test)] +mod turn_tests { + use super::SystemPrint; + use vectorcraft_ui_egui::print::PrintService; + + #[test] + fn only_macos_queues_need_landscape_pages_turned() { + assert_eq!(SystemPrint.turns_landscape(), !cfg!(target_os = "macos")); + } +} diff --git a/apps/vectorcraft/src/system_fonts.rs b/apps/vectorcraft/src/system_fonts.rs index 6752aef676..67bbf7843a 100644 --- a/apps/vectorcraft/src/system_fonts.rs +++ b/apps/vectorcraft/src/system_fonts.rs @@ -1,39 +1,56 @@ -//! Windows: the font files in DirectWrite's system font collection, scanned with the font folders -//! (`vectorcraft_text::set_platform_font_files`). The desktop app and `vectorcraft-cli` (exports, -//! MCP) both install it; the CLI shares this file. +//! Windows: the font files in DirectWrite's system font collection and those of the fonts GDI has +//! loaded, scanned with the font folders (`vectorcraft_text::set_platform_font_files`). The desktop +//! app and `vectorcraft-cli` (exports, MCP) both install it; the CLI shares this file. //! //! Font services such as Adobe Fonts load their fonts with GDI at run time, from files in their //! own folders, without installing them: the font folders and the registry don't list them. Since -//! Windows 10 (version 1607) DirectWrite's system font collection holds them too +//! Windows 10 (version 1607) DirectWrite's system font collection is meant to hold them too //! (, //! "Support for Adobe Typekit and other font-service clients"), so VectorCraft lists them as other -//! apps do, reading the files in place (#579). +//! apps do, reading the files in place (#579). It doesn't always: on some machines the fonts +//! Creative Cloud loads are in GDI's font list (Word and the font dialogs show them) but not in +//! the collection (#1258). So the families GDI lists that the collection doesn't name are asked +//! for one by one: a GDI font selected into a device context gives the DirectWrite font face +//! GDI uses (`IDWriteGdiInterop::CreateFontFaceFromHdc`), and that face its files. //! -//! DirectWrite is COM, which has no safe API, hence the scoped `unsafe_code` allowance. +//! DirectWrite is COM and GDI a C API, neither with a safe API, hence the scoped `unsafe_code` +//! allowance. #![allow(unsafe_code)] -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Mutex; +use windows::Win32::Foundation::LPARAM; use windows::Win32::Graphics::DirectWrite::{ - DWRITE_FACTORY_TYPE_SHARED, DWriteCreateFactory, IDWriteFactory3, IDWriteFontSet, IDWriteLocalFontFileLoader, + DWRITE_FACTORY_TYPE_SHARED, DWRITE_FONT_PROPERTY_ID_WIN32_FAMILY_NAME, DWriteCreateFactory, IDWriteFactory3, IDWriteFontFile, IDWriteFontSet, + IDWriteGdiInterop, IDWriteLocalFontFileLoader, IDWriteStringList, +}; +use windows::Win32::Graphics::Gdi::{ + CreateCompatibleDC, CreateFontIndirectW, DEFAULT_CHARSET, DeleteDC, DeleteObject, EnumFontFamiliesExW, HDC, HGDIOBJ, LOGFONTW, RASTER_FONTTYPE, + SelectObject, TEXTMETRICW, }; use windows::core::Interface; /// The most fonts read from the collection (a system has a few thousand). const MAX_FONTS: u32 = 1 << 16; +/// The most families and faces taken from GDI's font list. +const MAX_GDI_FONTS: usize = 1 << 16; +/// The most files one font face is made of (one, but for a few Type 1 fonts). +const MAX_FACE_FILES: u32 = 8; /// The longest file path taken, in UTF-16 units (Windows' own limit). const MAX_PATH: u32 = 32_767; -/// Have the font scans read the font files DirectWrite lists. +/// Have the font scans read the font files DirectWrite and GDI list. pub fn install() { vectorcraft_text::set_platform_font_files(font_files); } /// The local files of the fonts in DirectWrite's system font collection as it is now (fonts -/// loaded since the last call included). None before Windows 10, or when DirectWrite fails: the -/// font folders and the registry still list the installed fonts. +/// loaded since the last call included), with those of the fonts GDI lists that the collection +/// leaves out. None before Windows 10, or when DirectWrite fails: the font folders and the +/// registry still list the installed fonts. fn font_files() -> Vec { - match collection_files() { + match listed_files() { Ok(files) => files.into_iter().collect(), Err(e) => { log::debug!("DirectWrite's system fonts aren't listed: {e}"); @@ -42,30 +59,48 @@ fn font_files() -> Vec { } } -fn collection_files() -> windows::core::Result> { +fn listed_files() -> windows::core::Result> { // SAFETY: plain DirectWrite calls on interfaces it returned, each checked for failure; the // collection is asked to check for fonts loaded since the factory last looked. - let set = unsafe { + let (factory, set) = unsafe { let factory: IDWriteFactory3 = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)?; let mut collection = None; factory.GetSystemFontCollection(false, &mut collection, true)?; - let Some(collection) = collection else { return Ok(BTreeSet::new()) }; - collection.GetFontSet()? + (factory, collection.map(|c| c.GetFontSet()).transpose()?) }; + let mut files = set.as_ref().map(collection_files).unwrap_or_default(); + // GDI's own names for the collection's families, the names GDI lists them by. + // SAFETY: a list DirectWrite returns, read by `strings`. + let named = set.as_ref().and_then(|s| unsafe { s.GetPropertyValues(DWRITE_FONT_PROPERTY_ID_WIN32_FAMILY_NAME) }.ok()); + let named: BTreeSet = named.as_ref().map(strings).unwrap_or_default().iter().map(|n| n.to_lowercase()).collect(); + match gdi_files(&factory, &named) { + Ok(more) => files.extend(more), + Err(e) => log::debug!("GDI's fonts aren't listed: {e}"), + } + Ok(files) +} + +fn collection_files(set: &IDWriteFontSet) -> BTreeSet { // SAFETY: a count of the set's fonts. let count = unsafe { set.GetFontCount() }.min(MAX_FONTS); // Faces of one file (a collection's, a variable font's instances) name it once. - Ok((0..count).filter_map(|i| local_path(&set, i)).collect()) + (0..count).filter_map(|i| local_path(set, i)).collect() } /// The path of the file holding font `i` of `set`, when it is a local file (not a downloadable /// font, nor one in memory). fn local_path(set: &IDWriteFontSet, i: u32) -> Option { - // SAFETY: `i` is below the set's count; the key DirectWrite hands back stays valid while - // `file` (which owns it) lives, and is passed back with its own size; the path buffer is - // sized from DirectWrite's answer plus the terminating NUL. + // SAFETY: `i` is below the set's count. + let file = unsafe { set.GetFontFaceReference(i).ok()?.GetFontFile().ok()? }; + file_path(&file) +} + +/// The path of `file`, when it is a local file. +fn file_path(file: &IDWriteFontFile) -> Option { + // SAFETY: the key DirectWrite hands back stays valid while `file` (which owns it) lives, and is + // passed back with its own size; the path buffer is sized from DirectWrite's answer plus the + // terminating NUL. unsafe { - let file = set.GetFontFaceReference(i).ok()?.GetFontFile().ok()?; let loader: IDWriteLocalFontFileLoader = file.GetLoader().ok()?.cast().ok()?; let (mut key, mut size) = (std::ptr::null_mut(), 0u32); file.GetReferenceKey(&mut key, &mut size).ok()?; @@ -79,6 +114,159 @@ fn local_path(set: &IDWriteFontSet, i: u32) -> Option { } } +/// The strings of `list`. +fn strings(list: &IDWriteStringList) -> Vec { + // SAFETY: indices below the list's count; each buffer is sized from DirectWrite's answer plus + // the terminating NUL. + let count = unsafe { list.GetCount() }.min(MAX_FONTS); + (0..count) + .filter_map(|i| unsafe { + let len = list.GetStringLength(i).ok()?; + if len > MAX_PATH { + return None; + } + let mut s = vec![0u16; len as usize + 1]; + list.GetString(i, &mut s).ok()?; + Some(String::from_utf16_lossy(s.get(..len as usize)?)) + }) + .collect() +} + +/// A memory device context, deleted when dropped. +struct MemoryDc(HDC); + +impl MemoryDc { + fn new() -> windows::core::Result { + // SAFETY: a device context compatible with the screen, owned by the guard. + let dc = unsafe { CreateCompatibleDC(None) }; + if dc.is_invalid() { Err(windows::core::Error::from_thread()) } else { Ok(Self(dc)) } + } +} + +impl Drop for MemoryDc { + fn drop(&mut self) { + // SAFETY: the guard's own device context, with its first font back in it. + // Failing to delete it leaks a handle, which there's nothing to do about. + let _ = unsafe { DeleteDC(self.0) }; + } +} + +/// The files of the faces of the font families GDI lists that DirectWrite's collection doesn't +/// name (`named`, lower case). +fn gdi_files(factory: &IDWriteFactory3, named: &BTreeSet) -> windows::core::Result> { + // SAFETY: a DirectWrite call checked for failure. + let interop = unsafe { factory.GetGdiInterop()? }; + let dc = MemoryDc::new()?; + let mut families = BTreeSet::new(); + enum_fonts(&dc, [0; 32], add_family, &mut families); + let mut faces = Vec::new(); + for family in families.iter().filter(|f| !named.contains(&face_name(f).to_lowercase())) { + enum_fonts(&dc, *family, add_face, &mut faces); + } + // A face listed once for each of its character sets is read once. + faces.sort_by_key(face_key); + faces.dedup_by_key(|f| face_key(f)); + // Asking for a face's files takes about a third of a millisecond, and the fonts are looked at + // every few seconds (#2576): the faces still listed keep the files they had while those exist. + // A face no longer listed is forgotten, so one activated again is asked for anew, and one + // whose files couldn't be read (GDI or DirectWrite failed, or it has no local file) is asked + // again at the next look. + let mut known = KNOWN_FACES.lock().unwrap_or_else(|e| e.into_inner()); + let mut now = BTreeMap::new(); + for f in &faces { + let key = face_key(f); + let files = match known.remove(&key) { + Some(files) if !files.is_empty() && files.iter().all(|p| std::path::Path::new(p).is_file()) => files, + _ => face_files(&interop, &dc, f), + }; + now.insert(key, files); + } + *known = now; + Ok(known.values().flatten().cloned().collect()) +} + +/// A GDI face: its name (NUL-padded), weight and whether it's italic. +type FaceKey = ([u16; 32], i32, u8); + +fn face_key(f: &LOGFONTW) -> FaceKey { + (f.lfFaceName, f.lfWeight, f.lfItalic) +} + +/// The files of the faces GDI listed at the last look ([`gdi_files`]). +static KNOWN_FACES: Mutex>> = Mutex::new(BTreeMap::new()); + +/// Have GDI call `add` with `out` for each font of the family named `family` (NUL-padded), or for +/// one font of each family when it's empty. +fn enum_fonts( + dc: &MemoryDc, + family: [u16; 32], + add: unsafe extern "system" fn(*const LOGFONTW, *const TEXTMETRICW, u32, LPARAM) -> i32, + out: &mut T, +) { + let query = LOGFONTW { lfCharSet: DEFAULT_CHARSET, lfFaceName: family, ..Default::default() }; + // SAFETY: `add` reads the fonts GDI passes and casts the LPARAM back to the `T` it is, which + // outlives the call (GDI calls back before returning). Its answer is the last callback's. + let _ = unsafe { EnumFontFamiliesExW(dc.0, &query, Some(add), LPARAM(std::ptr::from_mut(out) as isize), 0) }; +} + +/// A GDI font list callback adding the font's family name to the `BTreeSet<[u16; 32]>` in `out`. +unsafe extern "system" fn add_family(font: *const LOGFONTW, _: *const TEXTMETRICW, kind: u32, out: LPARAM) -> i32 { + // SAFETY: GDI passes a valid font, and `out` is the set `enum_fonts` was given. + let (Some(font), Some(out)) = (unsafe { font.as_ref() }, unsafe { (out.0 as *mut BTreeSet<[u16; 32]>).as_mut() }) else { + return 0; + }; + // Bitmap fonts have no file DirectWrite reads; `@` names are vertical writing's copies. + if kind & RASTER_FONTTYPE == 0 && font.lfFaceName.first().is_some_and(|&c| c != 0 && c != u16::from(b'@')) { + out.insert(font.lfFaceName); + } + i32::from(out.len() < MAX_GDI_FONTS) +} + +/// A GDI font list callback adding the font to the `Vec` in `out`. +unsafe extern "system" fn add_face(font: *const LOGFONTW, _: *const TEXTMETRICW, kind: u32, out: LPARAM) -> i32 { + // SAFETY: GDI passes a valid font, and `out` is the list `enum_fonts` was given. + let (Some(font), Some(out)) = (unsafe { font.as_ref() }, unsafe { (out.0 as *mut Vec).as_mut() }) else { + return 0; + }; + if kind & RASTER_FONTTYPE == 0 { + out.push(*font); + } + i32::from(out.len() < MAX_GDI_FONTS) +} + +/// `name`, NUL-padded, as a string. +fn face_name(name: &[u16; 32]) -> String { + String::from_utf16_lossy(name.split(|&c| c == 0).next().unwrap_or_default()) +} + +/// The local files of the DirectWrite font face GDI uses for `font`. +fn face_files(interop: &IDWriteGdiInterop, dc: &MemoryDc, font: &LOGFONTW) -> Vec { + // SAFETY: the font is selected into the guard's device context only while DirectWrite reads + // it, then the context's own font goes back and the font is deleted; the files array is + // sized from DirectWrite's count. + unsafe { + let gdi_font = CreateFontIndirectW(font); + if gdi_font.is_invalid() { + return Vec::new(); + } + let first = SelectObject(dc.0, HGDIOBJ::from(gdi_font)); + let face = interop.CreateFontFaceFromHdc(dc.0); + SelectObject(dc.0, first); + // Failing to delete it leaks a handle, which there's nothing to do about. + let _ = DeleteObject(HGDIOBJ::from(gdi_font)); + let Ok(face) = face else { return Vec::new() }; + let mut count = 0; + if face.GetFiles(&mut count, None).is_err() || count == 0 || count > MAX_FACE_FILES { + return Vec::new(); + } + let mut files = vec![None; count as usize]; + if face.GetFiles(&mut count, Some(files.as_mut_ptr())).is_err() { + return Vec::new(); + } + files.iter().flatten().filter_map(file_path).collect() + } +} + #[cfg(test)] mod tests { /// DirectWrite lists the installed fonts, by their files' full paths. @@ -89,4 +277,34 @@ mod tests { let fonts = std::path::Path::new(&std::env::var("WINDIR").unwrap()).join("Fonts").to_string_lossy().to_lowercase(); assert!(files.iter().any(|f| f.to_lowercase().starts_with(&fonts)), "{} files, {:?}", files.len(), files.first()); } + + /// A font loaded with GDI from a file without an extension outside the font folders, as + /// Creative Cloud loads Adobe Fonts, is listed by its file even though DirectWrite's collection + /// doesn't hold it (#1258): fonts loaded for one process never are. + #[test] + fn fonts_only_gdi_has_loaded_are_listed_by_their_files() { + use windows::Win32::Graphics::Gdi::{AddFontResourceExW, FR_PRIVATE, RemoveFontResourceExW}; + let dir = std::env::temp_dir().join(format!("vc-gdi-fonts-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("29457"); + let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf"); + let mut data = std::fs::read(source).unwrap(); + // Renamed (to a name as long) so no installed Source Sans 3 stands in for it. + let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); + for (from, to) in [(utf16("Source Sans 3"), utf16("GdiOnly Sans3")), (b"Source Sans 3".to_vec(), b"GdiOnly Sans3".to_vec())] { + let mut i = 0; + while let Some(at) = data[i..].windows(from.len()).position(|w| w == from) { + data[i + at..i + at + to.len()].copy_from_slice(&to); + i += at + to.len(); + } + } + std::fs::write(&file, data).unwrap(); + let path = windows::core::HSTRING::from(file.as_os_str()); + assert_eq!(unsafe { AddFontResourceExW(&path, FR_PRIVATE, None) }, 1); + let files = super::font_files(); + let _ = unsafe { RemoveFontResourceExW(&path, FR_PRIVATE.0, None) }; + let _ = std::fs::remove_dir_all(&dir); + let wanted = file.to_string_lossy().to_lowercase(); + assert!(files.iter().any(|f| f.to_lowercase() == wanted), "{wanted} not in {} files", files.len()); + } } diff --git a/apps/vectorcraft/src/tablet.rs b/apps/vectorcraft/src/tablet.rs new file mode 100644 index 0000000000..f2c1fd7251 --- /dev/null +++ b/apps/vectorcraft/src/tablet.rs @@ -0,0 +1,417 @@ +//! Linux: a drawing tablet's pen pressure under X11, XWayland included (#764). winit 0.30 hands a +//! pen to the window there as a mouse, without its pressure, so the app reads the pressure from +//! XInput2 itself and writes it into the UI's [`StylusFeed`] (`Services::stylus`), which the canvas +//! reads. +//! +//! The reader opens a second connection to the X server (x11rb's `RustConnection`, without +//! `unsafe` or libxcb) and selects XInput2 raw events for every device on the root window. Raw +//! events reach every client that selects them, also while winit holds the pointer grab of a +//! drag, and name the device that moved. A pointer device with an "Abs Pressure" valuator is a pen +//! (xf86-input-wacom, xf86-input-libinput and XWayland give a pen's pressure axis that label), +//! unless its XInput type is a touchpad's or a touchscreen's: its pressure, scaled from the +//! valuator's range to 0..1, goes into the feed. Any other pointer +//! device moving sets the feed to `None`. Raw events carry only the valuators that changed, so +//! the last pressure of each pen is kept. +//! +//! The X server lists a pen's eraser end as a device of its own, whose name or XInput type contains +//! "eraser" (xf86-input-wacom's "… Pen eraser" of type `ERASER`, xf86-input-libinput's +//! "… Eraser (0x…)" of type `ERASER`, XWayland's "xwayland-tablet eraser:N"). Its samples go into +//! the feed marked as the eraser end, and the canvas switches to the Eraser tool +//! ([`vectorcraft_ui_egui::stylus`]). +//! +//! The reader starts only for a window on X11. On native Wayland, `DISPLAY` names an XWayland +//! that receives none of the window's input. +//! +//! The mapping and the reader come from PhotoCraft's `crates/tablet` (`xi.rs` and `x11.rs`), with +//! the pressure axis only. +#![cfg_attr(not(target_os = "linux"), allow(dead_code))] + +use std::collections::HashMap; + +use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed}; + +/// Valuator numbers from this one on are ignored (the protocol allows 65,535; tablets have fewer +/// than 16). +const MAX_AXES: u16 = 64; + +/// Devices kept (a server could list thousands). +const MAX_DEVICES: usize = 256; + +/// The XInput types of finger devices (`XI_TOUCHPAD` and `XI_TOUCHSCREEN`): xf86-input-evdev labels +/// a touchpad's or a touchscreen's pressure axis "Abs Pressure" too, and they are not pens. +const FINGER_TYPES: &[&str] = &["TOUCHPAD", "TOUCHSCREEN"]; + +/// The "Abs Pressure" valuator of a pen: its number in a raw event's valuator mask, and its range. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Axis { + number: u16, + min: f64, + max: f64, +} + +impl Axis { + /// A raw value of this valuator as a pressure of 0..1; a value that is not a number is a + /// mouse's, 1. + fn pressure(&self, v: f64) -> f32 { + if !v.is_finite() { + return 1.0; + } + let span = self.max - self.min; + let unit = if span.is_finite() && span > 0.0 { (v - self.min) / span } else { v }; + unit.clamp(0.0, 1.0) as f32 + } +} + +/// A pointer device the X server lists. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Device { + id: u16, + /// The pressure valuator: a pen has one, a mouse, a touchpad or a touchscreen has none. + pressure: Option, + /// The eraser end of a pen: its name or its XInput type contains "eraser", in any case. + eraser: bool, +} + +impl Device { + /// From what the X server lists for the device: its name and each valuator's number, label, + /// minimum and maximum (`XIQueryDevice`), and its XInput type (`ListInputDevices`). + fn new(id: u16, name: &str, kind: Option<&str>, valuators: impl IntoIterator) -> Self { + let finger = kind.is_some_and(|k| FINGER_TYPES.contains(&k)); + let pressure = valuators + .into_iter() + .filter(|(number, ..)| *number < MAX_AXES) + .find(|(_, label, ..)| label == "Abs Pressure") + .map(|(number, _, min, max)| Axis { number, min, max }) + .filter(|_| !finger); + let eraser = [Some(name), kind].into_iter().flatten().any(|s| s.to_ascii_lowercase().contains("eraser")); + Self { id, pressure, eraser } + } +} + +/// What a raw event means for the feed. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Update { + /// Nothing: a device the last listing didn't have (a master, or one added since). + Keep, + /// The pressure and end of a pen, or `None` for another pointer. + Set(Option), +} + +/// The pointer devices and the last pressure of each pen. +#[derive(Debug, Default)] +struct Pens { + devices: HashMap, + last: HashMap, +} + +impl Pens { + /// Replace the device list (at the start, and when devices come and go or change). + fn set_devices(&mut self, devices: impl IntoIterator) { + self.devices = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect(); + self.last.retain(|id, _| self.devices.contains_key(id)); + } + + /// A raw motion or button event of device `id`, with the valuators that changed. + fn handle(&mut self, id: u16, valuators: impl IntoIterator) -> Update { + let Some(device) = self.devices.get(&id) else { return Update::Keep }; + let Some(axis) = device.pressure else { return Update::Set(None) }; + let eraser = device.eraser; + let last = self.last.entry(id).or_insert(0.0); + for (number, v) in valuators { + if number == axis.number { + *last = axis.pressure(v); + } + } + Update::Set(Some(PenSample { pressure: *last, eraser })) + } + + /// A raw event as the X server sends it: its valuator mask and the values of the valuators + /// set in it. A pen's sample or another pointer's `None` goes into `feed`. + fn raw_event(&mut self, feed: &StylusFeed, id: u16, mask: &[u32], values: &[f64]) { + if let Update::Set(sample) = self.handle(id, valuators(mask, values)) { + feed.set_sample(sample); + } + } +} + +/// The values a raw event carries: the valuator numbers set in `mask` (32 to a word, lowest bit +/// first), each paired in order with one of `values`. Mask bits past the last value are ignored. +fn valuators<'a>(mask: &'a [u32], values: &'a [f64]) -> impl Iterator + 'a { + let numbers = mask + .iter() + .enumerate() + .flat_map(|(w, bits)| (0..32u32).filter(move |b| bits & (1 << b) != 0).map(move |b| w.saturating_mul(32).saturating_add(b as usize))); + numbers.zip(values.iter().copied()).filter_map(|(n, v)| u16::try_from(n).ok().map(|n| (n, v))) +} + +/// An X 32.32 fixed-point value. +fn fp3232(integral: i32, frac: u32) -> f64 { + f64::from(integral) + f64::from(frac) / 4_294_967_296.0 +} + +/// Start reading pen pressure for a window on X11: the feed the reader writes into, or `None` +/// (logged) when the X server can't be reached or has no XInput 2.1. +#[cfg(target_os = "linux")] +pub fn start() -> Option { + let feed = StylusFeed::default(); + match x11::spawn(feed.clone()) { + Ok(()) => Some(feed), + Err(e) => { + log::warn!("tablet pressure: {e}"); + None + } + } +} + +#[cfg(target_os = "linux")] +mod x11 { + use std::collections::HashMap; + + use vectorcraft_ui_egui::stylus::StylusFeed; + use x11rb::connection::{Connection as _, RequestConnection as _}; + use x11rb::protocol::Event; + use x11rb::protocol::xinput::{self, ConnectionExt as _, DeviceClassData, DeviceType, XIEventMask}; + use x11rb::protocol::xproto::ConnectionExt as _; + use x11rb::rust_connection::RustConnection; + + use super::{Device, MAX_AXES, MAX_DEVICES, Pens, fp3232}; + + /// `XIAllDevices`: every device, the slave devices that name a pen included. + const ALL_DEVICES: u16 = 0; + + /// Connect to `$DISPLAY` (the display winit opened the window on), check for XInput 2.1 (raw + /// events for every client that selects them), select the raw events, and read them on a + /// thread of its own until the connection closes. + pub fn spawn(feed: StylusFeed) -> Result<(), String> { + let (conn, screen) = RustConnection::connect(None).map_err(|e| format!("can't connect to the X server: {e}"))?; + let root = conn.setup().roots.get(screen).map(|s| s.root).ok_or_else(|| format!("X screen {screen} not found"))?; + let version = + conn.xinput_xi_query_version(2, 2).map_err(|e| e.to_string())?.reply().map_err(|e| format!("the X server has no XInput 2: {e}"))?; + if (version.major_version, version.minor_version) < (2, 1) { + return Err(format!("the X server has XInput {}.{}, and raw events need 2.1", version.major_version, version.minor_version)); + } + let mask = XIEventMask::RAW_MOTION + | XIEventMask::RAW_BUTTON_PRESS + | XIEventMask::RAW_BUTTON_RELEASE + | XIEventMask::HIERARCHY + | XIEventMask::DEVICE_CHANGED; + conn.xinput_xi_select_events(root, &[xinput::EventMask { deviceid: ALL_DEVICES, mask: vec![mask] }]) + .map_err(|e| e.to_string())? + .check() + .map_err(|e| format!("XISelectEvents failed: {e}"))?; + let mut pens = Pens::default(); + pens.set_devices(query_devices(&conn)); + std::thread::Builder::new() + .name("vectorcraft-tablet-x11".into()) + .spawn(move || run(&conn, &mut pens, &feed)) + .map(drop) + .map_err(|e| format!("can't start the tablet thread: {e}")) + } + + fn run(conn: &RustConnection, pens: &mut Pens, feed: &StylusFeed) { + // A connection error (the display went away) ends the loop; an event that x11rb cannot + // parse is skipped, and `Pens` bounds what the rest can hold. + while let Ok(raw) = conn.wait_for_raw_event() { + let Ok(event) = conn.parse_event(&raw) else { continue }; + match event { + Event::XinputRawMotion(e) | Event::XinputRawButtonPress(e) | Event::XinputRawButtonRelease(e) => { + let values: Vec = e.axisvalues.iter().map(|v| fp3232(v.integral, v.frac)).collect(); + pens.raw_event(feed, e.deviceid, &e.valuator_mask, &values); + } + Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => pens.set_devices(query_devices(conn)), + _ => {} + } + } + } + + /// The slave pointer devices with their names and pressure valuators (none on any error). + fn query_devices(conn: &RustConnection) -> Vec { + let Ok(reply) = conn.xinput_xi_query_device(ALL_DEVICES).map_err(drop).and_then(|c| c.reply().map_err(drop)) else { return Vec::new() }; + let kinds = device_kinds(conn); + let mut out = Vec::new(); + for info in reply.infos.iter().take(MAX_DEVICES) { + if info.type_ != DeviceType::SLAVE_POINTER && info.type_ != DeviceType::FLOATING_SLAVE { + continue; + } + let valuators = info.classes.iter().take(usize::from(MAX_AXES)).filter_map(|c| match &c.data { + DeviceClassData::Valuator(v) => { + let label = atom_name(conn, v.label)?; + Some((v.number, label, fp3232(v.min.integral, v.min.frac), fp3232(v.max.integral, v.max.frac))) + } + _ => None, + }); + let name = String::from_utf8_lossy(&info.name); + out.push(Device::new(info.deviceid, &name, kinds.get(&info.deviceid).map(String::as_str), valuators.collect::>())); + } + out + } + + /// Each device's XInput type name, by device id (none on any error). + fn device_kinds(conn: &RustConnection) -> HashMap { + let Ok(reply) = conn.xinput_list_input_devices().map_err(drop).and_then(|c| c.reply().map_err(drop)) else { return HashMap::new() }; + reply.devices.iter().take(MAX_DEVICES).filter_map(|d| Some((u16::from(d.device_id), atom_name(conn, d.device_type)?))).collect() + } + + fn atom_name(conn: &RustConnection, atom: u32) -> Option { + if atom == 0 { + return None; + } + let reply = conn.get_atom_name(atom).ok()?.reply().ok()?; + Some(String::from_utf8_lossy(&reply.name).into_owned()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The valuators of a Wacom pen as the X server lists them: x and y, then pressure from 0 to + /// 65,535. + fn pen_valuators() -> Vec<(u16, String, f64, f64)> { + vec![ + (0, "Abs X".to_string(), 0.0, 44704.0), + (1, "Abs Y".to_string(), 0.0, 27940.0), + (2, "Abs Pressure".to_string(), 0.0, 65535.0), + (3, "Abs Tilt X".to_string(), -64.0, 63.0), + ] + } + + fn pen(id: u16) -> Device { + Device::new(id, "Wacom Intuos Pro M Pen stylus", Some("STYLUS"), pen_valuators()) + } + + fn mouse(id: u16) -> Device { + Device::new(id, "Logitech USB Optical Mouse", Some("MOUSE"), [(0, "Rel X".to_string(), -1.0, -1.0), (1, "Rel Y".to_string(), -1.0, -1.0)]) + } + + #[test] + fn the_mask_pairs_valuator_numbers_with_values() { + let v: Vec<_> = valuators(&[0b10_0101, 1], &[1.0, 2.0, 3.0, 4.0]).collect(); + assert_eq!(v, vec![(0, 1.0), (2, 2.0), (5, 3.0), (32, 4.0)]); + // Fewer values than mask bits (malformed): the values that are there. + assert_eq!(valuators(&[u32::MAX; 4], &[7.0]).count(), 1); + assert_eq!(valuators(&[], &[7.0]).count(), 0); + } + + #[test] + fn a_device_with_an_abs_pressure_valuator_is_a_pen() { + assert_eq!(pen(9).pressure, Some(Axis { number: 2, min: 0.0, max: 65535.0 })); + assert_eq!(mouse(12).pressure, None); + let pad = Device::new(13, "Wacom Intuos Pro M Pad pad", Some("PAD"), [(5, "Abs Wheel".to_string(), 0.0, 71.0)]); + assert_eq!(pad.pressure, None, "a tablet's pad is no pen"); + let far = Device::new(14, "", Some("STYLUS"), [(MAX_AXES, "Abs Pressure".to_string(), 0.0, 1.0)]); + assert_eq!(far.pressure, None, "valuator numbers past the limit are ignored"); + // The types libinput and XWayland give pens, and a device whose type wasn't listed. + for kind in [Some("TABLET"), Some("ERASER"), Some("xwayland-tablet stylus"), None] { + assert!(Device::new(15, "", kind, pen_valuators()).pressure.is_some(), "{kind:?}"); + } + // xf86-input-evdev labels a touchpad's and a touchscreen's finger pressure "Abs Pressure". + for kind in ["TOUCHPAD", "TOUCHSCREEN"] { + assert_eq!(Device::new(16, "", Some(kind), pen_valuators()).pressure, None, "{kind}"); + } + } + + /// The eraser end of a pen is a device of its own, whose name or XInput type contains + /// "eraser", as xf86-input-wacom, xf86-input-libinput and XWayland list it. + #[test] + fn an_eraser_device_is_named_so() { + let erasers = [ + ("Wacom Intuos Pro M Pen eraser", Some("ERASER")), + ("HUION Kamvas Pen Eraser (0x1)", Some("ERASER")), + ("xwayland-tablet eraser:16", Some("xwayland-tablet eraser")), + ("Wacom Intuos Pro M Pen eraser", None), + ("Tablet Pen (0x2)", Some("ERASER")), + ]; + for (name, kind) in erasers { + let d = Device::new(10, name, kind, pen_valuators()); + assert!(d.eraser && d.pressure.is_some(), "{name} ({kind:?})"); + } + let tips = [ + ("Wacom Intuos Pro M Pen stylus", Some("STYLUS")), + ("HUION Kamvas Pen Pen (0x1)", Some("STYLUS")), + ("xwayland-tablet stylus:16", Some("xwayland-tablet stylus")), + ("Logitech USB Optical Mouse", Some("MOUSE")), + ("", None), + ]; + for (name, kind) in tips { + assert!(!Device::new(9, name, kind, pen_valuators()).eraser, "{name} ({kind:?})"); + } + } + + #[test] + fn the_eraser_device_sets_the_eraser_end() { + let mut pens = Pens::default(); + pens.set_devices([pen(9), Device::new(10, "Wacom Intuos Pro M Pen eraser", Some("ERASER"), pen_valuators()), mouse(12)]); + let feed = StylusFeed::default(); + pens.raw_event(&feed, 9, &[0b100], &[32767.5]); + assert_eq!(pens.handle(9, []), Update::Set(Some(PenSample { pressure: 0.5, eraser: false }))); + assert_eq!(feed.eraser(), Some(false)); + // Turned over, the pen hovers with its eraser end: the eraser device's first event, with + // no pressure yet. + pens.raw_event(&feed, 10, &[0b1], &[100.0]); + assert_eq!(pens.handle(10, []), Update::Set(Some(PenSample { pressure: 0.0, eraser: true }))); + assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(0.0))); + pens.raw_event(&feed, 10, &[0b100], &[65535.0]); + assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(1.0))); + // Back to the tip, with the tip's own last pressure. + pens.raw_event(&feed, 9, &[0b1], &[200.0]); + assert_eq!((feed.eraser(), feed.held()), (Some(false), Some(0.5))); + // A mouse: no pen end. + pens.raw_event(&feed, 12, &[0b1], &[3.0]); + assert_eq!(feed.eraser(), None); + } + + #[test] + fn a_pens_valuator_becomes_its_pressure_and_another_pointer_clears_it() { + let mut pens = Pens::default(); + pens.set_devices([pen(9), mouse(12)]); + let feed = StylusFeed::default(); + pens.raw_event(&feed, 9, &[0b101], &[100.0, 32767.5]); + assert_eq!(feed.held(), Some(0.5)); + // Raw events carry only the valuators that changed: a move without pressure keeps it. + pens.raw_event(&feed, 9, &[0b1], &[200.0]); + assert_eq!(feed.held(), Some(0.5)); + pens.raw_event(&feed, 9, &[0b100], &[65535.0]); + assert_eq!(feed.held(), Some(1.0)); + // The mouse moves: no pen pressure until the pen moves again. + pens.raw_event(&feed, 12, &[0b1], &[3.0]); + assert_eq!(feed.held(), None); + pens.raw_event(&feed, 9, &[0b1], &[300.0]); + assert_eq!(feed.held(), Some(1.0), "the pen's last pressure"); + // A master device or one not listed yet changes nothing. + pens.raw_event(&feed, 2, &[0b100], &[0.0]); + assert_eq!(feed.held(), Some(1.0)); + // A pen whose first event carries no pressure is hovering: it presses with 0. + pens.set_devices([pen(9), pen(10)]); + pens.raw_event(&feed, 10, &[0b1], &[5.0]); + assert_eq!(feed.press(), Some(0.0)); + } + + #[test] + fn hostile_device_data_gives_a_pressure_within_0_to_1() { + let ranges = [(5.0, 5.0), (1.0, -1.0), (f64::NEG_INFINITY, f64::INFINITY), (f64::NAN, f64::NAN)]; + for (min, max) in ranges { + let mut pens = Pens::default(); + pens.set_devices([Device::new(1, "", None, [(2, "Abs Pressure".to_string(), min, max)])]); + for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN, -0.0, 1e300, 0.5] { + let Update::Set(Some(PenSample { pressure: p, .. })) = pens.handle(1, [(2, v)]) else { panic!("{min}..{max}: {v} gave no pressure") }; + assert!((0.0..=1.0).contains(&p), "{min}..{max}: {v} gave {p}"); + } + } + let mut pens = Pens::default(); + pens.set_devices((0..2000u16).map(|i| Device::new(i, "", None, []))); + assert!(pens.devices.len() <= MAX_DEVICES, "the device list is bounded"); + // Values for valuators the pen doesn't have are ignored. + pens.set_devices([pen(3)]); + let Update::Set(Some(PenSample { pressure: p, .. })) = pens.handle(3, valuators(&[u32::MAX; 2048], &[0.5; 4096]).collect::>()) else { + panic!("the pen gave no pressure") + }; + assert!(p < 0.001, "{p}"); + } + + #[test] + fn fixed_point_values() { + assert_eq!(fp3232(3, 1 << 31), 3.5); + assert_eq!(fp3232(-2, 0), -2.0); + } +} diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs new file mode 100644 index 0000000000..e6096c54a7 --- /dev/null +++ b/apps/vectorcraft/src/tests.rs @@ -0,0 +1,309 @@ +use super::*; + +fn ui_state_with_prefs(engine_prefs: serde_json::Value) -> vectorcraft_ui_egui::UiState { + vectorcraft_ui_egui::UiState { engine_prefs, ..Default::default() } +} + +/// Shortcut overrides an earlier version saved still load: its spellings, `panel:` keys, an +/// override that can't fire (#487), an entry for a command this version lacks, and an old set +/// name. +#[test] +fn shortcut_overrides_from_an_earlier_version_load() { + use serde_json::json; + use vectorcraft_ui_egui::{keymap, shortcut_editor}; + let mut raw = serde_json::to_value(vectorcraft_ui_egui::UiState::default()).unwrap(); + raw["shortcut_overrides"] = json!({ + "tool:pen": "Shift+9", + "edit.preferences": "", + "panel:layers": "Cmd+Alt+Shift+F7", + "tool:groupSelection": "Shift+ShiftLeft", + "test.unknown": "Cmd+Alt+Shift+F9", + "view.grid": "Cmd+Period", + }); + raw["shortcut_set"] = json!(shortcut_editor::LEGACY_PRESETS[0].0); + let ui = decode_saved_prefs(&serde_json::to_vec(&raw).unwrap()).unwrap().sanitized(); + assert_eq!(ui.shortcut_set, shortcut_editor::LEGACY_PRESETS[0].1); + let km = keymap::keymap_with(&ui.shortcut_overrides); + let text = |key: &str| keymap::effective_with(&km, key); + assert_eq!(text("tool:pen").as_deref(), Some("Shift+9")); + assert_eq!(text("edit.preferences"), None); + assert_eq!(text("panel:layers").as_deref(), Some("Cmd+Alt+Shift+F7")); + assert_eq!(text("tool:groupSelection").as_deref(), shortcut_editor::default_of("tool:groupSelection"), "back on its default"); + assert_eq!(text("view.grid").as_deref(), Some("Cmd+Period")); + let period = keymap::vc_chord("Cmd+.").unwrap(); + assert_eq!(keymap::lookup(&km, &period).map(|c| c.id), Some("view.grid".to_string())); + assert_eq!(text("test.unknown").as_deref(), Some("Cmd+Alt+Shift+F9"), "kept"); + assert!(km.problems().iter().any(|p| format!("{p:?}") == r#"UnknownCommand { key: "test.unknown" }"#), "reported"); +} + +#[test] +fn opening_files_unminimizes_and_focuses_the_window() { + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| bring_window_forward(ui.ctx())); + // Nothing paints in the test: drop the font atlas upload egui expects to be applied. + out.textures_delta.clear(); + let cmds = &out.viewport_output[&egui::ViewportId::ROOT].commands; + assert!(cmds.contains(&egui::ViewportCommand::Minimized(false))); + assert!(cmds.contains(&egui::ViewportCommand::Focus)); +} + +#[test] +fn unreadable_saved_docking_keeps_preferences_and_every_workspace() { + use serde_json::json; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("window.panel.float", json!({"panel":"layers"})).unwrap(); + app.ui.toolbar = false; + app.ui.engine_prefs = json!({"interfaceLanguage":"fr", "uiBrightness":"light"}); + app.ui.custom_workspaces = + vec![vectorcraft_ui_egui::workspaces::capture(&app.ui, "Future"), vectorcraft_ui_egui::workspaces::capture(&app.ui, "Valid")]; + app.ui.workspace_changes = vec![vectorcraft_ui_egui::workspaces::capture(&app.ui, "Future")]; + let original = serde_json::to_value(&app.ui).unwrap(); + let valid_location = original["docking_hidden"]["layers"].clone(); + assert!(valid_location.is_object()); + for invalid_layout in [json!({"root":{"FutureNode":{}},"floating":[]}), json!(false)] { + for invalid_hidden in [json!({"layers":{"placement":{"FuturePlacement":{}}},"swatches":valid_location}), json!(["malformed"])] { + let mut raw = original.clone(); + raw["docking"] = invalid_layout.clone(); + raw["docking_hidden"] = invalid_hidden.clone(); + raw["custom_workspaces"][0]["docking"] = invalid_layout.clone(); + raw["custom_workspaces"][0]["dockingHidden"] = invalid_hidden.clone(); + raw["workspace_changes"][0]["docking"] = invalid_layout.clone(); + raw["workspace_changes"][0]["dockingHidden"] = invalid_hidden.clone(); + assert!(serde_json::from_value::(raw.clone()).is_err(), "runtime serde stays strict"); + let loaded = decode_saved_prefs(&serde_json::to_vec(&raw).unwrap()).unwrap(); + assert_eq!(loaded.engine_prefs, app.ui.engine_prefs); + assert!(!loaded.toolbar); + assert!(loaded.docking.is_none()); + assert!(!loaded.docking_hidden.contains_key("layers")); + if invalid_hidden.is_object() { + assert_eq!(serde_json::to_value(loaded.docking_hidden.get("swatches")).unwrap(), valid_location); + } else { + assert!(loaded.docking_hidden.is_empty()); + } + assert_eq!(loaded.custom_workspaces.len(), 2); + assert_eq!(loaded.custom_workspaces[0].name, "Future"); + assert!(loaded.custom_workspaces[0].docking.is_none()); + assert!(!loaded.custom_workspaces[0].docking_hidden.contains_key("layers")); + assert_eq!(serde_json::to_value(&loaded.custom_workspaces[1]).unwrap(), original["custom_workspaces"][1]); + assert_eq!(loaded.workspace_changes.len(), 1, "a remembered layout is recovered, not the whole file lost"); + assert!(loaded.workspace_changes[0].docking.is_none()); + } + } + let roundtrip = decode_saved_prefs(&serde_json::to_vec(&original).unwrap()).unwrap(); + assert_eq!(serde_json::to_value(roundtrip).unwrap(), original); + assert!( + decode_saved_prefs(&serde_json::to_vec(&json!({"toolbar":"invalid"})).unwrap()).is_none(), + "unrelated fields retain normal strict parsing" + ); +} + +#[test] +fn an_unreadable_ui_json_is_kept_beside_it() { + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("vectorcraft-ui-prefs-{}-{stamp}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let path = dir.join("ui.json"); + super::keep_prefs_copy(&path, b"{\"docking\": {\"root\": {\"FutureNode\": {}}}}", "ui.unreadable"); + super::keep_prefs_copy(&path, b"not json", "ui.unreadable"); + super::keep_prefs_copy(&path, b"{}", "ui.before-layout-migration"); + let first = std::fs::read(dir.join("ui.unreadable.json")).unwrap(); + let second = std::fs::read(dir.join("ui.unreadable-2.json")).unwrap(); + let before = std::fs::read(dir.join("ui.before-layout-migration.json")).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert!(first.starts_with(b"{\"docking\""), "the first copy is not replaced"); + assert_eq!(second, b"not json"); + assert_eq!(before, b"{}"); + assert!(!super::KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed), "ui.json can be saved once a copy is kept"); +} + +#[test] +fn the_image_trace_preview_setting_is_kept_across_a_restart() { + for preview in [false, true] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.ui.image_trace_preview = preview; + let saved = prefs_bytes(&app).unwrap(); + let loaded = decode_saved_prefs(&saved).unwrap().sanitized(); + assert_eq!(loaded.image_trace_preview, preview, "Preview {preview} after a restart"); + } +} + +#[test] +fn the_system_title_bar_preference_keeps_the_window_decorations() { + use craft_window::{Frame, Layout}; + + // The System Title Bar preference (Preferences › User Interface) is read the same way on + // every platform; a missing or unreadable value is `false`. + assert!(!super::opted_into_system_title_bar(None), "no preferences: the default"); + let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false})); + assert!(!super::opted_into_system_title_bar(Some(&off))); + let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true})); + assert!(super::opted_into_system_title_bar(Some(&on))); + + // The suite-wide mapping (Frame + preference -> whether VectorCraft draws its own title + // bar). The desktop frame (macOS, Windows, X11, KDE/Wayland, …) always keeps native + // decorations; the app frame (GNOME/Wayland, or a `VECTORCRAFT_TITLEBAR` override) draws + // our own title bar — unless the user opted into the system title bar, which forces the + // native frame back on. + let app = Frame::App(Layout::default()); + let desktop = Frame::Desktop; + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + { + assert!(super::custom_titlebar_from(&app, false), "GNOME/Wayland: VectorCraft draws its own"); + assert!(!super::custom_titlebar_from(&app, true), "System Title Bar preference forces native"); + assert!(!super::custom_titlebar_from(&desktop, false), "KDE/X11/…: keep the compositor's frame"); + assert!(!super::custom_titlebar_from(&desktop, true)); + } + // macOS and Windows keep today's behavior, independent of the probed frame: the pref still + // forces the native frame back on where a custom one would otherwise be drawn. + #[cfg(any(target_os = "macos", target_os = "windows"))] + { + assert_eq!(super::custom_titlebar_from(&desktop, false), super::CUSTOM_TITLEBAR); + assert_eq!(super::custom_titlebar_from(&app, false), super::CUSTOM_TITLEBAR, "the probe does not change macOS/Windows"); + assert!(!super::custom_titlebar_from(&desktop, true)); + } + + assert_eq!(super::native_options(false).viewport.decorations, Some(true)); + assert_eq!(super::native_options(true).viewport.decorations, Some(false)); +} + +/// The file extensions the macOS bundle declares: its document types and its own exported type. +fn plist_extensions(plist: &str) -> Vec<&str> { + ["CFBundleTypeExtensions", "public.filename-extension"] + .iter() + .flat_map(|key| plist.split(key).skip(1)) + .filter_map(|rest| rest.split("").next()) + .flat_map(|array| array.split("").skip(1)) + .filter_map(|s| s.split("").next()) + .collect() +} + +/// Finder offers the app for every file File › Open reads (#295, #354) but those with an +/// extension in `UNASSOCIATED_EXTS`, takes over no other app's files, and hands them to the app +/// rather than to AppKit's document machinery. +#[test] +fn the_macos_bundle_opens_every_readable_format() { + let plist = include_str!("../../../packaging/macos/Info.plist.in"); + let declared = plist_extensions(plist); + for e in fileio::OPEN_EXTS.iter().filter(|e| !fileio::UNASSOCIATED_EXTS.contains(e)) { + assert!(declared.contains(e), "Info.plist.in doesn't declare .{e}"); + } + for e in &declared { + assert!(fileio::OPEN_EXTS.contains(e), "Info.plist.in declares .{e}, which the app doesn't open"); + } + assert!(!plist.contains("NSDocumentClass"), "not an NSDocument app: AppKit would refuse the files"); + let types = plist.matches("CFBundleTypeName").count(); + assert!(types > 1 && plist.matches("LSHandlerRank").count() == types, "every document type has a rank"); + assert_eq!(plist.matches("Owner").count(), 2, "only VectorCraft documents and templates are owned"); +} + +/// The MIME types a Linux desktop gives each extension in `OPEN_EXTS` but `UNASSOCIATED_EXTS` +/// (one row per type): shared-mime-info's, or one that `ai.storyteller.vectorcraft.mime.xml` +/// declares. +const LINUX_TYPES: &[(&str, &str)] = &[ + ("vectorcraft", "application/x-vectorcraft"), + ("drawcraft", "application/x-vectorcraft"), + ("svg", "image/svg+xml"), + ("svgz", "image/svg+xml-compressed"), + ("pdf", "application/pdf"), + ("ai", "application/illustrator"), // brand-ok: shared-mime-info's type + ("ait", "application/x-ai-template"), + ("png", "image/png"), + ("jpg", "image/jpeg"), + ("jpeg", "image/jpeg"), + ("gif", "image/gif"), + ("webp", "image/webp"), + ("tif", "image/tiff"), + ("tiff", "image/tiff"), + ("bmp", "image/bmp"), + ("vctemplate", "application/x-vectorcraft-template"), + ("dxf", "image/vnd.dxf"), + ("emf", "image/emf"), + ("wmf", "image/wmf"), + ("eps", "image/x-eps"), + ("af", "application/x-affinity"), + ("afdesign", "application/x-affinity"), + ("afpub", "application/x-affinity"), +]; + +/// The types in `LINUX_TYPES` that shared-mime-info defines. The MIME package declares every +/// other one. +const LINUX_SHARED_TYPES: &[&str] = &[ + "image/svg+xml", + "image/svg+xml-compressed", + "application/pdf", + "application/illustrator", // brand-ok: shared-mime-info's type + "image/png", + "image/jpeg", + "image/gif", + "image/webp", + "image/tiff", + "image/bmp", + "image/vnd.dxf", + "image/emf", + "image/wmf", + "image/x-eps", +]; + +/// Extensions in `LINUX_TYPES` whose type the MIME package matches by file content and not by a +/// glob, with the package's `` rule for that type (its lines joined, indentation removed). +const LINUX_BY_CONTENT: &[(&str, &str)] = &[( + "af", + // `MAGIC` at offset 0 and `DOCUMENT_KIND` at offset 8 (crates/affinity/src/container.rs). + r#""#, +)]; + +/// The desktop entry lists a MIME type for every extension in `OPEN_EXTS` but +/// `UNASSOCIATED_EXTS`, and the app's MIME package declares the types shared-mime-info doesn't +/// have. +#[test] +fn the_linux_desktop_entry_opens_every_readable_format() { + let desktop = include_str!("../../../packaging/linux/ai.storyteller.vectorcraft.desktop"); + let mime = include_str!("../../../packaging/linux/ai.storyteller.vectorcraft.mime.xml"); + let listed: Vec<&str> = + desktop.lines().find_map(|l| l.strip_prefix("MimeType=")).unwrap_or_default().split(';').filter(|t| !t.is_empty()).collect(); + // Each type the MIME package declares, with the extensions of its globs and its `` + // rule (empty when it has none) in the form `LINUX_BY_CONTENT` gives. + let declared: Vec<(&str, Vec<&str>, String)> = mime + .split("").next().unwrap_or_default(); + let globs = body.split("")) { + (Some(start), Some(end)) => body[start..end + "".len()].lines().map(str::trim).collect(), + _ => String::new(), + }; + (block.split('"').next().unwrap_or_default(), globs, magic) + }) + .collect(); + let mut associated: Vec<&str> = fileio::OPEN_EXTS.iter().copied().filter(|e| !fileio::UNASSOCIATED_EXTS.contains(e)).collect(); + let mut typed: Vec<&str> = LINUX_TYPES.iter().map(|(e, _)| *e).collect(); + associated.sort_unstable(); + typed.sort_unstable(); + typed.dedup(); + assert_eq!(typed, associated, "a MIME type for each extension the packaging associates with the app"); + for (e, t) in LINUX_TYPES { + assert!(listed.contains(t), "the desktop entry doesn't list {t} (.{e})"); + let package = declared.iter().find(|(name, ..)| name == t); + if LINUX_SHARED_TYPES.contains(t) { + assert!(package.is_none(), "{t} is shared-mime-info's, and the MIME package declares it again"); + continue; + } + let Some((_, globs, magic)) = package else { panic!("the MIME package doesn't declare {t} (.{e})") }; + if let Some((_, rule)) = LINUX_BY_CONTENT.iter().find(|(content, _)| content == e) { + assert!(!globs.contains(e), "{t} matches .{e} files by content only"); + assert_eq!(magic, rule, "{t}'s magic rule for .{e} files"); + } else { + assert!(globs.contains(e), "{t} has no *.{e} glob"); + } + } + for t in &listed { + assert!(LINUX_TYPES.iter().any(|(_, known)| known == t), "the desktop entry lists {t}, which the app doesn't open"); + } + for (t, globs, _) in &declared { + assert!(listed.contains(t), "the desktop entry doesn't list the declared {t}"); + for g in globs { + assert!(LINUX_TYPES.contains(&(*g, *t)), "{t}'s *.{g} isn't a file the app opens as {t}"); + } + } +} diff --git a/apps/vectorcraft/src/titlebar.rs b/apps/vectorcraft/src/titlebar.rs new file mode 100644 index 0000000000..3d538ec884 --- /dev/null +++ b/apps/vectorcraft/src/titlebar.rs @@ -0,0 +1,120 @@ +use super::*; + +/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets +/// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches +/// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon. +fn app_icon() -> egui::IconData { + #[cfg(target_os = "macos")] + let png: &[u8] = include_bytes!("../../../assets/app-icon/vectorcraft-macos-512.png"); + #[cfg(not(target_os = "macos"))] + let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.vectorcraft.png"); + eframe::icon_data::from_png_bytes(png).unwrap_or_default() +} + +/// Windows shows a window's big icon (`ICON_BIG`) in the taskbar and Alt+Tab; eframe sets only the +/// small one (the title bar's), so the taskbar showed a generic icon. Set the big one too. +#[cfg(windows)] +pub(crate) fn set_taskbar_icon(w: &winit::window::Window) { + use winit::platform::windows::WindowExtWindows as _; + let icon = app_icon(); + // An icon that can't be made leaves the generic one: nothing else depends on it. + if let Ok(i) = winit::window::Icon::from_rgba(icon.rgba, icon.width, icon.height) { + w.set_taskbar_icon(Some(i)); + } +} + +/// "name (backend, kind)" of the adapter the window renders with, for Help › About and bug reports. +#[cfg(feature = "wgpu")] +pub(crate) fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String { + format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type) +} + +/// Windows and Linux: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`). +/// macOS keeps its traffic lights over the integrated title strip. +/// +/// Used on macOS and Windows (where VectorCraft keeps today's frame regardless of the +/// `craft-window` probe) and by the tests; Linux and the BSDs take the decision from the probe. +#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] +pub(crate) const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos"); + +/// Whether the user asked for the system title bar in Preferences › User Interface › System Title +/// Bar. Read from the saved preferences before the window opens; a missing or unreadable value is +/// `false` (the default). This preference forces the desktop/native frame back on. +pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool { + saved.map(|ui| ui.engine_prefs.get("systemTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false) +} + +/// Whether this start draws its own title bar, given the frame the shared `craft-window` crate +/// decided and the user's System Title Bar preference. +/// +/// The suite-wide rule (`craft_window::Choice`) is: the desktop draws the frame +/// ([`craft_window::Frame::Desktop`]) on macOS, Windows, X11 and any Wayland compositor with +/// server-side decorations (KDE, Sway, Hyprland, COSMIC); the app draws it +/// ([`craft_window::Frame::App`]) only where the compositor leaves it to the app (GNOME's Mutter), +/// or when `VECTORCRAFT_TITLEBAR` overrides the probe. VectorCraft draws its own title bar exactly +/// when `craft-window` says the app owns the frame **and** the user has not opted into the system +/// title bar; the preference always forces the native frame back on. +/// +/// macOS and Windows keep today's behavior and are decided by [`CUSTOM_TITLEBAR`] rather than the +/// probe: `craft-window` returns `Frame::Desktop` for both (the OS always draws a frame), but +/// VectorCraft insets its content under the macOS traffic lights and draws its own caption buttons +/// on Windows — an overdraw on an OS-decorated window that is VectorCraft's choice, not +/// `craft-window`'s. Only Linux and the BSDs take the decision from the probe. +#[cfg(not(any(target_os = "macos", target_os = "windows")))] +pub(crate) fn custom_titlebar_from(frame: &craft_window::Frame, opted_into_system: bool) -> bool { + matches!(frame, craft_window::Frame::App(_)) && !opted_into_system +} + +/// macOS and Windows: today's behavior, independent of the `craft-window` probe (see +/// [`custom_titlebar_from`]). macOS never draws its own frame (`CUSTOM_TITLEBAR` is `false`); +/// Windows draws its own caption unless the user opted into the system title bar. +#[cfg(any(target_os = "macos", target_os = "windows"))] +pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_system: bool) -> bool { + CUSTOM_TITLEBAR && !opted_into_system +} + +/// Whether this start draws its own title bar. Probes the shared `craft-window` crate once (its +/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System +/// Title Bar preference. Call once at startup, before [`native_options`]. +/// +/// On Linux, Preferences › Performance › Linux Display Server › X11 opens the window through +/// XWayland (below). A GNOME/Wayland probe would say `Frame::App` there, but the window really runs +/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native +/// frame, the same as a real X11 session. An explicit `VECTORCRAFT_TITLEBAR` override still wins. +pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool { + let choice = craft_window::Choice::probe(craft_window::Prefix::new("VECTORCRAFT")); + let opted_into_system = opted_into_system_title_bar(saved); + #[cfg(target_os = "linux")] + { + let pref = saved.and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str); + // `overridden() == None` means the probe decided (no VECTORCRAFT_TITLEBAR). When the window + // will actually open on X11 (XWayland) — the user asked for it *and* the X11 libraries are + // present, the same two conditions the launch path checks below — that run is effectively + // X11, so keep the native frame. If the libraries are missing, startup stays on Wayland, so + // the probe's own decision (app-drawn on GNOME) must stand. + let forced_to_x11 = xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) && xwayland::x11_libraries_found(); + if choice.overridden().is_none() && forced_to_x11 { + return custom_titlebar_from(&craft_window::Frame::Desktop, opted_into_system); + } + } + custom_titlebar_from(choice.frame(), opted_into_system) +} + +pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions { + eframe::NativeOptions { + viewport: egui::ViewportBuilder::default() + .with_title("VectorCraft") + .with_inner_size(window::DEFAULT_SIZE) + .with_min_inner_size(window::MIN_SIZE) + .with_drag_and_drop(true) + .with_decorations(!custom_titlebar) + .with_fullsize_content_view(true) + .with_titlebar_shown(false) + .with_title_shown(false) + .with_icon(app_icon()) + .with_app_id("ai.storyteller.vectorcraft"), + #[cfg(feature = "windows7")] + renderer: eframe::Renderer::Glow, + ..Default::default() + } +} diff --git a/apps/vectorcraft/src/window.rs b/apps/vectorcraft/src/window.rs index e953264237..abe60f69ff 100644 --- a/apps/vectorcraft/src/window.rs +++ b/apps/vectorcraft/src/window.rs @@ -110,7 +110,8 @@ fn fit(size: [f32; 2], room: [f32; 2]) -> [f32; 2] { } /// Size and place the new window (eframe shows it after drawing the first frame) and return its -/// geometry. +/// geometry. On Linux the window may not be mapped yet, so [`apply_pending_maximize`] must run +/// until the host reports maximized (fixes #3635). pub fn restore(window: &winit::window::Window, saved: Option) -> WindowGeometry { let handles: Vec<_> = window.available_monitors().collect(); let monitors: Vec = handles.iter().map(|m| Monitor::new(m.position(), m.size(), m.scale_factor())).collect(); @@ -121,22 +122,41 @@ pub fn restore(window: &winit::window::Window, saved: Option) -> } // Returns the new size when it applies at once; either way the window gets it. let _ = window.request_inner_size(LogicalSize::new(g.size[0], g.size[1])); + #[cfg(not(target_os = "linux"))] if g.maximized { window.set_maximized(true); } g } +/// Keep asking the host to maximize until it sticks, or give up after a few frames. +pub fn apply_pending_maximize(window: &winit::window::Window, want: bool, tries: &mut u8) -> bool { + if !want { + return false; + } + if window.is_maximized() { + return false; + } + if *tries == 0 { + return false; + } + *tries -= 1; + window.set_maximized(true); + true +} + /// Per frame: remember the window's geometry for the next launch. Minimized or full screen keeps /// the last one; maximized only sets its flag, so un-maximizing next time restores the last size. -pub fn track(ctx: &egui::Context, geometry: &mut Option) { +/// `host_maximized` is the window manager's idea of maximized when egui does not report it (#3635). +pub fn track(ctx: &egui::Context, geometry: &mut Option, host_maximized: Option) { let zoom = ctx.zoom_factor(); ctx.input(|i| { let v = i.viewport(); if v.minimized == Some(true) || v.fullscreen == Some(true) { return; } - if v.maximized == Some(true) { + let maximized = v.maximized == Some(true) || host_maximized == Some(true); + if maximized { if let Some(g) = geometry { g.maximized = true; } @@ -222,7 +242,7 @@ mod tests { let mut frame = |info: egui::ViewportInfo| { let mut input = egui::RawInput::default(); input.viewports.insert(egui::ViewportId::ROOT, info); - ctx.run_ui(input, |ui| track(ui.ctx(), &mut geometry)).textures_delta.clear(); + ctx.run_ui(input, |ui| track(ui.ctx(), &mut geometry, None)).textures_delta.clear(); geometry }; let rect = egui::Rect::from_min_size(egui::pos2(20.0, 30.0), egui::vec2(1000.0, 600.0)); @@ -253,4 +273,19 @@ mod tests { let back: vectorcraft_ui_egui::UiState = serde_json::from_value(json).unwrap(); assert_eq!(back.window, None); } + + #[test] + fn the_host_maximized_flag_is_remembered_when_egui_does_not_report_it() { + let ctx = egui::Context::default(); + let mut geometry = Some(WindowGeometry { pos: Some([10, 20]), size: [800.0, 600.0], maximized: false }); + let rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1920.0, 1080.0)); + let mut input = egui::RawInput::default(); + input.viewports.insert( + egui::ViewportId::ROOT, + egui::ViewportInfo { inner_rect: Some(rect), outer_rect: Some(rect), maximized: None, ..Default::default() }, + ); + let mut out = ctx.run_ui(input, |ui| track(ui.ctx(), &mut geometry, Some(true))); + out.textures_delta.clear(); + assert_eq!(geometry, Some(WindowGeometry { pos: Some([10, 20]), size: [800.0, 600.0], maximized: true })); + } } diff --git a/apps/vectorcraft/src/window_frame.rs b/apps/vectorcraft/src/window_frame.rs index 950673da8f..e69806ac29 100644 --- a/apps/vectorcraft/src/window_frame.rs +++ b/apps/vectorcraft/src/window_frame.rs @@ -11,10 +11,17 @@ //! //! Windows sizes a maximize by the frame its styles describe, so a window maximized while its //! caption is gone is sized without one: its rect covers the whole monitor, taskbar included, and -//! the shell reads a caption-less window covering its monitor as a full-screen app (#1977). The -//! guard therefore also trims a parked maximize's rect back to the work area plus its own frame, -//! clear of the taskbar, as PhotoCraft does (storytold/photocraft#3308). winit pins the client -//! area to the work area either way (`WM_NCCALCSIZE`), so the app's pixels do not move. +//! the shell reads a caption-less window covering its monitor as a full-screen app (#1977). With +//! the taskbar on the top or a side edge, the strip between the window's edge and the client area +//! that winit pins to the work area (`WM_NCCALCSIZE`) is drawn as a classic title bar (#3242, +//! #3723). The guard therefore also moves a parked maximize's rect back inside the work area on +//! every edge, plus its own frame, clear of the taskbar wherever it is, and repaints the window, as +//! PhotoCraft does (storytold/photocraft#3308, storytold/photocraft#5237). +//! +//! An auto-hidden taskbar reserves no work area, so that move leaves a maximize covering the whole +//! monitor. In PhotoCraft the taskbar then did not show when the pointer reached its edge +//! (storytold/photocraft#4845). On each edge with an auto-hidden taskbar the guard stops the window +//! one pixel short of the monitor instead, as PhotoCraft does (storytold/photocraft#6878). /// Run once per frame; a no-op once the window is borderless. pub type WindowFrameFn = Box; @@ -24,7 +31,8 @@ pub use platform::service; #[cfg(all(windows, feature = "wgpu"))] mod platform { use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle}; - use winsafe::{HWND, HwndPlace, POINT, SIZE, co}; + use winsafe::prelude::Handle; + use winsafe::{AtomStr, HWND, HwndPlace, POINT, SIZE, co}; /// A guard that keeps the window borderless each frame, or `None` with the system title bar /// (the window is decorated) or when its handle can't be found. @@ -76,12 +84,14 @@ mod platform { HwndPlace::None, POINT::new(), SIZE::new(), - co::SWP::FRAMECHANGED | co::SWP::NOMOVE | co::SWP::NOSIZE | co::SWP::NOZORDER | co::SWP::NOACTIVATE, + co::SWP::FRAMECHANGED | co::SWP::NOCOPYBITS | co::SWP::NOMOVE | co::SWP::NOSIZE | co::SWP::NOZORDER | co::SWP::NOACTIVATE, ); } - /// [`super::clamped_height`] for this frame's window: trim a maximized window whose rect runs - /// under the taskbar back to the work area plus its frame. No-op otherwise. + /// [`super::clamped_rect`] for this frame's window: move a maximized window whose rect runs + /// under a taskbar on any edge back inside the work area plus its frame, and repaint it. A + /// maximized window that covers its whole monitor instead stops one pixel short of each edge + /// with an auto-hidden taskbar ([`super::short_of_autohide_taskbars`]). No-op otherwise. fn keep_clear_of_the_taskbar(hwnd: &HWND) { if !hwnd.IsZoomed() { return; @@ -90,17 +100,48 @@ mod platform { return; }; let (m, w) = (mi.rcMonitor, mi.rcWork); - let Some(height) = - super::clamped_height((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom)) - else { + let (rect, monitor, work) = ((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom)); + // The taskbars are looked up (a few `FindWindowEx` calls) only while the window covers its + // whole monitor, which it no longer does once trimmed. + let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work).or_else(|| { + super::covers(rect, monitor).then(|| super::short_of_autohide_taskbars(rect, monitor, work, &taskbar_edges(monitor))).flatten() + }) else { return; }; + let (Some(width), Some(height)) = (right.checked_sub(left), bottom.checked_sub(top)) else { + return; + }; + // The frame moves while winit keeps the client rect on the work area: `NOCOPYBITS` and the + // invalidation have the whole window drawn again instead of the old frame's pixels being + // copied into the custom title bar. let _ = hwnd.SetWindowPos( HwndPlace::None, - POINT::new(), - SIZE { cx: r.right - r.left, cy: height }, - co::SWP::NOMOVE | co::SWP::NOZORDER | co::SWP::NOACTIVATE, + POINT { x: left, y: top }, + SIZE { cx: width, cy: height }, + co::SWP::FRAMECHANGED | co::SWP::NOCOPYBITS | co::SWP::NOZORDER | co::SWP::NOACTIVATE, ); + let _ = hwnd.InvalidateRect(None, false); + } + + /// The edges of `monitor` that have a taskbar, shown or auto-hidden: the primary monitor's + /// `Shell_TrayWnd` window and the other monitors' `Shell_SecondaryTrayWnd` windows. + fn taskbar_edges(monitor: super::Rect) -> Vec { + let mut edges = Vec::new(); + for class in ["Shell_TrayWnd", "Shell_SecondaryTrayWnd"] { + let mut after: Option = None; + // A monitor has at most one taskbar; the bound ends the walk if the shell keeps + // returning windows. + for _ in 0..64 { + let Ok(Some(tray)) = HWND::NULL.FindWindowEx(after.as_ref(), AtomStr::from_str(class), None) else { + break; + }; + if let Ok(r) = tray.GetWindowRect() { + edges.extend(super::taskbar_edge((r.left, r.top, r.right, r.bottom), monitor)); + } + after = Some(tray); + } + } + edges } } @@ -111,35 +152,115 @@ mod platform { } } -/// How far a parked maximize reaches past its monitor on the left, top and right: the resize border -/// (about 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but -/// being dragged or snapped, and is left alone. +/// How far a parked maximize reaches past a monitor or work-area edge: the resize border (about +/// 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but being +/// dragged or snapped, and is left alone. const FRAME: i32 = 32; -/// The height to trim a maximize to so its rect stops at the taskbar, or `None` when it already -/// does or `rect` (`left, top, right, bottom`, desktop coordinates) is not parked at its maximize -/// place. `monitor` is the monitor's full rect and `work` its work area (the monitor less the -/// taskbar) in the same coordinates. The parked check is against the full monitor, because that is -/// where Windows puts a caption-less maximize; the trim is against the work area. Platform-neutral -/// so it is tested everywhere. +/// The rect to move a maximize to so it stays inside the work area on every edge, plus the resize +/// border it was parked with, or `None` when it already does or `rect` (`left, top, right, +/// bottom`, desktop coordinates) is not parked at its maximize place. `monitor` is the monitor's +/// full rect and `work` its work area (the monitor less the taskbar) in the same coordinates. The +/// border is read from the edges that have no taskbar, and every edge must sit that far outside +/// either the monitor (where Windows puts a caption-less maximize) or the work area (where the +/// guard puts it), so a rect it already moved is left alone. Platform-neutral so it is tested +/// everywhere. #[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] -fn clamped_height(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option { +fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> { let (l, t, r, b) = rect; - let (ml, mt, mr, _) = monitor; - let (_, _, _, wb) = work; - let side = ml - l; - if !(0..=FRAME).contains(&side) || !(0..=FRAME).contains(&(mt - t)) || !(0..=FRAME).contains(&(r - mr)) { + let (ml, mt, mr, mb) = monitor; + let (wl, wt, wr, wb) = work; + if ml >= mr || mt >= mb || wl < ml || wt < mt || wr > mr || wb > mb || wl >= wr || wt >= wb { return None; } - if b <= wb + side { + // On an edge with a taskbar, the offsets from the monitor and from the work area can both + // look like a border, so only the edges without one are read. + let border = [ + (ml == wl).then(|| ml.checked_sub(l)).flatten(), + (mt == wt).then(|| mt.checked_sub(t)).flatten(), + (mr == wr).then(|| r.checked_sub(mr)).flatten(), + (mb == wb).then(|| b.checked_sub(mb)).flatten(), + ] + .into_iter() + .flatten() + .filter(|n| (0..=FRAME).contains(n)) + .min()?; + let parked = |monitor: Option, work: Option| monitor == Some(border) || work == Some(border); + if !parked(ml.checked_sub(l), wl.checked_sub(l)) + || !parked(mt.checked_sub(t), wt.checked_sub(t)) + || !parked(r.checked_sub(mr), r.checked_sub(wr)) + || !parked(b.checked_sub(mb), b.checked_sub(wb)) + { return None; } - Some(wb + side - t) + let corrected = (wl.checked_sub(border)?, wt.checked_sub(border)?, wr.checked_add(border)?, wb.checked_add(border)?); + (corrected != rect).then_some(corrected) +} + +/// A rect in desktop coordinates: `(left, top, right, bottom)`, right and bottom exclusive. +#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] +type Rect = (i32, i32, i32, i32); + +/// A monitor edge. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] +enum Edge { + Left, + Top, + Right, + Bottom, +} + +/// Whether `rect` reaches every edge of `monitor`, which the shell treats as a full-screen app. +#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] +fn covers(rect: Rect, monitor: Rect) -> bool { + rect.0 <= monitor.0 && rect.1 <= monitor.1 && rect.2 >= monitor.2 && rect.3 >= monitor.3 +} + +/// The edge of `monitor` that a taskbar with the rect `taskbar` sits on: the edge nearest the +/// taskbar's center, or `None` when the taskbar does not overlap the monitor. An auto-hidden +/// taskbar is parked mostly past its edge with a sliver left on the monitor, so its center can lie +/// outside the monitor. +#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] +fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option { + let (tl, tt, tr, tb) = (i64::from(taskbar.0), i64::from(taskbar.1), i64::from(taskbar.2), i64::from(taskbar.3)); + let (ml, mt, mr, mb) = (i64::from(monitor.0), i64::from(monitor.1), i64::from(monitor.2), i64::from(monitor.3)); + if tl >= tr || tt >= tb || ml >= mr || mt >= mb || tr <= ml || tl >= mr || tb <= mt || tt >= mb { + return None; + } + // The center and the distances are doubled, so nothing is rounded. + let (cx, cy) = (tl + tr, tt + tb); + [(Edge::Left, cx - 2 * ml), (Edge::Top, cy - 2 * mt), (Edge::Right, 2 * mr - cx), (Edge::Bottom, 2 * mb - cy)] + .into_iter() + .min_by_key(|&(_, distance)| distance) + .map(|(edge, _)| edge) +} + +/// A maximize that covers its monitor, trimmed to stop one pixel short of the monitor on each of +/// the `taskbars` edges where the work area reaches the monitor's edge (the taskbar there is +/// auto-hidden). `None` when `rect` does not cover the monitor or nothing is trimmed. +#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))] +fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: &[Edge]) -> Option { + if !covers(rect, monitor) { + return None; + } + let (mut l, mut t, mut r, mut b) = rect; + for edge in taskbars { + match edge { + Edge::Left if work.0 == monitor.0 => l = monitor.0.checked_add(1)?, + Edge::Top if work.1 == monitor.1 => t = monitor.1.checked_add(1)?, + Edge::Right if work.2 == monitor.2 => r = monitor.2.checked_sub(1)?, + Edge::Bottom if work.3 == monitor.3 => b = monitor.3.checked_sub(1)?, + _ => {} + } + } + let trimmed = (l, t, r, b); + (l < r && t < b && trimmed != rect).then_some(trimmed) } #[cfg(test)] mod tests { - use super::clamped_height; + use super::{Edge, clamped_rect, short_of_autohide_taskbars, taskbar_edge}; #[test] fn a_maximize_covering_the_taskbar_is_trimmed_to_the_work_area() { @@ -148,27 +269,97 @@ mod tests { // window was parked with. let monitor = (0, 0, 1920, 1080); let work = (0, 0, 1920, 1046); - assert_eq!(clamped_height((-7, -7, 1927, 1087), monitor, work), Some(1046 + 7 - (-7))); + assert_eq!(clamped_rect((-7, -7, 1927, 1087), monitor, work), Some((-7, -7, 1927, 1046 + 7))); } #[test] fn a_maximize_already_clear_of_the_taskbar_is_left_alone() { // What Windows sizes a framed maximize to: the work area plus the frame. - assert_eq!(clamped_height((-8, -8, 1928, 1054), (0, 0, 1920, 1080), (0, 0, 1920, 1046)), None); + assert_eq!(clamped_rect((-8, -8, 1928, 1054), (0, 0, 1920, 1080), (0, 0, 1920, 1046)), None); } #[test] - fn a_maximize_beside_a_side_taskbar_is_left_alone() { - // Taskbar on the left: the work area starts further right, but the monitor's bottom is - // still clear, so the rect reaches nothing. - assert_eq!(clamped_height((-8, -8, 1928, 1088), (0, 0, 1920, 1080), (48, 0, 1920, 1080)), None); + fn a_maximize_stays_clear_of_a_taskbar_on_any_edge() { + // A taskbar on the top or a side edge (#3242, #3723): the rect moves inside the work area + // there and keeps its frame on the other edges. Once moved, it is left alone. + let monitor = (0, 0, 1920, 1080); + let rect = (-8, -8, 1928, 1088); + for (work, expected) in [ + ((0, 0, 1920, 1046), (-8, -8, 1928, 1054)), + ((0, 48, 1920, 1080), (-8, 40, 1928, 1088)), + ((0, 2, 1920, 1080), (-8, -6, 1928, 1088)), + ((0, 0, 1920, 1078), (-8, -8, 1928, 1086)), + ((48, 0, 1920, 1080), (40, -8, 1928, 1088)), + ((0, 0, 1872, 1080), (-8, -8, 1880, 1088)), + ] { + assert_eq!(clamped_rect(rect, monitor, work), Some(expected), "work area {work:?}"); + assert_eq!(clamped_rect(expected, monitor, work), None, "already moved, work area {work:?}"); + } + } + + #[test] + fn a_top_taskbar_is_cleared_on_any_monitor_and_at_any_frame_size() { + // A monitor above and left of the primary one, at frame sizes up to the limit. + let monitor = (-1920, -1080, 0, 0); + let work = (-1920, -1032, 0, 0); + for border in [0, 8, 16, 32] { + let rect = (-1920 - border, -1080 - border, border, border); + let expected = (-1920 - border, -1032 - border, border, border); + assert_eq!(clamped_rect(rect, monitor, work), Some(expected), "border {border}"); + assert_eq!(clamped_rect(expected, monitor, work), None, "border {border}"); + } + } + + #[test] + fn a_maximize_without_a_reserved_taskbar_is_left_alone() { + let monitor = (0, 0, 1920, 1080); + assert_eq!(clamped_rect((-8, -8, 1928, 1088), monitor, monitor), None); } #[test] fn a_maximize_being_dragged_away_is_left_alone() { let monitor = (0, 0, 1920, 1080); let work = (0, 0, 1920, 1046); - assert_eq!(clamped_height((100, 200, 1100, 900), monitor, work), None, "moved"); - assert_eq!(clamped_height((-500, -7, 1427, 1087), monitor, work), None, "resized"); + assert_eq!(clamped_rect((100, 200, 1100, 900), monitor, work), None, "moved"); + assert_eq!(clamped_rect((-500, -7, 1427, 1087), monitor, work), None, "resized"); + let work = (0, 48, 1920, 1080); + assert_eq!(clamped_rect((-500, -8, 1428, 1088), monitor, work), None, "resized under a top taskbar"); + assert_eq!(clamped_rect((0, 48, 960, 1080), monitor, work), None, "snapped to half the screen"); + } + + #[test] + fn a_maximize_stops_a_pixel_short_of_an_auto_hidden_taskbar_edge() { + // An auto-hidden taskbar reserves no work area, so the work area is the whole monitor. + let monitor = (0, 0, 1920, 1080); + let rect = (-8, -8, 1928, 1088); + for (edge, expected) in [ + (Edge::Bottom, (-8, -8, 1928, 1079)), + (Edge::Top, (-8, 1, 1928, 1088)), + (Edge::Left, (1, -8, 1928, 1088)), + (Edge::Right, (-8, -8, 1919, 1088)), + ] { + assert_eq!(short_of_autohide_taskbars(rect, monitor, monitor, &[edge]), Some(expected), "{edge:?}"); + assert_eq!(short_of_autohide_taskbars(expected, monitor, monitor, &[edge]), None, "already trimmed, {edge:?}"); + assert_eq!(clamped_rect(expected, monitor, monitor), None, "left alone on the next frame, {edge:?}"); + } + assert_eq!(short_of_autohide_taskbars(rect, monitor, monitor, &[]), None, "no taskbar"); + // A taskbar that reserves its work area is moved clear of by `clamped_rect` instead. + assert_eq!(short_of_autohide_taskbars(rect, monitor, (0, 0, 1920, 1032), &[Edge::Bottom]), None, "shown taskbar"); + assert_eq!(short_of_autohide_taskbars((0, 0, 960, 1080), monitor, monitor, &[Edge::Bottom]), None, "half-screen"); + // A monitor above and left of the primary one. + let monitor = (-1920, -1080, 0, 0); + assert_eq!(short_of_autohide_taskbars((-1928, -1088, 8, 8), monitor, monitor, &[Edge::Top]), Some((-1928, -1079, 8, 8))); + } + + #[test] + fn a_taskbar_sits_on_the_monitor_edge_nearest_its_center() { + let monitor = (0, 0, 1920, 1080); + assert_eq!(taskbar_edge((0, 1032, 1920, 1080), monitor), Some(Edge::Bottom), "shown"); + assert_eq!(taskbar_edge((0, 1078, 1920, 1126), monitor), Some(Edge::Bottom), "auto-hidden"); + assert_eq!(taskbar_edge((0, -46, 1920, 2), monitor), Some(Edge::Top)); + assert_eq!(taskbar_edge((-60, 0, 2, 1080), monitor), Some(Edge::Left)); + assert_eq!(taskbar_edge((1918, 0, 1980, 1080), monitor), Some(Edge::Right)); + assert_eq!(taskbar_edge((1920, 1032, 3840, 1080), monitor), None, "other monitor"); + assert!(taskbar_edge((i32::MIN, i32::MIN, i32::MAX, i32::MAX), monitor).is_some(), "no overflow"); } } diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs new file mode 100644 index 0000000000..814ba55fe1 --- /dev/null +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -0,0 +1,450 @@ +//! Windows pen tablets: with Windows Ink, winit reports a pen in contact as a touch and drops its +//! barrel button, and egui-winit presses the primary button for the touch it makes the pointer, +//! so a pen pressed with its barrel button held clicks and drags with the left button. The +//! `WM_POINTERDOWN` message winit is about to handle still has the barrel button's state in its +//! second-button flag ("analogous to a mouse right button down", +//! ): [`msg_hook`] notes +//! it, and [`raw_input_hook`] makes the primary button of that contact the secondary one. +//! +//! winit also drops which end of the pen is down. For each pointer message of a pen, [`msg_hook`] +//! reads the pen's `POINTER_PEN_INFO` and writes its pressure and end into the canvas's pen feed +//! ([`start`]): `PEN_FLAG_INVERTED` ("The pen is inverted") or `PEN_FLAG_ERASER` ("The eraser +//! button is pressed") is the eraser end +//! (). Pointer +//! messages also come while the pen hovers, so turning the pen over selects the Eraser tool before +//! it touches. A message of another pointer, a pen leaving detection range or the window, or a +//! mouse message that Windows did not make from a pen or a touch +//! () +//! clears the feed. +#![cfg_attr(not(all(windows, not(target_vendor = "win7"))), allow(dead_code))] + +use std::cell::RefCell; +use std::sync::OnceLock; + +use egui::{Event, Modifiers, PointerButton, Pos2, TouchId, TouchPhase}; +use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed}; + +/// `POINTER_MESSAGE_FLAG_SECONDBUTTON` (`winuser.h`): in the high word of a pointer message's +/// `wParam`, a pen in contact with its barrel button pressed. +const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020; +/// `POINTER_MESSAGE_FLAG_INRANGE` (`winuser.h`): not set on the message of a pointer that has left +/// detection range. +const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002; +/// At most this many pointer contacts wait for their touch event. +const MAX_PENDING: usize = 16; +/// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`. +const PEN_FLAG_INVERTED: u32 = 0x0002; +const PEN_FLAG_ERASER: u32 = 0x0004; +/// `PEN_MASK_PRESSURE` (`winuser.h`), in `POINTER_PEN_INFO::penMask`: the pen reports pressure. +const PEN_MASK_PRESSURE: u32 = 0x0001; +/// `MI_WP_SIGNATURE` and `SIGNATURE_MASK`: the extra information of a mouse message that Windows +/// made from a pen or a touch. +const MI_WP_SIGNATURE: u32 = 0xFF51_5700; +const SIGNATURE_MASK: u32 = 0xFFFF_FF00; +/// `WM_MOUSEFIRST` to `WM_MOUSELAST` (`winuser.h`). +const MOUSE_MESSAGES: std::ops::RangeInclusive = 0x0200..=0x020E; +/// `WM_POINTERUPDATE`, `WM_POINTERDOWN`, `WM_POINTERUP`, `WM_POINTERENTER` and `WM_POINTERLEAVE` +/// (`winuser.h`). +const WM_POINTERUPDATE: u32 = 0x0245; +const WM_POINTERDOWN: u32 = 0x0246; +const WM_POINTERUP: u32 = 0x0247; +const WM_POINTERENTER: u32 = 0x0249; +const WM_POINTERLEAVE: u32 = 0x024A; + +thread_local! { + static STROKES: RefCell = RefCell::new(BarrelStrokes::default()); +} + +/// The pen feed [`msg_hook`] writes, once [`start`] has made it. +static FEED: OnceLock = OnceLock::new(); + +/// The canvas's pen feed, which [`msg_hook`] writes on the UI thread before winit handles each +/// message, so a press never waits for it. +pub fn start() -> StylusFeed { + FEED.get_or_init(StylusFeed::on_ui_thread).clone() +} + +/// winit's message hook (`EventLoopBuilderExtWindows::with_msg_hook`), which winit calls for each +/// message it takes from the thread's queue, before dispatching it: notes each pointer contact's id +/// and whether the barrel button was held, and writes the pen's pressure and end into the feed. +/// It never consumes the message. +#[cfg(all(windows, not(target_vendor = "win7")))] +#[allow(unsafe_code)] +pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { + use windows::Win32::UI::Input::Pointer::{GetPointerPenInfo, POINTER_FLAG_INCONTACT, POINTER_PEN_INFO}; + use windows::Win32::UI::WindowsAndMessaging::{GetMessageExtraInfo, MSG}; + // SAFETY: winit passes the `MSG` that `PeekMessageW` has just filled, which lives for this + // call; `as_ref` gives `None` for a null pointer. + let Some(msg) = (unsafe { msg.cast::().as_ref() }) else { + return false; + }; + if msg.message == WM_POINTERDOWN { + STROKES.with(|s| { + if let Ok(mut s) = s.try_borrow_mut() { + s.pointer_down(msg.wParam.0); + } + }); + } + let Some(feed) = FEED.get() else { + return false; + }; + let read_pen = || { + let mut info = POINTER_PEN_INFO::default(); + // SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a + // pointer that is not a pen. + unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?; + let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0; + Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact)) + }; + // SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message. + let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32); + if let Some(sample) = feed_update(msg.message, msg.wParam.0, read_pen, from_mouse) { + feed.set_sample(sample); + } + false +} + +/// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags` +/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen +/// in contact that reports none; and the eraser end while it is inverted or its eraser button is +/// pressed. +fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool) -> PenSample { + let pressure = match pressure { + 1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0, + _ if in_contact => 1.0, + _ => 0.0, + }; + PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0 } +} + +/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse, +/// not from a pen or a touch. +fn is_mouse(extra_info: u32) -> bool { + extra_info & SIGNATURE_MASK != MI_WP_SIGNATURE +} + +/// What the feed is set to for a message with this `wParam`: `Some(Some(sample))` for a pointer +/// message of a pen in range (`read_pen`), `Some(None)` for a pointer message of another pointer, +/// a pointer leaving detection range or the window, or a mouse message from a mouse +/// (`from_mouse`), and `None` to leave it as it is. +fn feed_update( + message: u32, + wparam: usize, + read_pen: impl FnOnce() -> Option, + from_mouse: impl FnOnce() -> bool, +) -> Option> { + match message { + WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP if (wparam >> 16) & POINTER_MESSAGE_FLAG_INRANGE == 0 => Some(None), + WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => Some(read_pen()), + WM_POINTERLEAVE => Some(None), + m if MOUSE_MESSAGES.contains(&m) && from_mouse() => Some(None), + _ => None, + } +} + +/// Before egui reads a frame's input: the primary button of a contact that started with the +/// barrel button held becomes the secondary button. +pub fn raw_input_hook(raw: &mut egui::RawInput) { + STROKES.with(|s| { + if let Ok(mut s) = s.try_borrow_mut() { + s.rewrite(&mut raw.events); + } + }); +} + +/// The pen contacts that press the secondary button. +#[derive(Default)] +struct BarrelStrokes { + /// Each `WM_POINTERDOWN`'s pointer id and whether the barrel button was held, oldest first, + /// until the touch of that contact starts. + pending: Vec<(u64, bool)>, + /// The contact whose touch started with the barrel button held, until it ends, the same pointer + /// starts another contact, or another contact starts with the barrel button held. + right: Option, +} + +/// A contact that started with the barrel button held. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Right { + id: TouchId, + /// Its secondary button is down: the press went to egui and the release has not. + down: bool, +} + +impl BarrelStrokes { + /// A `WM_POINTERDOWN` with this `wParam`, whose low word is the pointer id and whose high word + /// holds the pointer flags. + fn pointer_down(&mut self, wparam: usize) { + if self.pending.len() >= MAX_PENDING { + self.pending.remove(0); + } + self.pending.push(((wparam & 0xffff) as u64, (wparam >> 16) & POINTER_MESSAGE_FLAG_SECONDBUTTON != 0)); + } + + /// Makes the primary button of the right contact the secondary one. egui-winit sends a touch's + /// pointer button with the touch event it comes from: the press after the touch's start and + /// the pointer's move to it, the release right after its end. A canceled contact, or one + /// whose end never came (Windows does not promise one), gets a secondary release of its own. + fn rewrite(&mut self, events: &mut Vec) { + let release = |pos: Pos2| Event::PointerButton { pos, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }; + let mut out = Vec::with_capacity(events.len() + 1); + // The button event that comes next for the right contact: `Some(true)` for its press, + // `Some(false)` for its release. + let mut next = None; + for mut event in events.drain(..) { + let mut after = None; + match &mut event { + Event::Touch { id, phase, pos, .. } => { + let (id, phase, pos) = (*id, *phase, *pos); + if phase == TouchPhase::Start { + // Each start decides afresh, from the oldest contact of its pointer still waiting. + let barrel = match self.pending.iter().position(|&(p, _)| p == id.0) { + Some(i) => self.pending.remove(i).1, + None => false, + }; + if let Some(r) = self.right + && (barrel || r.id == id) + { + if r.down { + out.push(release(pos)); + } + self.right = None; + } + if barrel { + self.right = Some(Right { id, down: false }); + } + } + next = None; + if let Some(r) = self.right.filter(|r| r.id == id) { + match phase { + TouchPhase::Start => next = Some(true), + TouchPhase::Move => {} + TouchPhase::End => { + self.right = None; + next = Some(false); + } + TouchPhase::Cancel => { + self.right = None; + if r.down { + after = Some(release(pos)); + } + } + } + } + } + Event::PointerMoved(_) if next == Some(true) => {} + Event::PointerButton { button, pressed, .. } if next == Some(*pressed) && *button == PointerButton::Primary => { + *button = PointerButton::Secondary; + if let Some(r) = self.right.as_mut() { + r.down = *pressed; + } + next = None; + } + _ => next = None, + } + out.push(event); + out.extend(after); + } + *events = out; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::{TouchDeviceId, pos2}; + + /// `POINTER_MESSAGE_FLAG_INRANGE`, `_INCONTACT` and `_FIRSTBUTTON` (`winuser.h`): a pen tip + /// touching down. + const TIP: usize = 0x0002 | 0x0004 | 0x0010; + /// `POINTER_MESSAGE_FLAG_INRANGE` and `_INCONTACT` with the barrel button. + const BARREL: usize = 0x0002 | 0x0004 | POINTER_MESSAGE_FLAG_SECONDBUTTON; + + fn down(strokes: &mut BarrelStrokes, id: usize, flags: usize) { + strokes.pointer_down((flags << 16) | id); + } + + /// The events egui reads after the hook. + fn rewrite(strokes: &mut BarrelStrokes, events: &[Event]) -> Vec { + let mut events = events.to_vec(); + strokes.rewrite(&mut events); + events + } + + fn touch(id: u64, phase: TouchPhase) -> Event { + Event::Touch { device_id: TouchDeviceId(1), id: TouchId(id), phase, pos: pos2(10.0, 20.0), force: Some(0.5) } + } + + fn button(button: PointerButton, pressed: bool) -> Event { + Event::PointerButton { pos: pos2(10.0, 20.0), button, pressed, modifiers: Modifiers::NONE } + } + + /// What egui-winit sends for the touch that drives the pointer. + fn start(id: u64) -> Vec { + vec![touch(id, TouchPhase::Start), Event::PointerMoved(pos2(10.0, 20.0)), button(PointerButton::Primary, true)] + } + + fn end(id: u64) -> Vec { + vec![touch(id, TouchPhase::End), button(PointerButton::Primary, false), Event::PointerGone] + } + + fn buttons(events: &[Event]) -> Vec<(PointerButton, bool)> { + events.iter().filter_map(|e| if let Event::PointerButton { button, pressed, .. } = e { Some((*button, *pressed)) } else { None }).collect() + } + + const SECONDARY_DOWN: (PointerButton, bool) = (PointerButton::Secondary, true); + const SECONDARY_UP: (PointerButton, bool) = (PointerButton::Secondary, false); + const PRIMARY_DOWN: (PointerButton, bool) = (PointerButton::Primary, true); + const PRIMARY_UP: (PointerButton, bool) = (PointerButton::Primary, false); + + #[test] + fn a_pen_contact_with_the_barrel_button_presses_the_secondary_button() { + let mut strokes = BarrelStrokes::default(); + down(&mut strokes, 7, BARREL); + assert_eq!(buttons(&rewrite(&mut strokes, &start(7))), [SECONDARY_DOWN]); + let moved = [touch(7, TouchPhase::Move), Event::PointerMoved(pos2(15.0, 25.0))]; + assert_eq!(rewrite(&mut strokes, &moved), moved); + assert_eq!(buttons(&rewrite(&mut strokes, &end(7))), [SECONDARY_UP]); + assert_eq!(strokes.right, None, "the next contact starts afresh"); + assert!(strokes.pending.is_empty()); + } + + #[test] + fn a_pen_contact_with_the_tip_alone_keeps_the_primary_button() { + let mut strokes = BarrelStrokes::default(); + down(&mut strokes, 7, TIP); + let events = [start(7), end(7)].concat(); + assert_eq!(rewrite(&mut strokes, &events), events); + } + + #[test] + fn contacts_of_a_pen_within_one_frame_keep_their_order() { + // A tap with the barrel button held, then one with the tip alone, before the next frame. + let mut strokes = BarrelStrokes::default(); + down(&mut strokes, 7, BARREL); + down(&mut strokes, 7, TIP); + let events = rewrite(&mut strokes, &[start(7), end(7), start(7), end(7)].concat()); + assert_eq!(buttons(&events), [SECONDARY_DOWN, SECONDARY_UP, PRIMARY_DOWN, PRIMARY_UP]); + } + + #[test] + fn a_mouse_button_right_after_a_barrel_contact_keeps_its_button() { + let mut strokes = BarrelStrokes::default(); + down(&mut strokes, 7, BARREL); + let events = [start(7), vec![button(PointerButton::Primary, true)], end(7), vec![button(PointerButton::Primary, false)]].concat(); + assert_eq!(buttons(&rewrite(&mut strokes, &events)), [SECONDARY_DOWN, PRIMARY_DOWN, SECONDARY_UP, PRIMARY_UP]); + } + + #[test] + fn other_touches_and_the_mouse_keep_the_primary_button_during_a_barrel_contact() { + let mut strokes = BarrelStrokes::default(); + down(&mut strokes, 7, BARREL); + down(&mut strokes, 9, TIP); + let events = [start(7), start(9), vec![button(PointerButton::Primary, true)], end(9)].concat(); + assert_eq!(buttons(&rewrite(&mut strokes, &events)), [SECONDARY_DOWN, PRIMARY_DOWN, PRIMARY_DOWN, PRIMARY_UP]); + assert_eq!(strokes.right, Some(Right { id: TouchId(7), down: true }), "the barrel contact goes on"); + } + + #[test] + fn a_contact_after_a_lost_end_releases_the_secondary_button_first() { + let mut strokes = BarrelStrokes::default(); + down(&mut strokes, 7, BARREL); + rewrite(&mut strokes, &start(7)); + // No end arrives for that contact; the pen touches down again with the tip alone. + down(&mut strokes, 7, TIP); + let events = rewrite(&mut strokes, &[start(7), end(7)].concat()); + assert_eq!(buttons(&events), [SECONDARY_UP, PRIMARY_DOWN, PRIMARY_UP]); + assert_eq!(strokes.right, None); + // Another pen's barrel contact takes over from one whose end was lost. + down(&mut strokes, 7, BARREL); + rewrite(&mut strokes, &start(7)); + down(&mut strokes, 8, BARREL); + let events = rewrite(&mut strokes, &[start(8), end(8)].concat()); + assert_eq!(buttons(&events), [SECONDARY_UP, SECONDARY_DOWN, SECONDARY_UP]); + } + + #[test] + fn a_canceled_barrel_contact_releases_the_secondary_button() { + let mut strokes = BarrelStrokes::default(); + down(&mut strokes, 7, BARREL); + let events = rewrite(&mut strokes, &[start(7), vec![touch(7, TouchPhase::Cancel), Event::PointerGone]].concat()); + assert_eq!(buttons(&events), [SECONDARY_DOWN, SECONDARY_UP]); + assert_eq!(strokes.right, None); + } + + #[test] + fn a_barrel_contact_that_never_pressed_releases_nothing() { + // A finger drives the pointer, so egui-winit sends no button for the pen. + let mut strokes = BarrelStrokes::default(); + down(&mut strokes, 7, BARREL); + let events = [vec![touch(7, TouchPhase::Start)], vec![touch(7, TouchPhase::Cancel)]].concat(); + assert_eq!(rewrite(&mut strokes, &events), events); + down(&mut strokes, 7, BARREL); + down(&mut strokes, 7, TIP); + let events = [vec![touch(7, TouchPhase::Start)], start(7)].concat(); + assert_eq!(buttons(&rewrite(&mut strokes, &events)), [PRIMARY_DOWN]); + } + + /// `PEN_FLAG_BARREL` (`winuser.h`). + const PEN_FLAG_BARREL: u32 = 0x0001; + + #[test] + fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() { + let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true).eraser; + assert!(!eraser(0), "the tip"); + assert!(!eraser(PEN_FLAG_BARREL), "the barrel button"); + assert!(eraser(PEN_FLAG_INVERTED), "turned over"); + assert!(eraser(PEN_FLAG_ERASER), "the eraser button"); + assert!(eraser(PEN_FLAG_INVERTED | PEN_FLAG_ERASER)); + assert!(eraser(PEN_FLAG_INVERTED | PEN_FLAG_BARREL)); + } + + #[test] + fn a_pens_pressure_is_the_one_winit_gives_its_touch() { + assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true).pressure, 0.5); + assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true).pressure, 1.0); + assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false), PenSample { pressure: 0.0, eraser: true }, "hovering"); + assert_eq!(pen_sample(0, 0, 0, true).pressure, 1.0, "a pen in contact that reports no pressure presses fully"); + assert_eq!(pen_sample(300, 0, 0, true).pressure, 1.0, "a pressure without the pressure mask is not one"); + assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true).pressure, 1.0, "as winit, which gives no force for 0"); + assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false).pressure, 0.0); + } + + #[test] + fn mouse_messages_from_a_pen_or_a_touch_are_told_apart() { + assert!(is_mouse(0), "a mouse"); + assert!(!is_mouse(0xFF51_5701), "a pen"); + assert!(!is_mouse(0xFF51_5780), "a touch"); + assert!(is_mouse(0xFF51_5600)); + } + + #[test] + fn pen_messages_set_the_feed_and_other_pointers_clear_it() { + let pen = PenSample { pressure: 0.0, eraser: true }; + // `POINTER_MESSAGE_FLAG_INRANGE` in the high word of `wParam`, pointer 7 in the low word. + let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7; + let no_mouse = || -> bool { panic!("a pointer message is not a mouse message") }; + let no_pen = || -> Option { panic!("no pen to read") }; + for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] { + assert_eq!(feed_update(m, in_range, || Some(pen), no_mouse), Some(Some(pen)), "{m:#x}"); + assert_eq!(feed_update(m, in_range, || None, no_mouse), Some(None), "a touch: {m:#x}"); + assert_eq!(feed_update(m, 7, no_pen, no_mouse), Some(None), "out of range: {m:#x}"); + } + assert_eq!(feed_update(WM_POINTERLEAVE, in_range, no_pen, no_mouse), Some(None)); + // WM_MOUSEMOVE and WM_LBUTTONDOWN. + assert_eq!(feed_update(0x0200, 0, no_pen, || true), Some(None), "a mouse moved"); + assert_eq!(feed_update(0x0201, 0, no_pen, || false), None, "made from a pen"); + // WM_KEYDOWN. + assert_eq!(feed_update(0x0100, 0, no_pen, || -> bool { panic!("not a mouse message") }), None); + } + + #[test] + fn contacts_whose_touch_never_arrives_are_bounded() { + let mut strokes = BarrelStrokes::default(); + for id in 0..40 { + down(&mut strokes, id, BARREL); + } + assert_eq!(strokes.pending.len(), MAX_PENDING); + assert_eq!(strokes.pending.last(), Some(&(39, true))); + } +} diff --git a/apps/vectorcraft/tests/automation_args.rs b/apps/vectorcraft/tests/it/automation_args.rs similarity index 80% rename from apps/vectorcraft/tests/automation_args.rs rename to apps/vectorcraft/tests/it/automation_args.rs index ffb8773efe..93b33fa16d 100644 --- a/apps/vectorcraft/tests/automation_args.rs +++ b/apps/vectorcraft/tests/it/automation_args.rs @@ -1,6 +1,3 @@ -// 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::process::{Command, Stdio}; use std::time::{Duration, Instant}; @@ -25,7 +22,9 @@ fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) { .stderr(Stdio::piped()) .spawn() .unwrap(); - let deadline = Instant::now() + Duration::from_secs(5); + // Long enough for the binary to start on a loaded machine (the workspace's other tests run + // meanwhile), short enough to catch a desktop that started instead of exiting. + let deadline = Instant::now() + Duration::from_secs(30); let timed_out = loop { if child.try_wait().unwrap().is_some() { break false; @@ -58,11 +57,17 @@ fn missing_empty_or_option_operands_fail_before_startup() { } } +/// #3546: a root flag may be given more than once, in either spelling; a bad later operand still +/// stops the app before it starts. #[test] -fn duplicate_roots_fail_for_both_spellings() { +fn repeated_roots_are_accepted_for_both_spellings() { for flag in ["--automation-read-root", "--automation-write-root"] { - rejects(&[flag, ".", &format!("{flag}=.")], &format!("{flag} given twice")); - rejects(&[&format!("{flag}=."), flag, "."], &format!("{flag} given twice")); + let out = Command::new(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()); + rejects(&[flag, ".", flag, ""], &format!("{flag} needs a non-empty folder")); + rejects(&[&format!("{flag}=."), flag], &format!("{flag} needs a folder")); } } diff --git a/apps/vectorcraft/tests/help.rs b/apps/vectorcraft/tests/it/help.rs similarity index 60% rename from apps/vectorcraft/tests/help.rs rename to apps/vectorcraft/tests/it/help.rs index 5c77ecdbb7..059b9c476c 100644 --- a/apps/vectorcraft/tests/help.rs +++ b/apps/vectorcraft/tests/it/help.rs @@ -1,22 +1,22 @@ -// 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)] - //! `vectorcraft --help` prints the usage and exits before the app starts (#2110): run from a //! terminal, SSH or an agent's shell it used to open the window (or hang without a display). +use std::io::Read; 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, so a regression fails instead of opening a window. +/// 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) .args(args) .env_remove("DISPLAY") .env_remove("WAYLAND_DISPLAY") .env_remove("WAYLAND_SOCKET") - .env_remove("VECTORCRAFT_CONTROL_PORT") + .env("VECTORCRAFT_CONTROL_PORT", "not-a-port") .env("VECTORCRAFT_NO_PREFS", "1") .envs(env.iter().copied()) .stdin(Stdio::null()) @@ -24,15 +24,28 @@ fn run(args: &[&str], env: &[(&str, &str)]) -> Output { .stderr(Stdio::piped()) .spawn() .unwrap(); - let deadline = Instant::now() + Duration::from_secs(5); - while child.try_wait().unwrap().is_none() { - if Instant::now() >= deadline { - child.kill().unwrap(); - panic!("{args:?}: the app started instead of printing its usage"); - } - std::thread::sleep(Duration::from_millis(10)); - } - child.wait_with_output().unwrap() + // Both pipes end when the binary exits, however long a loaded machine takes to start it. The + // deadline only stops a binary that is still running. + let deadline = Instant::now() + Duration::from_secs(120); + let stdout = read_to_end(child.stdout.take().unwrap()); + let stderr = read_to_end(child.stderr.take().unwrap()); + let recv = |rx: &mpsc::Receiver>| rx.recv_timeout(deadline.saturating_duration_since(Instant::now())); + let (Ok(stdout), Ok(stderr)) = (recv(&stdout), recv(&stderr)) else { + child.kill().unwrap(); + panic!("{args:?}: the app started instead of printing its usage"); + }; + Output { status: child.wait().unwrap(), stdout, stderr } +} + +/// Reads `pipe` to its end on another thread. +fn read_to_end(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver> { + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let mut buf = Vec::new(); + let _ = pipe.read_to_end(&mut buf); + let _ = tx.send(buf); + }); + rx } fn prints_usage(args: &[&str], env: &[(&str, &str)]) { diff --git a/apps/vectorcraft/tests/it/main.rs b/apps/vectorcraft/tests/it/main.rs new file mode 100644 index 0000000000..d9dcf39cbb --- /dev/null +++ b/apps/vectorcraft/tests/it/main.rs @@ -0,0 +1,6 @@ +//! Integration tests: one test binary for the crate, one module per area. +// 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 automation_args; +mod help; diff --git a/assets/icons/dc-para-bullets.svg b/assets/icons/dc-para-bullets.svg new file mode 100644 index 0000000000..b87e678601 --- /dev/null +++ b/assets/icons/dc-para-bullets.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-para-numbers.svg b/assets/icons/dc-para-numbers.svg new file mode 100644 index 0000000000..27eb3cc2b1 --- /dev/null +++ b/assets/icons/dc-para-numbers.svg @@ -0,0 +1 @@ + diff --git a/clippy.toml b/clippy.toml index 0369326bcf..d02d2c40cc 100644 --- a/clippy.toml +++ b/clippy.toml @@ -3,3 +3,6 @@ allow-unwrap-in-tests = true allow-expect-in-tests = true allow-panic-in-tests = true +disallowed-types = [ + { path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" }, +] diff --git a/contributors/people.toml b/contributors/people.toml index 62fcd8d180..d43e6fa1b7 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -140,3 +140,32 @@ sync_github_name = false [people.KaboomFox] sync_github_name = true + +[people.odysseexp] +real_name = "Harley Paiva" +sync_github_name = true + +[people.addibble] +sync_github_name = true + +[people.mockydevs] +real_name = "Don Omondi" +display_name = "Don Omondi" + +[people.alpha-rock] +display_name = "Aditya Sisodiya" + +[people.Ronfo2013] +real_name = "Angelo Bernardini" +display_name = "Angelo Bernardini" +sync_github_name = false + +[people.DCaioP] +real_name = "Caio Pontes Magalhães" +display_name = "Caio Pontes" +sync_github_name = false + +[people.xbirks] +real_name = "Andrés Ortega Montoya" +display_name = "Andrés Ortega Montoya" +sync_github_name = false diff --git a/crates/affinity/README.md b/crates/affinity/README.md index 4ffdbabd88..62e2974d26 100644 --- a/crates/affinity/README.md +++ b/crates/affinity/README.md @@ -11,6 +11,7 @@ Affinity files. | Affinity | VectorCraft | |---|---| | Pages, Publisher spreads (one or two pages) | artboards, spreads side by side | +| Master pages (`MpCh`) shown on pages through master page instances (`MPIN`: master, page offset, master page, count) | a locked "Master A, B…" layer at the bottom holding each master page's objects on the pages that show it | | Artboards (legacy `ABEn` or Affinity 3 `phrp`/`aprp`), with name, paint and any transform | artboards plus a clip group with the actual vector outline, background and stroke | | Layers (`Scop`), groups (`Grup`), pass-through or isolated | layers and sublayers, groups | | Curves (`PCrv`): cubic subpaths, closed flags, live corners (`CnrD`) | paths (multi-subpath curves fill even-odd) | @@ -21,22 +22,24 @@ Affinity files. | Pixel masks (`MRst`, attached or as a layer in a group) | opacity mask | | Solid fills: RGBA, HSLA, CMYK, grey, Lab (D50) | fill appearance (alpha as fill opacity) | | Linear, elliptical and radial gradients with Affinity's midpoint bias | gradients (the bias as the midpoint where the blend is half way) | -| Strokes: weight, scale with object, dash pattern and phase, alignment, miter limit, behind the fill | stroke appearance | +| Strokes: weight, scale with object, dash pattern and phase, alignment, miter limit, behind the fill; a stroke whose style is None (every shape stores one, black and 1 px) is left out | stroke appearance | | Fill layers (`FRst`) | filled rectangles | -| Artistic and frame text: Unicode scalar-indexed runs, stored fallback font, family/weight/style, boolean OpenType features, all caps, size, tracking, fixed leading, colour, paragraph alignment, first baseline | point type and area type | +| Artistic and frame text: Unicode scalar-indexed runs, stored fallback font, family/weight/style, boolean OpenType features, all caps, underline, strikethrough, size, tracking, horizontal scale, fixed leading, colour, outlined characters, first baseline; each paragraph's alignment, indents, space before and after, fixed and automatic leading; frame text sized by its text scale (`FTxS`), not its frame's transform | point type and area type, one paragraph style per paragraph; artistic text whose paragraphs align differently keeps them aligned within its longest line (by indents), as Affinity draws it; a frame's first line hangs from its capitals' tops, and a frame whose last lines' descenders hang out of it is made just tall enough to show them; line breaks inside a paragraph become paragraphs without spacing between them; table cells place their text as Affinity does (centred from the capitals' tops to the last baseline, reaching out of a cell too short for it) | +| Tables (`TxtT`): grid, cell text, merged cells, cell insets and vertical alignment, the line on every cell edge | a group of area type per cell and a stroked line per edge (VectorCraft has no tables) | | Placed images (`ImgN`): the original JPEG/PNG embedded in the file | embedded images | -| Pixel layers (`Rstr`): RGBA 8/16-bit and CMYK 8-bit tiles, cropped to their content; source-backed RGBA8 JPEG/PNG tiles with matching dimensions and zero origin | embedded PNG images | -| Embedded documents and symbols (`EmbN`) | the picture Affinity cached of them | +| Pixel layers (`Rstr`): RGBA 8/16-bit and CMYK 8-bit tiles, cropped to their content; source-backed RGBA8 JPEG/PNG tiles with matching dimensions and zero origin; the document's CMYK colour profile (`CMYP`) | embedded PNG images; CMYK layers through the document's profile (relative colorimetric, black-point compensation, as Affinity converts them), or, without one, CMYK images that keep their inks | +| Embedded Affinity documents (`EmbN` with an `EmDc` entry), four deep at most | their first page's content, editable (their artboards only clip, they don't become artboards; their master pages are left out); other embedded documents and symbols as the picture Affinity cached of them | +| Layer effects: drop shadows, outer glows, inner shadows; outlines; colour and gradient overlays in any blend mode | Stylize › Drop Shadow and Outer Glow, Inner Glow at the edge (approximated); one more stroke on shapes (around their own stroke), the characters' stroke on text; overlays baked into fill, stroke, text colours and pixels (a group's over its children's) | | Opacity, visibility, lock, names, the blend modes VectorCraft has | the same | Everything else is reported in the import warnings, one line per kind with a count, never -dropped silently: layer effects, adjustment layers and live filters, brush and pressure strokes, -transparency gradients, fill opacity, bitmap fills, master pages, conical gradients (as radial), +dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush and pressure strokes, +transparency gradients, fill opacity, bitmap fills, master pages based on other master pages, conical gradients (as radial), special shapes (cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), corner types other than round or straight, stars with rounded points, several fills or strokes on one object (the -active one is used), outlined or scaled text, text fields such as page numbers, frames with -columns or a curved outline, paragraph indents/spacing, mixed paragraph alignments, unsupported font selectors, grey/Lab/32-bit pixels, CMYK pixels (converted to RGB without the -document's profile) and Affinity-only blend modes (Add, Linear Light… as Normal). +active one is used), skewed or flipped text, characters of different transparency in one text, text fields such as page numbers, text threading, frames with +columns or a curved outline, table cell fills, unsupported font selectors, grey/Lab/32-bit pixels, CMYK pixels with transparency in a document +without a CMYK profile (converted through VectorCraft's working CMYK profile) and Affinity-only blend modes (Add, Linear Light… as Normal). When the native document can't be read at all, the engine opens the embedded PNG preview instead, with a warning that names the reason; that preview can't be placed, used as a template or mined @@ -78,10 +81,22 @@ of CC0 sample files. * **Read-only.** Nothing is written in Affinity's format; export waits until someone can check written files in Affinity itself. -The reader also has an independent copy in PhotoCraft's `photocraft-affinity`. +The reader also has independent copies in PhotoCraft's `photocraft-affinity` and DesignCraft's +`designcraft-affinity`. Tables, paragraph formats, text scale, master pages, layer effects, +overlays, embedded documents, large pixel layers and HEIC photos were added in DesignCraft +([storytold/designcraft#291](https://github.com/storytold/designcraft/pull/291)) and brought back +here, from the same public fixtures and the thumbnails of documents their owners made, used only +locally. Automatic leading (the font size plus the font's line gap, for artistic and frame text) +was fitted on the thumbnails of one such local document with 56 artboards and on the public Patchy +text-frame fixture. ## Validation +* `engine/tests/it/affinity_features.rs` covers pages, several artboards per canvas and per spread, + master pages, tables, paragraph formats, text scale, layer effects, overlays and embedded + documents (whose artboards don't become artboards) on synthetic documents, and mutates them. + `engine/tests/it/affinity_local.rs` compares every artboard of local documents with their thumbnail + when `AFFINITY_SAMPLES` points at a folder (never in CI; nothing is committed). * Unit tests on synthetic containers built by the `synth` feature (stored, zlib and zstd entries, checksums, budgets, cycles, hostile streams, every truncation) and property tests of random mutations. @@ -91,7 +106,7 @@ The reader also has an independent copy in PhotoCraft's `photocraft-affinity`. feature probes plus one separately identified derived regression input from [SethRobinson/Patchy](https://github.com/SethRobinson/Patchy). Only document data and provenance notices were inspected, never that project's importer or authoring scripts. -* `tests/real_files.rs` parses every file and freezes the modeled features of all 33 current +* `tests/it/real_files.rs` parses every file and freezes the modeled features of all 33 current `.af` files. Native raster tests compare decoded pixels with independent embedded images; text tests assert Unicode run boundaries, fallback fonts and feature retention. * `engine/tests/affinity_corpus.rs` requires editable native import, exact `.vectorcraft` @@ -104,9 +119,14 @@ The reader also has an independent copy in PhotoCraft's `photocraft-affinity`. pass CI. Run locally with `AFFINITY_CORPUS_REQUIRED=1` for the same strict gate. * Synthetic engine regressions cover nested, rotated and curved artboards, negative origins, multiple spreads and resolution conversion, alongside text recovery and native save/export. -* `engine/tests/import_fuzz.rs` mutates a synthetic native document's stream and archive and checks - that whatever opens also renders and exports; `fuzz/` has `cargo-fuzz` targets for the whole - reader (`container`) and the object stream (`stream`): +* `engine/tests/import_fuzz.rs` mutates a synthetic native document's stream and archive, and + documents with layer effects, colour overlays (also over tables), line styles, paragraph and + character formats, tables, master pages, CMYK pixel layers and embedded documents (the embedding + and the embedded stream), and checks that whatever opens also renders and exports. + `tests/it/import_limits.rs` builds hostile documents against the limits below: grids of 16 million + cells, grids and stories shared by many layers, 200 000 paragraphs, a document embedded hundreds + of times. `fuzz/` has `cargo-fuzz` targets for the whole reader (`container`) and the object + stream (`stream`): ```sh cd crates/affinity @@ -132,11 +152,23 @@ anything is allocated: a value takes about 40 bytes in memory however few it too those 189 public documents uses 3.3 million), 384 levels of object nesting, 128 levels of layers, 500 000 layers, four million curve nodes per curve; compound outlines also cap recursion at 128 levels, operand visits at 100 000 and cumulative geometry work at four million, rejecting cycles and partial results on limits. -Pie sweeps normalize finite angles in constant time. Pixel layers are limited to 64 megapixels -(cropped to their content first); gradients to 1024 stops. Text collection is bounded to a -million characters per node before allocation, with a cumulative 16 MiB budget for owned font -names, features and gradient stops. Exhaustion warns and uses default attributes for remaining -text, preserving its characters. +Pie sweeps normalize finite angles in constant time. Pixel layers are decoded at no more than 64 +megapixels each (cropped to their content first; larger ones are read at a half, a quarter… of +their resolution) and 512 megapixels for the whole document; pixel masks are read only over what +they mask (all of it under artistic text, whose glyphs only the layout places). One budget covers +the whole read: layers, pixels, 16 million characters of stories and 262 144 table cells, so +content that many layers link, or a document embedded many times, can't multiply them. Embedded +documents nest four deep at most; both of their readings are charged to that budget and to the +importing document's archive limits, also when they fail part of the way. Tables have at most +4096 rows and columns and 65 536 cells, and 64 layer effects per node are read. Gradients are +limited to 1024 stops. Text collection is bounded to a million characters per node before +allocation, with a cumulative 16 MiB budget for owned font names (256 bytes at most each), +features and gradient stops; paragraph formats are matched to runs by binary search. Exhaustion +warns and uses default attributes for remaining text, preserving its characters. Colour and +gradient overlays share one work budget per import (`overlay::MAX_WORK`: the nodes and pixels +each is baked into); past it they are left out, and said. In VectorCraft, master pages are +copied onto at most as many objects, characters and pixels as a document may hold, a few times +over, and objects beyond `MAX_COORD` of the origin are left out. Every archive entry's CRC-32 and size must match. Malformed input returns an `Error`; the crate has no panics outside tests. diff --git a/crates/affinity/src/container.rs b/crates/affinity/src/container.rs index 31179a3a0e..6b1df95103 100644 --- a/crates/affinity/src/container.rs +++ b/crates/affinity/src/container.rs @@ -263,6 +263,21 @@ impl<'a> Archive<'a> { } /// 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> { let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?.clone(); let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?; diff --git a/crates/affinity/src/geometry.rs b/crates/affinity/src/geometry.rs index 5d74638ada..8e84e48077 100644 --- a/crates/affinity/src/geometry.rs +++ b/crates/affinity/src/geometry.rs @@ -215,7 +215,13 @@ fn anchors(records: &[Value]) -> Option> { 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()) { - let corner = |a: &Anchor| radii.iter().filter(|(rec, _)| *rec == a.record).map(|(_, r)| *r).fold(0.0, f64::max); + // 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(); diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs index 4be46c7770..38d86a8990 100644 --- a/crates/affinity/src/lib.rs +++ b/crates/affinity/src/lib.rs @@ -14,6 +14,7 @@ mod access; pub mod container; mod geometry; pub mod model; +pub mod overlay; pub mod paint; pub mod preview; mod raster; diff --git a/crates/affinity/src/model.rs b/crates/affinity/src/model.rs index 298e32be21..a6d18f339e 100644 --- a/crates/affinity/src/model.rs +++ b/crates/affinity/src/model.rs @@ -1,4 +1,4 @@ -//! The document model VectorCraft imports: spreads, artboards, layers, groups, curves, shapes, +//! 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. @@ -8,6 +8,16 @@ 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]); @@ -175,17 +185,54 @@ pub struct TextRun { /// 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, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +/// 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, @@ -202,12 +249,69 @@ pub struct Text { 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), } @@ -246,11 +350,78 @@ pub enum Kind { 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, @@ -264,6 +435,8 @@ pub struct Node { 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, } @@ -285,347 +458,14 @@ 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, -} - -/// Deepest layer nesting followed; deeper content is reported, not imported. -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; - -/// 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 { - let mut archive = Archive::open(bytes, limits)?; - let doc = archive.read("doc.dat")?; - let s = stream::parse(&doc)?; - let mut reader = Reader::new(&s, &mut archive); - reader.pixels_left = pixels; - reader.document() -} - -pub(crate) struct Reader<'s, 'a, 'b> { - pub(crate) s: &'s Stream, - pub(crate) archive: &'b mut Archive<'a>, - pub(crate) dpi: f64, - warnings: BTreeMap, - nodes: usize, - active: HashSet, - /// Pixels the pixel layers still to come may decode ([`MAX_LAYER_PIXELS`] in all). - pub(crate) pixels_left: u64, -} - -impl<'s, 'a, 'b> Reader<'s, 'a, 'b> { - fn new(s: &'s Stream, archive: &'b mut Archive<'a>) -> Self { - Self { s, archive, dpi: 72.0, warnings: BTreeMap::new(), nodes: 0, active: HashSet::new(), pixels_left: MAX_LAYER_PIXELS } - } - - pub(crate) fn warn(&mut self, what: impl Into) { - *self.warnings.entry(what.into()).or_default() += 1; - } - - 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"))?; - let mut spreads = Vec::new(); - for spread in s.objs(doc, b"Chld") { - if !s.is(spread, b"Sprd") { - self.warn("an unknown kind of page"); - continue; - } - let pages = pages(s, spread); - 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, Affine::IDENTITY, 0)?; - if mask.is_some() { - self.warn("mask layers directly on a page (imported without them)"); - } - spreads.push(Spread { bounds, pages, transparent, nodes }); - } - if spreads.is_empty() { - return Err(Error::Malformed("document has no pages")); - } - if !s.objs(doc, b"MpCh").is_empty() { - self.warn("master pages (their content is not placed on the pages that use them)"); - } - let warnings = self.warnings.into_iter().map(|(w, n)| if n > 1 { format!("{w} ({n}×)") } else { w }).collect(); - Ok(Document { dpi: self.dpi, spreads, saved_by, warnings }) - } - - /// The children of `parent`, and the pixel mask a mask layer among them puts on the parent. - fn children(&mut self, parent: ObjId, world: Affine, depth: usize) -> Result<(Vec, Option), Error> { - let s = self.s; - let mut out = Vec::new(); - let mut mask = None; - for c in s.objs(parent, b"Chld") { - 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); - match crate::raster::mask(self, c, local.then(world))? { - Some(m) if mask.is_none() => mask = Some(m), - Some(_) => self.warn("several pixel masks on one layer (only the first is used)"), - None => {} - } - 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); - } - self.nodes += 1; - if self.nodes > MAX_NODES { - return Err(Error::Limit("too many layers")); - } - // 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)); - let name = s.str(id, b"Desc").unwrap_or_default().to_string(); - 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)? - }; - // A compound's children are its operands, already merged into its outline. - let (children, child_mask) = if class == Tag::of(b"Comp") { (Vec::new(), None) } else { self.children(id, world, depth)? }; - let (mask, attached_mask) = self.attached_masks(id, world)?; - let pixel_mask = attached_mask.or(child_mask); - self.active.remove(&id); - if s.objs(id, b"FiEf").iter().any(|e| s.bool(*e, b"Enab") != Some(false)) { - self.warn("layer effects (shadows, glows, outlines, bevels…)"); - } - Ok(Some(Node { class, name, visible, locked, opacity, blend, kind, mask, pixel_mask, children })) - } - - 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); - }; - let (fills, strokes) = paint::node_paint(self, id, world); - Kind::Shape { path: local.transformed(world), fills, strokes, even_odd } - } - 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"EmbN" => 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 - } - }) - } - - /// 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) -> 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)? { - 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 { - self.warn(format!("{} layers attached to other layers (imported without them)", describe(class))); - } - } - Ok((mask, pixels)) - } - - 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 } - } -} - -/// Page rectangles: `SpMd.PagR[].rctp` (Publisher 2, Affinity 3) or `SprB` split into `PagC` -/// equal pages (Publisher 1 facing spreads). -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) } -} - -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", - } + /// 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 new file mode 100644 index 0000000000..0a48193e2b --- /dev/null +++ b/crates/affinity/src/model/bounds.rs @@ -0,0 +1,142 @@ +use super::read::MAX_TREE_DEPTH; +use super::*; + +/// 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 new file mode 100644 index 0000000000..755e93745a --- /dev/null +++ b/crates/affinity/src/model/read.rs @@ -0,0 +1,605 @@ +use super::bounds::{describe, is_container, mask_extent, nodes_bounds, pages, rect, tree_bounds, union}; +use super::*; + +/// 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; + +/// 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, +} + +impl Budget { + pub(crate) const FULL: Budget = Budget { nodes: MAX_NODES, pixels: MAX_LAYER_PIXELS, chars: MAX_DOCUMENT_CHARS, cells: MAX_DOCUMENT_CELLS }; +} + +/// 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); + 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; + for c in s.objs(parent, b"Chld") { + 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).collect(); + 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); + }; + 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)"), + } + } + out + } + + /// 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 { + 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 } + } +} diff --git a/crates/affinity/src/overlay.rs b/crates/affinity/src/overlay.rs new file mode 100644 index 0000000000..170c50ec38 --- /dev/null +++ b/crates/affinity/src/overlay.rs @@ -0,0 +1,663 @@ +//! 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)), + 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))) => { + let q = m.apply(Point { x: (i % width) as f64 + 0.5, y: (i / width) as f64 + 0.5 }); + let c = sample(g, 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()) +} + +/// The gradient's colour at unit-space point `q`. +fn sample(g: &Gradient, 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; + } + for w in g.stops.windows(2) { + let [a, b] = [&w[0], &w[1]]; + if t <= b.offset { + 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 index c4ebff8446..8f9e424aae 100644 --- a/crates/affinity/src/paint.rs +++ b/crates/affinity/src/paint.rs @@ -126,6 +126,9 @@ pub struct Stroke { /// 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()), @@ -136,6 +139,14 @@ fn floats(v: &Value) -> Option> { /// 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> { @@ -167,7 +178,13 @@ pub(crate) fn color(r: &mut Reader, id: ObjId) -> Option { } b"Pant" => { r.warn("spot colours (imported as their RGB equivalent)"); - return s.obj(id, b"srgb").and_then(|c| color(r, c)).or_else(|| s.obj(id, b"base").and_then(|c| color(r, c))); + 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 }, _ => { @@ -283,7 +300,7 @@ pub(crate) fn node_paint(r: &mut Reader, id: ObjId, local: Affine) -> (Vec Option { +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 { @@ -295,6 +312,13 @@ fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, behind: bool) 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 @@ -312,6 +336,10 @@ fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, behind: bool) _ => 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) { diff --git a/crates/affinity/src/raster.rs b/crates/affinity/src/raster.rs index 98334717d3..d458c08a7d 100644 --- a/crates/affinity/src/raster.rs +++ b/crates/affinity/src/raster.rs @@ -39,6 +39,9 @@ pub(crate) fn node_image(r: &mut Reader, id: ObjId, world: Affine) -> Result {} 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)"), @@ -66,8 +69,17 @@ pub(crate) fn node_image(r: &mut Reader, id: ObjId, world: Affine) -> Result Result, Error> { +/// 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); @@ -76,7 +88,41 @@ pub(crate) fn mask(r: &mut Reader, id: ObjId, world: Affine) -> Result 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. @@ -99,33 +145,41 @@ pub(crate) fn embedded(r: &mut Reader, id: ObjId, world: Affine) -> Result 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); - let pixels = u64::from(w) * u64::from(h); - if pixels > MAX_PIXELS { - r.warn("pixel layers larger than 64 megapixels"); - return Ok(None); + // 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 Some(left) = r.pixels_left.checked_sub(pixels) else { + 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.pixels_left = left; + 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) => { - r.warn("CMYK pixel layers (converted to RGB without the document's colour profile)"); - (5, 1) - } + Some(4) => (5, 1), _ => { r.warn("pixel layers in grey, Lab or 32-bit formats"); return Ok(None); @@ -152,11 +206,48 @@ fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affi } 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), &mut cache)?); + 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 { @@ -167,17 +258,9 @@ fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affi }; 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 if channels == 5 { - let k = 1.0 - v[3]; - ((1.0 - v[0]) * k, (1.0 - v[1]) * k, (1.0 - v[2]) * k, v[4]) - } else { - (v[0], v[1], v[2], v[3]) - }; + 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)); } - let transform = Affine([1.0, 0.0, 0.0, 1.0, f64::from(x0), f64::from(y0)]).then(world); Ok(Some(Image { width: w, height: h, pixels: Pixels::Rgba8(rgba), transform })) } @@ -229,28 +312,57 @@ fn tag(prefix: &[u8; 3], c: usize) -> [u8; 4] { [prefix[0], prefix[1], prefix[2], b'0' + c as u8] } -/// One channel of level 0, cropped to (x0, y0, w, h) pixels; `bps` bytes per sample. +/// 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)); + let states: Vec = match s.field(bitmap, &tag(b"Sta", c)) { + Some(Value::Array(a)) => a.iter().map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(), + _ => 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 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 * 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)); - let states: Vec = match s.field(bitmap, &tag(b"Sta", c)) { - Some(Value::Array(a)) => a.iter().map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(), - _ => Vec::new(), - }; + let (tw, th, states) = grid(s, bitmap, c, bps); let tiles = s.objs(bitmap, &tag(b"Idx", c)); - let row = (w as usize) * bps; - let mut out = vec![0u8; row * h as usize]; + 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; @@ -267,7 +379,7 @@ fn plane( continue; } let name = s.entry(blck, b"Data").ok_or(Error::Malformed("pixel tile without data"))?.to_string(); - if !cache.contains_key(&name) { + 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") { @@ -276,10 +388,20 @@ fn plane( 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, row, (bx0, py0, bx1, py1), (ox, oy), |x, y| tile.get(y * TILE + x).copied().unwrap_or(0)); + copy(&mut out, &at, (ox, oy), |x, y| tile.get(y * TILE + x).copied().unwrap_or(0)); continue; } 3 => { @@ -289,9 +411,7 @@ fn plane( 5 => { if let Some((source_width, pixels)) = source.as_ref() { let (ox, oy) = (tx * TILE, ty * TILE); - copy(&mut out, row, (bx0, py0, bx1, py1), (ox, oy), |x, y| { - pixels.get(((oy + y) * source_width + ox + x) * 4 + c - 1).copied().unwrap_or(0) - }); + 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)"); @@ -300,17 +420,38 @@ fn plane( _ => return Err(Error::Malformed("unknown pixel tile state")), }; if let Some(v) = fill { - copy(&mut out, row, (bx0, py0, bx1, py1), (tx * TILE, ty * TILE), |_, _| v); + copy(&mut out, &at, (tx * TILE, ty * TILE), |_, _| v); } } Ok(out) } -/// Copy the overlap of a tile at byte column `ox`, row `oy` into the cropped plane. -fn copy(out: &mut [u8], row: usize, (bx0, py0, bx1, py1): (usize, usize, usize, usize), (ox, oy): (usize, usize), at: impl Fn(usize, usize) -> u8) { - for y in oy.max(py0)..(oy + TILE).min(py1) { +/// 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) { - if let Some(b) = out.get_mut((y - py0) * row + (x - bx0)) { + 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); } } @@ -323,6 +464,15 @@ mod tests { 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()); @@ -333,18 +483,29 @@ mod tests { /// 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(0, 0)), + (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..=4 { + 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(vec![5, 4]))); + 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}")))])]), @@ -369,18 +530,44 @@ mod tests { 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].into_iter().map(|v| vec![v; TILE_BYTES]).collect(); - synth::container( - &[ - ("doc.dat", &doc, Method::Zlib), - ("c/1", &block, Method::Zlib), - ("d/1", &tiles[0], Method::Zlib), - ("d/2", &tiles[1], Method::Zlib), - ("d/3", &tiles[2], Method::Zlib), - ("d/4", &tiles[3], Method::Zlib), - ], - None, - ) + 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] diff --git a/crates/affinity/src/stream.rs b/crates/affinity/src/stream.rs index a755747c45..7a3010251f 100644 --- a/crates/affinity/src/stream.rs +++ b/crates/affinity/src/stream.rs @@ -303,6 +303,10 @@ impl Parser<'_> { 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")); } diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs index 006f9e7bda..eeb709d34d 100644 --- a/crates/affinity/src/tests.rs +++ b/crates/affinity/src/tests.rs @@ -1,4 +1,4 @@ -//! Unit tests on synthetic inputs; `tests/real_files.rs` covers public Affinity documents. +//! Unit tests on synthetic inputs; `tests/it/real_files.rs` covers public Affinity documents. mod preview { use crate::container::header; @@ -261,6 +261,32 @@ mod archive { assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_)))); } + // 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]; diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs index 2b632cab32..1a3b6e5442 100644 --- a/crates/affinity/src/text.rs +++ b/crates/affinity/src/text.rs @@ -2,7 +2,7 @@ //! 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, Point, Reader, Text, TextRun, rect}; +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}; @@ -11,92 +11,16 @@ 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 mut runs = Vec::new(); - let mut 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") { - 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. - let budget = MAX_CHARS - 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) 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 { - let inline = s.objs(seg, b"Glys").len(); - v.extend(std::iter::repeat_n('\u{FFFC}', inline.min(budget + 1 - v.len()))); - placeholders |= inline > 0; - v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take(budget + 1 - v.len())); - if v.len() > budget { - break; - } - } - v - } - }; - let truncated = chars.len() > budget; - if truncated { - chars.truncate(budget); - r.warn("text longer than a million characters (truncated)"); - } - total += chars.len(); - let mut start = 0usize; - for run in s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default() { - 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; - } - let text = characters(&chars, start, end); - start = end; - push_run(r, &mut runs, s.obj(run, b"Item"), text, world, &mut attribute_budget); - } - if start < chars.len() { - let text = characters(&chars, start, chars.len()); - push_run(r, &mut runs, None, text, world, &mut attribute_budget); - } - for paragraph in s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default() { - if let Some(attrs) = s.obj(paragraph, b"Item") { - let paragraph = paragraph_align(r, attrs); - match align { - None => align = Some(paragraph), - Some(first) if first != paragraph => r.warn("mixed paragraph alignments (the first alignment is used)"), - _ => {} - } - } - } - if truncated { - break; - } - } - if placeholders { - r.warn("text fields such as page numbers (left out of the text)"); - } - let align = align.unwrap_or(Align::Left); + 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, @@ -111,19 +35,256 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option { r.warn("text frames with a curved outline (imported as rectangular frames)"); } } - Some(Text { runs, align, anchor: Point { x: anchor_x, y: first_baseline }, frame: if artistic { None } else { Some(bounds) }, transform: world }) + 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; + +/// 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() { + match target.and_then(|i| cells.get_mut(i)) { + Some(cell) => cell.runs.push(TextRun { text: part.to_string(), ..run.clone() }), + None => 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") { + 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 s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default() { + 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 s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default() { + 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) { +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() => run_attrs(r, attrs, text, world, attribute_budget), + 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() { @@ -137,10 +298,15 @@ fn push_run(r: &mut Reader, runs: &mut Vec, attrs: Option, text: 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, } } }; @@ -195,13 +361,33 @@ fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine, attribut fill = Paint::Solid(Color::Gray { v: 0.0, a: 1.0 }); } } - if attribute_budget.is_some() && objects.get(1).copied().flatten().and_then(|f| paint::descriptor(r, f, world)).is_some_and(|p| p != Paint::None) - { - r.warn("outlined (stroked) text"); - } - if slot(doubles, 10, float).is_some_and(|h| (h - 1.0).abs() > 1e-3) { - r.warn("horizontally scaled text"); + // 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 @@ -220,8 +406,8 @@ fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine, attribut 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 = metadata_string(r, attribute_budget, font.and_then(|f| s.str(f, b"Post")).unwrap_or_default()); - let family = metadata_string(r, attribute_budget, font.and_then(|f| s.str(f, b"Famy")).unwrap_or_default()); + 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) { @@ -238,10 +424,15 @@ fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine, attribut 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(), } } @@ -260,6 +451,17 @@ fn charge_attributes(r: &mut Reader, budget: &mut Option, bytes: usize) - } } +/// 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() } @@ -303,13 +505,18 @@ fn font_features(r: &mut Reader, attrs: Option, attribute_budget: &mut Op (features, all_caps) } -fn paragraph_align(r: &mut Reader, p: ObjId) -> Align { - // Nonzero offsets in these slots are present in the public text-indent and text-para-spacing - // fixtures. Their layout is not represented by this importer; retain text and report the gap. - if (1..=6).any(|i| slot(r.s.field(p, b"Doub"), i, float).is_some_and(|v| v.abs() > 1e-9)) { - r.warn("paragraph indents or spacing (imported with defaults)"); - } - match slot(r.s.field(p, b"Ints"), 0, int) { +/// 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, @@ -318,5 +525,29 @@ fn paragraph_align(r: &mut Reader, p: ObjId) -> Align { 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/import_limits.rs b/crates/affinity/tests/it/import_limits.rs new file mode 100644 index 0000000000..088c33912f --- /dev/null +++ b/crates/affinity/tests/it/import_limits.rs @@ -0,0 +1,176 @@ +//! Crafted documents can't make the reader allocate or work without bound: tables, shared +//! stories, paragraphs and embedded documents stay within the whole read's budget, however often +//! a file links or embeds the same content. Original synthetic documents in the reader's +//! accepted schema; no Affinity software or files were used. + +use crate::text_fixture::*; +use vectorcraft_affinity::{ + Document, Error, Limits, + model::{Kind, Node}, + read, + synth::{self, F, Method, tag}, +}; + +type Field = (vectorcraft_affinity::stream::Tag, F); + +/// A document of one spread holding `nodes`, plus these other archive entries. +fn file(nodes: Vec, entries: &[(&str, &[u8])]) -> Vec { + let spread = F::Obj(tag(b"Sprd"), vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(nodes))]); + let mut root = vec![(tag(b"DocR"), F::Obj(tag(b"DocN"), vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]; + let mut next_id = 1000; + for (_, value) in &mut root { + shared_objects(value, &mut next_id); + } + let data = synth::stream(&root); + let mut all = vec![("doc.dat", data.as_slice(), Method::Zlib)]; + all.extend(entries.iter().map(|(name, bytes)| (*name, *bytes, Method::Stored))); + synth::container(&all, None) +} + +fn open(nodes: Vec) -> Document { + read(&file(nodes, &[]), Limits::default()).unwrap() +} + +fn all(nodes: &[Node]) -> Vec<&Node> { + let mut out = Vec::new(); + for n in nodes { + out.push(n); + out.extend(all(&n.children)); + } + out +} + +fn warned(d: &Document, needle: &str) -> bool { + d.warnings.iter().any(|w| w.contains(needle)) +} + +fn story(text: &str) -> F { + F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![block(utf8(text), vec![run(text.chars().count() as i32, None)], &[])]))]) +} + +fn artistic(story: F) -> F { + F::Obj( + tag(b"TxtA"), + vec![ + (tag(b"StSt"), story), + (tag(b"TxtH"), F::Obj(tag(b"ArFr"), vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, 100.0, 20.0])), (tag(b"ArtV"), F::F64(16.0))])), + ], + ) +} + +/// A table frame (`TbFr`) with a grid of `cols` × `rows` cells and no cell objects or lines. +fn grid(cols: usize, rows: usize) -> Vec { + let pos = |n: usize| { + let v: Vec = (0..=n).map(|i| i as f64).collect(); + F::Obj(tag(b"TPos"), vec![(tag(b"Posn"), array_f64(b"Posn", &v))]) + }; + let table = F::Obj(tag(b"Tabl"), vec![(tag(b"CPos"), pos(cols)), (tag(b"RPos"), pos(rows))]); + vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, cols as f64, rows as f64])), (tag(b"Tabl"), table)] +} + +fn table(frame: F) -> F { + F::Obj(tag(b"TxtT"), vec![(tag(b"StSt"), story("A")), (tag(b"TxtH"), frame)]) +} + +fn tables(d: &Document) -> Vec<&vectorcraft_affinity::model::Table> { + all(&d.spreads[0].nodes).into_iter().filter_map(|n| if let Kind::Table(t) = &n.kind { Some(t) } else { None }).collect() +} + +#[test] +fn a_table_of_more_than_65536_cells_is_left_out_before_its_cells_are_made() { + // 4096 × 4096 is within each dimension's limit but 16.7 million cells. + let d = open(vec![table(F::Obj(tag(b"TbFr"), grid(4096, 4096))), table(F::Obj(tag(b"TbFr"), grid(256, 256)))]); + let t = tables(&d); + assert_eq!(t.len(), 1); + assert_eq!((t[0].cells.len(), t[0].vertical.len(), t[0].horizontal.len()), (65536, 0, 0), "no lines when they don't match"); + assert!(warned(&d, "tables with more than 65536 cells"), "{:?}", d.warnings); +} + +#[test] +fn tables_sharing_one_grid_stay_within_the_cells_of_one_document() { + // One 65536-cell grid linked from five tables: four fill the document's 262144 cells. + let shared = F::Def(2_000_000, vec![tag(b"TbFr")], grid(256, 256)); + let d = open((0..5).map(|i| table(if i == 0 { shared.clone() } else { F::Ref(2_000_000) })).collect()); + assert_eq!(tables(&d).len(), 4); + assert!(warned(&d, "tables beyond the cells one document may hold"), "{:?}", d.warnings); +} + +#[test] +fn a_shared_story_is_read_within_the_characters_of_one_document() { + // A story of a million characters linked from twenty text layers: 16 million in all. + let text = "x".repeat(1 << 20); + let shared = F::Def(2_000_000, vec![tag(b"Stry")], vec![(tag(b"Blok"), F::Shared(vec![block(utf8(&text), vec![run(1 << 20, None)], &[])]))]); + let d = open((0..20).map(|i| artistic(if i == 0 { shared.clone() } else { F::Ref(2_000_000) })).collect()); + let chars: usize = all(&d.spreads[0].nodes) + .into_iter() + .filter_map(|n| if let Kind::Text(t) = &n.kind { Some(t.runs.iter().map(|r| r.text.len()).sum::()) } else { None }) + .sum(); + assert_eq!(chars, 16 << 20); + assert!(warned(&d, "text beyond the characters one document may hold"), "{:?}", d.warnings); +} + +#[test] +fn many_paragraphs_and_runs_are_matched_in_about_linear_time() { + // 200 000 paragraphs, each with its own run and format. + let n = 200_000; + let text = "a\u{2029}".repeat(n); + let fmt = + |end: usize| vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))]; + let blk = F::Obj( + tag(b"StBl"), + vec![ + (tag(b"Glyp"), utf8(&text)), + (tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])), + (tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])), + ], + ); + let started = std::time::Instant::now(); + let d = open(vec![artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]))]); + let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") }; + assert_eq!(t.runs.len(), n); + // (About half a second; quadratic matching took over half a minute on the same machine.) + assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed()); +} + +/// A shape node of `size` px. +fn rect(size: f64) -> F { + F::Obj(tag(b"ShpN"), vec![(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, size, size])), (tag(b"Shpe"), F::Obj(tag(b"ShNR"), vec![]))]) +} + +/// An instance of the embedded document in archive entry `edc/1`, with `children` of its own. +fn embedded(children: Vec) -> F { + let content = F::Obj(tag(b"EmbC"), vec![(tag(b"EmbC"), F::Entry("edc/1".into()))]); + let mut fields = vec![(tag(b"Bitm"), F::Obj(tag(b"EmbR"), vec![(tag(b"EmCn"), content)]))]; + if !children.is_empty() { + fields.push((tag(b"Chld"), F::Shared(children))); + } + F::Obj(tag(b"EmbN"), fields) +} + +fn embedding(inner: &[u8], nodes: Vec) -> Vec { + let mut entry = b"EmDc\0\0\0\0".to_vec(); + entry.extend_from_slice(inner); + file(nodes, &[("edc/1", &entry)]) +} + +#[test] +fn an_embedded_documents_content_stays_with_its_node() { + // Read before the node's own children, which must not take it. + let inner = file(vec![rect(10.0), rect(20.0)], &[]); + let d = read(&embedding(&inner, vec![embedded(vec![rect(5.0)])]), Limits::default()).unwrap(); + let node = &d.spreads[0].nodes[0]; + assert_eq!(node.children.len(), 3, "its own child and the embedded document's two shapes"); + assert!(node.children.iter().all(|c| c.children.is_empty())); +} + +#[test] +fn embedding_one_document_many_times_shares_one_budget() { + // 2000 shapes, embedded 300 times and read twice each: 1.2 million nodes, past the 500 000 + // a whole read may take (each embedding used to have an allowance of its own). + let inner = file((0..2000).map(|_| rect(10.0)).collect(), &[]); + let outer = embedding(&inner, (0..300).map(|_| embedded(Vec::new())).collect()); + assert!(matches!(read(&outer, Limits::default()), Err(Error::Limit(_)))); + // Embedded fewer times, it opens. + let d = read(&embedding(&inner, (0..50).map(|_| embedded(Vec::new())).collect()), Limits::default()).unwrap(); + assert_eq!(all(&d.spreads[0].nodes).len(), 50 + 50 * 2000); +} diff --git a/crates/affinity/tests/it/main.rs b/crates/affinity/tests/it/main.rs new file mode 100644 index 0000000000..84b3430191 --- /dev/null +++ b/crates/affinity/tests/it/main.rs @@ -0,0 +1,20 @@ +//! Integration tests: one test binary for the crate, one module per area. +// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[path = "../support/corpus.rs"] +mod corpus; +#[path = "../support/features.rs"] +mod features; +#[cfg(feature = "synth")] +#[path = "../support/text_fixture.rs"] +mod text_fixture; + +#[cfg(feature = "synth")] +mod import_limits; +#[cfg(feature = "synth")] +mod outline_limits; +mod raster; +mod real_files; +#[cfg(feature = "synth")] +mod text; diff --git a/crates/affinity/tests/outline_limits.rs b/crates/affinity/tests/it/outline_limits.rs similarity index 98% rename from crates/affinity/tests/outline_limits.rs rename to crates/affinity/tests/it/outline_limits.rs index b48eb494b2..74151c192f 100644 --- a/crates/affinity/tests/outline_limits.rs +++ b/crates/affinity/tests/it/outline_limits.rs @@ -1,7 +1,5 @@ //! Original synthetic graph tests for bounded `.af` outline expansion. These model the reader's //! accepted schema, without using Affinity software, third-party parser code or external assets. -#![cfg(feature = "synth")] -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use vectorcraft_affinity::{ Document, Limits, diff --git a/crates/affinity/tests/raster.rs b/crates/affinity/tests/it/raster.rs similarity index 91% rename from crates/affinity/tests/raster.rs rename to crates/affinity/tests/it/raster.rs index e477b4d26b..794b4c4f13 100644 --- a/crates/affinity/tests/raster.rs +++ b/crates/affinity/tests/it/raster.rs @@ -1,7 +1,6 @@ //! Pixel retention on current Affinity 3 documents published under MIT by Patchy. //! Assertions use this reader's archive/stream and the original embedded image bytes; //! no third-party Affinity parser, source code or application is used as an oracle. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use vectorcraft_affinity::{ Archive, Limits, @@ -9,8 +8,7 @@ use vectorcraft_affinity::{ stream, }; -#[path = "support/corpus.rs"] -mod corpus; +use crate::corpus; fn images(nodes: &[Node], out: &mut Vec) { for node in nodes { @@ -103,13 +101,16 @@ fn rotated_scaled_pixels_keep_the_full_affine_transform() { } #[test] -fn cmyk_and_lab_losses_are_reported() { +fn cmyk_pixels_stay_cmyk_and_lab_losses_are_reported() { + // CMYK layers keep their inks for the importer to convert through a colour profile. let Some((_, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return }; assert_eq!(images.len(), 1); assert_eq!((images[0].width, images[0].height), (64, 48)); - let Pixels::Rgba8(pixels) = &images[0].pixels else { panic!() }; - assert_eq!(crc32fast::hash(pixels), 0x5872bb76); - assert_eq!(cmyk.warnings, ["CMYK pixel layers (converted to RGB without the document's colour profile)"]); + let Pixels::Cmyka8(pixels) = &images[0].pixels else { panic!() }; + assert_eq!(pixels.len(), 64 * 48 * 5); + assert_eq!(crc32fast::hash(pixels), 0x56b1f659); + assert!(cmyk.warnings.is_empty(), "{:?}", cmyk.warnings); + assert_eq!(cmyk.cmyk_profile, None, "this file embeds no profile"); let (_, lab, images) = read_fixture("patchy-lab.af").unwrap(); assert!(images.is_empty()); assert_eq!(lab.warnings, ["pixel layers in grey, Lab or 32-bit formats"]); diff --git a/crates/affinity/tests/real_files.rs b/crates/affinity/tests/it/real_files.rs similarity index 93% rename from crates/affinity/tests/real_files.rs rename to crates/affinity/tests/it/real_files.rs index 66beca8420..a1d72bd019 100644 --- a/crates/affinity/tests/real_files.rs +++ b/crates/affinity/tests/it/real_files.rs @@ -2,16 +2,13 @@ //! `corpus/affinity`, or any folder of `.af`/`.afdesign`/`.afphoto`/`.afpub` files named by //! `AFFINITY_SAMPLES` (searched recursively). CI requires a complete, checksum-verified pinned //! corpus via `AFFINITY_CORPUS_REQUIRED=1`; ordinary local runs may skip an absent corpus. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::path::{Path, PathBuf}; use vectorcraft_affinity::{Archive, Limits, stream}; -#[path = "support/corpus.rs"] -mod corpus; -#[path = "support/features.rs"] -mod features; +use crate::corpus; +use crate::features; fn files(dir: &Path, out: &mut Vec) { for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { @@ -90,7 +87,7 @@ fn public_documents_map_to_the_model() { #[test] fn affinity3_feature_retention_matches_pinned_signatures() { let Some(dir) = corpus::pinned() else { return }; - let expected = include_str!("support/affinity3-signatures.txt"); + let expected = include_str!("../support/affinity3-signatures.txt"); let mut checked = std::collections::BTreeSet::new(); for line in expected.lines().filter(|l| !l.starts_with('#') && !l.is_empty()) { let (name, signature) = line.split_once('\t').expect("signature row must have a tab"); @@ -108,7 +105,7 @@ fn affinity3_feature_retention_matches_pinned_signatures() { doc.saved_by ); } - let manifest = include_str!("../../../xtask/affinity-corpus.sha256"); + let manifest = include_str!("../../../../xtask/affinity-corpus.sha256"); let af_names: std::collections::BTreeSet<_> = manifest.lines().filter_map(|l| l.split_once(" ")).map(|(_, n)| n).filter(|n| n.ends_with(".af")).collect(); assert_eq!(checked, af_names, "every pinned .af file needs a reviewed structural baseline"); diff --git a/crates/affinity/tests/text.rs b/crates/affinity/tests/it/text.rs similarity index 79% rename from crates/affinity/tests/text.rs rename to crates/affinity/tests/it/text.rs index 8d6a203e51..35a621f810 100644 --- a/crates/affinity/tests/text.rs +++ b/crates/affinity/tests/it/text.rs @@ -1,17 +1,11 @@ //! Synthetic `.af` version-12 text regression oracles; see support/text_fixture.rs for provenance. //! Unicode ranges below test the scalar-index contract corroborated by the pinned Affinity 3 //! mixed-run fixture. Broad complex typography still needs independent visual validation. -#![cfg(feature = "synth")] -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -mod support { - pub mod corpus; - pub mod text_fixture; -} -use support::text_fixture::*; +use crate::text_fixture::*; use vectorcraft_affinity::{ Document, Limits, - model::{Align, Kind, Text}, + model::{Align, Kind, Paragraph, Text}, paint::{Color, Paint}, synth::{F, tag}, }; @@ -108,7 +102,7 @@ fn mixed_paragraph_alignments_are_explicitly_reported() { let d = read(vec![block(utf8("one\u{2029}"), vec![run(4, None)], &[2]), block(utf8("two"), vec![run(3, None)], &[0, 1])]); assert_eq!(content(text(&d)), "one\u{2029}two"); assert_eq!(text(&d).align, Align::Right); - assert!(warning(&d, "mixed paragraph alignments")); + assert!(warning(&d, "mixed paragraph formats")); } #[test] @@ -179,7 +173,7 @@ fn stored_fallback_font_is_used_only_when_it_names_a_font() { #[test] fn real_affinity3_text_fixtures_confirm_unicode_and_caps_fields() { - let Some(corpus) = support::corpus::pinned() else { return }; + let Some(corpus) = crate::corpus::pinned() else { return }; // Files fetched at the commit and sha256 in xtask/affinity-corpus.sha256. No Patchy parser // source was read; assertions describe this crate's parsing of its published MIT documents. let load = |name: &str| vectorcraft_affinity::read(&std::fs::read(corpus.join(name)).unwrap(), Limits::default()).unwrap(); @@ -194,10 +188,22 @@ fn real_affinity3_text_fixtures_confirm_unicode_and_caps_fields() { assert_eq!(texts.len(), 2); assert!(texts[0].runs[0].all_caps); assert_eq!(texts[1].runs[0].features, ["smcp"]); - for name in ["patchy-text-indent.af", "patchy-text-para-spacing.af"] { + // Indents and paragraph spacing are read (values in document pixels, as these fixtures set + // them in Affinity's paragraph panel). + let paragraphs = |name: &str| -> Vec { let d = load(name); - assert!(warning(&d, "paragraph indents or spacing"), "{name}: {:?}", d.warnings); - } + assert!(!warning(&d, "paragraph"), "{name}: {:?}", d.warnings); + d.spreads[0] + .nodes + .iter() + .filter_map(|n| if let Kind::Text(t) = &n.kind { Some(t) } else { None }) + .flat_map(|t| t.runs.iter().map(|r| r.paragraph)) + .collect() + }; + let p = paragraphs("patchy-text-indent.af"); + assert_eq!(p.iter().map(|p| (p.left, p.first, p.space_after)).collect::>(), [(40.0, 0.0, 12.0), (0.0, 25.0, 12.0)]); + let p = paragraphs("patchy-text-para-spacing.af"); + assert_eq!(p.iter().map(|p| (p.space_before, p.space_after)).collect::>(), [(9.0, 17.0)]); } proptest::proptest! { @@ -247,9 +253,19 @@ fn excessive_feature_settings_are_bounded_and_reported() { assert!(warning(&d, "more than 256 text feature settings")); } +#[test] +fn font_names_longer_than_256_bytes_are_dropped() { + // Each paragraph and run carries its font's name: a huge one would be copied with each. + let d = read(vec![block(utf8("x"), vec![run(1, Some(attrs(&"F".repeat(257), "Inter-Regular", 400, false, 12.0)))], &[])]); + let r = &text(&d).runs[0]; + assert!(r.family.is_empty() && r.postscript == "Inter-Regular"); + assert!(warning(&d, "font names longer than 256 bytes")); +} + #[test] fn shared_font_metadata_amplification_is_bounded_without_losing_characters() { - let mut a = attrs(&"F".repeat(16 * 1024), &"P".repeat(16 * 1024), 400, false, 12.0); + // The longest font names kept (see `font_names_longer_than_256_bytes_are_dropped`). + let mut a = attrs(&"F".repeat(256), &"P".repeat(256), 400, false, 12.0); if let F::Obj(_, fields) = &mut a { let settings = F::Obj( tag(b"OtAt"), @@ -266,11 +282,12 @@ fn shared_font_metadata_amplification_is_bounded_without_losing_characters() { } let F::Obj(class, fields) = a else { panic!("attributes must be an object") }; let mut runs = vec![run(1, Some(F::Def(42, vec![class], fields)))]; - runs.extend((2..=1000).map(|end| run(end, Some(F::Ref(42))))); - let d = read(vec![block(utf8(&"x".repeat(1000)), runs, &[])]); + // About 7.7 kB of names and features per run: the budget runs out after about 2200 runs. + runs.extend((2..=4000).map(|end| run(end, Some(F::Ref(42))))); + let d = read(vec![block(utf8(&"x".repeat(4000)), runs, &[])]); let t = text(&d); - assert_eq!(content(t), "x".repeat(1000)); - assert_eq!(t.runs.len(), 1000); + assert_eq!(content(t), "x".repeat(4000)); + assert_eq!(t.runs.len(), 4000); let metadata: usize = t .runs .iter() @@ -279,7 +296,7 @@ fn shared_font_metadata_amplification_is_bounded_without_losing_characters() { .map(|s| s.len() + std::mem::size_of::()) .sum(); assert!(metadata <= 16 << 20, "shared metadata was amplified to {metadata} bytes"); - assert_eq!(t.runs[0].family.len(), 16 * 1024); + assert_eq!(t.runs[0].family.len(), 256); assert_eq!(t.runs[0].features.len(), 256); assert!(t.runs.last().unwrap().family.is_empty()); assert!(t.runs.last().unwrap().features.is_empty()); @@ -320,3 +337,39 @@ fn shared_gradient_attributes_are_bounded_without_losing_characters() { assert!(warning(&d, "text attribute budget exceeded")); assert!(!warning(&d, "text without character attributes"), "budget recovery must not claim source attributes are absent"); } + +#[test] +fn shared_gradient_outlines_are_bounded_without_losing_characters() { + let color = + F::Def(43, vec![tag(b"RGBA")], vec![(tag(b"_col"), F::Struct([0.2f32, 0.4, 0.6, 1.0].iter().flat_map(|v| v.to_le_bytes()).collect()))]); + let mut colors = vec![color]; + colors.extend((1..1024).map(|_| F::Ref(43))); + let positions = (0..1024).map(|i| [(i as f32) / 1023.0, 0.5].iter().flat_map(|v| v.to_le_bytes()).collect()).collect(); + let pen = F::Obj( + tag(b"FilG"), + vec![(tag(b"Grad"), F::Obj(tag(b"Grad"), vec![(tag(b"Cols"), F::Shared(colors)), (tag(b"Posn"), F::Records(8, positions))]))], + ); + let style = F::Obj(tag(b"LSty"), vec![(tag(b"Wght"), F::F64(2.0))]); + // `Objs` 1 and 2: the outline's paint and line style, shared by every run. + let attrs = F::Def(42, vec![tag(b"GAtt")], vec![(tag(b"Objs"), F::Shared(vec![solid(1.0), pen, style]))]); + let mut runs = vec![run(1, Some(attrs))]; + runs.extend((2..=1000).map(|end| run(end, Some(F::Ref(42))))); + let d = read(vec![block(utf8(&"x".repeat(1000)), runs, &[])]); + let t = text(&d); + assert_eq!(content(t), "x".repeat(1000)); + assert_eq!(t.runs.len(), 1000); + let stop_count: usize = t + .runs + .iter() + .filter_map(|r| r.stroke.as_ref()) + .map(|s| match &s.paint { + Paint::Gradient(g) => g.stops.len(), + _ => 0, + }) + .sum(); + assert!(stop_count * std::mem::size_of::() <= 16 << 20); + let Some(Paint::Gradient(first)) = t.runs[0].stroke.as_ref().map(|s| &s.paint) else { panic!("the first outline must fit") }; + assert_eq!(first.stops.len(), 1024); + assert!(t.runs.last().unwrap().stroke.is_none()); + assert!(warning(&d, "text attribute budget exceeded")); +} diff --git a/crates/affinity/tests/support/affinity3-signatures.txt b/crates/affinity/tests/support/affinity3-signatures.txt index fb6c94b29f..779a58552e 100644 --- a/crates/affinity/tests/support/affinity3-signatures.txt +++ b/crates/affinity/tests/support/affinity3-signatures.txt @@ -1,33 +1,33 @@ -affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=df3c417b;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["brush and pressure strokes (imported as plain strokes) (114×)", "layer effects (shadows, glows, outlines, bevels…) (156×)"] -affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=d0387de4;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 559, "subpaths": 881};boards=[];fonts={};warnings=["brush and pressure strokes (imported as plain strokes) (545×)", "layer effects (shadows, glows, outlines, bevels…) (245×)"] -affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=b966f693;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["brush and pressure strokes (imported as plain strokes) (54×)", "layer effects (shadows, glows, outlines, bevels…) (278×)"] -affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=ac448123;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 288, "subpaths": 656};boards=[];fonts={};warnings=["brush and pressure strokes (imported as plain strokes)", "layer effects (shadows, glows, outlines, bevels…) (339×)"] -patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=10a37502;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] -patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=c65409b4;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] -patchy-artboards.af dpi=72;spreads=1;model_crc32=f1ae5644;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[] -patchy-blend-affinity.af dpi=72;spreads=1;model_crc32=f6691ff9;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"] -patchy-cmyk.af dpi=72;spreads=1;model_crc32=5145b5a1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=["CMYK pixel layers (converted to RGB without the document's colour profile)"] -patchy-dpi300.af dpi=300;spreads=1;model_crc32=0c23e7c8;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-embedded-jpeg.af dpi=72;spreads=1;model_crc32=090c674b;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-fx-blur.af dpi=72;spreads=1;model_crc32=3f1b8b44;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["layer effects (shadows, glows, outlines, bevels…) (2×)"] -patchy-fx-gradient.af dpi=72;spreads=1;model_crc32=e868c992;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=["layer effects (shadows, glows, outlines, bevels…) (3×)"] -patchy-fx.af dpi=72;spreads=1;model_crc32=5a1c34ac;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=["layer effects (shadows, glows, outlines, bevels…) (5×)"] -patchy-group.af dpi=72;spreads=1;model_crc32=c217ab38;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[] -patchy-incremental-chain.af dpi=72;spreads=1;model_crc32=63ad778e;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=["layer effects (shadows, glows, outlines, bevels…)"] -patchy-lab.af dpi=72;spreads=1;model_crc32=01e8a926;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"] -patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=9ce9937e;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-live-filter.af dpi=72;spreads=1;model_crc32=30c5f8ee;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=1bb23571;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-rgba8.af dpi=72;spreads=1;model_crc32=1bb23571;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-shapes-2.af dpi=72;spreads=1;model_crc32=7828d3cd;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.af dpi=72;spreads=1;model_crc32=7519f5fe;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=b6137f6e;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=b5527e72;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×)"] -patchy-text-frame.af dpi=72;spreads=1;model_crc32=7a2cd32d;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=["paragraph indents or spacing (imported with defaults)"] -patchy-text-indent.af dpi=72;spreads=1;model_crc32=30ee834c;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)", "paragraph indents or spacing (imported with defaults) (2×)"] -patchy-text-para-spacing.af dpi=72;spreads=1;model_crc32=3d580ad2;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "paragraph indents or spacing (imported with defaults)"] -patchy-text-rotated.af dpi=72;spreads=1;model_crc32=ad77772a;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"] -patchy-text-runs.af dpi=72;spreads=1;model_crc32=a8da3052;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "paragraph indents or spacing (imported with defaults)", "text uses a stored fallback font (imported with that font)"] -patchy-transform.af dpi=72;spreads=1;model_crc32=f8807611;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] -patchy-vector-mask.af dpi=72;spreads=1;model_crc32=1851fd90;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"] -patchy-vector.af dpi=72;spreads=1;model_crc32=b89a91d3;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[] +affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=d23a6900;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)", "brush and pressure strokes (imported as plain strokes) (114×)"] +affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=b8cecb1c;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)", "brush and pressure strokes (imported as plain strokes) (534×)"] +affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=23d1e39c;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)", "brush and pressure strokes (imported as plain strokes) (54×)"] +affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=cafb7572;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush and pressure strokes (imported as plain strokes)"] +patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=36ab962f;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] +patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=e2eac05e;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"] +patchy-artboards.af dpi=72;spreads=1;model_crc32=0037a28e;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[] +patchy-blend-affinity.af dpi=72;spreads=1;model_crc32=8497c917;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"] +patchy-cmyk.af dpi=72;spreads=1;model_crc32=56754ce9;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-dpi300.af dpi=300;spreads=1;model_crc32=2561f9d3;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-embedded-jpeg.af dpi=72;spreads=1;model_crc32=ab4b6fbf;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-fx-blur.af dpi=72;spreads=1;model_crc32=29b5083b;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"] +patchy-fx-gradient.af dpi=72;spreads=1;model_crc32=96cd10be;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[] +patchy-fx.af dpi=72;spreads=1;model_crc32=7c8d4d20;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[] +patchy-group.af dpi=72;spreads=1;model_crc32=dc37ab6c;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[] +patchy-incremental-chain.af dpi=72;spreads=1;model_crc32=38c9c5f4;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-lab.af dpi=72;spreads=1;model_crc32=df3a4e40;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"] +patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=8776a8a0;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +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.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×)"] +patchy-text-frame.af dpi=72;spreads=1;model_crc32=3bff8ef9;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[] +patchy-text-indent.af dpi=72;spreads=1;model_crc32=dc36dfc5;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"] +patchy-text-para-spacing.af dpi=72;spreads=1;model_crc32=6408f39b;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"] +patchy-text-rotated.af dpi=72;spreads=1;model_crc32=3d1de559;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"] +patchy-text-runs.af dpi=72;spreads=1;model_crc32=7820b881;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"] +patchy-transform.af dpi=72;spreads=1;model_crc32=8d56df84;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[] +patchy-vector-mask.af dpi=72;spreads=1;model_crc32=80ca946a;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"] +patchy-vector.af dpi=72;spreads=1;model_crc32=b36a9767;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[] diff --git a/crates/affinity/tests/support/features.rs b/crates/affinity/tests/support/features.rs index 31d3eb53fe..f7024feb62 100644 --- a/crates/affinity/tests/support/features.rs +++ b/crates/affinity/tests/support/features.rs @@ -35,7 +35,12 @@ pub fn signature(doc: &Document) -> String { } "texts" } + Kind::Table(t) => { + *counts.entry("table_cells").or_default() += t.cells.len(); + "tables" + } Kind::Image(_) => "images", + Kind::MasterInstance { .. } => "master_instances", Kind::Unsupported => "unsupported", }; *counts.entry(key).or_default() += 1; diff --git a/crates/affinity/tests/support/text_fixture.rs b/crates/affinity/tests/support/text_fixture.rs index d629253d3c..574a0ca38a 100644 --- a/crates/affinity/tests/support/text_fixture.rs +++ b/crates/affinity/tests/support/text_fixture.rs @@ -140,7 +140,7 @@ pub const IDENTITY: [f64; 6] = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0]; // Shared arrays require definitions/references, whereas inline fields use Obj. Give the original // fixture objects independent shared IDs without making the fixture descriptions noisy. -fn shared_objects(value: &mut F, next_id: &mut u32) { +pub fn shared_objects(value: &mut F, next_id: &mut u32) { match value { F::Shared(items) => { for item in items { diff --git a/crates/brush/src/colorize.rs b/crates/brush/src/colorize.rs index b9c85c12e3..9ef049f860 100644 --- a/crates/brush/src/colorize.rs +++ b/crates/brush/src/colorize.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{AppearanceItem, Node}; +use vectorcraft_doc::{AppearanceItem, Node, NodeKind}; use crate::Colorization; @@ -43,7 +43,8 @@ fn map_paint(p: &mut Paint, mode: Colorization, key: &Color) { } /// Recolour `n` (recursively) for a stroke painted `stroke`, and strip brushes from its strokes so -/// brush output never recurses. Non-solid stroke paints leave the art's colours alone. +/// brush output never recurses. Non-solid stroke paints leave the art's colours alone. Type is +/// recolored like paths: its characters' solid fills and strokes as well as its own. pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) { let key = match (mode, stroke.color()) { (Colorization::None, _) | (_, None) => None, @@ -65,15 +66,43 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) { } } } + if let (Some(k), NodeKind::Text(t)) = (&key, &mut n.kind) { + for r in &mut t.runs { + map_paint(&mut r.style.fill, mode, k); + map_paint(&mut r.style.stroke, mode, k); + } + } if let Some(ch) = n.children_mut() { for c in ch.iter_mut() { walk(Arc::make_mut(c), mode, key); } } + // A mask's art is drawn too: a brush on its strokes would run this brush again. Its colours + // are the mask's values, so they stay. + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + strip_brushes(Arc::make_mut(&mut m.art)); + } } walk(n, mode, key); } +/// Strip the brushes from every stroke under `n`, its masks' art included. +fn strip_brushes(n: &mut Node) { + for it in &mut n.appearance.items { + if let AppearanceItem::Stroke(s) = it { + s.brush = None; + } + } + if let Some(ch) = n.children_mut() { + for c in ch.iter_mut() { + strip_brushes(Arc::make_mut(c)); + } + } + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + strip_brushes(Arc::make_mut(&mut m.art)); + } +} + /// Mix every solid paint under `n` towards `color` by `amount` (0..1) — the Symbol Stainer. pub fn tint_node(n: &mut Node, color: &Color, amount: f32) { let amount = amount.clamp(0.0, 1.0); @@ -88,8 +117,10 @@ pub fn tint_node(n: &mut Node, color: &Color, amount: f32) { } if let vectorcraft_doc::NodeKind::Text(t) = &mut n.kind { for r in &mut t.runs { - if let Paint::Solid { color: c, .. } = &mut r.style.fill { - *c = c.lerp(color, amount); + for p in [&mut r.style.fill, &mut r.style.stroke] { + if let Paint::Solid { color: c, .. } = p { + *p = Paint::solid(c.lerp(color, amount)); + } } } } @@ -119,6 +150,8 @@ pub fn instance_art(art: &Node, inst: &Node) -> Node { /// The solid colours of the fills and strokes under `nodes`, most used first (then in the order /// they first appear): the colours Brush Options offers as Hue Shift's key colour, the first being /// its default. +/// Type's characters count as well: each run's fill, and its stroke when the stroke is wider +/// than 0. pub fn art_colors<'a>(nodes: impl IntoIterator) -> Vec { fn walk(n: &Node, seen: &mut std::collections::HashMap) { for it in &n.appearance.items { @@ -131,6 +164,15 @@ pub fn art_colors<'a>(nodes: impl IntoIterator) -> Vec { seen.entry(c.to_hex()).or_insert((0, order, c)).0 += 1; } } + if let NodeKind::Text(t) = &n.kind { + for r in &t.runs { + let stroke = (r.style.stroke_width > 0.0).then_some(&r.style.stroke); + for c in [Some(&r.style.fill), stroke].into_iter().flatten().filter_map(Paint::color) { + let order = seen.len(); + seen.entry(c.to_hex()).or_insert((0, order, c)).0 += 1; + } + } + } for c in n.children().into_iter().flatten() { walk(c, seen); } diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index a53d205191..422f09d9c2 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -285,6 +285,13 @@ 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. + #[serde(skip_serializing_if = "Option::is_none")] + pub width_mode: Option, + /// The width at the heaviest pen pressure (%), for Pressure (`width` without one). + #[serde(skip_serializing_if = "Option::is_none")] + pub width_max: Option, pub flip_along: bool, pub flip_across: bool, /// When true, art is placed on each run between sharp corners so folds do not overlap. @@ -295,6 +302,15 @@ pub struct ArtBrush { 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. + pub fn width_range(&self) -> (f64, f64) { + match self.width_mode { + Some(Variation::Pressure) => (self.width, self.width_max.unwrap_or(self.width)), + _ => (self.width, self.width), + } + } } impl Default for ArtBrush { @@ -304,6 +320,8 @@ impl Default for ArtBrush { direction: Direction::LeftToRight, scale: ArtScale::Stretch, width: 100.0, + width_mode: None, + width_max: None, flip_along: false, flip_across: false, overlap: false, @@ -413,6 +431,8 @@ impl Bristle { pub const SIZE_RANGE: (f64, f64) = (0.1, 1296.0); pub const LENGTH_RANGE: (f64, f64) = (25.0, 300.0); pub const PERCENT_RANGE: (f64, f64) = (1.0, 100.0); + /// The most characters `brush.new` and `brush.options` take for a new bristle brush name. + pub const MAX_NAME_CHARS: usize = 31; } impl Default for Bristle { @@ -456,6 +476,43 @@ impl Brush { } } + /// [`Brush::art`], to change (relink the resources it uses). + pub fn art_mut(&mut self) -> Vec<&mut Node> { + match &mut self.kind { + BrushKind::Scatter(s) => vec![&mut s.art], + BrushKind::Art(a) => vec![&mut a.art], + BrushKind::Pattern(p) => std::iter::once(&mut p.side) + .chain([&mut p.outer_corner, &mut p.inner_corner, &mut p.start, &mut p.end].into_iter().flatten()) + .collect(), + BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => vec![], + } + } + + /// A brush definition from JSON (a stored library entry or a command's params), its values + /// kept within their ranges ([`Brush::sanitize`]). A Hue Shift colorization without a `key` + /// takes the color the art's fills and strokes use most (the first of [`art_colors`]), or + /// black when they use no solid color. + pub fn from_json(mut v: serde_json::Value) -> Result { + let keyless = v.get("colorization").is_some_and(|c| { + c.get("method").and_then(serde_json::Value::as_str) == Some("hueShift") && c.get("key").is_none_or(serde_json::Value::is_null) + }); + if keyless { + // Read the art with the colorization field left out. + let mut plain = v.clone(); + if let Some(o) = plain.as_object_mut() { + o.remove("colorization"); + } + let b: Brush = serde_json::from_value(plain)?; + let key = art_colors(b.art()).first().copied().unwrap_or(vectorcraft_color::Color::BLACK); + if let Some(c) = v.get_mut("colorization").and_then(serde_json::Value::as_object_mut) { + c.insert("key".into(), serde_json::to_value(key)?); + } + } + let mut b: Brush = serde_json::from_value(v)?; + b.sanitize(); + Ok(b) + } + /// Keep every value of the definition within its range (definitions come from files and /// commands, so they are untrusted): numbers are clamped, non-numbers take the default. pub fn sanitize(&mut self) { @@ -481,6 +538,11 @@ 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) { + a.width_mode = None; + } + a.width_max = a.width_max.map(|w| within(w, ArtBrush::WIDTH_RANGE, a.width)); if let ArtScale::BetweenGuides { start, end } = &mut a.scale { *start = within(*start, (0.0, 1.0), 0.0); *end = within(*end, (0.0, 1.0), 1.0); @@ -517,14 +579,9 @@ pub fn library(doc: &Document) -> Vec { } /// Parse a stored library value (malformed entries are skipped, values kept within their -/// ranges — see [`Brush::sanitize`]). +/// ranges; see [`Brush::from_json`]). pub fn parse_library(v: &serde_json::Value) -> Vec { - let parse = |b: &serde_json::Value| { - let mut b: Brush = serde_json::from_value(b.clone()).ok()?; - b.sanitize(); - Some(b) - }; - v.as_array().map(|a| a.iter().filter_map(parse).collect()).unwrap_or_default() + v.as_array().map(|a| a.iter().filter_map(|b| Brush::from_json(b.clone()).ok()).collect()).unwrap_or_default() } /// Store `lib` as the document's brush library. @@ -570,7 +627,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), + BrushKind::Art(a) => warp::art(a, bp, w, stroke.pressure.as_ref()), BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke.pressure.as_ref(), &brush.name), BrushKind::Pattern(p) => warp::pattern(p, bp, w), }; @@ -667,6 +724,10 @@ fn leave_out_brushed(doc: &Document, nodes: &mut Vec, known: &mut Known) { /// with the stroke's opacity folded into the piece opacity. `None` if nothing is brushed. pub fn node_pieces(doc: &Document, n: &Node) -> Option> { let bp = node_bezpath(n)?; + // The library is parsed for a stroke that names a brush, not for every path. + if !n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if st.brush.is_some())) { + return None; + } let lib = library(doc); let mut out = vec![]; let mut any = false; diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 3dcdbf9bcd..0968f5d6ce 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -308,6 +308,69 @@ fn tints_colorization_uses_stroke_colour() { assert_eq!(white.appearance.fill_paint().color().unwrap().to_rgb(), [1.0, 1.0, 1.0]); } +/// Point type at (0, 0) whose characters are painted `fill` and `stroke` (1 pt wide). +fn type_art(fill: Paint, stroke: Paint) -> Node { + use vectorcraft_doc::{CharStyle, TextObject}; + let style = CharStyle { fill, stroke, stroke_width: 1.0, ..CharStyle::default() }; + Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(0.0, 0.0), "Ag", style)))) +} + +/// The characters' fills and strokes of every piece of type in `nodes`. +fn run_paints(nodes: &[Node]) -> Vec<(Paint, Paint)> { + let mut out = vec![]; + for n in nodes { + n.walk(&mut |c| { + if let NodeKind::Text(t) = &c.kind { + out.extend(t.runs.iter().map(|r| (r.style.fill.clone(), r.style.stroke.clone()))); + } + }); + } + out +} + +/// A scatter brush's colorization recolors the type in its art as it recolors the art's paths. +#[test] +fn scatter_colorization_recolors_type() { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0); + let mut path = rect_art(10.0, 4.0); + path.appearance.set_fill(red.clone()); + let art = Node::group(NodeId(0), vec![Arc::new(path), Arc::new(type_art(red.clone(), red.clone()))]); + let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::Tints, ..Default::default() }) }; + let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 100.0, 0.0), &blue); + assert!(!out.is_empty()); + let path_fill = out[0].children().unwrap()[0].appearance.fill_paint(); + assert_ne!(path_fill, red); + let paints = run_paints(&out); + assert_eq!(paints.len(), out.len()); + assert!(paints.iter().all(|p| *p == (path_fill.clone(), path_fill.clone())), "{paints:?}"); + // Black type takes the stroke color itself. + let black = Paint::solid(Color::BLACK); + let b = Brush { + name: "s".into(), + kind: BrushKind::Scatter(Scatter { art: type_art(black.clone(), black), colorization: Colorization::Tints, ..Default::default() }), + }; + let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 100.0, 0.0), &blue); + assert!(!out.is_empty()); + assert!(run_paints(&out).iter().all(|p| *p == (blue.paint.clone(), blue.paint.clone()))); +} + +/// The Symbol Stainer mixes the characters' strokes of type toward the stain, as it mixes their fills. +#[test] +fn stain_mixes_type_strokes_too() { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let blue = Color::rgb(0.0, 0.0, 1.0); + let mut art = type_art(red.clone(), red); + tint_node(&mut art, &blue, 1.0); + assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]); + // Characters painted with a global swatch lose the link, as a path's paint does: the mixed color + // is not the swatch's color. + let linked = Paint::Solid { color: Color::rgb(1.0, 0.0, 0.0), swatch: Some("Red".into()), tint: 0.5 }; + let mut art = type_art(linked.clone(), linked); + tint_node(&mut art, &blue, 1.0); + assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]); +} + #[test] fn library_defaults_store_and_find() { let mut d = Document::new(100.0, 100.0); @@ -522,6 +585,78 @@ fn scatter_values_follow_their_modes() { assert!(serde_json::to_value(&unsaved).unwrap().get("modes").is_none(), "not saved when unset"); } +/// Art Brush Options: with Width on Pressure the art goes from Width at the lightest pen pressure +/// to the second width at the heaviest, along the stroke where the pen pressed; Fixed keeps Width. +#[test] +fn art_brush_width_follows_the_pressure() { + let brush = |mode: Option, max: Option| { + 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, mode, max); + } + 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); + let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]); + // 4 pt art at 50 %: 1 pt either side at the lightest; at 300 %: 6 pt at the heaviest. + let out = draw(&brush(Some(Variation::Pressure), Some(300.0)), &ramp); + assert!(near(half_width(&out, 0.0, 1.0), 1.0, 0.1), "{}", half_width(&out, 0.0, 1.0)); + assert!(near(half_width(&out, 99.0, 100.0), 6.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)); + // The stroke weight scales it. + let out = draw(&brush(Some(Variation::Pressure), Some(300.0)), &StrokeLayer { width: 2.0, ..ramp.clone() }); + assert!(near(half_width(&out, 99.0, 100.0), 12.0, 0.2), "{}", half_width(&out, 99.0, 100.0)); + // Without recorded pressure, half way between the two widths. + assert!(near(bounds(&draw(&brush(Some(Variation::Pressure), Some(300.0)), &stroke(1.0))).height(), 7.0, 1e-6)); + // Fixed (or a definition without a mode) keeps Width, whatever the pressure and the second width. + for (mode, max) in [(None, Some(300.0)), (None, None), (Some(Variation::Pressure), None)] { + let out = draw(&brush(mode, max), &ramp); + assert!(near(bounds(&out).height(), 2.0, 1e-6), "{mode:?} {max:?}: {:?}", bounds(&out)); + } + // A stroke in the art takes the width at the middle of its path: 50 % and 300 % for an even + // light and heavy pressure, 175 % without recorded pressure. + let mut stroked = brush(Some(Variation::Pressure), Some(300.0)); + if let BrushKind::Art(a) = &mut stroked.kind { + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + bp.line_to((10.0, 0.0)); + a.art = Node::path(NodeId(0), vectorcraft_geom::PathData::from_bezpath(&bp), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0)); + } + for (st, want) in [(pressed(vec![(0.0, 0.0), (1.0, 0.0)]), 1.0), (pressed(vec![(0.0, 1.0), (1.0, 1.0)]), 6.0), (stroke(1.0), 3.5)] { + let out = draw(&stroked, &st); + let w = out.first().and_then(|n| n.appearance.stroke()).map(|s| s.width); + assert!(w.is_some_and(|w| near(w, want, 1e-6)), "{want}: {w:?}"); + } + // Stretch Between Guides: an end outside the guides keeps the proportions of the width at its + // end of the stroke. A 2 pt marker at the start of 10 × 4 pt art (guides at 20 % and 80 %), + // 100 % to 300 % wide: 2 pt long at the lightest pressure, 6 pt at the heaviest. + let marker = + Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, -1.0, 2.0, 1.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let mut spacer = rect_art(10.0, 4.0); + spacer.appearance = Appearance::default().into(); + let art = Node::group(NodeId(0), vec![std::sync::Arc::new(spacer), std::sync::Arc::new(marker)]); + let mut guided = art_brush(art, ArtScale::BetweenGuides { start: 0.2, end: 0.8 }); + if let BrushKind::Art(a) = &mut guided.kind { + (a.width_mode, a.width_max) = (Some(Variation::Pressure), Some(300.0)); + } + for (p, long) in [(0.0, 2.0), (1.0, 6.0)] { + let out = draw(&guided, &pressed(vec![(0.0, p), (1.0, p)])); + let m = out.first().and_then(|g| g.children()).and_then(|c| c.get(1)).and_then(|m| m.geometric_bounds()); + assert!(m.is_some_and(|m| near(m.x0, 0.0, 1e-6) && near(m.x1, long, 1e-6)), "{p}: {m:?}"); + } + // A mode the width does not take is read as Fixed, and the second width is kept within range. + let lib = parse_library(&serde_json::json!([ + {"name": "a", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "random", "width_max": 1e308}, + {"name": "b", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "pressure", "width_max": 0.0}, + ])); + let [BrushKind::Art(a), BrushKind::Art(b)] = [&lib[0].kind, &lib[1].kind] else { panic!("{lib:?}") }; + assert_eq!((a.width_mode, a.width_max, b.width_mode, b.width_max), (None, Some(1000.0), Some(Variation::Pressure), Some(1.0))); + // A brush without the new fields is written back without them. + let plain = serde_json::to_value(art_brush(rect_art(10.0, 4.0), ArtScale::Stretch)).unwrap(); + assert!(plain.get("width_mode").is_none() && plain.get("width_max").is_none(), "{plain}"); +} + /// Definitions from files and commands are kept within their ranges. #[test] fn sanitize_keeps_values_within_their_ranges() { @@ -557,11 +692,46 @@ fn art_colors_list_the_most_used_first() { |c: Color| Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::basic(Paint::solid(c), Paint::None, 0.0)); let g = Node::group(NodeId(0), vec![Arc::new(path(red)), Arc::new(path(blue)), Arc::new(path(blue))]); assert_eq!(art_colors([&g]), vec![blue, red]); + // Type counts its characters' fills and drawn strokes. + let text = type_art(Paint::solid(red), Paint::solid(red)); + let g = Node::group(NodeId(0), vec![Arc::new(path(blue)), Arc::new(text.clone())]); + assert_eq!(art_colors([&g]), vec![red, blue]); + let NodeKind::Text(mut t) = text.kind else { panic!("not type") }; + t.runs[0].style.stroke_width = 0.0; + let text = Node::new(NodeId(0), NodeKind::Text(t)); + let g = Node::group(NodeId(0), vec![Arc::new(text), Arc::new(path(blue)), Arc::new(path(blue))]); + assert_eq!(art_colors([&g]), vec![blue, red], "a stroke 0 wide is not counted"); let b = defaults().iter().find(|b| b.name == "Chain").unwrap(); assert_eq!(b.art().len(), 3, "the side and both corner tiles"); assert!(calli(0.0, 100.0, 3.0).art().is_empty()); } +/// A Hue Shift definition without a key color takes the art's most used color, or black when the +/// art has no solid color; a key that is given is kept. +#[test] +fn hue_shift_without_a_key_takes_the_most_used_art_color() { + let red = Color::rgb(1.0, 0.0, 0.0); + let blue = Color::rgb(0.0, 0.0, 1.0); + let path = |fill: Paint| Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::basic(fill, Paint::None, 0.0)); + let art = Node::group(NodeId(0), vec![Arc::new(path(Paint::solid(red))), Arc::new(path(Paint::solid(blue))), Arc::new(path(Paint::solid(blue)))]); + let lib = parse_library(&serde_json::json!([ + {"name": "s", "type": "scatter", "art": art, "colorization": {"method": "hueShift"}}, + {"name": "a", "type": "art", "art": art, "colorization": {"method": "hueShift", "key": null}}, + {"name": "p", "type": "pattern", "side": art, "colorization": {"method": "hueShift", "key": red}}, + {"name": "n", "type": "art", "art": path(Paint::None), "colorization": {"method": "hueShift"}}, + ])); + let keys: Vec<(&str, Colorization)> = lib.iter().map(|b| (b.name.as_str(), b.kind.colorization())).collect(); + assert_eq!( + keys, + vec![ + ("s", Colorization::HueShift { key: blue }), + ("a", Colorization::HueShift { key: blue }), + ("p", Colorization::HueShift { key: red }), + ("n", Colorization::HueShift { key: Color::BLACK }), + ] + ); +} + /// Brush pieces draw no brushed stroke, also not by name: a symbol instance whose art is brushed /// is left out, a pattern paint whose tile is brushed becomes no paint, and plain ones stay. #[test] @@ -595,3 +765,81 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() { assert_eq!(fills, [Paint::Pattern { pattern: "plain".into(), xf: vectorcraft_geom::Affine::IDENTITY }, Paint::None]); } } + +/// Anchors a brushed stroke emitted, which is what the output budget counts. +fn anchors(nodes: &[Node]) -> usize { + nodes + .iter() + .map(|n| match &n.kind { + NodeKind::Path { path, .. } => path.subpaths.iter().map(|s| s.anchors.len()).sum::(), + _ => 0, + }) + .sum() +} + +/// A path of `subpaths` long parallel lines, each long enough to want more tiles than the +/// per-run cap allows. +fn many_long_subpaths(subpaths: usize) -> BezPath { + let mut bp = BezPath::new(); + for i in 0..subpaths { + let y = i as f64 * 50.0; + bp.move_to((0.0, y)); + bp.line_to((300_000.0, y)); + } + bp +} + +/// #3594: the per-factor caps are per track, and a path has as many tracks as it has subpaths, +/// so they multiply instead of bounding. Measured before the budget: 20,000 nodes and 320,000 +/// anchors for one subpath, and exactly N times that for N, so sixteen gave 5,120,000. +#[test] +fn pattern_output_is_capped_across_subpaths_not_only_per_run() { + let brush = pattern_brush(PatternFit::Stretch, false); + let one = stroke_pieces(&Document::new(1.0, 1.0), &brush, &many_long_subpaths(1), &stroke(1.0)); + assert_eq!(one.len(), 20_000, "one track still fills its own per-run cap"); + let a1 = anchors(&one); + assert!(a1 < 2_000_000, "one track stays under the total budget: {a1}"); + + // Sixteen tracks would be sixteen times that without a total budget. + // Four tracks are 4 x 320,000 anchors, still inside the budget, so nothing is cut: the + // budget must not bite before the per-factor caps have actually multiplied past it. + let four = stroke_pieces(&Document::new(1.0, 1.0), &brush, &many_long_subpaths(4), &stroke(1.0)); + assert_eq!(four.len(), 4 * 20_000, "four tracks are under the budget and keep every piece"); + assert_eq!(anchors(&four), 4 * a1); + + // Sixteen would be 5,120,000 anchors. The budget is what stops it, not the per-run caps. + let many = stroke_pieces(&Document::new(1.0, 1.0), &brush, &many_long_subpaths(16), &stroke(1.0)); + let an = anchors(&many); + assert!(an <= 2_000_000, "sixteen subpaths must not exceed the budget: {an}"); + assert!(an > anchors(&four), "but more is drawn than four tracks' worth: {an}"); + assert!(many.len() < 16 * 20_000, "and fewer pieces than the per-run caps alone would allow: {}", many.len()); +} + +/// The same for scatter, whose per-track guard is also 20,000 copies. +#[test] +fn scatter_output_is_capped_across_subpaths() { + let b = Brush { + name: "s".into(), + kind: BrushKind::Scatter(Scatter { art: rect_art(4.0, 4.0), colorization: Colorization::None, ..Default::default() }), + }; + let few = stroke_pieces(&Document::new(1.0, 1.0), &b, &many_long_subpaths(1), &stroke(1.0)); + let per_track = anchors(&few); + assert!(per_track > 0, "one track draws something"); + // Enough tracks that the per-track guards alone would pass the budget. + let tracks = 2_000_000 / per_track + 4; + let many = stroke_pieces(&Document::new(1.0, 1.0), &b, &many_long_subpaths(tracks), &stroke(1.0)); + let an = anchors(&many); + assert!(an <= 2_000_000, "{tracks} tracks must not exceed the budget: {an}"); + assert!(an > per_track, "but more is drawn than one track's worth: {an}"); + assert!(many.len() < tracks * few.len().max(1), "fewer copies than the per-track guards alone would allow"); +} + +/// A short, ordinary stroke is untouched by the budget: it is the absurd ones that are cut. +#[test] +fn an_ordinary_stroke_is_unaffected_by_the_budget() { + let brush = pattern_brush(PatternFit::Stretch, false); + let sq = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)).to_bezpath(); + let out = stroke_pieces(&Document::new(1.0, 1.0), &brush, &sq, &stroke(1.0)); + assert_eq!(out.len(), 40, "ten tiles on each of the four sides, as before the budget"); + assert!(anchors(&out) < 2_000_000); +} diff --git a/crates/brush/src/track.rs b/crates/brush/src/track.rs index e02bcf48d3..85ccbd9904 100644 --- a/crates/brush/src/track.rs +++ b/crates/brush/src/track.rs @@ -156,6 +156,9 @@ impl Track { } } +/// The most flattened elements of a path kept. +const MAX_FLATTENED: usize = 4_000_000; + /// Flatten `bp` into tracks (one per subpath) with `tol` accuracy. pub fn tracks(bp: &BezPath, tol: f64) -> Vec { let mut out = vec![]; @@ -165,8 +168,20 @@ pub fn tracks(bp: &BezPath, tol: f64) -> Vec { out.push(t); } }; + // Far outside any drawing a curve flattens to millions of points; past a few million, the + // rest are not kept. + let b = bp.control_box(); + let extent = b.x0.abs().max(b.x1.abs()).max(b.y0.abs()).max(b.y1.abs()); + // NaN coordinates must be rejected too, so keep the negation of the `<=` check. + if extent.is_nan() || extent > 1e9 { + return out; + } let mut els = vec![]; - kurbo::flatten(bp.iter(), tol.max(1e-4), |el| els.push(el)); + kurbo::flatten(bp.iter(), tol.max(1e-4), |el| { + if els.len() < MAX_FLATTENED { + els.push(el); + } + }); for el in els { match el { PathEl::MoveTo(p) => { diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index 35031741e1..d20fe57009 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -16,6 +16,21 @@ use crate::{ArtBrush, ArtScale, Direction, PatternBrush, PatternFit, Scatter, Va const MAX_SEG: f64 = 1.5; /// Hard cap on subdivisions per art segment. const MAX_SUB: usize = 4000; +/// Anchors one brushed stroke may emit in total, across every track, tile and copy. +/// +/// Each factor is capped on its own (20,000 tiles a run, [`MAX_SUB`] subdivisions a segment, +/// 20,000 copies a track), but those caps are per track and a path has as many tracks as it has +/// subpaths, so they multiply rather than bound: one track at its cap measures 20,000 nodes and +/// 320,000 anchors, and sixteen subpaths measure exactly sixteen times that (#3594). This is the +/// cap on the product. The per-factor caps still shape each one. +/// +/// The same figure as the stacked-effects budget (`effects::distort::MAX_COPY_ANCHORS`, #3578), +/// and bounded the same way: per brushed stroke rather than per document, so many strokes that +/// each reach it still add up. Six times what one track at its own cap draws, so it bites only +/// where the caps were multiplying. +const MAX_ANCHORS: usize = 2_000_000; +/// Nodes [`anchors_of`] walks into before it gives up and charges the whole budget. +const MAX_WALK: usize = 10_000; /// Bend every path under `n` through `f`. Paths are flattened with `flat_tol` (art space) and /// segments subdivided so none is longer than `max_du` along x. Stroke widths scale by @@ -154,6 +169,33 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option f64) -> Option { + let cy = b.center().y; + let x0 = b.x0; + let f = move |p: Point| { + let s = along.at(p.x - x0); + t.map(s, (p.y - cy) * cross * widen(s)) + }; + let factor = |n: &Node| n.geometric_bounds().map_or(1.0, |r| widen(along.at(r.center().x - x0))); + let art = widen_strokes(art, &factor); + let scale = along.max_scale().max(cross.abs()).max(1e-6); + let flat_tol = tolerance(b.height().max(b.width()) * scale) / scale; + warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), cross.abs()) +} + +/// `n` with the strokes of it and of everything inside it scaled by `factor` of the object they +/// belong to. +fn widen_strokes(n: &Node, factor: &dyn Fn(&Node) -> f64) -> Node { + let mut out = n.clone(); + out.appearance.scale_strokes(factor(n)); + if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } = &mut out.kind { + *children = children.iter().map(|c| Arc::new(widen_strokes(c, factor))).collect(); + } + out +} + /// Arc-length spans to place art on when [`ArtBrush::overlap`] is on: one run between each sharp /// corner (the whole path when it has none). fn art_runs(t: &Track) -> Vec<(f64, f64)> { @@ -174,7 +216,17 @@ fn art_runs(t: &Track) -> Vec<(f64, f64)> { bounds.windows(2).map(|w| (w[0], w[1])).collect() } -fn art_on_run(a: &ArtBrush, t: &Track, s0: f64, s1: f64, art: &Node, b: Rect, cross: f64) -> Option { +/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1, and +/// `width` the width (%) there. +fn art_on_run( + t: &Track, + (s0, s1): (f64, f64), + a: &ArtBrush, + (art, b): (&Node, Rect), + cross: f64, + width: f64, + widen: &dyn Fn(f64) -> f64, +) -> Option { let l = s1 - s0; if l <= 1e-9 { return None; @@ -184,33 +236,49 @@ fn art_on_run(a: &ArtBrush, t: &Track, s0: f64, s1: f64, art: &Node, b: Rect, cr ArtScale::Stretch => (AlongMap::linear(w, s0, s1), cross), ArtScale::Proportional => { let k = l / w; - (AlongMap::linear(w, s0, s1), k * a.width / 100.0) + (AlongMap::linear(w, s0, s1), k * width / 100.0) } ArtScale::BetweenGuides { start, end } => { let (g0, g1) = (start.clamp(0.0, 1.0) * w, end.clamp(0.0, 1.0) * w); let (g0, g1) = (g0.min(g1), g0.max(g1)); - let fixed = (g0 + (w - g1)) * cross; + // The ends keep the proportions of the width at their end of the run. + let (c0, c1) = (cross * widen(s0), cross * widen(s1)); + let fixed = g0 * c0 + (w - g1) * c1; if fixed >= l || g1 - g0 < 1e-9 { (AlongMap::linear(w, s0, s1), cross) } else { - (AlongMap { xs: [0.0, g0, g1, w], ss: [s0, s0 + g0 * cross, s1 - (w - g1) * cross, s1] }, cross) + (AlongMap { xs: [0.0, g0, g1, w], ss: [s0, s0 + g0 * c0, s1 - (w - g1) * c1, s1] }, cross) } } }; - bend(t, art, b, along, cross) + bend_widened(t, art, b, along, cross, widen) } -pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64) -> Vec { +/// 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 { let Some((art, b)) = oriented(&a.art, a.direction, a.flip_along, a.flip_across) else { return vec![] }; - let cross = weight * a.width / 100.0; + let (light, heavy) = a.width_range(); + let width = light.max(heavy); + let cross = weight * width / 100.0; let mut out = vec![]; for t in tracks(bp, 0.05) { - if t.len() <= 1e-9 { + let l = t.len(); + if l <= 1e-9 { continue; } - let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, t.len())] }; - for (s0, s1) in runs { - if let Some(n) = art_on_run(a, &t, s0, s1, &art, b, cross) { + let widen = |s: f64| { + if light == heavy || width <= 0.0 { + return 1.0; + } + // 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); + (light + (heavy - light) * p) / width + }; + let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] }; + for run in runs { + if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, width, &widen) { out.push(n); } } @@ -235,8 +303,11 @@ pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option< let (aw, ah) = (b.width().max(1e-3), b.height().max(1e-3)); let mut rng = Rng::new(seed_of(bp, name)); let [size_mode, spacing_mode, scatter_mode, rotation_mode] = sc.modes(); - let mut out = vec![]; + let mut out = Budget::default(); for t in tracks(bp, 0.05) { + if out.full() { + break; + } let l = t.len(); // The pen pressure at arc length `at` (half way without a recorded one). let pressure_at = |at: f64| pressure.map_or(PressureProfile::MID, |p| p.at(if l > 1e-9 { at / l } else { 0.0 })); @@ -270,10 +341,61 @@ pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option< let xf = Affine::translate(place.to_vec2()) * Affine::rotate(base - rot) * Affine::scale(size) * Affine::translate(-b.center().to_vec2()); let mut n = sc.art.clone(); n.transform(xf, true); - out.push(n); + out.take(Some(n)); + if out.full() { + break; + } } } - out + out.out +} + +/// Anchors `n` and its children hold. Walked with a stack rather than by recursion, and a tree +/// deeper or wider than [`MAX_WALK`] nodes is charged the whole budget rather than undercounted, +/// so an art tile cannot buy room by nesting. +fn anchors_of(n: &Node) -> usize { + let (mut total, mut seen) = (0usize, 0usize); + let mut stack = vec![n]; + while let Some(n) = stack.pop() { + seen += 1; + if seen > MAX_WALK { + return MAX_ANCHORS; + } + if let NodeKind::Path { path, .. } = &n.kind { + total = total.saturating_add(path.subpaths.iter().map(|s| s.anchors.len()).sum::()); + } + if let Some(c) = n.children() { + stack.extend(c.iter().map(Arc::as_ref)); + } + } + total +} + +/// Brush output collected under [`MAX_ANCHORS`]. +/// +/// A piece is taken whole or not at all, so the art a brush places is never half-drawn; the +/// total is therefore the budget plus at most one piece. +#[derive(Default)] +struct Budget { + out: Vec, + anchors: usize, +} + +impl Budget { + /// Take a piece if there is room. `None` (art that could not be placed) costs nothing. + fn take(&mut self, n: Option) { + let Some(n) = n else { return }; + if self.full() { + return; + } + self.anchors = self.anchors.saturating_add(anchors_of(&n)); + self.out.push(n); + } + + /// Whether the budget is spent, so the caller can stop walking the path. + fn full(&self) -> bool { + self.anchors >= MAX_ANCHORS + } } /// A tile placed on [s0, s1] of the track (stretched along, `cross` across). @@ -291,8 +413,11 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec let end = pb.end.as_ref().and_then(orient); let tw = side.1.width() * k; let gap = tw * pb.spacing.max(0.0) / 100.0; - let mut out = vec![]; + let mut out = Budget::default(); for t in tracks(bp, 0.05) { + if out.full() { + break; + } let l = t.len(); if l <= 1e-9 { continue; @@ -314,7 +439,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec * Affine::translate(-bb.center().to_vec2()); let mut n = art.clone(); n.transform(xf, true); - out.push(n); + out.take(Some(n)); } // Runs between corners (closed tracks wrap past the end). let mut bounds: Vec = corners.iter().map(|c| c.1).collect(); @@ -346,7 +471,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec { let w = st.1.width() * k; if b - a > w { - out.extend(tile_on(&t, st, a, a + w, k)); + out.take(tile_on(&t, st, a, a + w, k)); a += w; } } @@ -356,7 +481,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec { let w = en.1.width() * k; if b - a > w { - out.extend(tile_on(&t, en, b - w, b, k)); + out.take(tile_on(&t, en, b - w, b, k)); b -= w; } } @@ -372,7 +497,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec let (w, g) = (tw * f, gap * f); for i in 0..n.min(20000) { let s0 = a + i as f64 * (w + g); - out.extend(tile_on(&t, &side, s0, s0 + w, k)); + out.take(tile_on(&t, &side, s0, s0 + w, k)); + if out.full() { + break; + } } } PatternFit::AddSpace => { @@ -381,7 +509,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec let lead = if n == 1 { (avail - tw) / 2.0 } else { 0.0 }; for i in 0..n.min(20000) { let s0 = a + lead + i as f64 * (tw + g.max(0.0)); - out.extend(tile_on(&t, &side, s0, s0 + tw, k)); + out.take(tile_on(&t, &side, s0, s0 + tw, k)); + if out.full() { + break; + } } } PatternFit::Approximate => { @@ -390,11 +521,14 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec let lead = (avail - used) / 2.0; for i in 0..n.min(20000) { let s0 = a + lead + i as f64 * unit; - out.extend(tile_on(&t, &side, s0, s0 + tw, k)); + out.take(tile_on(&t, &side, s0, s0 + tw, k)); + if out.full() { + break; + } } } } } } - out + out.out } diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index b729d8000e..1e43c45dc2 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -3,7 +3,7 @@ //! dimensions, as groups), and colours, lineweights, linetypes and transparency resolved through //! layers and blocks. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::rc::Rc; use std::sync::Arc; @@ -23,12 +23,17 @@ const PT_PER_MM: f64 = 72.0 / 25.4; const THINNEST: f64 = 0.25; /// The most objects an import makes. const MAX_NODES: usize = 2_000_000; +/// The most block visits (one per insert copy) an import makes, whatever they produce. +const MAX_VISITS: usize = 10_000_000; +/// The most path elements an import makes (blocks drawn as art are copied for every placement). +const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 }; /// How far from the origin art may lie (points): the canvas. pub(crate) const MAX_EXTENT: f64 = 4.0e6; const NESTED: &str = "blocks nested more than 8 deep, or inside themselves, are left out"; const XREFS: &str = "blocks referencing other drawings (external references) are left out"; const TOO_MANY: &str = "the drawing has more than 2,000,000 objects: the rest are left out"; +const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points: the rest are left out"; /// What a block's art takes from the insert that places it: its colour, lineweight, linetype /// and opacity where the art says "by block", and its layer for art on layer 0. @@ -52,6 +57,9 @@ pub(crate) struct Build<'d, 'a> { sensitive: HashMap, /// Symbol names by block and what it inherits (`None`: the block has no art). symbols: HashMap<(String, Inherit), Option>, + /// Names of the symbols made so far, and the next suffix to try for each label. + symbol_names: HashSet, + next_suffix: HashMap, /// Blocks being drawn, outermost first. stack: Vec, /// Document space per drawing unit, and its symbols' (no translation). @@ -60,6 +68,9 @@ pub(crate) struct Build<'d, 'a> { /// Lineweights are multiplied by this. lw_scale: f64, nodes: usize, + visits: usize, + /// Path elements made so far. + elements: usize, warnings: Vec, } @@ -108,11 +119,15 @@ impl<'d, 'a> Build<'d, 'a> { bounds: HashMap::new(), sensitive: HashMap::new(), symbols: HashMap::new(), + symbol_names: HashSet::new(), + next_suffix: HashMap::new(), stack: vec![], map: Affine::IDENTITY, symbol_map: Affine::IDENTITY, lw_scale: 1.0, nodes: 0, + visits: 0, + elements: 0, warnings: vec![], } } @@ -362,7 +377,8 @@ impl<'d, 'a> Build<'d, 'a> { let k = self.d.header.ltscale * p.ltscale * scale; // Dashes (positive), gaps (negative) and dots (0), merged into dash, gap, dash, gap… let mut out: Vec = vec![]; - for v in pattern { + // (A linetype has a few elements; every path keeps its own copy of the dashes.) + for v in pattern.iter().take(64) { let dash = *v >= 0.0; let len = v.abs() * k; match out.len().is_multiple_of(2) { @@ -442,6 +458,12 @@ impl<'d, 'a> Build<'d, 'a> { } fn path(&mut self, bp: &BezPath, fill: bool, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option { + let n = bp.elements().len(); + if self.elements.saturating_add(n) > MAX_ELEMENTS { + self.warn(TOO_MANY_POINTS); + return None; + } + self.elements += n; let mut bp = bp.clone(); bp.apply_affine(map); super::curve::bounds(&bp)?; @@ -473,7 +495,14 @@ impl<'d, 'a> Build<'d, 'a> { let path = PathData::from_bezpath(&bp); let kind = |path: PathData| NodeKind::Path { path, rule, live: None, clipping: false, guide: false }; let mut n = if path.subpaths.len() > 1 { - // Several loops (a hatch with islands) paint as one compound path. + // Several loops (a hatch with islands) paint as one compound path. Each loop is an + // object of its own, so it counts against the node limit like any other (`item` + // counts the compound path itself). + if self.nodes.saturating_add(path.subpaths.len()) >= MAX_NODES { + self.warn(TOO_MANY); + return None; + } + self.nodes += path.subpaths.len(); let children = path .subpaths .into_iter() @@ -552,6 +581,13 @@ impl<'d, 'a> Build<'d, 'a> { /// The art of block `name` drawn by `map`, as one object. fn art(&mut self, name: &str, map: Affine, inh: &Inherit, depth: u32) -> Option { + self.visits += 1; + if self.visits > MAX_VISITS { + if self.visits == MAX_VISITS + 1 { + self.warn(TOO_MANY); + } + return None; + } let items = self.block(name)?; if !self.enter(name, depth) { return None; @@ -584,7 +620,8 @@ impl<'d, 'a> Build<'d, 'a> { let art = self.art(name, map, &key.1, depth); let made = art.map(|art| { let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()); - let symbol = unique(label, |n| self.doc.symbols.iter().any(|s| s.name == n)); + let symbol = unique(label, &mut self.next_suffix, &self.symbol_names); + self.symbol_names.insert(symbol.clone()); self.doc.symbols.push(Symbol { name: symbol.clone(), art: Arc::new(art) }); symbol }); @@ -611,10 +648,17 @@ fn rgb_color([r, g, b]: [u8; 3]) -> Color { Color::rgb8(r, g, b) } -/// `base`, or `base 2`, `base 3`… when taken. -fn unique(base: &str, taken: impl Fn(&str) -> bool) -> String { - if !taken(base) { +/// `base`, or `base 2`, `base 3`… when taken; `next` remembers where each base left off. +fn unique(base: &str, next: &mut HashMap, taken: &HashSet) -> String { + if !taken.contains(base) { return base.to_string(); } - (2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| base.to_string()) + let i = next.entry(base.to_string()).or_insert(2); + loop { + let name = format!("{base} {i}"); + *i += 1; + if !taken.contains(&name) { + return name; + } + } } diff --git a/crates/cad/src/import/curve.rs b/crates/cad/src/import/curve.rs index c913a8bd61..a348ce67ab 100644 --- a/crates/cad/src/import/curve.rs +++ b/crates/cad/src/import/curve.rs @@ -17,6 +17,8 @@ const MAX_DEPTH: u32 = 12; const MAX_ELEMENTS: usize = 200_000; /// The highest spline degree read. const MAX_DEGREE: usize = 11; +/// Spline weights below this fraction of the largest are read as this fraction. +const MIN_RELATIVE_WEIGHT: f64 = 1e-100; /// A polyline vertex: its point and the bulge of the segment that starts there (the tangent of a /// quarter of the arc's angle; positive turns counter-clockwise). @@ -121,7 +123,9 @@ struct H { impl H { fn lerp(self, o: Self, t: f64) -> Self { - Self { x: self.x + (o.x - self.x) * t, y: self.y + (o.y - self.y) * t, w: self.w + (o.w - self.w) * t } + // Exact at both ends, so a weight far smaller than its neighbour's doesn't cancel to 0. + let s = 1.0 - t; + Self { x: self.x * s + o.x * t, y: self.y * s + o.y * t, w: self.w * s + o.w * t } } fn point(self) -> Option { (self.w.abs() > 1e-300).then(|| Point::new(self.x / self.w, self.y / self.w)).filter(|p| p.x.is_finite() && p.y.is_finite()) @@ -139,7 +143,11 @@ pub(crate) fn nurbs(degree: usize, knots: &[f64], ctrl: &[Point], weights: Optio if knots.windows(2).any(|w| w[1] < w[0]) { return None; } - let weight = |i: usize| weights.and_then(|w| w.get(i)).copied().filter(|w| *w > 0.0 && w.is_finite()).unwrap_or(1.0); + let raw = |i: usize| weights.and_then(|w| w.get(i)).copied().filter(|w| *w > 0.0 && w.is_finite()).unwrap_or(1.0); + // Scaling all weights alike leaves the curve unchanged: relative to the largest, so tiny ones + // don't underflow, and floored so a weight tiny next to the others can't either. + let max_w = (0..n).map(raw).fold(0.0, f64::max); + let weight = |i: usize| (raw(i) / max_w).max(MIN_RELATIVE_WEIGHT); let hs: Vec = ctrl.iter().enumerate().map(|(i, p)| H { x: p.x * weight(i), y: p.y * weight(i), w: weight(i) }).collect(); let rational = (0..n).any(|i| (weight(i) - weight(0)).abs() > 1e-12); let (lo, hi) = ctrl.iter().fold((Point::new(f64::MAX, f64::MAX), Point::new(f64::MIN, f64::MIN)), |(lo, hi), p| { @@ -225,6 +233,11 @@ fn fit(bp: &mut BezPath, bez: &[H], t0: f64, t1: f64, tol: f64, depth: u32) -> O let (p3, d3) = eval(bez, t1)?; let h = (t1 - t0) / 3.0; let (c1, c2) = (p0 + d0 * h, p3 - d3 * h); + // Non-finite tangents never fit, so splitting wouldn't help: a line. + if ![c1, c2].iter().all(|p| p.x.is_finite() && p.y.is_finite()) { + bp.line_to(p3); + return Some(()); + } let cubic = kurbo::CubicBez::new(p0, c1, c2, p3); let close = (1..8).all(|i| { let s = f64::from(i) / 8.0; @@ -371,6 +384,21 @@ mod tests { } } + #[test] + fn tiny_spline_weights_flatten_to_a_handful_of_pieces() { + // Degree 5, three knot spans: fitted, not exact. + let ctrl: Vec = (0..8).map(|i| Point::new(f64::from(i) * 10.0, if i % 2 == 0 { 0.0 } else { 30.0 })).collect(); + let knots = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]; + let normal = nurbs(5, &knots, &ctrl, Some(&[1.0; 8])).unwrap().elements().len(); + // Scaling every weight alike leaves the curve as it is. + let tiny = nurbs(5, &knots, &ctrl, Some(&[1e-200; 8])).unwrap().elements().len(); + assert!(tiny <= normal + 8, "normal weights: {normal} elements, 1e-200 weights: {tiny} elements"); + // Weights tiny next to the others don't split every span to the limit either. + let mixed = [1.0, 1e-200, 1.0, 1e-200, 1.0, 1e-200, 1.0, 1e-200]; + let mixed = nurbs(5, &knots, &ctrl, Some(&mixed)).unwrap().elements().len(); + assert!(mixed < 500, "mixed weights: {mixed} elements"); + } + #[test] fn fit_points_make_a_smooth_curve_through_them() { let pts = [Point::new(0.0, 0.0), Point::new(10.0, 10.0), Point::new(20.0, 0.0)]; diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs index d11d6a35cc..59e1283cce 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -17,6 +17,8 @@ const DESCENT: f64 = 0.3; const LINE_SPACING: f64 = 5.0 / 3.0; /// The most copies one array insert (MINSERT) makes. const MAX_CELLS: i64 = 10_000; +/// The most copies all the array inserts of a file make together. +const MAX_TOTAL_CELLS: i64 = 2_000_000; /// Art farther than this from the origin (drawing units) is damaged data, left out. const MAX_COORD: f64 = 1e12; /// How far fit and aligned text may be squeezed or stretched to span their two points: at width @@ -184,12 +186,15 @@ pub(crate) struct Converter { /// Entity types left out, with how many. pub skipped: BTreeMap, pub warnings: Vec, + /// Array insert copies made so far, against [`MAX_TOTAL_CELLS`]. + cells: i64, } const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries"; const GRADIENT_HATCH: &str = "gradient hatches are filled with their first colour"; const MESHES: &str = "3D polygon meshes and polyface meshes are left out"; const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each"; +const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all"; const FAR_AWAY: &str = "entities with coordinates out of range are left out"; impl Converter { @@ -294,6 +299,15 @@ impl Converter { } else { (cols, rows) }; + // Past the file-wide budget, each insert keeps only its first copy. + let left = (MAX_TOTAL_CELLS - self.cells).max(1); + let (cols, rows) = if cols * rows > left { + self.warn(MANY_ARRAYS); + (cols.min(left), (left / cols.min(left)).max(1).min(rows)) + } else { + (cols, rows) + }; + self.cells = self.cells.saturating_add(cols * rows); let cells = (0..rows) .flat_map(|r| (0..cols).map(move |c| (r, c))) .map(|(r, c)| place * Affine::translate((c as f64 * cs, r as f64 * rs)) * Affine::scale_non_uniform(sx, sy)) @@ -536,7 +550,9 @@ fn boundary(c: &mut Cursor<'_, '_>) -> Option { // The boundary objects it was made from. if let Some(n) = c.count(97) { for _ in 0..n { - c.opt(330); + if c.opt(330).is_none() { + break; + } } } Some(bp) diff --git a/crates/cad/src/import/reader.rs b/crates/cad/src/import/reader.rs index 1d83475c36..8733c96c8d 100644 --- a/crates/cad/src/import/reader.rs +++ b/crates/cad/src/import/reader.rs @@ -421,20 +421,34 @@ fn font_family(g: &[Pair<'_>]) -> String { /// Model space, then each paper layout (its LAYOUT object, in tab order); a file without layout /// objects but with paper-space art has one paper layout. +/// The most bytes of layout and block names the layouts keep together. Each layout keeps its own +/// copy of its block's name, so many layouts naming one long block name multiplied it; real +/// drawings have a few dozen layouts with short names. +const MAX_LAYOUT_NAME_BYTES: usize = 4 << 20; + fn layouts(objects: &[Record<'_>], block_records: &HashMap, entities: &[Record<'_>]) -> Vec { let mut paper: Vec<(i64, LayoutDef)> = vec![]; + let mut seen = std::collections::HashSet::new(); + let mut name_bytes = 0usize; for r in objects.iter().filter(|r| r.kind == "LAYOUT") { // The layout's own groups follow its subclass marker. let own = r.g.iter().position(|p| p.code == 100 && p.value.trim() == "AcDbLayout").and_then(|i| r.g.get(i + 1..)).unwrap_or(&[]); let Some(name) = own.name(1) else { continue }; - let block = own.name(330).and_then(|h| block_records.get(&h.to_uppercase())).cloned(); - if name.eq_ignore_ascii_case(MODEL) || block.as_deref() == Some(MODEL_BLOCK) { + let block = own.name(330).and_then(|h| block_records.get(&h.to_uppercase())); + if name.eq_ignore_ascii_case(MODEL) || block.map(String::as_str) == Some(MODEL_BLOCK) { continue; } let Some(block) = block else { continue }; - if !paper.iter().any(|(_, l)| l.name.eq_ignore_ascii_case(name)) { - paper.push((own.int_or(71, i64::MAX), LayoutDef { name: name.to_string(), block: Some(block) })); + let key = name.to_ascii_lowercase(); + let cost = name.len() + block.len(); + // A layout past the allowance is skipped alone: a later short one is still offered, and a + // skipped one reserves neither its name nor its bytes. + if seen.contains(&key) || name_bytes.saturating_add(cost) > MAX_LAYOUT_NAME_BYTES { + continue; } + seen.insert(key); + name_bytes += cost; + paper.push((own.int_or(71, i64::MAX), LayoutDef { name: name.to_string(), block: Some(block.clone()) })); } paper.sort_by_key(|(order, _)| *order); if paper.is_empty() && groups(entities).any(in_paper_space) { diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index 895b702262..d0dde65c90 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -380,6 +380,27 @@ fn solid_hatches_fill_and_pattern_hatches_outline() { assert!(square.appearance.fill().is_some_and(|f| !f.paint.is_none())); } +#[test] +fn hatch_declaring_many_absent_source_handles_parses_quickly() { + let base = hatch("1"); + let at = |code: i32, from: usize| from + base[from..].iter().position(|p| p.0 == code).unwrap(); + let first = at(92, 0); + let end = at(97, first) + 1; + let mut boundary = base[first..end].to_vec(); + *boundary.last_mut().unwrap() = (97, "10000000"); + let n = 300; + let mut e: Vec<(i32, &'static str)> = base[..first].to_vec(); + e[at(91, 0)] = (91, "300"); + for _ in 0..n { + e.extend_from_slice(&boundary); + } + e.extend_from_slice(&base[end..]); + let start = std::time::Instant::now(); + let r = open(&entities(&e), &points()); + assert!(start.elapsed() < std::time::Duration::from_millis(400), "took {:?}", start.elapsed()); + assert_eq!(r.document.layers[0].children().unwrap().len(), 1, "{:?}", r.warnings); +} + /// A solid hatch: a loop of a line and a spline edge (`fit` its fit data, if any), followed by /// `source` (the loop's source-object count and handles), and a square hole. fn spline_edged_hatch(fit: &[(i32, &'static str)], source: &[(i32, &'static str)]) -> Vec<(i32, &'static str)> { @@ -712,6 +733,27 @@ fn by_block_colours_make_a_symbol_per_look() { assert_eq!(doc.symbols.len(), 1); } +#[test] +fn many_by_block_looks_import_in_linear_time() { + let by_block: &[(i32, &str)] = &[(0, "LINE"), (8, "0"), (62, "0"), (10, "5"), (20, "5"), (11, "15"), (21, "5")]; + let n = 4000; + let mut inserts: Vec<(i32, &'static str)> = vec![]; + for i in 0..n { + let colour: &'static str = Box::leak((i + 1).to_string().into_boxed_str()); + inserts.extend([(0, "INSERT"), (2, "Door"), (420, colour), (10, "0"), (20, "0")]); + } + let text = with_door(by_block, &inserts); + let start = std::time::Instant::now(); + let doc = open(&text, &points()).document; + let took = start.elapsed(); + let mut names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names.len(), n); + names.sort_unstable(); + names.dedup(); + assert_eq!(names.len(), n, "names stay unique"); + assert!(took < std::time::Duration::from_secs(4), "import took {took:?}"); +} + #[test] fn array_inserts_attributes_and_dimensions() { let inserts = [ @@ -757,6 +799,48 @@ fn array_inserts_attributes_and_dimensions() { assert_eq!(bounds(&leaves(&doc)[0]).width(), 50.0); } +#[test] +fn nested_array_inserts_of_nothing_stop_at_the_work_budget() { + let block = |name: &'static str, inner: Option<&'static str>| { + let mut b = vec![(0, "BLOCK"), (2, name), (70, "1"), (10, "0"), (20, "0")]; + if let Some(i) = inner { + b.extend([(0, "INSERT"), (2, i), (10, "0"), (20, "0"), (70, "300"), (44, "1")]); + } + b.push((0, "ENDBLK")); + b + }; + let mut blocks = block("*A", Some("*B")); + blocks.extend(block("*B", Some("*C"))); + blocks.extend(block("*C", None)); + let top = [(0, "INSERT"), (2, "*A"), (10, "0"), (20, "0"), (70, "300"), (44, "1")]; + let r = open(&drawing(&[], &[], &blocks, &top), &points()); + assert!(r.warnings.iter().any(|w| w.contains("more than")), "{:?}", r.warnings); +} + +#[test] +fn an_array_of_a_large_anonymous_block_stops_at_the_path_element_budget() { + // A 2,000-vertex polyline in *U1, placed in a 100 × 10 array: 2,000,000 path elements when + // every cell is copied, twice the budget tests import with. + let mut owned: Vec<(i32, String)> = vec![(0, "BLOCK".into()), (2, "*U1".into()), (70, "1".into()), (10, "0".into()), (20, "0".into())]; + owned.extend([(0, "LWPOLYLINE".into()), (90, "2000".into()), (70, "0".into())]); + for i in 0..2000 { + owned.extend([(10, i.to_string()), (20, (i % 2).to_string())]); + } + owned.push((0, "ENDBLK".into())); + let blocks: Vec<(i32, &str)> = owned.iter().map(|(c, v)| (*c, v.as_str())).collect(); + let inserts = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "100"), (71, "10"), (44, "2000"), (45, "2")]; + let r = open(&drawing(&[], &[], &blocks, &inserts), &points()); + let mut elements = 0; + r.document.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + elements += path.to_bezpath().elements().len(); + } + }); + assert!(elements > 0); + assert!(elements <= 1_000_000, "{elements} path elements"); + assert!(r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings); +} + #[test] fn blocks_inside_themselves_are_left_out_without_hanging() { let blocks = [ @@ -1019,3 +1103,49 @@ fn entities_extruded_along_minus_z_are_mirrored() { let b = bounds(&leaves(&doc)[0]); assert!((b.center().x + 50.0).abs() < 1e-6, "the centre's x is mirrored: {b:?}"); } + +/// A drawing with one paper block record (handle `A`) and a LAYOUT object per name. +fn with_layouts(names: &[String]) -> Vec { + let mut s = String::from( + " 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nBLOCK_RECORD\n 0\nBLOCK_RECORD\n 5\nA\n 2\n*Paper_Space\n 0\nENDTAB\n 0\nENDSEC\n 0\nSECTION\n 2\nOBJECTS\n", + ); + for n in names { + s.push_str(&format!(" 0\nLAYOUT\n100\nAcDbLayout\n 1\n{n}\n330\nA\n")); + } + s.push_str(" 0\nENDSEC\n 0\nEOF\n"); + s.into_bytes() +} + +#[test] +fn many_paper_layouts_are_read_in_linear_time() { + let names: Vec = (0..100_000).map(|i| format!("L{i}")).collect(); + let bytes = with_layouts(&names); + let t = std::time::Instant::now(); + let info = info(&bytes).unwrap(); + assert_eq!(info.layouts.len(), names.len() + 1); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "layout de-duplication is quadratic: {:?}", t.elapsed()); +} + +#[test] +fn paper_layout_names_are_unique_ignoring_case() { + let names = ["Layout1", "LAYOUT1", "Other"].map(String::from); + let info = info(&with_layouts(&names)).unwrap(); + assert_eq!(info.layouts, ["Model", "Layout1", "Other"]); +} + +#[test] +fn many_array_inserts_of_a_missing_block_stay_bounded() { + let one = [(0, "INSERT"), (8, "0"), (2, "NOPE"), (10, "0"), (20, "0"), (70, "100"), (71, "100"), (44, "1"), (45, "1")]; + let e: Vec<(i32, &str)> = (0..3000).flat_map(|_| one).collect(); + let bytes = entities(&e); + let text = reader::decode(&bytes); + let (pairs, _) = reader::pairs(&text).unwrap(); + let d = reader::Drawing::read(&pairs); + let model = d.layout("Model").or(d.layouts.first()).unwrap(); + let mut conv = entity::Converter::default(); + let items = conv.items(&d.layout_records(model)); + assert_eq!(items.len(), 3000); + let total: usize = items.iter().map(|i| if let entity::Geom::Insert(ins) = &i.geom { ins.cells.len() } else { 0 }).sum(); + assert!(total <= 2_000_000 + 3000, "total cells materialised: {total}"); + assert!(conv.warnings.iter().any(|w| w.contains("array inserts")), "{:?}", conv.warnings); +} diff --git a/crates/cad/src/import/text.rs b/crates/cad/src/import/text.rs index caf5f9bea2..137d9cc317 100644 --- a/crates/cad/src/import/text.rs +++ b/crates/cad/src/import/text.rs @@ -4,13 +4,13 @@ /// A single-line text value (TEXT, ATTRIB) as plain text. pub(crate) fn plain(s: &str) -> String { - percent_codes(&escapes(s)) + percent_codes(&escapes(s, false)) } /// A multiline text value (MTEXT) as plain text with `\n` between paragraphs, and the font family /// its first font change names. pub(crate) fn mtext(s: &str) -> (String, Option) { - let s = escapes(s); + let s = escapes(s, true); let mut out = String::with_capacity(s.len()); let mut family = None; let mut chars = s.chars().peekable(); @@ -25,7 +25,7 @@ pub(crate) fn mtext(s: &str) -> (String, Option) { Some('S') => { // A stacked fraction `\Snum^den;` (or / or #): written as num/den. let arg = until_semicolon(&mut chars); - out.push_str(&arg.replace(['^', '#'], "/")); + out.push_str(&arg.replace("^ ", "^").replace(['^', '#'], "/")); } Some(f @ ('f' | 'F')) => { let arg = until_semicolon(&mut chars); @@ -63,20 +63,38 @@ fn until_semicolon(chars: &mut std::iter::Peekable>) -> Stri } /// `\U+XXXX` Unicode escapes (how files before DXF 2007 hold characters outside their code page) -/// and caret escapes: `^ ` is a caret, `^I` a tab; other control characters are dropped. -fn escapes(s: &str) -> String { +/// and caret escapes: `^ ` is a caret, `^I` a tab; other control characters are dropped. In +/// multiline text (`mtext`) `\\` is an escaped backslash and is kept as is, so that a `U+` after +/// it stays literal, and the `^` in a stacked fraction `\Snum^den;` is left for the caller. +fn escapes(s: &str, mtext: bool) -> String { let mut out = String::with_capacity(s.len()); let mut rest = s; while let Some(c) = rest.chars().next() { let after = rest.get(c.len_utf8()..).unwrap_or(""); + if mtext && c == '\\' && after.starts_with('\\') { + out.push_str("\\\\"); + rest = after.get(1..).unwrap_or(""); + continue; + } if c == '\\' && let Some(hex) = after.strip_prefix("U+").or_else(|| after.strip_prefix("u+")).and_then(|h| h.get(..4)) + && hex.bytes().all(|b| b.is_ascii_hexdigit()) && let Some(ch) = u32::from_str_radix(hex, 16).ok().and_then(char::from_u32) { out.push(ch); rest = after.get(6..).unwrap_or(""); continue; } + if mtext + && c == '\\' + && let Some(tail) = after.strip_prefix('S') + { + let end = tail.find(';').map_or(tail.len(), |i| i + 1); + out.push_str("\\S"); + out.push_str(tail.get(..end).unwrap_or("")); + rest = tail.get(end..).unwrap_or(""); + continue; + } if c == '^' && let Some(next) = after.chars().next() { @@ -135,6 +153,14 @@ fn percent_codes(s: &str) -> String { mod tests { use super::*; + #[test] + fn unicode_escape_requires_four_hex_digits() { + assert_eq!(plain("\\U++041"), "\\U++041"); + assert_eq!(plain("\\U+00G1"), "\\U+00G1"); + assert_eq!(plain("\\U+ 041"), "\\U+ 041"); + assert_eq!(plain("\\U+00C9"), "É"); + } + #[test] fn control_codes_and_escapes() { assert_eq!(plain("45%%d %%p0.1 %%c20 100%%% %%uunder%%u"), "45° ±0.1 ⌀20 100% under"); @@ -152,6 +178,10 @@ mod tests { // Carets are written "^ " (a caret before another character is a control character). assert_eq!(mtext("x\\S3^ 4;").0, "x3/4"); assert_eq!(mtext("x\\S3#4;").0, "x3/4"); + assert_eq!(mtext("\\S1^2;").0, "1/2"); + assert_eq!(mtext("\\S+1^-2;^I").0, "+1/-2\t"); assert_eq!(mtext("trailing\\").0, "trailing\\"); + assert_eq!(mtext("a\\\\U+0041b").0, "a\\U+0041b", "an escaped backslash is not a Unicode escape"); + assert_eq!(mtext("a\\U+0041b").0, "aAb"); } } diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 84e4a3aee3..1e7baac26b 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -33,6 +33,9 @@ const WIDE_LINES: &str = const STROKE_EXTRAS: &str = "stroke alignment, width profiles, arrowheads and brushes are left out (Maximize Editability writes strokes as lines)"; const CLIPPING: &str = "clipping masks are not applied: the art they clip is written whole"; const TYPE_ITEMS: &str = "fills and strokes added to whole type objects are left out of text entities (outline the text to keep them)"; +/// The warning for an image left out because it can't be decoded: the note raster exports give +/// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). +const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; /// One segment of a subpath, cubics for every curve. #[derive(Clone, Copy)] @@ -165,12 +168,32 @@ fn subpaths(bp: &BezPath) -> Vec { 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; + +/// The most entities (handles) a drawing is written with. +const MAX_ENTITIES: u32 = 10_000_000; + +/// The largest x or y a path may have to be flattened, and the most points its polygons keep. +const MAX_COORD: f64 = 1e9; +const MAX_POINTS: usize = 4_000_000; + /// `bp` flattened into polygons (each closing implicitly), consecutive repeats dropped. fn polygons(bp: &BezPath) -> Vec> { + // Far outside any drawing, a curve flattens to millions of points at this tolerance. + let b = bp.control_box(); + if !matches!( + b.x0.abs().max(b.x1.abs()).max(b.y0.abs()).max(b.y1.abs()).partial_cmp(&MAX_COORD), + Some(std::cmp::Ordering::Less | std::cmp::Ordering::Equal) + ) { + return vec![]; + } let mut out: Vec> = vec![]; let mut cur: Vec = vec![]; - let push = |p: Point, cur: &mut Vec| { - if cur.last().is_none_or(|q| q.distance(p) > 1e-9) { + let mut points = 0usize; + let mut push = |p: Point, cur: &mut Vec| { + if points < MAX_POINTS && cur.last().is_none_or(|q| q.distance(p) > 1e-9) { + points += 1; cur.push(p); } }; @@ -205,21 +228,37 @@ fn symbol_name(name: &str, long: bool) -> String { s.trim().to_string() } -/// `base` made unique among `taken` (any case) by `_2`, `_3`…, within `max` characters. -fn unique(base: &str, taken: &[&str], max: usize) -> String { - let base = if base.is_empty() { "Layer".to_string() } else { base.to_string() }; - let free = |n: &str| !taken.iter().any(|t| t.eq_ignore_ascii_case(n)); - if free(&base) { - return base; +/// The names a DXF table holds (compared in any case), and the next suffix to try for each base, +/// so identical names don't each search the suffixes before. +#[derive(Default)] +struct Names { + taken: std::collections::HashSet, + next: HashMap, +} + +impl Names { + /// Names that are there already. + fn with(names: &[&str]) -> Self { + Self { taken: names.iter().map(|n| n.to_lowercase()).collect(), next: HashMap::new() } } - (2..) - .map(|i| { - let suffix = format!("_{i}"); + + /// `base` made unique by `_2`, `_3`…, within `max` characters; the name is taken from now on. + fn unique(&mut self, base: &str, max: usize) -> String { + let base = if base.is_empty() { "Layer".to_string() } else { base.to_string() }; + if self.taken.insert(base.to_lowercase()) { + return base; + } + let next = self.next.entry(base.to_lowercase()).or_insert(2); + loop { + let suffix = format!("_{next}"); + *next += 1; let keep: String = base.chars().take(max.saturating_sub(suffix.len())).collect(); - format!("{keep}{suffix}") - }) - .find(|n| free(n)) - .unwrap_or(base) + let name = format!("{keep}{suffix}"); + if self.taken.insert(name.to_lowercase()) { + return name; + } + } + } } fn overlaps(a: Rect, b: Rect) -> bool { @@ -248,12 +287,14 @@ pub(crate) struct Scene<'a> { e: Codes, next: u32, layers: Vec, + layer_names: Names, /// The DXF layer art goes on, and its flags. layer: String, flags: LayerFlags, linetypes: Vec, /// (style name, font family). styles: Vec<(String, String)>, + style_names: Names, images: Vec, files: Vec, /// Image keys → index into `images` (`None`: left out). @@ -280,10 +321,12 @@ impl<'a> Scene<'a> { e: Codes::new(o.version), next: fixed::FIRST_FREE, layers: vec![], + layer_names: Names::with(&["0", "Defpoints"]), layer: "0".into(), flags: LayerFlags { off: false, locked: false, plot: true }, linetypes: vec![], styles: vec![], + style_names: Names::with(&[crate::writer::STANDARD_STYLE]), images: vec![], files: vec![], by_key: HashMap::new(), @@ -347,6 +390,12 @@ impl<'a> Scene<'a> { if let NodeKind::Layer { template: true, .. } = n.kind { return; } + // Symbols that hold symbols are written in full for each instance: depth alone doesn't + // bound how many entities that is. + if self.next.saturating_sub(fixed::FIRST_FREE) > MAX_ENTITIES { + self.warn("the drawing is too large for DXF: what follows 10 million entities was left out"); + return; + } // Hidden layers are written, switched off. let layer = n.is_layer(); if !force && !n.visible && !layer { @@ -449,9 +498,7 @@ impl<'a> Scene<'a> { fn add_layer(&mut self, n: &Node) -> String { let long = self.o.version.r2000(); let base = symbol_name(n.name.as_deref().unwrap_or("Layer"), long); - let mut taken: Vec<&str> = self.layers.iter().map(|l| l.name.as_str()).collect(); - taken.extend(["0", "Defpoints"]); - let name = unique(&base, &taken, if long { 255 } else { 31 }); + let name = self.layer_names.unique(&base, if long { 255 } else { 31 }); let aci = match n.kind { NodeKind::Layer { color, .. } => nearest_aci(color.rgb(), ColorDepth::Aci256), _ => 7, @@ -852,17 +899,30 @@ impl<'a> Scene<'a> { let angle = b.atan2(a).to_degrees(); for line in &layout.lines { let Some(glyphs) = layout.glyphs.get(line.glyph_start..line.glyph_end) else { continue }; - for run in glyphs.chunk_by(|x, y| x.run == y.run) { - let Some(first) = run.first() else { continue }; + // A list marker is a TEXT entity of its own, holding the marker's characters where its + // characters' glyphs are drawn (not its tab's). + let marked: Vec<(usize, &vectorcraft_text::PositionedGlyph, Option<&vectorcraft_text::ListMarker>)> = + glyphs.iter().enumerate().map(|(k, g)| (line.glyph_start + k, g, layout.marker_of(line.glyph_start + k))).collect(); + for chunk in marked.chunk_by(|x, y| x.1.run == y.1.run && x.2.is_some() == y.2.is_some()) { + let run: Vec<&vectorcraft_text::PositionedGlyph> = + chunk.iter().filter(|(k, _, m)| m.is_none_or(|m| m.tab != *k)).map(|(_, g, _)| *g).collect(); + let Some(&first) = run.first() else { continue }; let lo = run.iter().map(|g| g.byte).min().unwrap_or(first.byte); let hi = run.iter().map(|g| g.byte + g.len).max().unwrap_or(lo); - let Some(s) = plain.get(lo..hi).map(str::trim_end).filter(|s| !s.trim().is_empty()) else { continue }; + // A right-to-left paragraph's marker is drawn with its tab first and its number's + // period at the number's left; the TEXT entity holds the characters in that order. + let marker = chunk.first().and_then(|(_, _, m)| *m).map(|m| match m.text.strip_suffix('.') { + Some(number) if m.tab == m.glyphs.start => format!(".{number}"), + _ => m.text.clone(), + }); + let Some(s) = marker.as_deref().or_else(|| plain.get(lo..hi).map(str::trim_end)).filter(|s| !s.trim().is_empty()) else { continue }; let Some(cs) = t.runs.get(first.run).map(|r| &r.style) else { continue }; let paint = if cs.fill.is_none() { &cs.stroke } else { &cs.fill }; let Some(rgb) = self.paint_rgb(paint) else { continue }; let style = self.style(rgb, 1.0, None, None); let text_style = self.text_style(&cs.font_family); - let height = cs.size * cs.v_scale / 100.0 * CAP_HEIGHT * across; + // The height is that of the size the layout draws: Shrink Text to Fit scales the size by `layout.fit_scale`. + let height = cs.size * layout.fit_scale * cs.v_scale / 100.0 * CAP_HEIGHT * across; let width = if cs.v_scale > 0.0 { cs.h_scale / cs.v_scale } else { 1.0 }; let origin = run.iter().map(|g| g.origin).min_by(|p, q| p.x.total_cmp(&q.x)).unwrap_or(first.origin); let p = self.pt(t.xf * origin); @@ -893,9 +953,7 @@ impl<'a> Scene<'a> { return name.clone(); } let long = self.o.version.r2000(); - let mut taken: Vec<&str> = self.styles.iter().map(|(n, _)| n.as_str()).collect(); - taken.push(crate::writer::STANDARD_STYLE); - let name = unique(&symbol_name(family, long), &taken, if long { 255 } else { 31 }); + let name = self.style_names.unique(&symbol_name(family, long), if long { 255 } else { 31 }); self.styles.push((name.clone(), family.to_string())); name } @@ -906,7 +964,7 @@ impl<'a> Scene<'a> { self.warn(NO_IMAGES); return; } - let Some(i) = self.image_def(&im.key) else { 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))); let map = self.to_dxf * im.xf; @@ -948,12 +1006,13 @@ impl<'a> Scene<'a> { } } - /// The image file for image `key`, encoded once in the chosen format (`None`: left out). - fn image_def(&mut self, key: &str) -> Option { + /// The image file for image `im`, encoded once in the chosen format (`None`: left out). + fn image_def(&mut self, im: &ImageObject) -> Option { + let key = im.key.as_str(); if let Some(i) = self.by_key.get(key) { return *i; } - let made = self.encode_image(key); + let made = self.encode_image(im); let i = match made { Ok((file, size)) => { let handle = self.handle(); @@ -970,10 +1029,19 @@ impl<'a> Scene<'a> { i } - /// Image `key` as a file in the chosen format, and its size in pixels. - fn encode_image(&self, key: &str) -> Result<(DxfImage, (u32, u32)), String> { - let blob = self.doc.images.get(key).filter(|b| !b.bytes.is_empty()).ok_or_else(|| format!("image '{key}' has no pixels and was left out"))?; - let img = image::load_from_memory(&blob.bytes).map_err(|_| format!("image '{key}' could not be decoded and was left out"))?; + /// Image `im` as a file in the chosen format, and its size in pixels. + fn encode_image(&self, im: &ImageObject) -> Result<(DxfImage, (u32, u32)), String> { + let blob = self.doc.image_blob(im).filter(|b| !b.bytes.is_empty()).ok_or_else(|| "an image has no pixels and was left out".to_string())?; + // The pixels it converts to (RGBA, 4 bytes each) are read from its header before decoding. + let (w, h) = image::ImageReader::new(Cursor::new(blob.bytes.as_slice())) + .with_guessed_format() + .ok() + .and_then(|r| r.into_dimensions().ok()) + .ok_or_else(|| UNDECODED.to_string())?; + if u64::from(w) * u64::from(h) > MAX_IMAGE_PIXELS { + return Err("an image is too large for DXF and was left out".to_string()); + } + let img = image::load_from_memory(&blob.bytes).map_err(|_| UNDECODED.to_string())?; let size = (img.width(), img.height()); let mut bytes = vec![]; let written = match self.o.raster { @@ -991,7 +1059,7 @@ impl<'a> Scene<'a> { rgb.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut bytes, 90)) } }; - written.map_err(|e| format!("image '{key}' could not be written: {e}"))?; + written.map_err(|e| format!("an image could not be written: {e}"))?; Ok((DxfImage { name: format!("{}.{}", blob.content_key(), self.o.raster.extension()), bytes }, size)) } } diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 3701d11a9d..46b09f5ff2 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -456,6 +456,87 @@ fn type_is_text_or_outlines() { } } +/// A list paragraph's bullet is a TEXT entity of its own where it is drawn, and the paragraph's +/// text starts after it, at the left indent. +#[test] +fn a_bullet_is_text_of_its_own_before_its_paragraph() { + let mut d = text_doc("Item", 20.0); + let id = d.layers[0].children().unwrap()[0].id; + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + t.para.list = Some(vectorcraft_doc::text::ParaList::bulleted(vectorcraft_doc::text::Bullet::Dot)); + t.para.left_indent = 18.0; + t.para.first_line_indent = -18.0; + } + let out = export(&d, &DxfOptions { version: DxfVersion::R2018, preserve: Preserve::Editability, ..opts(&d) }).unwrap(); + let e = entities(&out); + assert_eq!(kinds(&out), ["TEXT", "TEXT"]); + assert_eq!((get(&e[0], 1), get(&e[1], 1)), (Some("\u{2022}"), Some("Item"))); + assert_eq!((all(&e[0], 10)[0], all(&e[1], 10)[0]), (10.0, 28.0), "the bullet at the anchor, the text 18 pt on"); + // In a right-to-left paragraph the bullet is drawn after the text, at the right, and its tab + // lies between the two. + let mut d = text_doc("שלום", 20.0); + let id = d.layers[0].children().unwrap()[0].id; + let mut bullet_x = f64::NAN; + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + t.para.list = Some(vectorcraft_doc::text::ParaList::bulleted(vectorcraft_doc::text::Bullet::Dot)); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let m = &lay.markers[0]; + let bullet = m.glyphs.clone().find(|&i| i != m.tab).unwrap(); + assert!(lay.glyphs[m.tab].origin.x < lay.glyphs[bullet].origin.x, "the tab before the bullet"); + bullet_x = 10.0 + lay.glyphs[bullet].origin.x; + } + let out = export(&d, &DxfOptions { version: DxfVersion::R2018, preserve: Preserve::Editability, ..opts(&d) }).unwrap(); + let e = entities(&out); + assert_eq!(kinds(&out), ["TEXT", "TEXT"]); + assert_eq!((get(&e[0], 1), get(&e[1], 1)), (Some("שלום"), Some("\u{2022}"))); + assert!((all(&e[1], 10)[0] - bullet_x).abs() < 1e-6, "the bullet where it is drawn: {} and {bullet_x}", all(&e[1], 10)[0]); +} + +/// A numbered list paragraph's number and period are a TEXT entity of their own where they are +/// drawn, in the order they are drawn: in a right-to-left paragraph the period comes first, at the +/// number's left. +#[test] +fn a_number_is_text_of_its_own_before_its_paragraph() { + use vectorcraft_doc::text::{NumberStyle, ParaList}; + let numbered = |text: &str, count: u32| { + let mut d = text_doc(text, 20.0); + let id = d.layers[0].children().unwrap()[0].id; + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + t.para.list = Some(ParaList::numbered(NumberStyle::Arabic)); + t.para.left_indent = 30.0; + t.para.first_line_indent = -30.0; + t.list_count = count; + } + let out = export(&d, &DxfOptions { version: DxfVersion::R2018, preserve: Preserve::Editability, ..opts(&d) }).unwrap(); + entities(&out).iter().map(|e| (get(e, 1).map(str::to_string), all(e, 10)[0])).collect::>() + }; + assert_eq!(numbered("Item", 11), [(Some("12.".to_string()), 10.0), (Some("Item".to_string()), 40.0)]); + let rtl = numbered("שלום", 11); + assert_eq!(rtl.iter().map(|(s, _)| s.clone().unwrap_or_default()).collect::>(), ["שלום", ".12"]); + assert!(rtl[1].1 > rtl[0].1, "the number right of the text: {rtl:?}"); +} + +/// Area type that Shrink Text to Fit scales down is written at the height it draws at. +#[test] +fn shrunk_area_type_is_text_at_the_size_it_draws_at() { + let mut d = text_doc("Plan A, plan B and plan C", 20.0); + let id = d.layers[0].children().unwrap()[0].id; + let mut fit = 1.0; + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + t.kind = vectorcraft_doc::TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 120.0, 30.0)) }; + t.area.fit = vectorcraft_doc::AreaFit::ShrinkText { min_percent: 10.0 }; + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + assert!(!lay.overflow && lay.fit_scale < 0.9, "the text is shrunk to fit: {}", lay.fit_scale); + fit = lay.fit_scale; + } + let out = export(&d, &DxfOptions { preserve: Preserve::Editability, ..opts(&d) }).unwrap(); + let e = entities(&out); + assert!(!e.is_empty() && e.iter().all(|e| kind(e) == "TEXT"), "{:?}", kinds(&out)); + for e in &e { + assert!((all(e, 40)[0] - 14.0 * fit).abs() < 1e-6, "the cap height of {} pt type: {:?}", 20.0 * fit, all(e, 40)); + } +} + #[test] fn text_outside_ascii_is_escaped_before_2007() { let d = text_doc("Größe", 12.0); @@ -479,6 +560,7 @@ fn images_link_png_or_jpeg_files() { xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0), link: None, placement: Default::default(), + pixels: None, }; vec![Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))] }); @@ -505,6 +587,32 @@ fn images_link_png_or_jpeg_files() { assert!(r12.warnings.iter().any(|w| w.contains("no images"))); } +#[test] +fn images_without_pixels_are_left_out_with_one_note() { + // One image has no data in the document, and the other image's data is empty. + let mut d = doc_with(|d| { + ["raster-1", "raster-2"] + .into_iter() + .map(|key| { + let im = ImageObject { + key: key.into(), + width: 4, + height: 2, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))) + }) + .collect() + }); + d.images.insert("raster-2".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(vec![]), proxy: None }); + let out = export(&d, &opts(&d)).unwrap(); + assert!(entities(&out).is_empty() && out.images.is_empty()); + assert_eq!(out.warnings, ["an image has no pixels and was left out"]); +} + #[test] fn crop_leaves_out_art_outside_the_region() { let d = shapes_doc(); diff --git a/crates/color/src/cms/mod.rs b/crates/color/src/cms.rs similarity index 100% rename from crates/color/src/cms/mod.rs rename to crates/color/src/cms.rs diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 5d4f1c9745..8201b8b97f 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -1,6 +1,7 @@ //! ICC profiles through `moxcms` (pure Rust): built-in RGB spaces and user-supplied `.icc` files, //! and the profiles exports embed ([`encode_builtin`]), written in code from the CMS. +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use moxcms::{ @@ -8,7 +9,7 @@ use moxcms::{ RenderingIntent, ToneReprCurve, TransformF32Executor, TransformOptions, Vector3d, }; -use super::{CmsError, Intent, ProfileKind, lab}; +use super::{CmsError, Intent, ProfileKind, lab, profiles_generation}; fn moxcms_intent(i: Intent) -> RenderingIntent { match i { @@ -27,12 +28,17 @@ fn intent_index(i: Intent) -> usize { type Xf = Option>; -/// A direct transform's cache key: destination name, intent index, black-point compensation. -type DirectKey = (String, usize, bool); +/// A direct transform's cache key: destination [`IccProfile::id`], [`profiles_generation`] it was +/// built in, intent index, black-point compensation. The id tells a reloaded profile from the old +/// one of the same name, which settings built before the reload still convert into; the +/// generation only lets the cache drop what reloads left behind. +type DirectKey = (u64, u64, usize, bool); /// A parsed ICC profile plus lazily-built transforms to/from sRGB. pub struct IccProfile { pub name: String, + /// Unique to this instance: never reused, unlike its name or address. + id: u64, pub kind: ProfileKind, /// The file it was loaded from (empty for profiles made in code). source: Vec, @@ -82,8 +88,10 @@ impl IccProfile { other => return Err(CmsError::Unsupported(format!("profile colour space {other:?} is not RGB, CMYK or Gray"))), }; let name = name.or_else(|| text(&profile.description)).unwrap_or_else(|| format!("Untitled {kind:?} profile")); + static NEXT_ID: AtomicU64 = AtomicU64::new(0); Ok(Self { name, + id: NEXT_ID.fetch_add(1, Ordering::Relaxed), kind, source: Vec::new(), profile, @@ -95,6 +103,9 @@ impl IccProfile { } pub fn from_bytes(name: Option, bytes: &[u8]) -> Result { + if !localized_text_fits(bytes) { + return Err(CmsError::BadProfile(format!("its localized names take more than {} KB", MAX_LOCALIZED_TEXT >> 10))); + } let p = ColorProfile::new_from_slice(bytes).map_err(|e| CmsError::BadProfile(format!("{e:?}")))?; Ok(Self { source: bytes.to_vec(), ..Self::from_profile(name, p)? }) } @@ -179,8 +190,11 @@ impl IccProfile { if dest.kind != ProfileKind::Rgb { return None; } - let key = (dest.name.clone(), intent_index(intent), bpc); + let generation = profiles_generation(); + let key = (dest.id, generation, intent_index(intent), bpc); let mut cache = self.direct.lock().unwrap_or_else(|e| e.into_inner()); + // an older generation's entries can't match again: drop them so reloads don't pile up + cache.retain(|(k, _)| k.1 == generation); if let Some((_, t)) = cache.iter().find(|(k, _)| *k == key) { return t.clone(); } @@ -393,3 +407,36 @@ pub(super) fn gray_profile(name: &str) -> ColorProfile { p.gray_trc = ColorProfile::new_srgb().red_trc; labelled(p, name) } + +/// Most bytes of UTF-16 the localized names (`mluc` tags) of a profile may take together. +const MAX_LOCALIZED_TEXT: usize = 1 << 20; + +/// Whether the localized-name records of the `mluc` tags in ICC `bytes` take at most +/// [`MAX_LOCALIZED_TEXT`] together. moxcms copies each record into a string of its own, and records +/// may all point at the same bytes, so a profile under a megabyte could make it allocate +/// gigabytes. A table it can't read is left to moxcms to refuse. +pub(crate) fn localized_text_fits(bytes: &[u8]) -> bool { + let be32 = |b: &[u8], at: usize| b.get(at..at.checked_add(4)?).map(|v| u32::from_be_bytes([v[0], v[1], v[2], v[3]]) as usize); + let Some(tags) = be32(bytes, 128) else { return true }; + let mut total = 0usize; + for i in 0..tags { + let Some(entry) = i.checked_mul(12).and_then(|e| e.checked_add(132)) else { return false }; + let (Some(offset), Some(size)) = (be32(bytes, entry + 4), be32(bytes, entry + 8)) else { break }; + let Some(tag) = offset.checked_add(size).and_then(|end| bytes.get(offset..end)) else { continue }; + if !tag.starts_with(b"mluc") { + continue; + } + let records = be32(tag, 8).unwrap_or(0); + for r in 0..records { + // Each record's header: language, country, length, offset. + let Some(length) = r.checked_mul(12).and_then(|h| be32(tag, h + 16 + 4)) else { break }; + // Each record counts its 12-byte header too: records of length 0 are not free, so + // many tags pointing at one `mluc` can't make this loop quadratic. + total = total.saturating_add(length).saturating_add(12); + if total > MAX_LOCALIZED_TEXT { + return false; + } + } + } + true +} diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs index b3796d4444..46e44cd760 100644 --- a/crates/color/src/cms/tests_icc.rs +++ b/crates/color/src/cms/tests_icc.rs @@ -113,11 +113,11 @@ fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() { assert_eq!(abs(true), abs(false)); } -/// #1584: the profiles written here (built-in RGB spaces) have every tag on a 4-byte boundary and -/// a size that is a multiple of 4 (ICC.1 §7.1.2), and still read back as the same space. +/// #1584: every built-in profile (RGB, CMYK and gray) has each tag on a 4-byte boundary and a size +/// that is a multiple of 4 (ICC.1 §7.1.2), and still reads back as the same space. #[test] -fn written_profiles_align_their_tags() { - for name in [super::SRGB, super::DISPLAY_P3, super::WIDE_GAMUT_RGB, super::PROPHOTO_RGB] { +fn builtin_profiles_align_their_sizes_and_tags() { + for name in BUILTIN_RGB.into_iter().chain(BUILTIN_CMYK).chain([GRAY]) { let icc = super::icc_bytes(name).unwrap(); let be = |at: usize| u32::from_be_bytes([icc[at], icc[at + 1], icc[at + 2], icc[at + 3]]) as usize; assert_eq!(be(0), icc.len(), "{name}: header size"); @@ -152,3 +152,77 @@ fn cmyk_profiles_have_the_tags_of_an_output_profile() { assert!(p.lut_a_to_b_saturation.is_some() && p.lut_b_to_a_saturation.is_some() && p.gamut.is_some(), "{name}"); } } + +/// A profile whose localized-name records all point at one long string is refused before moxcms +/// copies each of them; a few short names pass. +#[test] +fn aliased_localized_names_are_refused() { + let profile = |records: u32, length: u32| { + let mut b = vec![0u8; 128]; + b.extend(1u32.to_be_bytes()); + let tag_at = 128 + 4 + 12; + let size = 16 + 12 * records + length; + b.extend(b"desc"); + b.extend((tag_at as u32).to_be_bytes()); + b.extend(size.to_be_bytes()); + b.extend(b"mluc"); + b.extend([0; 4]); + b.extend(records.to_be_bytes()); + b.extend(12u32.to_be_bytes()); + for _ in 0..records { + b.extend(b"enUS"); + b.extend(length.to_be_bytes()); + b.extend((16 + 12 * records).to_be_bytes()); + } + b.extend(vec![0u8; length as usize]); + b + }; + assert!(super::icc::localized_text_fits(&profile(3, 64))); + assert!(!super::icc::localized_text_fits(&profile(4096, 64 << 10))); +} + +/// Reloading an RGB profile under the name it had (a new file for "My RGB") changes what CMYK +/// converts to in it: the direct CMYK → RGB transform isn't kept from the old file. +#[test] +fn a_reloaded_rgb_profile_replaces_the_direct_cmyk_transform_into_it() { + let cmyk = register_icc(&icc_bytes(GENERIC_CMYK).unwrap(), Some("Reload Test CMYK".into())).unwrap().name; + let rgb = "Reload Test RGB"; + let cyan = [1.0, 0.0, 0.0, 0.0]; + let convert = || { + let cms = Cms::new(&ColorSettings { rgb: rgb.into(), cmyk: cmyk.clone(), ..ColorSettings::default() }).unwrap(); + cms.cmyk_to_rgb(cyan, Intent::RelativeColorimetric) + }; + register_icc(&icc::builtin_rgb_bytes(SRGB).unwrap(), Some(rgb.into())).unwrap(); + let in_srgb = convert(); + register_icc(&icc::builtin_rgb_bytes(PROPHOTO_RGB).unwrap(), Some(rgb.into())).unwrap(); + let in_prophoto = convert(); + // What a CMYK profile loaded afresh gives in the new file. + let fresh = register_icc(&icc_bytes(GENERIC_CMYK).unwrap(), Some("Reload Test CMYK 2".into())).unwrap().name; + let want = Cms::new(&ColorSettings { rgb: rgb.into(), cmyk: fresh, ..ColorSettings::default() }) + .unwrap() + .cmyk_to_rgb(cyan, Intent::RelativeColorimetric); + assert!(in_srgb.iter().zip(want).any(|(a, b)| (a - b).abs() > 0.05), "sRGB {in_srgb:?} vs ProPhoto {want:?}"); + assert!(in_prophoto.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4), "after the reload {in_prophoto:?}, want {want:?}"); +} + +/// The app loads a profile and only then switches to the new settings, so the working spaces +/// built before the reload keep converting in between: a CMYK color they convert after it doesn't +/// leave the old RGB file's transform for the settings built afterwards. +#[test] +fn settings_built_before_a_reload_dont_leave_the_old_transform_to_the_new_ones() { + let cmyk = register_icc(&icc_bytes(GENERIC_CMYK).unwrap(), Some("Stale Test CMYK".into())).unwrap().name; + let rgb = "Stale Test RGB"; + let cyan = [1.0, 0.0, 0.0, 0.0]; + let settings = ColorSettings { rgb: rgb.into(), cmyk: cmyk.clone(), ..ColorSettings::default() }; + register_icc(&icc::builtin_rgb_bytes(SRGB).unwrap(), Some(rgb.into())).unwrap(); + let old = Cms::new(&settings).unwrap(); + let in_srgb = old.cmyk_to_rgb(cyan, Intent::RelativeColorimetric); + register_icc(&icc::builtin_rgb_bytes(PROPHOTO_RGB).unwrap(), Some(rgb.into())).unwrap(); + assert_eq!(old.cmyk_to_rgb(cyan, Intent::RelativeColorimetric), in_srgb, "the old settings keep the old file"); + let in_prophoto = Cms::new(&settings).unwrap().cmyk_to_rgb(cyan, Intent::RelativeColorimetric); + // What a CMYK profile loaded afresh gives in the new file. + let fresh = register_icc(&icc_bytes(GENERIC_CMYK).unwrap(), Some("Stale Test CMYK 2".into())).unwrap().name; + let want = Cms::new(&ColorSettings { cmyk: fresh, ..settings }).unwrap().cmyk_to_rgb(cyan, Intent::RelativeColorimetric); + assert!(in_srgb.iter().zip(want).any(|(a, b)| (a - b).abs() > 0.05), "sRGB {in_srgb:?} vs ProPhoto {want:?}"); + assert!(in_prophoto.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4), "after the reload {in_prophoto:?}, want {want:?}"); +} diff --git a/crates/color/src/freeform.rs b/crates/color/src/freeform.rs index 751e238969..798367ba4c 100644 --- a/crates/color/src/freeform.rs +++ b/crates/color/src/freeform.rs @@ -162,8 +162,9 @@ impl Freeform { /// ([`Color::lerp_keep_model`]). pub fn recolor(&mut self, g: &Gradient) { let n = self.points.len(); - for (k, p) in self.points.iter_mut().enumerate() { - (p.color, p.opacity) = g.sample_with(k as f32 / (n - 1).max(1) as f32, Color::lerp_keep_model); + let at = (0..n).map(|k| k as f32 / (n - 1).max(1) as f32); + for (p, (color, opacity)) in self.points.iter_mut().zip(g.sample_increasing_with(at, Color::lerp_keep_model)) { + (p.color, p.opacity) = (color, opacity); } } diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 1c2b96c6e1..528d560336 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -31,6 +31,75 @@ impl GradientKind { } } +/// How a gradient mixes the colours between its stops (the Gradient panel's Method). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum GradientMethod { + /// Mixed in display RGB, as gradients always were. + #[default] + Classic, + /// 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, +} + +impl GradientMethod { + /// Parse a method name (`classic`, `perceptual`; any case). + pub fn parse(s: &str) -> Option { + [Self::Classic, Self::Perceptual].into_iter().find(|m| m.label().eq_ignore_ascii_case(s)) + } + pub fn label(self) -> &'static str { + match self { + Self::Classic => "Classic", + Self::Perceptual => "Perceptual", + } + } + 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). + pub fn mix(self, a: &Color, b: &Color, t: f32) -> Color { + match self { + Self::Classic => Color::lerp(a, b, t), + Self::Perceptual => { + use crate::libraries::{oklab_to_srgb, srgb_to_oklab}; + let (p, q, t) = (srgb_to_oklab(a.to_rgb()), srgb_to_oklab(b.to_rgb()), f64::from(t)); + let [r, g, bl] = oklab_to_srgb(p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t, p[2] + (q[2] - p[2]) * t); + 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)) + } + } + } +} + +/// 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; +/// Most times each half of a Perceptual gradient's segment (either side of its midpoint) is +/// halved to keep within [`PERCEPTUAL_TOLERANCE`]. +const PERCEPTUAL_DEPTH: u32 = 10; + +/// 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(); + let (c0, c1) = (at(v0), at(v1)); + let stray = [0.25, 0.5, 0.75] + .into_iter() + .flat_map(|u: f32| { + let c = at(v0 + (v1 - v0) * u); + (0..3).map(move |k| (c0[k] + (c1[k] - c0[k]) * u - c[k]).abs()) + }) + .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); + out.push(m); + perceptual_steps(a, b, (m, v1), depth + 1, out); + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GradientStop { /// 0..=1 along the gradient. @@ -64,6 +133,16 @@ impl GradientStop { } } +/// The colour and opacity at `t` between stops `a` and `b`, through `a`'s midpoint (`u` = midpoint +/// maps to `v` = ½), mixed by `mix`. +fn between(a: &GradientStop, b: &GradientStop, t: f32, mix: &impl Fn(&Color, &Color, f32) -> Color) -> (Color, f32) { + let span = (b.offset - a.offset).max(1e-6); + let u = (t - a.offset) / span; + let m = a.midpoint.clamp(0.01, 0.99); + let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) }; + (mix(&a.color, &b.color, v), a.opacity + (b.opacity - a.opacity) * v) +} + fn one() -> f32 { 1.0 } @@ -75,19 +154,39 @@ fn half() -> f32 { pub struct Gradient { pub kind: GradientKind, pub stops: Vec, + /// Dither: a fill of this gradient is drawn as pixels with fine noise of up to a colour level + /// added, which hides the steps (banding) between the levels 8-bit colour has. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub dither: bool, + /// 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, } impl Default for Gradient { /// Illustrator's default "White, Black" gradient. fn default() -> Self { - Self { kind: GradientKind::Linear, stops: vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)] } + Self::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)]) } } impl Gradient { - /// Colour and opacity at `t` (honours midpoints). + /// 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 } + } + /// Colour and opacity at `t` (honours midpoints and the method). pub fn sample(&self, t: f32) -> (Color, f32) { - self.sample_with(t, Color::lerp) + self.sample_with(t, |a, b, v| self.method.mix(a, b, v)) + } + /// [`Self::sample`], a Classic gradient's neighbouring stop colours of one model mixed in it + /// (CMYK stays CMYK; [`Color::lerp_keep_model`]) rather than in display RGB, a Perceptual + /// gradient's as [`Self::sample`] mixes them. + pub fn sample_keep_model(&self, t: f32) -> (Color, f32) { + match self.method { + GradientMethod::Classic => self.sample_with(t, Color::lerp_keep_model), + m => self.sample_with(t, |a, b, v| m.mix(a, b, v)), + } } /// [`Gradient::sample`] with neighbouring stop colours mixed by `mix` (e.g. in their own colour /// model rather than display RGB). @@ -102,12 +201,7 @@ impl Gradient { for w in stops.windows(2) { let (a, b) = (&w[0], &w[1]); if t <= b.offset { - let span = (b.offset - a.offset).max(1e-6); - let u = (t - a.offset) / span; - // Map through the midpoint: u=mid → 0.5. - let m = a.midpoint.clamp(0.01, 0.99); - let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) }; - return (mix(&a.color, &b.color, v), a.opacity + (b.opacity - a.opacity) * v); + return between(a, b, t, &mix); } } match stops.last() { @@ -115,20 +209,79 @@ impl Gradient { None => (Color::BLACK, 1.0), } } - /// Stops expanded so that midpoints are represented as explicit stops (for renderers without midpoints). + /// [`Self::sample_with`] at each of `ts`, which must not decrease. Each search starts where + /// the one before it stopped, so the work is the samples plus the stops, not their product. + pub fn sample_increasing_with(&self, ts: impl IntoIterator, mix: impl Fn(&Color, &Color, f32) -> Color) -> Vec<(Color, f32)> { + let stops = &self.stops; + // The shared index assumes ordered stops; others (a file's, unsorted) sample one by one. + if stops.windows(2).any(|w| w[1].offset < w[0].offset) { + return ts.into_iter().map(|t| self.sample_with(t, &mix)).collect(); + } + let mut j = 0; + ts.into_iter() + .map(|t| { + let Some(first) = stops.first() else { return (Color::BLACK, 1.0) }; + if t <= first.offset { + return (first.color, first.opacity); + } + // The first pair whose end `t` doesn't pass, as `sample_with` finds it: one that a + // smaller `t` passed, this one passes too. + while j + 1 < stops.len() && t > stops[j + 1].offset { + j += 1; + } + match (stops.get(j), stops.get(j + 1)) { + (Some(a), Some(b)) => between(a, b, t, &mix), + _ => stops.last().map_or((Color::BLACK, 1.0), |l| (l.color, l.opacity)), + } + }) + .collect() + } + /// Stops expanded so that midpoints are represented as explicit stops (for renderers without + /// midpoints), and a Perceptual gradient's segments as stops on its curve (for renderers that + /// mix linearly; within [`PERCEPTUAL_TOLERANCE`] of it). pub fn expanded_stops(&self) -> Vec<(f32, Color, f32)> { self.expanded().map(|(t, c, o, _)| (t, c, o)).collect() } /// [`Self::expanded_stops`], each stop that stands for a midpoint with that midpoint (`None` - /// on the gradient's own stops). + /// on the gradient's own stops and a Perceptual gradient's other in-between stops). pub fn expanded(&self) -> impl Iterator)> + '_ { + // Direct interpolation matches `sample` only for strictly increasing offsets. + let increasing = self.stops.windows(2).all(|w| w[0].offset < w[1].offset); self.stops.iter().enumerate().flat_map(move |(i, s)| { - let mid = self.stops.get(i + 1).filter(|_| (s.midpoint - 0.5).abs() > 1e-3).map(|n| { + let next = self.stops.get(i + 1); + let off_centre = (s.midpoint - 0.5).abs() > 1e-3; + // Classic: a stop at the midpoint, when it is off-centre. + let classic = next.filter(|_| off_centre && self.method.is_classic()).map(|n| { let t = s.offset + (n.offset - s.offset) * s.midpoint; - let (c, o) = self.sample(t); + // Mixed from the two stops it lies between, as `sample` would: searching all the + // stops again for each midpoint made many stops cost their square. + let mix = |a: &Color, b: &Color, v| self.method.mix(a, b, v); + let (c, o) = if increasing { between(s, n, t, &mix) } else { self.sample_with(t, mix) }; (t, c, o, Some(s.midpoint)) }); - std::iter::once((s.offset, s.color, s.opacity, None)).chain(mid) + // Perceptual: stops along the mix (`v`) where a straight line would stray from it, the + // midpoint (v = ½) among them, placed through the midpoint as [`Self::sample`] maps them. + let perceptual = next.filter(|_| !self.method.is_classic()).map(|n| { + let mut vs = Vec::new(); + perceptual_steps(&s.color, &n.color, (0.0, 0.5), 1, &mut vs); + vs.push(0.5); + perceptual_steps(&s.color, &n.color, (0.5, 1.0), 1, &mut vs); + let m = s.midpoint.clamp(0.01, 0.99); + vs.into_iter().map(move |v| { + let mid = v == 0.5; + let u = if mid { + s.midpoint + } else if v < 0.5 { + 2.0 * v * m + } else { + m + (v - 0.5) * 2.0 * (1.0 - m) + }; + let t = s.offset + (n.offset - s.offset) * u; + let o = s.opacity + (n.opacity - s.opacity) * v; + (t, self.method.mix(&s.color, &n.color, v), o, (mid && off_centre).then_some(s.midpoint)) + }) + }); + std::iter::once((s.offset, s.color, s.opacity, None)).chain(classic).chain(perceptual.into_iter().flatten()) }) } /// The same ramp the other way round: the stops in reverse order at mirrored offsets, each @@ -172,7 +325,7 @@ impl Gradient { ); } stops.push(stop(1.0, to)); - Gradient { kind: GradientKind::Linear, stops } + Gradient::new(GradientKind::Linear, stops) } } @@ -534,295 +687,118 @@ impl GradientPaint { f.transform(a); } } + /// 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)? + 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 or radial 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 + /// [`dither_noise`] before it is rounded to a level. + pub fn pixels( + &self, + bounds: Rect, + area: Rect, + cols: u16, + rows: u16, + fill: bool, + rgb: &dyn Fn(&Color) -> [f32; 3], + ) -> impl Iterator + use<> { + self.pixels_within(bounds, area, cols, rows, [0..cols, 0..rows], fill, rgb) + } + /// [`Self::pixels`] for the cells in columns `cells[0]` and rows `cells[1]` of the grid only, + /// row by row: the same pixels, noise and all, the whole grid has there. + #[allow(clippy::too_many_arguments)] + pub fn pixels_within( + &self, + bounds: Rect, + area: Rect, + cols: u16, + rows: u16, + cells: [std::ops::Range; 2], + fill: bool, + rgb: &dyn Fn(&Color) -> [f32; 3], + ) -> impl Iterator + use<> { + let (kind, geom, dither) = (self.gradient.kind, self.resolve(bounds), fill && self.gradient.dither); + let ramp = Ramp::new(&self.gradient, rgb); + 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 level = |k: usize| { + let noise = if dither { dither_noise(i, j, k as u32) } else { 0.0 }; + (c[k].clamp(0.0, 1.0) * 255.0 + noise).round().clamp(0.0, 255.0) as u8 + }; + [level(0), level(1), level(2), (c[3].clamp(0.0, 1.0) * 255.0).round() as u8] + }) + } +} + +/// A gradient's colours ready to be sampled pixel by pixel, in a colour space of the caller's +/// (display RGB, or an ink's coverage): its stops, midpoints and a Perceptual gradient's +/// in-between colours as stops (as [`Gradient::expanded_stops`]), each turned into that space +/// once, with colour and opacity mixed linearly between them, each on its own (as the renderer's +/// vector gradients mix them). +pub struct Ramp { + stops: Vec<(f32, [f32; 4])>, +} + +impl Ramp { + pub fn new(g: &Gradient, rgb: &dyn Fn(&Color) -> [f32; 3]) -> Self { + let stops = g + .expanded() + .map(|(t, c, o, _)| { + let [r, gr, b] = rgb(&c); + (t, [r, gr, b, o]) + }) + .collect(); + Self { stops } + } + /// Unpremultiplied colour and opacity at `t`, padded past the ends (transparent black + /// without stops). + pub fn at(&self, t: f32) -> [f32; 4] { + let Some(&(t0, first)) = self.stops.first() else { return [0.0; 4] }; + // Not after the first stop (or not a number): its colour. + if t.partial_cmp(&t0) != Some(std::cmp::Ordering::Greater) { + return first; + } + for w in self.stops.windows(2) { + let ((a, ca), (b, cb)) = (w[0], w[1]); + if t <= b { + let u = if b - a > 1e-9 { (t - a) / (b - a) } else { 1.0 }; + return std::array::from_fn(|k| ca[k] + (cb[k] - ca[k]) * u); + } + } + self.stops.last().map_or([0.0; 4], |s| s.1) + } +} + +/// Seed of [`dither_noise`]: fixed, so a dithered gradient draws and exports the same pixels on +/// every run. +const DITHER_SEED: u32 = 0x5eed_d17e; + +/// An integer hash that mixes every input bit into every output bit (the "lowbias32" mix). +fn mix32(mut v: u32) -> u32 { + v ^= v >> 16; + v = v.wrapping_mul(0x7feb_352d); + v ^= v >> 15; + v = v.wrapping_mul(0x846c_a68b); + v ^ (v >> 16) +} + +/// Dither noise for colour channel `channel` of pixel (`x`, `y`), in colour levels: -1..1, +/// densest around 0 (the sum of two uniform values: noise that hides steps between levels without +/// a pattern of its own), the same for the same pixel on every run. +pub fn dither_noise(x: u32, y: u32, channel: u32) -> f32 { + let h = mix32(x ^ mix32(y ^ mix32(channel ^ DITHER_SEED))); + ((h & 0xffff) as f32 + (h >> 16) as f32) / 65535.0 - 1.0 } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn sample_endpoints_and_mid() { - let g = Gradient::default(); - assert_eq!(g.sample(0.0).0.to_hex(), "#ffffff"); - assert_eq!(g.sample(1.0).0.to_hex(), "#000000"); - let mid = g.sample(0.5).0.to_rgb()[0]; - assert!((mid - 0.5).abs() < 1e-5); - } - - #[test] - fn midpoint_shifts() { - let mut g = Gradient::default(); - g.stops[0].midpoint = 0.25; - // At t = 0.25 we should be half way. - assert!((g.sample(0.25).0.to_rgb()[0] - 0.5).abs() < 1e-5); - assert_eq!(g.expanded_stops().len(), 3); - } - - #[test] - fn fit_linear_horizontal() { - let g = GradientGeom::fit(GradientKind::Linear, Rect::new(0.0, 0.0, 100.0, 50.0), 0.0); - assert_eq!(g.start, Point::new(0.0, 25.0)); - assert_eq!(g.end, Point::new(100.0, 25.0)); - assert!((g.angle_deg()).abs() < 1e-9); - let v = GradientGeom::fit(GradientKind::Linear, Rect::new(0.0, 0.0, 100.0, 50.0), 90.0); - assert!((v.angle_deg() - 90.0).abs() < 1e-9); - assert!((v.length() - 50.0).abs() < 1e-9); - } - - #[test] - fn reverse_stops() { - let mut g = Gradient::default(); - g.reverse(); - assert_eq!(g.stops[0].color.to_hex(), "#000000"); - assert_eq!(g.stops[0].offset, 0.0); - } - - /// #1007: reversing mirrors off-centre midpoints with their segments, so the ramp is the same - /// the other way round. - #[test] - fn reverse_mirrors_midpoints() { - let stop = |offset, hex, midpoint| GradientStop { midpoint, ..GradientStop::new(offset, Color::from_hex(hex).unwrap()) }; - let two = Gradient { kind: GradientKind::Linear, stops: vec![stop(0.0, "#ff0000", 0.2), stop(1.0, "#0000ff", 0.5)] }; - let three = - Gradient { kind: GradientKind::Linear, stops: vec![stop(0.0, "#ff0000", 0.2), stop(0.3, "#00ff00", 0.8), stop(1.0, "#0000ff", 0.5)] }; - for g in [two, three] { - let mut r = g.clone(); - r.reverse(); - let mids: Vec = r.stops.iter().map(|s| s.midpoint).collect(); - let want: Vec = g.stops.iter().rev().skip(1).map(|s| 1.0 - s.midpoint).chain([0.5]).collect(); - assert!(mids.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-6), "{mids:?} {want:?}"); - for i in 0..=20 { - let t = i as f32 / 20.0; - let ((a, ao), (b, bo)) = (g.sample(t), r.sample(1.0 - t)); - let same = a.to_rgba8(1.0).iter().zip(b.to_rgba8(1.0)).all(|(x, y)| x.abs_diff(y) <= 1); - assert!(same && (ao - bo).abs() < 1e-6, "t {t}: {a:?} vs {b:?}"); - } - r.reverse(); - let back = r.stops.iter().zip(&g.stops).all(|(a, b)| (a.offset - b.offset).abs() < 1e-6 && (a.midpoint - b.midpoint).abs() < 1e-6); - assert!(back, "reversed twice, it is as it was: {:?}", r.stops); - } - } - - fn close(a: Point, b: Point) -> bool { - a.distance(b) < 1e-9 - } - - fn linear(start: (f64, f64), end: (f64, f64)) -> GradientGeom { - GradientGeom { start: start.into(), end: end.into(), aspect: 1.0, focal: None } - } - - #[test] - fn rotate_90_gives_vertical_vector() { - let mut g = linear((0.0, 0.0), (100.0, 0.0)); - g.transform(Affine::rotate(std::f64::consts::FRAC_PI_2), GradientKind::Linear); - assert!(close(g.start, Point::ZERO) && close(g.end, Point::new(0.0, 100.0)), "{g:?}"); - assert!((g.angle_deg() + 90.0).abs() < 1e-9); - } - - #[test] - fn reflect_swaps_start_and_end() { - let mut g = linear((0.0, 25.0), (100.0, 25.0)); - // Reflect across the vertical axis through x = 50. - let flip = Affine::translate((50.0, 0.0)) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate((-50.0, 0.0)); - g.transform(flip, GradientKind::Linear); - assert!(close(g.start, Point::new(100.0, 25.0)) && close(g.end, Point::new(0.0, 25.0)), "{g:?}"); - } - - #[test] - fn non_uniform_scale_turns_a_circle_into_an_ellipse() { - let mut g = GradientGeom { start: Point::new(10.0, 10.0), end: Point::new(20.0, 10.0), aspect: 1.0, focal: None }; - g.transform(Affine::scale_non_uniform(2.0, 1.0), GradientKind::Radial); - assert!(close(g.start, Point::new(20.0, 10.0)) && close(g.end, Point::new(40.0, 10.0)), "{g:?}"); - assert!((g.aspect - 0.5).abs() < 1e-9); - // A vertical vector keeps its axis: the ellipse is twice as wide as the vector is long. - let mut v = GradientGeom { start: Point::ZERO, end: Point::new(0.0, -10.0), aspect: 1.0, focal: None }; - v.transform(Affine::scale_non_uniform(2.0, 1.0), GradientKind::Radial); - assert!(close(v.end, Point::new(0.0, -10.0)) && (v.aspect - 2.0).abs() < 1e-9, "{v:?}"); - } - - #[test] - fn samples_follow_shear_and_rotation() { - let shear = Affine::new([1.0, 0.3, 0.7, 1.2, 15.0, -4.0]) * Affine::rotate(0.4); - for kind in [GradientKind::Linear, GradientKind::Radial] { - let g = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(80.0, 55.0), aspect: 0.6, focal: None }; - let mut m = g; - m.transform(shear, kind); - for p in [Point::new(30.0, 40.0), Point::new(55.0, 70.0), Point::new(90.0, 10.0), Point::new(-20.0, 48.0)] { - let (a, b) = (g.param_at(kind, p), m.param_at(kind, shear * p)); - assert!((a - b).abs() < 1e-9, "{kind:?} at {p:?}: {a} vs {b}"); - } - } - } - - #[test] - fn radial_fit_uses_the_angle_and_param_honours_aspect() { - let b = Rect::new(0.0, 0.0, 100.0, 60.0); - let g = GradientGeom::fit(GradientKind::Radial, b, 90.0); - assert!(close(g.start, Point::new(50.0, 30.0)) && close(g.end, Point::new(50.0, -20.0)), "end above the centre: {g:?}"); - let e = GradientGeom { start: Point::ZERO, end: Point::new(10.0, 0.0), aspect: 0.5, focal: None }; - assert!((e.param_at(GradientKind::Radial, Point::new(0.0, 5.0)) - 1.0).abs() < 1e-12); - assert!((e.param_at(GradientKind::Radial, Point::new(5.0, 0.0)) - 0.5).abs() < 1e-12); - assert!((e.param_at(GradientKind::Linear, Point::new(5.0, 7.0)) - 0.5).abs() < 1e-12); - } - - fn g3() -> Gradient { - let mut g = Gradient::default(); - g.stops.insert(1, GradientStop::new(0.5, Color::rgb(1.0, 0.0, 0.0))); - g - } - - #[test] - fn insert_samples_color_and_sorts() { - let g = Gradient::default(); - let (stops, i) = insert_stop(&g, 0.25); - assert_eq!(stops.len(), 3); - assert_eq!(i, 1); - let r = stops[1].color.to_rgb()[0]; - assert!((r - 0.75).abs() < 1e-4, "sampled {r}"); - let (stops, i) = insert_stop(&g, 2.0); - assert_eq!(i, 2); - assert_eq!(stops[2].offset, 1.0); - } - - #[test] - fn remove_keeps_two() { - let g = g3(); - let v = remove_stop(&g.stops, 1).unwrap(); - assert_eq!(v.len(), 2); - assert!(remove_stop(&v, 0).is_none()); - assert!(remove_stop(&g.stops, 9).is_none()); - } - - #[test] - fn move_reorders_and_tracks_index() { - let g = g3(); - let (v, i) = move_stop(&g.stops, 0, 0.8); - assert_eq!(i, 1); - assert_eq!(v[1].color.to_hex(), "#ffffff"); - assert!(v.windows(2).all(|w| w[0].offset <= w[1].offset)); - let (v, i) = move_stop(&g.stops, 1, -3.0); - // Clamped to 0 and placed after the existing stop at 0. - assert_eq!((i, v[i].offset, v[i].color.to_hex()), (1, 0.0, "#ff0000".to_string())); - } - - #[test] - fn duplicate_copies_the_stop_to_a_new_offset() { - let g = g3(); - let (v, i) = duplicate_stop(&g.stops, 1, 0.9); - assert_eq!((v.len(), i, v[i].offset, v[i].color.to_hex()), (4, 2, 0.9, "#ff0000".to_string())); - assert_eq!(v[1], g.stops[1], "the original stays"); - assert_eq!(duplicate_stop(&g.stops, 7, 0.5).0, g.stops); - } - - #[test] - fn swap_exchanges_only_the_colours() { - let mut g = g3(); - g.stops[0].opacity = 0.25; - let v = swap_stop_colors(&g.stops, 0, 1); - assert_eq!((v[0].color.to_hex(), v[1].color.to_hex()), ("#ff0000".to_string(), "#ffffff".to_string())); - assert_eq!((v[0].offset, v[0].opacity, v[1].offset, v[1].opacity), (0.0, 0.25, 0.5, 1.0)); - assert_eq!(swap_stop_colors(&g.stops, 0, 9), g.stops); - } - - #[test] - fn midpoint_math() { - let g = g3(); - assert_eq!(midpoint_pos(&g.stops, 0), Some(0.25)); - assert_eq!(midpoint_pos(&g.stops, 2), None); - let m = midpoint_from_pos(&g.stops, 1, 0.6).unwrap(); - assert!((m - 0.2).abs() < 1e-5); - assert_eq!(midpoint_from_pos(&g.stops, 1, 0.51).unwrap(), 0.13); - let v = set_midpoint(&g.stops, 0, 0.99); - assert_eq!(v[0].midpoint, 0.87); - } - - #[test] - fn rebase_keeps_relative_positions() { - let mut g = GradientGeom { start: Point::new(110.0, 150.0), end: Point::new(190.0, 120.0), aspect: 0.5, focal: None }; - g.rebase(Rect::new(100.0, 100.0, 200.0, 200.0), Rect::new(500.0, 0.0, 700.0, 50.0)); - assert!(close(g.start, Point::new(520.0, 25.0)) && close(g.end, Point::new(680.0, 10.0)) && g.aspect == 0.5, "{g:?}"); - // A box without height (a horizontal line) keeps the offset from its centre line. - let mut h = GradientGeom { start: Point::new(0.0, 12.0), end: Point::new(10.0, 10.0), aspect: 1.0, focal: None }; - h.rebase(Rect::new(0.0, 10.0, 10.0, 10.0), Rect::new(0.0, 0.0, 20.0, 40.0)); - assert!(close(h.start, Point::new(0.0, 22.0)) && close(h.end, Point::new(20.0, 20.0)), "{h:?}"); - // Unplaced paints have nothing to move. - let mut p = GradientPaint::new(Gradient::default()); - p.rebase(Rect::new(0.0, 0.0, 1.0, 1.0), Rect::new(5.0, 5.0, 9.0, 9.0)); - assert_eq!(p.geom, None); - } - - #[test] - fn pin_fixes_the_fit_once() { - let mut p = GradientPaint::new(Gradient::default()); - p.angle = 90.0; - let b = Rect::new(0.0, 0.0, 100.0, 50.0); - p.pin(b); - assert_eq!(p.geom, Some(GradientGeom::fit(GradientKind::Linear, b, 90.0))); - p.pin(Rect::new(0.0, 0.0, 1.0, 1.0)); - assert_eq!(p.geom, Some(GradientGeom::fit(GradientKind::Linear, b, 90.0))); - } - - /// A 100 pt circle at (200, 200) with its focal point 40 pt left of the centre. - fn off_centre() -> GradientGeom { - let mut g = GradientGeom { start: Point::new(200.0, 200.0), end: Point::new(300.0, 200.0), aspect: 1.0, focal: None }; - g.set_focal(Some(Point::new(160.0, 200.0))); - g - } - - #[test] - fn focal_round_trips_through_serde_and_defaults_to_none() { - let g = off_centre(); - let s = serde_json::to_string(&g).unwrap(); - assert!(s.contains("\"focal\""), "{s}"); - assert_eq!(serde_json::from_str::(&s).unwrap(), g); - // Placements saved before focal points existed load centred, and centred ones write none. - let old: GradientGeom = serde_json::from_str(r#"{"start":{"x":0.0,"y":0.0},"end":{"x":1.0,"y":0.0}}"#).unwrap(); - assert_eq!((old.focal, old.aspect), (None, 1.0)); - assert!(!serde_json::to_string(&old).unwrap().contains("focal")); - } - - #[test] - fn focal_follows_transforms_and_rebases() { - let mut g = off_centre(); - let a = Affine::translate((10.0, -5.0)) * Affine::rotate(0.7) * Affine::scale_non_uniform(2.0, 0.5); - let f = a * g.focal.unwrap(); - g.transform(a, GradientKind::Radial); - assert!(close(g.focal.unwrap(), f), "{g:?}"); - // Still at the same parameter: the first stop. - assert!(g.param_at(GradientKind::Radial, f).abs() < 1e-9); - let mut h = off_centre(); - h.rebase(Rect::new(100.0, 100.0, 300.0, 300.0), Rect::new(0.0, 0.0, 100.0, 100.0)); - assert!(close(h.focal.unwrap(), Point::new(30.0, 50.0)) && close(h.start, Point::new(50.0, 50.0)), "{h:?}"); - } - - #[test] - fn param_runs_from_the_focal_point_to_the_ellipse() { - let g = off_centre(); - let t = |x: f64, y: f64| g.param_at(GradientKind::Radial, Point::new(x, y)); - assert!(t(160.0, 200.0).abs() < 1e-9); - // The extent circle is the last stop all round. - for a in [0.0f64, 1.0, 2.5, 4.0] { - let p = Point::new(200.0 + 100.0 * a.cos(), 200.0 + 100.0 * a.sin()); - assert!((g.param_at(GradientKind::Radial, p) - 1.0).abs() < 1e-9, "{a}"); - } - // The centre lies on the level-2/7 circle: centred 2/7 of the way back to the focal point - // (0.4 of the radius off), with a radius of 2/7. - assert!((t(200.0, 200.0) - 2.0 / 7.0).abs() < 1e-9, "{}", t(200.0, 200.0)); - assert!(t(180.0, 200.0) < t(220.0, 200.0), "nearer the focal side is earlier"); - assert_eq!(GradientGeom { focal: None, ..g }.param_at(GradientKind::Radial, Point::new(250.0, 200.0)), 0.5); - } - - #[test] - fn focal_is_kept_inside_the_ellipse_and_follows_its_reshaping() { - let mut g = off_centre(); - g.set_focal(Some(Point::new(500.0, 200.0))); - assert!(close(g.focal.unwrap(), Point::new(299.0, 200.0)), "pulled inside: {g:?}"); - g.set_focal(Some(Point::new(200.0, 200.0))); - assert_eq!(g.focal, None, "on the centre: centred"); - // A new vector and aspect keep it in its place in the ellipse. - let before = off_centre(); - let mut h = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.0, 50.0), aspect: 0.5, focal: None }; - h.keep_focal_from(&before); - assert!(close(h.focal.unwrap(), Point::new(0.0, -20.0)), "{h:?}"); - } -} +mod tests; diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs new file mode 100644 index 0000000000..19e9f44fc7 --- /dev/null +++ b/crates/color/src/gradient/tests.rs @@ -0,0 +1,457 @@ +use super::*; + +#[test] +fn sample_endpoints_and_mid() { + let g = Gradient::default(); + assert_eq!(g.sample(0.0).0.to_hex(), "#ffffff"); + assert_eq!(g.sample(1.0).0.to_hex(), "#000000"); + let mid = g.sample(0.5).0.to_rgb()[0]; + assert!((mid - 0.5).abs() < 1e-5); +} + +/// Sampling increasing positions in one pass gives what sampling each alone does, out-of-order +/// and repeated stop offsets included. +#[test] +fn increasing_samples_match_single_samples() { + let stop = |offset: f32, hex: &str, midpoint: f32| GradientStop { midpoint, ..GradientStop::new(offset, Color::from_hex(hex).unwrap()) }; + let g = Gradient::new( + GradientKind::Linear, + vec![stop(0.1, "#ff0000", 0.3), stop(0.4, "#00ff00", 0.7), stop(0.4, "#0000ff", 0.5), stop(0.2, "#ffff00", 0.5), stop(0.9, "#000000", 0.5)], + ); + let ts: Vec = (0..=40).map(|k| k as f32 / 40.0).collect(); + let one_by_one: Vec<_> = ts.iter().map(|&t| g.sample_with(t, Color::lerp_keep_model)).collect(); + assert_eq!(g.sample_increasing_with(ts, Color::lerp_keep_model), one_by_one); +} + +#[test] +fn midpoint_shifts() { + let mut g = Gradient::default(); + g.stops[0].midpoint = 0.25; + // At t = 0.25 we should be half way. + assert!((g.sample(0.25).0.to_rgb()[0] - 0.5).abs() < 1e-5); + assert_eq!(g.expanded_stops().len(), 3); +} + +#[test] +fn fit_linear_horizontal() { + let g = GradientGeom::fit(GradientKind::Linear, Rect::new(0.0, 0.0, 100.0, 50.0), 0.0); + assert_eq!(g.start, Point::new(0.0, 25.0)); + assert_eq!(g.end, Point::new(100.0, 25.0)); + assert!((g.angle_deg()).abs() < 1e-9); + let v = GradientGeom::fit(GradientKind::Linear, Rect::new(0.0, 0.0, 100.0, 50.0), 90.0); + assert!((v.angle_deg() - 90.0).abs() < 1e-9); + assert!((v.length() - 50.0).abs() < 1e-9); +} + +#[test] +fn reverse_stops() { + let mut g = Gradient::default(); + g.reverse(); + assert_eq!(g.stops[0].color.to_hex(), "#000000"); + assert_eq!(g.stops[0].offset, 0.0); +} + +/// #1007: reversing mirrors off-centre midpoints with their segments, so the ramp is the same +/// the other way round. +#[test] +fn reverse_mirrors_midpoints() { + let stop = |offset, hex, midpoint| GradientStop { midpoint, ..GradientStop::new(offset, Color::from_hex(hex).unwrap()) }; + let two = Gradient::new(GradientKind::Linear, vec![stop(0.0, "#ff0000", 0.2), stop(1.0, "#0000ff", 0.5)]); + let three = Gradient::new(GradientKind::Linear, vec![stop(0.0, "#ff0000", 0.2), stop(0.3, "#00ff00", 0.8), stop(1.0, "#0000ff", 0.5)]); + for g in [two, three] { + let mut r = g.clone(); + r.reverse(); + let mids: Vec = r.stops.iter().map(|s| s.midpoint).collect(); + let want: Vec = g.stops.iter().rev().skip(1).map(|s| 1.0 - s.midpoint).chain([0.5]).collect(); + assert!(mids.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-6), "{mids:?} {want:?}"); + for i in 0..=20 { + let t = i as f32 / 20.0; + let ((a, ao), (b, bo)) = (g.sample(t), r.sample(1.0 - t)); + let same = a.to_rgba8(1.0).iter().zip(b.to_rgba8(1.0)).all(|(x, y)| x.abs_diff(y) <= 1); + assert!(same && (ao - bo).abs() < 1e-6, "t {t}: {a:?} vs {b:?}"); + } + r.reverse(); + let back = r.stops.iter().zip(&g.stops).all(|(a, b)| (a.offset - b.offset).abs() < 1e-6 && (a.midpoint - b.midpoint).abs() < 1e-6); + assert!(back, "reversed twice, it is as it was: {:?}", r.stops); + } +} + +fn close(a: Point, b: Point) -> bool { + a.distance(b) < 1e-9 +} + +fn linear(start: (f64, f64), end: (f64, f64)) -> GradientGeom { + GradientGeom { start: start.into(), end: end.into(), aspect: 1.0, focal: None } +} + +#[test] +fn rotate_90_gives_vertical_vector() { + let mut g = linear((0.0, 0.0), (100.0, 0.0)); + g.transform(Affine::rotate(std::f64::consts::FRAC_PI_2), GradientKind::Linear); + assert!(close(g.start, Point::ZERO) && close(g.end, Point::new(0.0, 100.0)), "{g:?}"); + assert!((g.angle_deg() + 90.0).abs() < 1e-9); +} + +#[test] +fn reflect_swaps_start_and_end() { + let mut g = linear((0.0, 25.0), (100.0, 25.0)); + // Reflect across the vertical axis through x = 50. + let flip = Affine::translate((50.0, 0.0)) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate((-50.0, 0.0)); + g.transform(flip, GradientKind::Linear); + assert!(close(g.start, Point::new(100.0, 25.0)) && close(g.end, Point::new(0.0, 25.0)), "{g:?}"); +} + +#[test] +fn non_uniform_scale_turns_a_circle_into_an_ellipse() { + let mut g = GradientGeom { start: Point::new(10.0, 10.0), end: Point::new(20.0, 10.0), aspect: 1.0, focal: None }; + g.transform(Affine::scale_non_uniform(2.0, 1.0), GradientKind::Radial); + assert!(close(g.start, Point::new(20.0, 10.0)) && close(g.end, Point::new(40.0, 10.0)), "{g:?}"); + assert!((g.aspect - 0.5).abs() < 1e-9); + // A vertical vector keeps its axis: the ellipse is twice as wide as the vector is long. + let mut v = GradientGeom { start: Point::ZERO, end: Point::new(0.0, -10.0), aspect: 1.0, focal: None }; + v.transform(Affine::scale_non_uniform(2.0, 1.0), GradientKind::Radial); + assert!(close(v.end, Point::new(0.0, -10.0)) && (v.aspect - 2.0).abs() < 1e-9, "{v:?}"); +} + +#[test] +fn samples_follow_shear_and_rotation() { + let shear = Affine::new([1.0, 0.3, 0.7, 1.2, 15.0, -4.0]) * Affine::rotate(0.4); + for kind in [GradientKind::Linear, GradientKind::Radial] { + let g = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(80.0, 55.0), aspect: 0.6, focal: None }; + let mut m = g; + m.transform(shear, kind); + for p in [Point::new(30.0, 40.0), Point::new(55.0, 70.0), Point::new(90.0, 10.0), Point::new(-20.0, 48.0)] { + let (a, b) = (g.param_at(kind, p), m.param_at(kind, shear * p)); + assert!((a - b).abs() < 1e-9, "{kind:?} at {p:?}: {a} vs {b}"); + } + } +} + +#[test] +fn radial_fit_uses_the_angle_and_param_honours_aspect() { + let b = Rect::new(0.0, 0.0, 100.0, 60.0); + let g = GradientGeom::fit(GradientKind::Radial, b, 90.0); + assert!(close(g.start, Point::new(50.0, 30.0)) && close(g.end, Point::new(50.0, -20.0)), "end above the centre: {g:?}"); + let e = GradientGeom { start: Point::ZERO, end: Point::new(10.0, 0.0), aspect: 0.5, focal: None }; + assert!((e.param_at(GradientKind::Radial, Point::new(0.0, 5.0)) - 1.0).abs() < 1e-12); + assert!((e.param_at(GradientKind::Radial, Point::new(5.0, 0.0)) - 0.5).abs() < 1e-12); + assert!((e.param_at(GradientKind::Linear, Point::new(5.0, 7.0)) - 0.5).abs() < 1e-12); +} + +fn g3() -> Gradient { + let mut g = Gradient::default(); + g.stops.insert(1, GradientStop::new(0.5, Color::rgb(1.0, 0.0, 0.0))); + g +} + +#[test] +fn insert_samples_color_and_sorts() { + let g = Gradient::default(); + let (stops, i) = insert_stop(&g, 0.25); + assert_eq!(stops.len(), 3); + assert_eq!(i, 1); + let r = stops[1].color.to_rgb()[0]; + assert!((r - 0.75).abs() < 1e-4, "sampled {r}"); + let (stops, i) = insert_stop(&g, 2.0); + assert_eq!(i, 2); + assert_eq!(stops[2].offset, 1.0); +} + +#[test] +fn remove_keeps_two() { + let g = g3(); + let v = remove_stop(&g.stops, 1).unwrap(); + assert_eq!(v.len(), 2); + assert!(remove_stop(&v, 0).is_none()); + assert!(remove_stop(&g.stops, 9).is_none()); +} + +#[test] +fn move_reorders_and_tracks_index() { + let g = g3(); + let (v, i) = move_stop(&g.stops, 0, 0.8); + assert_eq!(i, 1); + assert_eq!(v[1].color.to_hex(), "#ffffff"); + assert!(v.windows(2).all(|w| w[0].offset <= w[1].offset)); + let (v, i) = move_stop(&g.stops, 1, -3.0); + // Clamped to 0 and placed after the existing stop at 0. + assert_eq!((i, v[i].offset, v[i].color.to_hex()), (1, 0.0, "#ff0000".to_string())); +} + +#[test] +fn duplicate_copies_the_stop_to_a_new_offset() { + let g = g3(); + let (v, i) = duplicate_stop(&g.stops, 1, 0.9); + assert_eq!((v.len(), i, v[i].offset, v[i].color.to_hex()), (4, 2, 0.9, "#ff0000".to_string())); + assert_eq!(v[1], g.stops[1], "the original stays"); + assert_eq!(duplicate_stop(&g.stops, 7, 0.5).0, g.stops); +} + +#[test] +fn swap_exchanges_only_the_colours() { + let mut g = g3(); + g.stops[0].opacity = 0.25; + let v = swap_stop_colors(&g.stops, 0, 1); + assert_eq!((v[0].color.to_hex(), v[1].color.to_hex()), ("#ff0000".to_string(), "#ffffff".to_string())); + assert_eq!((v[0].offset, v[0].opacity, v[1].offset, v[1].opacity), (0.0, 0.25, 0.5, 1.0)); + assert_eq!(swap_stop_colors(&g.stops, 0, 9), g.stops); +} + +#[test] +fn midpoint_math() { + let g = g3(); + assert_eq!(midpoint_pos(&g.stops, 0), Some(0.25)); + assert_eq!(midpoint_pos(&g.stops, 2), None); + let m = midpoint_from_pos(&g.stops, 1, 0.6).unwrap(); + assert!((m - 0.2).abs() < 1e-5); + assert_eq!(midpoint_from_pos(&g.stops, 1, 0.51).unwrap(), 0.13); + let v = set_midpoint(&g.stops, 0, 0.99); + assert_eq!(v[0].midpoint, 0.87); +} + +#[test] +fn rebase_keeps_relative_positions() { + let mut g = GradientGeom { start: Point::new(110.0, 150.0), end: Point::new(190.0, 120.0), aspect: 0.5, focal: None }; + g.rebase(Rect::new(100.0, 100.0, 200.0, 200.0), Rect::new(500.0, 0.0, 700.0, 50.0)); + assert!(close(g.start, Point::new(520.0, 25.0)) && close(g.end, Point::new(680.0, 10.0)) && g.aspect == 0.5, "{g:?}"); + // A box without height (a horizontal line) keeps the offset from its centre line. + let mut h = GradientGeom { start: Point::new(0.0, 12.0), end: Point::new(10.0, 10.0), aspect: 1.0, focal: None }; + h.rebase(Rect::new(0.0, 10.0, 10.0, 10.0), Rect::new(0.0, 0.0, 20.0, 40.0)); + assert!(close(h.start, Point::new(0.0, 22.0)) && close(h.end, Point::new(20.0, 20.0)), "{h:?}"); + // Unplaced paints have nothing to move. + let mut p = GradientPaint::new(Gradient::default()); + p.rebase(Rect::new(0.0, 0.0, 1.0, 1.0), Rect::new(5.0, 5.0, 9.0, 9.0)); + assert_eq!(p.geom, None); +} + +#[test] +fn pin_fixes_the_fit_once() { + let mut p = GradientPaint::new(Gradient::default()); + p.angle = 90.0; + let b = Rect::new(0.0, 0.0, 100.0, 50.0); + p.pin(b); + assert_eq!(p.geom, Some(GradientGeom::fit(GradientKind::Linear, b, 90.0))); + p.pin(Rect::new(0.0, 0.0, 1.0, 1.0)); + assert_eq!(p.geom, Some(GradientGeom::fit(GradientKind::Linear, b, 90.0))); +} + +/// A 100 pt circle at (200, 200) with its focal point 40 pt left of the centre. +fn off_centre() -> GradientGeom { + let mut g = GradientGeom { start: Point::new(200.0, 200.0), end: Point::new(300.0, 200.0), aspect: 1.0, focal: None }; + g.set_focal(Some(Point::new(160.0, 200.0))); + g +} + +#[test] +fn focal_round_trips_through_serde_and_defaults_to_none() { + let g = off_centre(); + let s = serde_json::to_string(&g).unwrap(); + assert!(s.contains("\"focal\""), "{s}"); + assert_eq!(serde_json::from_str::(&s).unwrap(), g); + // Placements saved before focal points existed load centred, and centred ones write none. + let old: GradientGeom = serde_json::from_str(r#"{"start":{"x":0.0,"y":0.0},"end":{"x":1.0,"y":0.0}}"#).unwrap(); + assert_eq!((old.focal, old.aspect), (None, 1.0)); + assert!(!serde_json::to_string(&old).unwrap().contains("focal")); +} + +#[test] +fn focal_follows_transforms_and_rebases() { + let mut g = off_centre(); + let a = Affine::translate((10.0, -5.0)) * Affine::rotate(0.7) * Affine::scale_non_uniform(2.0, 0.5); + let f = a * g.focal.unwrap(); + g.transform(a, GradientKind::Radial); + assert!(close(g.focal.unwrap(), f), "{g:?}"); + // Still at the same parameter: the first stop. + assert!(g.param_at(GradientKind::Radial, f).abs() < 1e-9); + let mut h = off_centre(); + h.rebase(Rect::new(100.0, 100.0, 300.0, 300.0), Rect::new(0.0, 0.0, 100.0, 100.0)); + assert!(close(h.focal.unwrap(), Point::new(30.0, 50.0)) && close(h.start, Point::new(50.0, 50.0)), "{h:?}"); +} + +#[test] +fn param_runs_from_the_focal_point_to_the_ellipse() { + let g = off_centre(); + let t = |x: f64, y: f64| g.param_at(GradientKind::Radial, Point::new(x, y)); + assert!(t(160.0, 200.0).abs() < 1e-9); + // The extent circle is the last stop all round. + for a in [0.0f64, 1.0, 2.5, 4.0] { + let p = Point::new(200.0 + 100.0 * a.cos(), 200.0 + 100.0 * a.sin()); + assert!((g.param_at(GradientKind::Radial, p) - 1.0).abs() < 1e-9, "{a}"); + } + // The centre lies on the level-2/7 circle: centred 2/7 of the way back to the focal point + // (0.4 of the radius off), with a radius of 2/7. + assert!((t(200.0, 200.0) - 2.0 / 7.0).abs() < 1e-9, "{}", t(200.0, 200.0)); + assert!(t(180.0, 200.0) < t(220.0, 200.0), "nearer the focal side is earlier"); + assert_eq!(GradientGeom { focal: None, ..g }.param_at(GradientKind::Radial, Point::new(250.0, 200.0)), 0.5); +} + +#[test] +fn focal_is_kept_inside_the_ellipse_and_follows_its_reshaping() { + let mut g = off_centre(); + g.set_focal(Some(Point::new(500.0, 200.0))); + assert!(close(g.focal.unwrap(), Point::new(299.0, 200.0)), "pulled inside: {g:?}"); + g.set_focal(Some(Point::new(200.0, 200.0))); + assert_eq!(g.focal, None, "on the centre: centred"); + // A new vector and aspect keep it in its place in the ellipse. + let before = off_centre(); + let mut h = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.0, 50.0), aspect: 0.5, focal: None }; + h.keep_focal_from(&before); + assert!(close(h.focal.unwrap(), Point::new(0.0, -20.0)), "{h:?}"); +} + +#[test] +fn pixels_sample_the_ramp_at_each_cell_centre() { + // White → black left to right over a 10 × 2 box, a midpoint at 30% and a half-opaque end. + let mut g = GradientPaint::new(Gradient::default()); + g.gradient.stops[0].midpoint = 0.3; + g.gradient.stops[1].opacity = 0.5; + let b = Rect::new(0.0, 0.0, 10.0, 2.0); + let px: Vec<[u8; 4]> = g.pixels(b, b, 10, 2, true, &Color::to_rgb).collect(); + assert_eq!(px.len(), 20); + let ramp = Ramp::new(&g.gradient, &Color::to_rgb); + for (i, p) in px.iter().take(10).enumerate() { + let c = ramp.at((i as f32 + 0.5) / 10.0).map(|v| (v * 255.0).round() as u8); + assert_eq!(*p, c, "pixel {i}"); + } + assert_eq!(px[3], px[13], "rows alike"); + // The midpoint stop: grey at 30%; padded past the ends. + assert!((ramp.at(0.3)[0] - 0.5).abs() < 0.02, "{:?}", ramp.at(0.3)); + assert_eq!(ramp.at(-1.0), [1.0, 1.0, 1.0, 1.0]); + assert_eq!(ramp.at(2.0), [0.0, 0.0, 0.0, 0.5]); + assert_eq!(ramp.at(f32::NAN), [1.0, 1.0, 1.0, 1.0]); +} + +fn blue_yellow(method: GradientMethod) -> Gradient { + let mut g = Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::rgb(1.0, 1.0, 0.0))], + ); + g.method = method; + g +} + +/// Illustrator 30's Perceptual method mixes colours in a perceptually even way +/// (https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/control-perceptual-interpolation-in-gradients.html). +/// Here that is OKLab: blue → yellow passes through a light blue-grey, not the flat mid grey +/// a display RGB mix gives, and its lightness climbs evenly. +#[test] +fn perceptual_blue_to_yellow_is_not_the_grey_rgb_mix() { + let classic = blue_yellow(GradientMethod::Classic).sample(0.5).0.to_rgb(); + assert!(classic.iter().all(|v| (v - 0.5).abs() < 1e-5), "classic: the RGB mix {classic:?}"); + let p = blue_yellow(GradientMethod::Perceptual); + let [r, g, b] = p.sample(0.5).0.to_rgb(); + assert!(b > r + 0.1 && b > g + 0.05, "a blue-grey, not grey: {:?}", [r, g, b]); + assert!(r + g + b > 1.5 + 0.2, "lighter than the RGB mix: {:?}", [r, g, b]); + let lightness = |t: f32| crate::libraries::to_oklab(&p.sample(t).0)[0]; + let steps: Vec = (0..4).map(|k| lightness((k + 1) as f32 / 4.0) - lightness(k as f32 / 4.0)).collect(); + assert!(steps.iter().all(|d| (d - steps[0]).abs() < 1e-3), "even lightness steps: {steps:?}"); + // Ends and opacity as before. + assert_eq!(p.sample(0.0).0.to_hex(), "#0000ff"); + assert_eq!(p.sample(1.0).0.to_hex(), "#ffff00"); +} + +/// Renderers mix linearly between stops: a Perceptual segment becomes stops on the perceptual +/// curve (the midpoint diamond among them), more where it bends, close enough that the linear +/// ramp between them stays within half a colour level of the curve; a segment that hardly +/// bends needs few. +#[test] +fn perceptual_segments_expand_into_stops_on_the_curve() { + let pairs = [ + (Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0)), + (Color::BLACK, Color::rgb(1.0, 0.0, 0.0)), + (Color::rgb(0.0, 1.0, 0.0), Color::rgb(1.0, 0.0, 1.0)), + (Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::WHITE), + ]; + for (a, b) in pairs { + let mut p = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)]); + p.method = GradientMethod::Perceptual; + p.stops[0].midpoint = 0.3; + p.stops[1].opacity = 0.5; + let ex: Vec<_> = p.expanded().collect(); + assert!((3..=100).contains(&ex.len()), "{a:?} → {b:?}: {} stops", ex.len()); + assert!(ex.windows(2).all(|w| w[0].0 < w[1].0), "in order"); + assert_eq!(ex.iter().filter(|s| s.3.is_some()).count(), 1, "one stop stands for the midpoint"); + assert!(ex.iter().any(|s| s.3 == Some(0.3) && (s.0 - 0.3).abs() < 1e-6)); + let ramp = Ramp::new(&p, &Color::to_rgb); + for k in 0..=2000 { + let t = k as f32 / 2000.0; + let (c, o) = p.sample(t); + let [r, g, b] = c.to_rgb(); + let off = [r, g, b, o].iter().zip(ramp.at(t)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max); + assert!(off < 0.5 / 255.0, "{a:?} → {b:?} at {t}: {off}"); + } + } + let mut flat = Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, Color::rgb(0.2, 0.4, 0.6)), GradientStop::new(1.0, Color::rgb(0.25, 0.45, 0.6))], + ); + flat.method = GradientMethod::Perceptual; + assert_eq!(flat.expanded().count(), 3, "the ends and the midpoint"); +} + +/// Classic gradients expand as they always did: their stops, and a stop at each off-centre +/// midpoint, sampled in display RGB (so the renderer draws the same pixels as before). +#[test] +fn classic_gradients_expand_as_before() { + let mut g = Gradient::new( + GradientKind::Linear, + vec![ + GradientStop { midpoint: 0.2, ..GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)) }, + GradientStop { opacity: 0.4, ..GradientStop::new(0.45, Color::cmyk(0.1, 0.8, 0.0, 0.2)) }, + GradientStop { midpoint: 0.87, ..GradientStop::new(0.6, Color::rgb(1.0, 1.0, 0.0)) }, + GradientStop::new(1.0, Color::gray(0.3)), + ], + ); + // The expansion gradients had before they had a method. + let before: Vec<_> = g + .stops + .iter() + .enumerate() + .flat_map(|(i, s)| { + let mid = g.stops.get(i + 1).filter(|_| (s.midpoint - 0.5).abs() > 1e-3).map(|n| { + let t = s.offset + (n.offset - s.offset) * s.midpoint; + let (c, o) = g.sample_with(t, Color::lerp); + (t, c, o, Some(s.midpoint)) + }); + std::iter::once((s.offset, s.color, s.opacity, None)).chain(mid) + }) + .collect(); + assert_eq!(g.expanded().collect::>(), before); + assert_eq!(before.len(), 6); + assert_eq!(g.sample(0.3), g.sample_with(0.3, Color::lerp)); + assert_eq!(g.sample_keep_model(0.5), g.sample_with(0.5, Color::lerp_keep_model)); + g.method = GradientMethod::Perceptual; + assert_eq!(g.sample_keep_model(0.5), g.sample(0.5), "perceptual: one mix"); +} + +/// The method is written only when Perceptual, so files from before it (and Classic +/// gradients) read as Classic and new Classic files stay as they were. +#[test] +fn method_is_saved_only_when_perceptual() { + let classic = serde_json::to_value(Gradient::default()).unwrap(); + assert!(classic.get("method").is_none(), "{classic}"); + let old: Gradient = serde_json::from_value(serde_json::json!({"kind": "Linear", "stops": []})).unwrap(); + assert_eq!(old.method, GradientMethod::Classic); + let p = blue_yellow(GradientMethod::Perceptual); + let v = serde_json::to_value(&p).unwrap(); + assert_eq!(v["method"], "Perceptual"); + assert_eq!(serde_json::from_value::(v).unwrap(), p); + assert_eq!(GradientMethod::parse("perceptual"), Some(GradientMethod::Perceptual)); + assert_eq!(GradientMethod::parse("CLASSIC"), Some(GradientMethod::Classic)); + assert_eq!(GradientMethod::parse("smooth"), None); +} + +/// SVG and PDF can't mix colours perceptually: a Perceptual gradient is drawn as pixels there, +/// as Illustrator rasterises perceptual gradients saved as PDF or SVG, as a fill or a stroke, +/// dithered or not. +#[test] +fn perceptual_gradients_draw_as_pixels() { + for fill in [true, false] { + assert!(!GradientPaint::new(blue_yellow(GradientMethod::Classic)).draws_as_pixels(fill)); + assert!(GradientPaint::new(blue_yellow(GradientMethod::Perceptual)).draws_as_pixels(fill)); + let mut radial = blue_yellow(GradientMethod::Perceptual); + radial.kind = GradientKind::Radial; + radial.dither = true; + assert!(GradientPaint::new(radial).draws_as_pixels(fill)); + } +} diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 46439d29d0..5de064d6bc 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, GradientPaint, GradientStop}; +pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop}; pub use libraries::SwatchLibrary; pub use swatch::{Swatch, SwatchGroup, default_swatches}; @@ -111,6 +111,16 @@ impl Color { pub fn out_of_gamut(&self) -> bool { cms::active().out_of_gamut(self) } + /// The colour exactly, as a key: its model and its components' bits (colours that only look + /// alike, as a grey and the same RGB grey, differ). + pub fn key(&self) -> [u32; 5] { + match *self { + Color::Rgb { r, g, b } => [0, r.to_bits(), g.to_bits(), b.to_bits(), 0], + Color::Cmyk { c, m, y, k } => [1, c.to_bits(), m.to_bits(), y.to_bits(), k.to_bits()], + Color::Gray { k } => [2, k.to_bits(), 0, 0, 0], + Color::Lab { l, a, b } => [3, l.to_bits(), a.to_bits(), b.to_bits(), 0], + } + } pub fn to_rgba8(&self, alpha: f32) -> [u8; 4] { let [r, g, b] = self.to_rgb(); let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; @@ -146,6 +156,8 @@ impl Color { } else { 60.0 * ((r - g) / d + 4.0) }; + // f32 rounding in rem_euclid can yield exactly 360; wrap back to 0. + let h = if h >= 360.0 { 0.0 } else { h }; let s = if max <= 0.0 { 0.0 } else { d / max }; [h, s, max] } @@ -378,6 +390,18 @@ impl Paint { _ => None, } } + /// This stroke paint as the fill of the stroke's outline, so the outline looks as the stroke + /// did: without dither, which strokes ignore ([`GradientPaint::draws_as_pixels`]). + pub fn stroke_as_fill(&self) -> Paint { + match self { + Paint::Gradient(g) if g.gradient.dither => { + let mut g = g.clone(); + g.gradient.dither = false; + Paint::Gradient(g) + } + p => p.clone(), + } + } /// The Registration colour: 100% of every ink, linked to [`swatch::REGISTRATION`]. pub fn registration() -> Self { Paint::Solid { color: Color::cmyk(1.0, 1.0, 1.0, 1.0), swatch: Some(swatch::REGISTRATION.into()), tint: 1.0 } @@ -426,6 +450,12 @@ impl Paint { mod tests { use super::*; + #[test] + fn hue_below_360() { + let h = Color::Rgb { r: 1.0, g: 0.0, b: 1e-7 }.to_hsb()[0]; + assert!((0.0..360.0).contains(&h), "hue {h}"); + } + #[test] fn hex_roundtrip() { let c = Color::from_hex("#ff8000").unwrap(); diff --git a/crates/color/src/libraries.rs b/crates/color/src/libraries.rs index 163038777f..e96760d5c5 100644 --- a/crates/color/src/libraries.rs +++ b/crates/color/src/libraries.rs @@ -98,7 +98,7 @@ pub fn builtin_library(id: &str) -> Option> { // ---------- colour construction ---------- /// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped. -fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] { +pub(crate) fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] { let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b; let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b; let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b; @@ -113,7 +113,12 @@ fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] { /// OKLab `[l, a, b]` of a colour's display RGB. pub fn to_oklab(c: &Color) -> [f64; 3] { - let [r, g, b] = c.to_rgb_uncalibrated().map(|v| { + srgb_to_oklab(c.to_rgb_uncalibrated()) +} + +/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded). +pub(crate) fn srgb_to_oklab(rgb: [f32; 3]) -> [f64; 3] { + let [r, g, b] = rgb.map(|v| { let v = f64::from(v); if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } }); @@ -171,7 +176,7 @@ fn group(name: &str, swatches: Vec) -> SwatchGroup { /// A gradient swatch through `stops` of (offset, colour, opacity). pub(crate) fn gradient(name: &str, kind: GradientKind, stops: &[(f32, Color, f32)]) -> Swatch { let stops = stops.iter().map(|&(offset, color, opacity)| GradientStop { opacity, ..GradientStop::new(offset, color) }).collect(); - Swatch { name: name.into(), paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient { kind, stops }))), global: false, spot: false } + Swatch { name: name.into(), paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(kind, stops)))), global: false, spot: false } } /// `n` steps of OKLCH lightness from `l0` to `l1`, chroma `c(t)` and hue `h(t)` (`t` in 0..=1), diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index c8564e052a..b331d43e6a 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -181,14 +181,16 @@ fn css_comment(s: &str) -> String { fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String { let mut out = format!("/* {} */\n:root {{\n", css_comment(&lib.name)); - let mut taken: Vec = vec![]; + let mut taken: HashSet = HashSet::new(); + // The next number to try for each base, so repeated names don't search the ones used before. + let mut next: HashMap = HashMap::new(); let mut props = |out: &mut String, list: &[Swatch]| { for w in list.iter().filter(&keep) { let value = match &w.paint { Paint::Solid { color, .. } => css_color(color, 1.0), Paint::Gradient(g) if g.gradient.kind != GradientKind::Freeform => { let stops: Vec = - g.gradient.stops.iter().map(|s| format!("{} {}%", css_color(&s.color, s.opacity), (s.offset * 100.0).round())).collect(); + g.gradient.stops.iter().map(|s| format!("{} {}%", css_color(&s.color, s.opacity), s.offset * 100.0)).collect(); match g.gradient.kind { GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")), _ => format!("linear-gradient({}deg, {})", (90.0 - g.angle).rem_euclid(360.0).round(), stops.join(", ")), @@ -198,8 +200,18 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String { }; // Names differing only in case or punctuation map to one property: number the others. let base = css_property(&w.name); - let name = (1..).map(|i| if i == 1 { base.clone() } else { format!("{base}-{i}") }).find(|n| !taken.contains(n)).unwrap_or(base); - taken.push(name.clone()); + let name = if taken.insert(base.clone()) { + base + } else { + let n = next.entry(base.clone()).or_insert(1); + loop { + *n += 1; + let name = format!("{base}-{n}"); + if taken.insert(name.clone()) { + break name; + } + } + }; let note = if w.spot { " /* spot */" } else { "" }; out.push_str(&format!(" {name}: {value};{note}\n")); } @@ -371,7 +383,9 @@ fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary { continue; } if let Some(n) = line.strip_prefix("Name:") { - lib.name = n.trim().to_string(); + if !n.trim().is_empty() { + lib.name = n.trim().to_string(); + } continue; } // Comments, headers (`Columns: 4`) and anything else that isn't a colour are skipped. @@ -501,13 +515,24 @@ fn read_acb(bytes: &[u8], fallback: &str) -> Result { let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice()); let mut lib = SwatchLibrary { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() }; let mut names = UniqueNames::default(); + // Every name gets the prefix and the suffix, and is kept twice (the swatch's and the set of + // names taken): a megabyte book of long affixes and many colors came to hundreds of MB. + let mut kept = 0usize; for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) { + kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len())); + if kept > ACB_MAX_NAME_BYTES { + return Err(format!("the color book's names take more than {} MB", ACB_MAX_NAME_BYTES >> 20)); + } let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string()); lib.swatches.push(Swatch { name, paint: Paint::solid(color), global: spot, spot }); } Ok(lib) } +/// Most bytes a color book's full color names (with its prefix and suffix) may take, counted +/// twice as they are kept twice. +const ACB_MAX_NAME_BYTES: usize = 64 << 20; + /// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray. /// Components are clamped to their ranges. fn ase_swatch(body: &mut AseData) -> Result, String> { @@ -643,490 +668,4 @@ impl UniqueNames { } #[cfg(test)] -mod tests { - use super::*; - use crate::{Gradient, GradientPaint, GradientStop}; - use proptest::prelude::*; - - /// A color book's string: a `u32` count of UTF-16 code units, then the units. - fn acb_str(out: &mut Vec, s: &str) { - let units: Vec = s.encode_utf16().collect(); - out.extend((units.len() as u32).to_be_bytes()); - units.iter().for_each(|u| out.extend(u.to_be_bytes())); - } - - /// A color book in `space` (0 RGB, 2 CMYK, 7 Lab) with `colors` (name, components) and an - /// optional spot/process marker. - fn acb(space: u16, colors: &[(&str, &[u8])], marker: &[u8]) -> Vec { - let mut b = b"8BCB".to_vec(); - b.extend(1u16.to_be_bytes()); - b.extend(3000u16.to_be_bytes()); - for s in ["$$$/colorbook/Test/title=Test Book^R", "TEST ", " C", "a book"] { - acb_str(&mut b, s); - } - b.extend((colors.len() as u16).to_be_bytes()); - b.extend(7u16.to_be_bytes()); - b.extend(0u16.to_be_bytes()); - b.extend(space.to_be_bytes()); - for (name, comps) in colors { - acb_str(&mut b, name); - b.extend(b"TST001"); - b.extend(*comps); - } - b.extend(marker); - b - } - - /// #831: color books (`.acb`) are read: their colors in RGB, CMYK or Lab, named with the book's - /// prefix and suffix, spot unless the book says process; page padding is left out. - #[test] - fn color_books_are_read() { - let lib = read_bytes(&acb(0, &[("185", &[228, 0, 43]), ("", &[0, 0, 0]), ("Red 032", &[239, 51, 64])], b"spflspot"), "fallback").unwrap(); - assert_eq!(lib.name, "Test Book®"); - let names: Vec<&str> = lib.swatches.iter().map(|s| s.name.as_str()).collect(); - assert_eq!(names, ["TEST 185 C", "TEST Red 032 C"]); - assert!(lib.swatches.iter().all(|s| s.spot && s.global)); - assert_eq!(lib.swatches[0].paint.color(), Some(Color::rgb8(228, 0, 43))); - // CMYK ink is stored inverted; a book marked process gives process colors. - let lib = read_bytes(&acb(2, &[("Cyan", &[0, 255, 255, 255])], b"spflproc"), "x").unwrap(); - assert_eq!(lib.swatches[0].paint.color(), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0))); - assert!(!lib.swatches[0].spot && !lib.swatches[0].global); - // Lab: lightness 0..255 for 0..100, a and b offset by 128; no marker: spot. - let lib = read_bytes(&acb(7, &[("Grey", &[255, 128, 128])], b""), "x").unwrap(); - assert_eq!(lib.swatches[0].paint.color(), Some(Color::lab(100.0, 0.0, 0.0))); - assert!(lib.swatches[0].spot); - assert!(sniff_bytes(&acb(0, &[], b""))); - // Unsupported versions and color spaces, and short files, are errors. - let mut v2 = acb(0, &[], b""); - v2[5] = 2; - assert!(read_bytes(&v2, "x").is_err()); - assert!(read_bytes(&acb(1, &[("x", &[1, 2, 3])], b""), "x").is_err()); - let full = acb(0, &[("185", &[228, 0, 43])], b""); - for cut in 4..full.len() { - assert!(read_bytes(&full[..cut], "x").is_err(), "{cut} bytes"); - } - let mut huge = b"8BCB\0\x01\0\x01".to_vec(); - huge.extend(u32::MAX.to_be_bytes()); - assert!(read_bytes(&huge, "x").is_err(), "a string longer than the file"); - } - - fn sample() -> SwatchLibrary { - let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient { - kind: GradientKind::Linear, - stops: vec![ - GradientStop { midpoint: 0.4, ..GradientStop::new(0.0, Color::cmyk(0.1, 0.2, 0.3, 0.0)) }, - GradientStop { opacity: 0.5, ..GradientStop::new(1.0, Color::rgb8(255, 0, 0)) }, - ], - }))); - SwatchLibrary { - name: "Brand */ Colours".into(), - swatches: vec![ - Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(1.0, 0.5, 0.0, 0.2)), global: true, spot: true }, - Swatch { name: "Fade".into(), paint: grad, global: false, spot: false }, - Swatch { name: "Tiles".into(), paint: Paint::Pattern { pattern: "Dots".into(), xf: Default::default() }, global: false, spot: false }, - ], - groups: vec![SwatchGroup { - name: "Neutrals".into(), - swatches: vec![ - Swatch { name: "R=255 G=0 B=0".into(), paint: Paint::solid(Color::rgb8(255, 0, 0)), global: false, spot: false }, - Swatch { name: "Mist".into(), paint: Paint::solid(Color::gray(0.25)), global: true, spot: false }, - ], - }], - } - } - - /// `lib` written as text format `f`. - fn written(lib: &SwatchLibrary, f: PaletteFormat) -> String { - String::from_utf8(write(lib, f).unwrap()).unwrap() - } - - #[test] - fn native_round_trip_keeps_cmyk_spot_and_groups() { - let lib = sample(); - let text = written(&lib, PaletteFormat::Native); - assert!(sniff(&text)); - let back = read(&text, "fallback").unwrap(); - let mut expected = lib.clone(); - expected.swatches.retain(|w| !matches!(w.paint, Paint::Pattern { .. })); - assert_eq!(back, expected, "everything but the pattern comes back exactly"); - assert!(back.swatches[0].spot && back.swatches[0].global); - assert_eq!(back.swatches[0].paint.color(), Some(Color::cmyk(1.0, 0.5, 0.0, 0.2))); - assert!(read("{\"format\": \"other\", \"version\": 1, \"name\": \"x\"}", "x").is_err()); - } - - #[test] - fn gpl_writes_rgb_with_group_headers_and_reads_comments_and_headers() { - let text = written(&sample(), PaletteFormat::Gpl); - assert!(text.starts_with("GIMP Palette\nName: Brand */ Colours\n")); - assert!(text.contains("# Group: Neutrals\n255 0 0\tR=255 G=0 B=0\n"), "{text}"); - assert!(!text.contains("Fade") && !text.contains("Tiles"), "only solid colours"); - let back = read(&text, "x").unwrap(); - assert_eq!(back.name, "Brand */ Colours"); - assert_eq!(back.swatches.len(), 1); - assert_eq!(back.groups[0].swatches[1].paint.color(), Some(Color::rgb8(191, 191, 191)), "grey as 8-bit RGB"); - // Another tool's palette: comments, a Columns header, blank lines, unnamed and repeated names. - let other = "GIMP Palette\r\nName: Sunset\r\nColumns: 4\r\n# a comment\r\n\r\n 0 128 255\tSky Blue\r\n10 20 30\r\n0 0 0 Black\r\n1 1 1 Black\r\nbad line\r\n"; - let lib = read(other, "file").unwrap(); - assert_eq!(lib.name, "Sunset"); - let names: Vec<&str> = lib.swatches.iter().map(|w| w.name.as_str()).collect(); - assert_eq!(names, ["Sky Blue", "R=10 G=20 B=30", "Black", "Black 2"]); - assert_eq!(lib.swatches[0].paint.color(), Some(Color::rgb8(0, 128, 255))); - assert_eq!(read("GIMP Palette\n1 2 3 x\n", "Fallback").unwrap().name, "Fallback"); - // Colors and groups share names; an unnamed group is "Color Group". - let lib = read("GIMP Palette\n0 0 0 Black\n# Group: Black\n1 1 1 Black\n# Group:\n", "x").unwrap(); - let groups: Vec<(&str, Vec<&str>)> = - lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect(); - assert_eq!(groups, [("Black 2", vec!["Black 3"]), ("Color Group", vec![])]); - } - - #[test] - fn css_escapes_names_and_writes_gradients() { - assert_eq!(css_property("Sky Blue"), "--sky-blue"); - assert_eq!(css_property("R=255 G=0 B=0"), "--r\\=255-g\\=0-b\\=0"); - assert_eq!(css_property("#FF00CC"), "--\\#ff00cc"); - assert_eq!(css_property("Café 50%"), "--café-50\\%"); - assert_eq!(css_property(" "), "--swatch"); - let text = written(&sample(), PaletteFormat::Css); - assert!(text.starts_with("/* Brand * / Colours */\n:root {\n"), "{text}"); - assert!(text.contains(" --ink: #"), "{text}"); - assert!(text.contains("; /* spot */")); - assert!(text.contains(" --fade: linear-gradient(90deg, #"), "{text}"); - assert!(text.contains("#ff000080 100%)"), "half-transparent stop: {text}"); - assert!(text.contains(" /* Neutrals */\n --r\\=255-g\\=0-b\\=0: #ff0000;\n")); - assert!(!text.contains("tiles")); - // Names that collide once escaped are numbered. - let lib = SwatchLibrary { - name: "x".into(), - swatches: ["Red", "red"].map(|n| Swatch { name: n.into(), paint: Paint::solid(Color::BLACK), global: false, spot: false }).to_vec(), - groups: vec![], - }; - let text = written(&lib, PaletteFormat::Css); - assert!(text.contains("--red: #000000;") && text.contains("--red-2: #000000;")); - assert!(read(&text, "x").is_err(), "CSS is written only"); - } - - #[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. - let mut lib = sample(); - let Paint::Gradient(mut mesh) = lib.swatches[1].paint.clone() else { panic!("Fade is a gradient") }; - mesh.gradient.kind = GradientKind::Freeform; - lib.swatches.push(Swatch { name: "Mesh".into(), paint: Paint::Gradient(mesh), global: false, spot: false }); - lib.swatches.push(Swatch { name: "[None]".into(), paint: Paint::None, global: false, spot: false }); - let held = |f: PaletteFormat| lib.iter().filter(|w| f.holds(&w.paint)).count(); - assert_eq!(PaletteFormat::ALL.map(held), [5, 3, 3, 4], "vcswatches, gpl, ase, css"); - for f in [PaletteFormat::Native, PaletteFormat::Gpl, PaletteFormat::Ase] { - assert_eq!(read_bytes(&write(&lib, f).unwrap(), "x").unwrap().len(), held(f), "{f:?}"); - } - let css = written(&lib, PaletteFormat::Css); - assert_eq!(css.lines().filter(|l| l.starts_with(" --")).count(), held(PaletteFormat::Css), "one property each: {css}"); - } - - /// A swatch exchange file of `blocks` (type, body). - fn ase(blocks: &[(u16, Vec)]) -> Vec { - let mut out = b"ASEF\0\x01\0\0".to_vec(); - out.extend((blocks.len() as u32).to_be_bytes()); - for (kind, body) in blocks { - out.extend(kind.to_be_bytes()); - out.extend((body.len() as u32).to_be_bytes()); - out.extend(body); - } - out - } - - /// A name as `.ase` stores it. - fn ase_name(name: &str) -> Vec { - let units: Vec = name.encode_utf16().chain([0]).collect(); - let mut out = (units.len() as u16).to_be_bytes().to_vec(); - out.extend(units.iter().flat_map(|u| u.to_be_bytes())); - out - } - - /// A color block: name, model, components and color type. - fn ase_color(name: &str, model: &[u8; 4], values: &[f32], kind: u16) -> (u16, Vec) { - let mut body = ase_name(name); - body.extend(model); - body.extend(values.iter().flat_map(|v| v.to_be_bytes())); - body.extend(kind.to_be_bytes()); - (ASE_COLOR, body) - } - - #[test] - fn ase_reads_color_models_kinds_and_groups() { - let bytes = ase(&[ - ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0), - ase_color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1), - (ASE_GROUP_START, ase_name("Neutrals")), - ase_color("Mist", b"Gray", &[0.75], 2), - ase_color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2), - (ASE_GROUP_END, vec![]), - ase_color("Paper", b"RGB ", &[1.0, 1.0, 1.0], 2), - ]); - assert!(sniff_bytes(&bytes)); - let sw = |name: &str, color, global, spot| Swatch { name: name.into(), paint: Paint::solid(color), global, spot }; - let expected = SwatchLibrary { - name: "Brand".into(), - swatches: vec![ - sw("Sky", Color::rgb(0.0, 0.5, 1.0), true, false), - sw("Ink", Color::cmyk(1.0, 0.5, 0.0, 0.2), true, true), - sw("Paper", Color::WHITE, false, false), - ], - groups: vec![SwatchGroup { - name: "Neutrals".into(), - swatches: vec![sw("Mist", Color::gray(0.25), false, false), sw("Clay", Color::lab(50.0, 20.0, -30.0), false, false)], - }], - }; - assert_eq!(read_bytes(&bytes, "Brand").unwrap(), expected, "named after the file; 0 global, 1 spot, 2 process"); - // A lightness above 1 is L* itself. - let deep = read_bytes(&ase(&[ase_color("Deep", b"LAB ", &[53.0, 20.0, -30.0], 2)]), "x").unwrap(); - assert_eq!(deep.swatches[0].paint.color(), Some(Color::lab(53.0, 20.0, -30.0))); - // Text libraries read through the same call, also when they aren't valid UTF-8. - assert!(sniff_bytes(b"GIMP Palette\n1 2 3 x\n") && !sniff_bytes(b"ASE") && !sniff_bytes(&[0xff, 0xfe, 0])); - assert_eq!(read_bytes(b"GIMP Palette\n1 2 3 x\n", "F").unwrap().swatches.len(), 1); - let latin1 = b"GIMP Palette\n1 2 3 Caf\xe9\n"; - assert!(sniff_bytes(latin1)); - assert_eq!(read_bytes(latin1, "F").unwrap().swatches.len(), 1); - } - - #[test] - fn ase_names_unnamed_and_repeated_entries_and_skips_other_blocks() { - let mut untyped = ase_color("Plain", b"RGB ", &[0.2, 0.4, 0.6], 2); - untyped.1.truncate(untyped.1.len() - 2); - let bytes = ase(&[ - ase_color("Café 🎨", b"RGB ", &[1.0, 0.0, 0.0], 2), - ase_color("", b"CMYK", &[0.1, 0.2, 0.3, 0.0], 2), - ase_color(" Red ", b"RGB ", &[2.0, -1.0, f32::NAN], 0), - ase_color("Red", b"Gray", &[0.0], 2), - untyped, - ase_color("Hue", b"HSB ", &[0.1, 0.2, 0.3], 2), - (0x0042, vec![1, 2, 3]), - (ASE_GROUP_END, vec![]), - (ASE_GROUP_START, ase_name("")), - (ASE_GROUP_START, ase_name("Red")), - ase_color("Red", b"Gray", &[1.0], 2), - ]); - let lib = read_bytes(&bytes, "x").unwrap(); - let names: Vec<&str> = lib.swatches.iter().map(|w| w.name.as_str()).collect(); - assert_eq!(names, ["Café 🎨", "C=10 M=20 Y=30 K=0", "Red", "Red 2", "Plain"], "an HSB color and an unknown block are skipped"); - assert_eq!(lib.swatches[2].paint.color(), Some(Color::rgb(1.0, 0.0, 0.0)), "clamped, NaN read as 0"); - assert!(lib.swatches[2].global && !lib.swatches[4].global, "without a color type: process"); - // A group start ends the open group, and groups and colors share names. - let groups: Vec<(&str, Vec<&str>)> = - lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect(); - assert_eq!(groups, [("Color Group", vec![]), ("Red 3", vec!["Red 4"])]); - assert_eq!(lib.groups[1].swatches[0].paint.color(), Some(Color::gray(0.0)), "gray level 1 is white"); - } - - #[test] - fn damaged_ase_files_are_errors() { - let good = ase(&[(ASE_GROUP_START, ase_name("G")), ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0)]); - assert_eq!(read_bytes(&good, "x").unwrap().len(), 1); - for n in ASE_SIGNATURE.len()..good.len() { - assert!(read_bytes(&good[..n], "x").is_err(), "cut at {n}"); - } - let mut v2 = good.clone(); - v2[5] = 2; - assert!(read_bytes(&v2, "x").unwrap_err().contains("2.0"), "version 2.0"); - // Too many colors, or too many groups (empty group starts take 6 bytes each). - let colors: Vec<(u16, Vec)> = (0..=ASE_MAX_ENTRIES).map(|_| ase_color("Gray", b"Gray", &[0.5], 2)).collect(); - assert!(read_bytes(&ase(&colors), "x").unwrap_err().contains("more than")); - let groups: Vec<(u16, Vec)> = (0..=ASE_MAX_ENTRIES).map(|_| (ASE_GROUP_START, vec![])).collect(); - assert!(read_bytes(&ase(&groups), "x").unwrap_err().contains("more than")); - assert_eq!(read_bytes(&ase(&groups[1..]), "x").unwrap().groups.len(), ASE_MAX_ENTRIES, "up to the limit"); - } - - #[test] - fn ase_writes_each_model_kind_and_group() { - let sw = |name: &str, color, global, spot| Swatch { name: name.into(), paint: Paint::solid(color), global, spot }; - let tint = Swatch { - name: "Ink 40%".into(), - paint: Paint::Solid { color: Color::cmyk(0.4, 0.2, 0.0, 0.08), swatch: Some("Ink".into()), tint: 0.4 }, - global: false, - spot: false, - }; - // `sample()` holds the spot color Ink, the gradient Fade, the pattern Tiles and the group Neutrals. - let mut lib = sample(); - lib.swatches.insert(0, sw("Sky", Color::rgb(0.0, 0.5, 1.0), true, false)); - lib.swatches.push(tint); - lib.groups[0].swatches = vec![sw("Mist", Color::gray(0.25), false, false), sw("Clay", Color::lab(50.0, 20.0, -30.0), false, false)]; - lib.groups.push(SwatchGroup { name: "Empty".into(), swatches: vec![] }); - let bytes = write(&lib, PaletteFormat::Ase).unwrap(); - let expected = ase(&[ - ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0), - ase_color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1), - ase_color("Ink 40%", b"CMYK", &[0.4, 0.2, 0.0, 0.08], 2), - (ASE_GROUP_START, ase_name("Neutrals")), - ase_color("Mist", b"Gray", &[0.75], 2), - ase_color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2), - (ASE_GROUP_END, vec![]), - (ASE_GROUP_START, ase_name("Empty")), - (ASE_GROUP_END, vec![]), - ]); - assert_eq!(bytes, expected, "no gradient or pattern; the tint as the process color it shows"); - let back = read_bytes(&bytes, "Brand").unwrap(); - assert_eq!((back.len(), back.groups.len()), (5, 2), "the empty group stays"); - assert_eq!(PaletteFormat::parse(".ASE"), Some(PaletteFormat::Ase)); - assert!(PaletteFormat::Ase.readable() && PaletteFormat::Ase.binary() && !PaletteFormat::Gpl.binary()); - } - - #[test] - fn ase_names_lose_nul_and_stop_at_the_reader_limit() { - let names = ["Re\0d".to_string(), "é".repeat(1030), format!("a{}", "🎨".repeat(600))]; - let swatches = names.iter().map(|n| Swatch { name: n.clone(), paint: Paint::solid(Color::BLACK), global: false, spot: false }).collect(); - let lib = SwatchLibrary { name: "x".into(), swatches, groups: vec![] }; - let back = read_bytes(&write(&lib, PaletteFormat::Ase).unwrap(), "x").unwrap(); - let got: Vec<&str> = back.swatches.iter().map(|w| w.name.as_str()).collect(); - // At most 1024 UTF-16 code units, cut between characters: "a" and 511 two-unit emoji. - assert_eq!(got, ["Red".to_string(), "é".repeat(1024), format!("a{}", "🎨".repeat(511))]); - } - - #[test] - fn ase_clamps_components_and_writes_non_finite_ones_as_zero() { - let sw = |name: &str, color| Swatch { name: name.into(), paint: Paint::solid(color), global: false, spot: false }; - let swatches = vec![ - sw("Lab", Color::lab(100.5, 300.0, -300.0)), - sw("Rgb", Color::rgb(2.0, -1.0, f32::NAN)), - sw("Cmyk", Color::cmyk(1.5, 0.0, 0.0, f32::INFINITY)), - sw("Gray", Color::gray(1.5)), - ]; - let bytes = write(&SwatchLibrary { name: "x".into(), swatches, groups: vec![] }, PaletteFormat::Ase).unwrap(); - let expected = ase(&[ - ase_color("Lab", b"LAB ", &[1.0, 127.0, -128.0], 2), - ase_color("Rgb", b"RGB ", &[1.0, 0.0, 0.0], 2), - ase_color("Cmyk", b"CMYK", &[1.0, 0.0, 0.0, 0.0], 2), - ase_color("Gray", b"Gray", &[0.0], 2), - ]); - assert_eq!(bytes, expected, "clamped to the ranges .ase holds, a component that isn't finite as 0"); - // Lightness 100.5 is written as 1, which reads back as L* 100. - let back = read_bytes(&bytes, "x").unwrap(); - assert_eq!(back.swatches[0].paint.color(), Some(Color::lab(100.0, 127.0, -128.0))); - } - - #[test] - fn ase_write_refuses_more_entries_than_the_reader_takes() { - let gray = |i: usize| Swatch { name: format!("G{i}"), paint: Paint::solid(Color::gray(0.5)), global: false, spot: false }; - // The limit counts colors and groups: a group and `ASE_MAX_ENTRIES - 1` colors reach it. - let mut lib = SwatchLibrary { - name: "x".into(), - swatches: (1..ASE_MAX_ENTRIES).map(gray).collect(), - groups: vec![SwatchGroup { name: "Group".into(), swatches: vec![] }], - }; - let back = read_bytes(&write(&lib, PaletteFormat::Ase).unwrap(), "x").unwrap(); - assert_eq!((back.len(), back.groups.len()), (ASE_MAX_ENTRIES - 1, 1)); - lib.swatches.push(gray(0)); - let e = write(&lib, PaletteFormat::Ase).unwrap_err(); - assert!(e.contains("reads at most 100000 colors and groups from a swatch exchange file, and this library has 100001"), "{e}"); - // A gradient is left out and is not counted. - lib.swatches.last_mut().unwrap().paint = sample().swatches[1].paint.clone(); - assert!(write(&lib, PaletteFormat::Ase).is_ok()); - } - - /// A color in one of the four models, in the ranges `.ase` holds. - fn arb_color() -> impl Strategy { - let unit = || 0.0f32..=1.0; - prop_oneof![ - (unit(), unit(), unit()).prop_map(|(r, g, b)| Color::rgb(r, g, b)), - (unit(), unit(), unit(), unit()).prop_map(|(c, m, y, k)| Color::cmyk(c, m, y, k)), - unit().prop_map(Color::gray), - (0.0f32..=100.0, -128.0f32..=127.0, -128.0f32..=127.0).prop_map(|(l, a, b)| Color::lab(l, a, b)), - ] - } - - /// A swatch's paint with its global and spot flags: a solid color with any flags, a tint swatch - /// (both flags off) or a gradient. - fn arb_paint() -> impl Strategy { - prop_oneof![ - 4 => (arb_color(), any::(), any::()).prop_map(|(c, global, spot)| (Paint::solid(c), global, spot)), - 1 => arb_color().prop_map(|c| (Paint::Solid { color: c, swatch: Some("Base".into()), tint: 0.4 }, false, false)), - 1 => Just((sample().swatches[1].paint.clone(), false, false)), - ] - } - - /// Ungrouped swatches and color groups. A name is a number and up to 12 characters of any script - /// but NUL, trimmed, so swatches and groups have unique names, as in a document. - fn arb_library() -> impl Strategy { - let swatches = || prop::collection::vec((arb_paint(), "[^\\x00]{0,12}"), 0..12); - (swatches(), prop::collection::vec(("[^\\x00]{0,12}", swatches()), 0..4)).prop_map(|(loose, groups)| { - let mut n = 0; - let mut name = |prefix: &str, base: &str| { - n += 1; - format!("{prefix}{n} {base}").trim().to_string() - }; - let mut lib = SwatchLibrary { name: "Fuzz".into(), ..Default::default() }; - for ((paint, global, spot), base) in loose { - lib.swatches.push(Swatch { name: name("", &base), paint, global, spot }); - } - for (base, list) in groups { - let mut g = SwatchGroup { name: name("G", &base), swatches: vec![] }; - for ((paint, global, spot), base) in list { - g.swatches.push(Swatch { name: name("", &base), paint, global, spot }); - } - lib.groups.push(g); - } - lib - }) - } - - /// Are `got` and `want` in the same model, with every component within 1e-4? Lab lightness and - /// gray read back within `f32` rounding. - fn close(got: Color, want: Color) -> bool { - let near = |a: f32, b: f32| (a - b).abs() < 1e-4; - match (got, want) { - (Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => near(r, r2) && near(g, g2) && near(b, b2), - (Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => near(c, c2) && near(m, m2) && near(y, y2) && near(k, k2), - (Color::Gray { k }, Color::Gray { k: k2 }) => near(k, k2), - (Color::Lab { l, a, b }, Color::Lab { l: l2, a: a2, b: b2 }) => near(l, l2) && near(a, a2) && near(b, b2), - _ => false, - } - } - - /// The swatches of `list` as an `.ase` file reads them back: solid colors only, unlinked, spot - /// colors global. - fn ase_expected(list: &[Swatch]) -> Vec { - list.iter() - .filter_map(|w| Some(Swatch { name: w.name.clone(), paint: Paint::solid(w.paint.color()?), global: w.global || w.spot, spot: w.spot })) - .collect() - } - - /// Do swatches `got` have the names, flags and unlinked colors (within 1e-4) of `want`? - fn same_swatches(got: &[Swatch], want: &[Swatch]) -> bool { - got.len() == want.len() - && got.iter().zip(want).all(|(g, w)| { - let color = match (&g.paint, w.paint.color()) { - (Paint::Solid { color, swatch: None, .. }, Some(c)) => close(*color, c), - _ => false, - }; - g.name == w.name && g.global == w.global && g.spot == w.spot && color - }) - } - - proptest! { - #![proptest_config(ProptestConfig { failure_persistence: None, ..ProptestConfig::default() })] - - /// A written `.ase` file reads back as the library's solid colors in their own model, with - /// their names, kinds and color groups. - #[test] - fn ase_round_trip_keeps_models_kinds_and_groups(lib in arb_library()) { - let bytes = write(&lib, PaletteFormat::Ase).unwrap(); - prop_assert!(sniff_bytes(&bytes)); - let back = read_bytes(&bytes, &lib.name).unwrap(); - prop_assert_eq!(&back.name, &lib.name); - prop_assert!(same_swatches(&back.swatches, &ase_expected(&lib.swatches)), "{:?}", back.swatches); - prop_assert_eq!(back.groups.len(), lib.groups.len()); - for (g, want) in back.groups.iter().zip(&lib.groups) { - prop_assert_eq!(&g.name, &want.name); - prop_assert!(same_swatches(&g.swatches, &ase_expected(&want.swatches)), "{}: {:?}", g.name, g.swatches); - } - } - - /// A written `.vcswatches`, `.gpl` or `.ase` file reads back with as many swatches as - /// [`PaletteFormat::holds`] counts. - #[test] - fn written_files_read_back_with_the_swatches_holds_counts(lib in arb_library()) { - for f in [PaletteFormat::Native, PaletteFormat::Gpl, PaletteFormat::Ase] { - let back = read_bytes(&write(&lib, f).unwrap(), &lib.name).unwrap(); - prop_assert_eq!(back.len(), lib.iter().filter(|w| f.holds(&w.paint)).count(), "{:?}", f); - } - } - } -} +mod tests; diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs new file mode 100644 index 0000000000..b0342d7a52 --- /dev/null +++ b/crates/color/src/palette_io/tests.rs @@ -0,0 +1,517 @@ +use super::*; +use crate::{Gradient, GradientPaint, GradientStop}; +use proptest::prelude::*; + +#[test] +fn gpl_blank_name_keeps_fallback() { + let blank = "GIMP Palette\nName: \nColumns: 0\n#\n 1 2 3\tx\n"; + assert_eq!(read(blank, "fallback").unwrap().name, "fallback"); + let named = "GIMP Palette\nName: Warm\n 1 2 3\tx\n"; + assert_eq!(read(named, "fallback").unwrap().name, "Warm"); +} + +/// A color book's string: a `u32` count of UTF-16 code units, then the units. +fn acb_str(out: &mut Vec, s: &str) { + let units: Vec = s.encode_utf16().collect(); + out.extend((units.len() as u32).to_be_bytes()); + units.iter().for_each(|u| out.extend(u.to_be_bytes())); +} + +/// A color book in `space` (0 RGB, 2 CMYK, 7 Lab) with `colors` (name, components) and an +/// optional spot/process marker. +fn acb(space: u16, colors: &[(&str, &[u8])], marker: &[u8]) -> Vec { + let mut b = b"8BCB".to_vec(); + b.extend(1u16.to_be_bytes()); + b.extend(3000u16.to_be_bytes()); + for s in ["$$$/colorbook/Test/title=Test Book^R", "TEST ", " C", "a book"] { + acb_str(&mut b, s); + } + b.extend((colors.len() as u16).to_be_bytes()); + b.extend(7u16.to_be_bytes()); + b.extend(0u16.to_be_bytes()); + b.extend(space.to_be_bytes()); + for (name, comps) in colors { + acb_str(&mut b, name); + b.extend(b"TST001"); + b.extend(*comps); + } + b.extend(marker); + b +} + +/// #831: color books (`.acb`) are read: their colors in RGB, CMYK or Lab, named with the book's +/// prefix and suffix, spot unless the book says process; page padding is left out. +#[test] +fn color_books_are_read() { + let lib = read_bytes(&acb(0, &[("185", &[228, 0, 43]), ("", &[0, 0, 0]), ("Red 032", &[239, 51, 64])], b"spflspot"), "fallback").unwrap(); + assert_eq!(lib.name, "Test Book®"); + let names: Vec<&str> = lib.swatches.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["TEST 185 C", "TEST Red 032 C"]); + assert!(lib.swatches.iter().all(|s| s.spot && s.global)); + assert_eq!(lib.swatches[0].paint.color(), Some(Color::rgb8(228, 0, 43))); + // CMYK ink is stored inverted; a book marked process gives process colors. + let lib = read_bytes(&acb(2, &[("Cyan", &[0, 255, 255, 255])], b"spflproc"), "x").unwrap(); + assert_eq!(lib.swatches[0].paint.color(), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0))); + assert!(!lib.swatches[0].spot && !lib.swatches[0].global); + // Lab: lightness 0..255 for 0..100, a and b offset by 128; no marker: spot. + let lib = read_bytes(&acb(7, &[("Grey", &[255, 128, 128])], b""), "x").unwrap(); + assert_eq!(lib.swatches[0].paint.color(), Some(Color::lab(100.0, 0.0, 0.0))); + assert!(lib.swatches[0].spot); + assert!(sniff_bytes(&acb(0, &[], b""))); + // Unsupported versions and color spaces, and short files, are errors. + let mut v2 = acb(0, &[], b""); + v2[5] = 2; + assert!(read_bytes(&v2, "x").is_err()); + assert!(read_bytes(&acb(1, &[("x", &[1, 2, 3])], b""), "x").is_err()); + let full = acb(0, &[("185", &[228, 0, 43])], b""); + for cut in 4..full.len() { + assert!(read_bytes(&full[..cut], "x").is_err(), "{cut} bytes"); + } + let mut huge = b"8BCB\0\x01\0\x01".to_vec(); + huge.extend(u32::MAX.to_be_bytes()); + assert!(read_bytes(&huge, "x").is_err(), "a string longer than the file"); +} + +fn sample() -> SwatchLibrary { + let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![ + GradientStop { midpoint: 0.4, ..GradientStop::new(0.0, Color::cmyk(0.1, 0.2, 0.3, 0.0)) }, + GradientStop { opacity: 0.5, ..GradientStop::new(1.0, Color::rgb8(255, 0, 0)) }, + ], + )))); + SwatchLibrary { + name: "Brand */ Colours".into(), + swatches: vec![ + Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(1.0, 0.5, 0.0, 0.2)), global: true, spot: true }, + Swatch { name: "Fade".into(), paint: grad, global: false, spot: false }, + Swatch { name: "Tiles".into(), paint: Paint::Pattern { pattern: "Dots".into(), xf: Default::default() }, global: false, spot: false }, + ], + groups: vec![SwatchGroup { + name: "Neutrals".into(), + swatches: vec![ + Swatch { name: "R=255 G=0 B=0".into(), paint: Paint::solid(Color::rgb8(255, 0, 0)), global: false, spot: false }, + Swatch { name: "Mist".into(), paint: Paint::solid(Color::gray(0.25)), global: true, spot: false }, + ], + }], + } +} + +/// `lib` written as text format `f`. +fn written(lib: &SwatchLibrary, f: PaletteFormat) -> String { + String::from_utf8(write(lib, f).unwrap()).unwrap() +} + +#[test] +fn native_round_trip_keeps_cmyk_spot_and_groups() { + let lib = sample(); + let text = written(&lib, PaletteFormat::Native); + assert!(sniff(&text)); + let back = read(&text, "fallback").unwrap(); + let mut expected = lib.clone(); + expected.swatches.retain(|w| !matches!(w.paint, Paint::Pattern { .. })); + assert_eq!(back, expected, "everything but the pattern comes back exactly"); + assert!(back.swatches[0].spot && back.swatches[0].global); + assert_eq!(back.swatches[0].paint.color(), Some(Color::cmyk(1.0, 0.5, 0.0, 0.2))); + assert!(read("{\"format\": \"other\", \"version\": 1, \"name\": \"x\"}", "x").is_err()); +} + +#[test] +fn gpl_writes_rgb_with_group_headers_and_reads_comments_and_headers() { + let text = written(&sample(), PaletteFormat::Gpl); + assert!(text.starts_with("GIMP Palette\nName: Brand */ Colours\n")); + assert!(text.contains("# Group: Neutrals\n255 0 0\tR=255 G=0 B=0\n"), "{text}"); + assert!(!text.contains("Fade") && !text.contains("Tiles"), "only solid colours"); + let back = read(&text, "x").unwrap(); + assert_eq!(back.name, "Brand */ Colours"); + assert_eq!(back.swatches.len(), 1); + assert_eq!(back.groups[0].swatches[1].paint.color(), Some(Color::rgb8(191, 191, 191)), "grey as 8-bit RGB"); + // Another tool's palette: comments, a Columns header, blank lines, unnamed and repeated names. + let other = "GIMP Palette\r\nName: Sunset\r\nColumns: 4\r\n# a comment\r\n\r\n 0 128 255\tSky Blue\r\n10 20 30\r\n0 0 0 Black\r\n1 1 1 Black\r\nbad line\r\n"; + let lib = read(other, "file").unwrap(); + assert_eq!(lib.name, "Sunset"); + let names: Vec<&str> = lib.swatches.iter().map(|w| w.name.as_str()).collect(); + assert_eq!(names, ["Sky Blue", "R=10 G=20 B=30", "Black", "Black 2"]); + assert_eq!(lib.swatches[0].paint.color(), Some(Color::rgb8(0, 128, 255))); + assert_eq!(read("GIMP Palette\n1 2 3 x\n", "Fallback").unwrap().name, "Fallback"); + // Colors and groups share names; an unnamed group is "Color Group". + let lib = read("GIMP Palette\n0 0 0 Black\n# Group: Black\n1 1 1 Black\n# Group:\n", "x").unwrap(); + let groups: Vec<(&str, Vec<&str>)> = lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect(); + assert_eq!(groups, [("Black 2", vec!["Black 3"]), ("Color Group", vec![])]); +} + +#[test] +fn css_escapes_names_and_writes_gradients() { + assert_eq!(css_property("Sky Blue"), "--sky-blue"); + assert_eq!(css_property("R=255 G=0 B=0"), "--r\\=255-g\\=0-b\\=0"); + assert_eq!(css_property("#FF00CC"), "--\\#ff00cc"); + assert_eq!(css_property("Café 50%"), "--café-50\\%"); + assert_eq!(css_property(" "), "--swatch"); + let text = written(&sample(), PaletteFormat::Css); + assert!(text.starts_with("/* Brand * / Colours */\n:root {\n"), "{text}"); + assert!(text.contains(" --ink: #"), "{text}"); + assert!(text.contains("; /* spot */")); + assert!(text.contains(" --fade: linear-gradient(90deg, #"), "{text}"); + assert!(text.contains("#ff000080 100%)"), "half-transparent stop: {text}"); + assert!(text.contains(" /* Neutrals */\n --r\\=255-g\\=0-b\\=0: #ff0000;\n")); + assert!(!text.contains("tiles")); + // Names that collide once escaped are numbered. + let lib = SwatchLibrary { + name: "x".into(), + swatches: ["Red", "red"].map(|n| Swatch { name: n.into(), paint: Paint::solid(Color::BLACK), global: false, spot: false }).to_vec(), + groups: vec![], + }; + let text = written(&lib, PaletteFormat::Css); + assert!(text.contains("--red: #000000;") && text.contains("--red-2: #000000;")); + assert!(read(&text, "x").is_err(), "CSS is written only"); +} + +#[test] +fn css_preserves_fractional_gradient_stop_positions() { + for kind in [GradientKind::Linear, GradientKind::Radial] { + let lib = SwatchLibrary { + name: "Positions".into(), + swatches: vec![Swatch { + name: "Ramp".into(), + paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + kind, + vec![ + GradientStop::new(0.0, Color::BLACK), + GradientStop::new(0.125, Color::rgb8(255, 0, 0)), + GradientStop::new(0.12890625, Color::WHITE), + GradientStop::new(1.0, Color::rgb8(0, 0, 255)), + ], + )))), + global: false, + spot: false, + }], + groups: vec![], + }; + let text = written(&lib, PaletteFormat::Css); + assert!(text.contains("#000000 0%, #ff0000 12.5%, #ffffff 12.890625%, #0000ff 100%"), "{kind:?}: {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. + let mut lib = sample(); + let Paint::Gradient(mut mesh) = lib.swatches[1].paint.clone() else { panic!("Fade is a gradient") }; + mesh.gradient.kind = GradientKind::Freeform; + lib.swatches.push(Swatch { name: "Mesh".into(), paint: Paint::Gradient(mesh), global: false, spot: false }); + lib.swatches.push(Swatch { name: "[None]".into(), paint: Paint::None, global: false, spot: false }); + let held = |f: PaletteFormat| lib.iter().filter(|w| f.holds(&w.paint)).count(); + assert_eq!(PaletteFormat::ALL.map(held), [5, 3, 3, 4], "vcswatches, gpl, ase, css"); + for f in [PaletteFormat::Native, PaletteFormat::Gpl, PaletteFormat::Ase] { + assert_eq!(read_bytes(&write(&lib, f).unwrap(), "x").unwrap().len(), held(f), "{f:?}"); + } + let css = written(&lib, PaletteFormat::Css); + assert_eq!(css.lines().filter(|l| l.starts_with(" --")).count(), held(PaletteFormat::Css), "one property each: {css}"); +} + +/// A swatch exchange file of `blocks` (type, body). +fn ase(blocks: &[(u16, Vec)]) -> Vec { + let mut out = b"ASEF\0\x01\0\0".to_vec(); + out.extend((blocks.len() as u32).to_be_bytes()); + for (kind, body) in blocks { + out.extend(kind.to_be_bytes()); + out.extend((body.len() as u32).to_be_bytes()); + out.extend(body); + } + out +} + +/// A name as `.ase` stores it. +fn ase_name(name: &str) -> Vec { + let units: Vec = name.encode_utf16().chain([0]).collect(); + let mut out = (units.len() as u16).to_be_bytes().to_vec(); + out.extend(units.iter().flat_map(|u| u.to_be_bytes())); + out +} + +/// A color block: name, model, components and color type. +fn ase_color(name: &str, model: &[u8; 4], values: &[f32], kind: u16) -> (u16, Vec) { + let mut body = ase_name(name); + body.extend(model); + body.extend(values.iter().flat_map(|v| v.to_be_bytes())); + body.extend(kind.to_be_bytes()); + (ASE_COLOR, body) +} + +#[test] +fn ase_reads_color_models_kinds_and_groups() { + let bytes = ase(&[ + ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0), + ase_color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1), + (ASE_GROUP_START, ase_name("Neutrals")), + ase_color("Mist", b"Gray", &[0.75], 2), + ase_color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2), + (ASE_GROUP_END, vec![]), + ase_color("Paper", b"RGB ", &[1.0, 1.0, 1.0], 2), + ]); + assert!(sniff_bytes(&bytes)); + let sw = |name: &str, color, global, spot| Swatch { name: name.into(), paint: Paint::solid(color), global, spot }; + let expected = SwatchLibrary { + name: "Brand".into(), + swatches: vec![ + sw("Sky", Color::rgb(0.0, 0.5, 1.0), true, false), + sw("Ink", Color::cmyk(1.0, 0.5, 0.0, 0.2), true, true), + sw("Paper", Color::WHITE, false, false), + ], + groups: vec![SwatchGroup { + name: "Neutrals".into(), + swatches: vec![sw("Mist", Color::gray(0.25), false, false), sw("Clay", Color::lab(50.0, 20.0, -30.0), false, false)], + }], + }; + assert_eq!(read_bytes(&bytes, "Brand").unwrap(), expected, "named after the file; 0 global, 1 spot, 2 process"); + // A lightness above 1 is L* itself. + let deep = read_bytes(&ase(&[ase_color("Deep", b"LAB ", &[53.0, 20.0, -30.0], 2)]), "x").unwrap(); + assert_eq!(deep.swatches[0].paint.color(), Some(Color::lab(53.0, 20.0, -30.0))); + // Text libraries read through the same call, also when they aren't valid UTF-8. + assert!(sniff_bytes(b"GIMP Palette\n1 2 3 x\n") && !sniff_bytes(b"ASE") && !sniff_bytes(&[0xff, 0xfe, 0])); + assert_eq!(read_bytes(b"GIMP Palette\n1 2 3 x\n", "F").unwrap().swatches.len(), 1); + let latin1 = b"GIMP Palette\n1 2 3 Caf\xe9\n"; + assert!(sniff_bytes(latin1)); + assert_eq!(read_bytes(latin1, "F").unwrap().swatches.len(), 1); +} + +#[test] +fn ase_names_unnamed_and_repeated_entries_and_skips_other_blocks() { + let mut untyped = ase_color("Plain", b"RGB ", &[0.2, 0.4, 0.6], 2); + untyped.1.truncate(untyped.1.len() - 2); + let bytes = ase(&[ + ase_color("Café 🎨", b"RGB ", &[1.0, 0.0, 0.0], 2), + ase_color("", b"CMYK", &[0.1, 0.2, 0.3, 0.0], 2), + ase_color(" Red ", b"RGB ", &[2.0, -1.0, f32::NAN], 0), + ase_color("Red", b"Gray", &[0.0], 2), + untyped, + ase_color("Hue", b"HSB ", &[0.1, 0.2, 0.3], 2), + (0x0042, vec![1, 2, 3]), + (ASE_GROUP_END, vec![]), + (ASE_GROUP_START, ase_name("")), + (ASE_GROUP_START, ase_name("Red")), + ase_color("Red", b"Gray", &[1.0], 2), + ]); + let lib = read_bytes(&bytes, "x").unwrap(); + let names: Vec<&str> = lib.swatches.iter().map(|w| w.name.as_str()).collect(); + assert_eq!(names, ["Café 🎨", "C=10 M=20 Y=30 K=0", "Red", "Red 2", "Plain"], "an HSB color and an unknown block are skipped"); + assert_eq!(lib.swatches[2].paint.color(), Some(Color::rgb(1.0, 0.0, 0.0)), "clamped, NaN read as 0"); + assert!(lib.swatches[2].global && !lib.swatches[4].global, "without a color type: process"); + // A group start ends the open group, and groups and colors share names. + let groups: Vec<(&str, Vec<&str>)> = lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect(); + assert_eq!(groups, [("Color Group", vec![]), ("Red 3", vec!["Red 4"])]); + assert_eq!(lib.groups[1].swatches[0].paint.color(), Some(Color::gray(0.0)), "gray level 1 is white"); +} + +#[test] +fn damaged_ase_files_are_errors() { + let good = ase(&[(ASE_GROUP_START, ase_name("G")), ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0)]); + assert_eq!(read_bytes(&good, "x").unwrap().len(), 1); + for n in ASE_SIGNATURE.len()..good.len() { + assert!(read_bytes(&good[..n], "x").is_err(), "cut at {n}"); + } + let mut v2 = good.clone(); + v2[5] = 2; + assert!(read_bytes(&v2, "x").unwrap_err().contains("2.0"), "version 2.0"); + // Too many colors, or too many groups (empty group starts take 6 bytes each). + let colors: Vec<(u16, Vec)> = (0..=ASE_MAX_ENTRIES).map(|_| ase_color("Gray", b"Gray", &[0.5], 2)).collect(); + assert!(read_bytes(&ase(&colors), "x").unwrap_err().contains("more than")); + let groups: Vec<(u16, Vec)> = (0..=ASE_MAX_ENTRIES).map(|_| (ASE_GROUP_START, vec![])).collect(); + assert!(read_bytes(&ase(&groups), "x").unwrap_err().contains("more than")); + assert_eq!(read_bytes(&ase(&groups[1..]), "x").unwrap().groups.len(), ASE_MAX_ENTRIES, "up to the limit"); +} + +#[test] +fn ase_writes_each_model_kind_and_group() { + let sw = |name: &str, color, global, spot| Swatch { name: name.into(), paint: Paint::solid(color), global, spot }; + let tint = Swatch { + name: "Ink 40%".into(), + paint: Paint::Solid { color: Color::cmyk(0.4, 0.2, 0.0, 0.08), swatch: Some("Ink".into()), tint: 0.4 }, + global: false, + spot: false, + }; + // `sample()` holds the spot color Ink, the gradient Fade, the pattern Tiles and the group Neutrals. + let mut lib = sample(); + lib.swatches.insert(0, sw("Sky", Color::rgb(0.0, 0.5, 1.0), true, false)); + lib.swatches.push(tint); + lib.groups[0].swatches = vec![sw("Mist", Color::gray(0.25), false, false), sw("Clay", Color::lab(50.0, 20.0, -30.0), false, false)]; + lib.groups.push(SwatchGroup { name: "Empty".into(), swatches: vec![] }); + let bytes = write(&lib, PaletteFormat::Ase).unwrap(); + let expected = ase(&[ + ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0), + ase_color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1), + ase_color("Ink 40%", b"CMYK", &[0.4, 0.2, 0.0, 0.08], 2), + (ASE_GROUP_START, ase_name("Neutrals")), + ase_color("Mist", b"Gray", &[0.75], 2), + ase_color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2), + (ASE_GROUP_END, vec![]), + (ASE_GROUP_START, ase_name("Empty")), + (ASE_GROUP_END, vec![]), + ]); + assert_eq!(bytes, expected, "no gradient or pattern; the tint as the process color it shows"); + let back = read_bytes(&bytes, "Brand").unwrap(); + assert_eq!((back.len(), back.groups.len()), (5, 2), "the empty group stays"); + assert_eq!(PaletteFormat::parse(".ASE"), Some(PaletteFormat::Ase)); + assert!(PaletteFormat::Ase.readable() && PaletteFormat::Ase.binary() && !PaletteFormat::Gpl.binary()); +} + +#[test] +fn ase_names_lose_nul_and_stop_at_the_reader_limit() { + let names = ["Re\0d".to_string(), "é".repeat(1030), format!("a{}", "🎨".repeat(600))]; + let swatches = names.iter().map(|n| Swatch { name: n.clone(), paint: Paint::solid(Color::BLACK), global: false, spot: false }).collect(); + let lib = SwatchLibrary { name: "x".into(), swatches, groups: vec![] }; + let back = read_bytes(&write(&lib, PaletteFormat::Ase).unwrap(), "x").unwrap(); + let got: Vec<&str> = back.swatches.iter().map(|w| w.name.as_str()).collect(); + // At most 1024 UTF-16 code units, cut between characters: "a" and 511 two-unit emoji. + assert_eq!(got, ["Red".to_string(), "é".repeat(1024), format!("a{}", "🎨".repeat(511))]); +} + +#[test] +fn ase_clamps_components_and_writes_non_finite_ones_as_zero() { + let sw = |name: &str, color| Swatch { name: name.into(), paint: Paint::solid(color), global: false, spot: false }; + let swatches = vec![ + sw("Lab", Color::lab(100.5, 300.0, -300.0)), + sw("Rgb", Color::rgb(2.0, -1.0, f32::NAN)), + sw("Cmyk", Color::cmyk(1.5, 0.0, 0.0, f32::INFINITY)), + sw("Gray", Color::gray(1.5)), + ]; + let bytes = write(&SwatchLibrary { name: "x".into(), swatches, groups: vec![] }, PaletteFormat::Ase).unwrap(); + let expected = ase(&[ + ase_color("Lab", b"LAB ", &[1.0, 127.0, -128.0], 2), + ase_color("Rgb", b"RGB ", &[1.0, 0.0, 0.0], 2), + ase_color("Cmyk", b"CMYK", &[1.0, 0.0, 0.0, 0.0], 2), + ase_color("Gray", b"Gray", &[0.0], 2), + ]); + assert_eq!(bytes, expected, "clamped to the ranges .ase holds, a component that isn't finite as 0"); + // Lightness 100.5 is written as 1, which reads back as L* 100. + let back = read_bytes(&bytes, "x").unwrap(); + assert_eq!(back.swatches[0].paint.color(), Some(Color::lab(100.0, 127.0, -128.0))); +} + +#[test] +fn ase_write_refuses_more_entries_than_the_reader_takes() { + let gray = |i: usize| Swatch { name: format!("G{i}"), paint: Paint::solid(Color::gray(0.5)), global: false, spot: false }; + // The limit counts colors and groups: a group and `ASE_MAX_ENTRIES - 1` colors reach it. + let mut lib = SwatchLibrary { + name: "x".into(), + swatches: (1..ASE_MAX_ENTRIES).map(gray).collect(), + groups: vec![SwatchGroup { name: "Group".into(), swatches: vec![] }], + }; + let back = read_bytes(&write(&lib, PaletteFormat::Ase).unwrap(), "x").unwrap(); + assert_eq!((back.len(), back.groups.len()), (ASE_MAX_ENTRIES - 1, 1)); + lib.swatches.push(gray(0)); + let e = write(&lib, PaletteFormat::Ase).unwrap_err(); + assert!(e.contains("reads at most 100000 colors and groups from a swatch exchange file, and this library has 100001"), "{e}"); + // A gradient is left out and is not counted. + lib.swatches.last_mut().unwrap().paint = sample().swatches[1].paint.clone(); + assert!(write(&lib, PaletteFormat::Ase).is_ok()); +} + +/// A color in one of the four models, in the ranges `.ase` holds. +fn arb_color() -> impl Strategy { + let unit = || 0.0f32..=1.0; + prop_oneof![ + (unit(), unit(), unit()).prop_map(|(r, g, b)| Color::rgb(r, g, b)), + (unit(), unit(), unit(), unit()).prop_map(|(c, m, y, k)| Color::cmyk(c, m, y, k)), + unit().prop_map(Color::gray), + (0.0f32..=100.0, -128.0f32..=127.0, -128.0f32..=127.0).prop_map(|(l, a, b)| Color::lab(l, a, b)), + ] +} + +/// A swatch's paint with its global and spot flags: a solid color with any flags, a tint swatch +/// (both flags off) or a gradient. +fn arb_paint() -> impl Strategy { + prop_oneof![ + 4 => (arb_color(), any::(), any::()).prop_map(|(c, global, spot)| (Paint::solid(c), global, spot)), + 1 => arb_color().prop_map(|c| (Paint::Solid { color: c, swatch: Some("Base".into()), tint: 0.4 }, false, false)), + 1 => Just((sample().swatches[1].paint.clone(), false, false)), + ] +} + +/// Ungrouped swatches and color groups. A name is a number and up to 12 characters of any script +/// but NUL, trimmed, so swatches and groups have unique names, as in a document. +fn arb_library() -> impl Strategy { + let swatches = || prop::collection::vec((arb_paint(), "[^\\x00]{0,12}"), 0..12); + (swatches(), prop::collection::vec(("[^\\x00]{0,12}", swatches()), 0..4)).prop_map(|(loose, groups)| { + let mut n = 0; + let mut name = |prefix: &str, base: &str| { + n += 1; + format!("{prefix}{n} {base}").trim().to_string() + }; + let mut lib = SwatchLibrary { name: "Fuzz".into(), ..Default::default() }; + for ((paint, global, spot), base) in loose { + lib.swatches.push(Swatch { name: name("", &base), paint, global, spot }); + } + for (base, list) in groups { + let mut g = SwatchGroup { name: name("G", &base), swatches: vec![] }; + for ((paint, global, spot), base) in list { + g.swatches.push(Swatch { name: name("", &base), paint, global, spot }); + } + lib.groups.push(g); + } + lib + }) +} + +/// Are `got` and `want` in the same model, with every component within 1e-4? Lab lightness and +/// gray read back within `f32` rounding. +fn close(got: Color, want: Color) -> bool { + let near = |a: f32, b: f32| (a - b).abs() < 1e-4; + match (got, want) { + (Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => near(r, r2) && near(g, g2) && near(b, b2), + (Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => near(c, c2) && near(m, m2) && near(y, y2) && near(k, k2), + (Color::Gray { k }, Color::Gray { k: k2 }) => near(k, k2), + (Color::Lab { l, a, b }, Color::Lab { l: l2, a: a2, b: b2 }) => near(l, l2) && near(a, a2) && near(b, b2), + _ => false, + } +} + +/// The swatches of `list` as an `.ase` file reads them back: solid colors only, unlinked, spot +/// colors global. +fn ase_expected(list: &[Swatch]) -> Vec { + list.iter() + .filter_map(|w| Some(Swatch { name: w.name.clone(), paint: Paint::solid(w.paint.color()?), global: w.global || w.spot, spot: w.spot })) + .collect() +} + +/// Do swatches `got` have the names, flags and unlinked colors (within 1e-4) of `want`? +fn same_swatches(got: &[Swatch], want: &[Swatch]) -> bool { + got.len() == want.len() + && got.iter().zip(want).all(|(g, w)| { + let color = match (&g.paint, w.paint.color()) { + (Paint::Solid { color, swatch: None, .. }, Some(c)) => close(*color, c), + _ => false, + }; + g.name == w.name && g.global == w.global && g.spot == w.spot && color + }) +} + +proptest! { + #![proptest_config(ProptestConfig { failure_persistence: None, ..ProptestConfig::default() })] + + /// A written `.ase` file reads back as the library's solid colors in their own model, with + /// their names, kinds and color groups. + #[test] + fn ase_round_trip_keeps_models_kinds_and_groups(lib in arb_library()) { + let bytes = write(&lib, PaletteFormat::Ase).unwrap(); + prop_assert!(sniff_bytes(&bytes)); + let back = read_bytes(&bytes, &lib.name).unwrap(); + prop_assert_eq!(&back.name, &lib.name); + prop_assert!(same_swatches(&back.swatches, &ase_expected(&lib.swatches)), "{:?}", back.swatches); + prop_assert_eq!(back.groups.len(), lib.groups.len()); + for (g, want) in back.groups.iter().zip(&lib.groups) { + prop_assert_eq!(&g.name, &want.name); + prop_assert!(same_swatches(&g.swatches, &ase_expected(&want.swatches)), "{}: {:?}", g.name, g.swatches); + } + } + + /// A written `.vcswatches`, `.gpl` or `.ase` file reads back with as many swatches as + /// [`PaletteFormat::holds`] counts. + #[test] + fn written_files_read_back_with_the_swatches_holds_counts(lib in arb_library()) { + for f in [PaletteFormat::Native, PaletteFormat::Gpl, PaletteFormat::Ase] { + let back = read_bytes(&write(&lib, f).unwrap(), &lib.name).unwrap(); + prop_assert_eq!(back.len(), lib.iter().filter(|w| f.holds(&w.paint)).count(), "{:?}", f); + } + } +} diff --git a/crates/color/src/recolor.rs b/crates/color/src/recolor.rs index ef63fe845a..818a5fbe49 100644 --- a/crates/color/src/recolor.rs +++ b/crates/color/src/recolor.rs @@ -264,6 +264,8 @@ pub struct RowMap { mean_l: f32, /// Hue turn from the key colour to the new colour (Hue Shift). turn: f32, + /// Whether colours take the new colour in its own model, not in the model they had. + own_model: bool, } impl RowMap { @@ -274,7 +276,20 @@ impl RowMap { Method::TintsShades => mean_l(&row.iter().map(|c| (*c, c.to_lab())).collect::>()), _ => 0.0, }; - Self { method, to, key, mean_l, turn: to.to_hsb()[0] - key.to_hsb()[0] } + Self { method, to, key, mean_l, turn: to.to_hsb()[0] - key.to_hsb()[0], own_model: false } + } + + /// With `own`, current colours take the new colour in the new colour's model (an RGB colour + /// replaced by a CMYK one becomes CMYK) instead of keeping the model they had. + pub fn with_own_model(mut self, own: bool) -> Self { + self.own_model = own; + self + } + + /// True when current colour `c` keeps a colour model other than the new colour's (so the new + /// colour is converted into `c`'s model and may look different from what was asked for). + pub fn converts(&self, c: Color) -> bool { + !self.own_model && c.model() != self.to.model() } /// The colour of the row the new colour stands for. @@ -301,7 +316,7 @@ impl RowMap { /// The new colour of current colour `c`, in `c`'s model. pub fn map(&self, c: Color) -> Color { - let to = keep_model(c, self.to); + let to = if self.own_model { self.to } else { keep_model(c, self.to) }; match self.method { Method::Exact => to, Method::PreserveTints if is_tint(c, self.key) => to.tinted(tint_of(c, self.key)), @@ -314,7 +329,13 @@ impl RowMap { Method::HueShift if c == self.key => to, Method::HueShift => { let [h, s, v] = c.to_hsb(); - if s <= 0.0 { c } else { keep_model(c, Color::from_hsb(h + self.turn, s, v)) } + if s <= 0.0 { + if self.own_model { c.in_model(self.to.model()) } else { c } + } else if self.own_model { + Color::from_hsb(h + self.turn, s, v).in_model(self.to.model()) + } else { + keep_model(c, Color::from_hsb(h + self.turn, s, v)) + } } } } @@ -576,6 +597,16 @@ mod tests { assert!(cluster(&[], &[], 3).is_empty()); } + #[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); + let row = [Color::rgb(0.2, 0.2, 0.9), Color::rgb(0.1, 0.1, 0.5), Color::rgb(0.3, 0.3, 0.3)]; + let own = RowMap::new(Method::HueShift, &row, to).with_own_model(true); + assert!(row.iter().all(|c| own.map(*c).model() == to.model()), "key and other colours alike"); + let kept = RowMap::new(Method::HueShift, &row, to); + assert!(row.iter().all(|c| kept.map(*c).model() == c.model())); + } + #[test] fn palette_snaps_to_the_nearest_colour() { let p = Palette::new([Color::rgb(1.0, 0.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0), Color::gray(0.5)]); diff --git a/crates/color/src/swatch.rs b/crates/color/src/swatch.rs index 21f9af988b..12ae31220a 100644 --- a/crates/color/src/swatch.rs +++ b/crates/color/src/swatch.rs @@ -123,13 +123,13 @@ fn base_swatches() -> (Vec, Vec) { .collect(); let grad = |name: &str, a: &str, b: &str, kind: GradientKind| Swatch { name: name.into(), - paint: Paint::Gradient(Box::new(crate::GradientPaint::new(Gradient { + paint: Paint::Gradient(Box::new(crate::GradientPaint::new(Gradient::new( kind, - stops: vec![ + vec![ GradientStop::new(0.0, Color::from_hex(a).unwrap_or(Color::WHITE)), GradientStop::new(1.0, Color::from_hex(b).unwrap_or(Color::BLACK)), ], - }))), + )))), global: false, spot: false, }; diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 5260be9104..0ee88bf3b7 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -20,6 +20,7 @@ zune-jpeg = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } +chrono = { workspace = true } [dev-dependencies] jpeg-encoder = { workspace = true } diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index b336ff1529..4ac758ffa9 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -4,658 +4,14 @@ use serde::{Deserialize, Serialize}; use vectorcraft_color::{BlendMode, Color, Paint}; -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum LineCap { - #[default] - Butt, - Round, - Square, -} +mod layers; +mod profile; +mod stroke_style; -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum LineJoin { - #[default] - Miter, - Round, - Bevel, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum StrokeAlign { - #[default] - Center, - Inside, - Outside, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct Dash { - /// Dash, gap, dash, gap… (up to 6 values in the Stroke panel). - pub pattern: Vec, - #[serde(default)] - pub offset: f64, - /// "Aligns dashes to corners and path ends, adjusting lengths to fit". - #[serde(default)] - pub align_corners: bool, -} - -impl Dash { - /// Whether the pattern draws dashes. As in PDF (`d` operator) and SVG (`stroke-dasharray`), a - /// pattern with a negative or non-finite value, or whose values are all zero, is invalid and the - /// stroke is drawn solid. - pub fn is_dashed(&self) -> bool { - self.pattern.iter().all(|v| v.is_finite() && *v >= 0.0) && self.pattern.iter().any(|v| *v > 0.0) - } - /// Scale the dash and gap lengths and the offset by `s`. - pub fn scale(&mut self, s: f64) { - self.pattern.iter_mut().for_each(|v| *v *= s); - self.offset *= s; - } -} - -/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum Arrowhead { - Triangle, - TriangleOpen, - Circle, - CircleOpen, - Square, - SquareOpen, - Bar, - Diamond, - Arrow, - ArrowOpen, - Barbed, - /// One barb, on the left of the direction the head points. - HalfArrowLeft, - /// One barb, on the right of the direction the head points. - HalfArrowRight, - Concave, - DoubleBar, - Feather, - DotOnBar, - Chevron, - DoubleArrow, - Target, - Star, - Cross, - Plus, - Hexagon, - HexagonOpen, - Tag, - TagOpen, - HalfCircle, - Drop, - Slash, - DoubleSlash, - DiamondOpen, - TriangleReverse, - Swallowtail, - Bracket, - Fork, - Leaf, - Kite, - TriangleBar, - Oval, -} - -impl Arrowhead { - /// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks). - pub const ALL: [Arrowhead; 40] = [ - Arrowhead::Arrow, - Arrowhead::ArrowOpen, - Arrowhead::Barbed, - Arrowhead::Concave, - Arrowhead::DoubleArrow, - Arrowhead::HalfArrowLeft, - Arrowhead::HalfArrowRight, - Arrowhead::Chevron, - Arrowhead::Feather, - Arrowhead::Swallowtail, - Arrowhead::Triangle, - Arrowhead::TriangleOpen, - Arrowhead::TriangleReverse, - Arrowhead::TriangleBar, - Arrowhead::Kite, - Arrowhead::Leaf, - Arrowhead::Drop, - Arrowhead::Circle, - Arrowhead::CircleOpen, - Arrowhead::HalfCircle, - Arrowhead::Oval, - Arrowhead::Target, - Arrowhead::Square, - Arrowhead::SquareOpen, - Arrowhead::Tag, - Arrowhead::TagOpen, - Arrowhead::Diamond, - Arrowhead::DiamondOpen, - Arrowhead::Hexagon, - Arrowhead::HexagonOpen, - Arrowhead::Star, - Arrowhead::Cross, - Arrowhead::Plus, - Arrowhead::Bar, - Arrowhead::DoubleBar, - Arrowhead::DotOnBar, - Arrowhead::Slash, - Arrowhead::DoubleSlash, - Arrowhead::Bracket, - Arrowhead::Fork, - ]; - - /// The name the arrowhead menus show. - pub fn label(self) -> &'static str { - match self { - Arrowhead::Triangle => "Triangle", - Arrowhead::TriangleOpen => "Triangle (open)", - Arrowhead::Circle => "Circle", - Arrowhead::CircleOpen => "Circle (open)", - Arrowhead::Square => "Square", - Arrowhead::SquareOpen => "Square (open)", - Arrowhead::Bar => "Bar", - Arrowhead::Diamond => "Diamond", - Arrowhead::Arrow => "Arrow", - Arrowhead::ArrowOpen => "Arrow (open)", - Arrowhead::Barbed => "Barbed", - Arrowhead::HalfArrowLeft => "Half Arrow (left)", - Arrowhead::HalfArrowRight => "Half Arrow (right)", - Arrowhead::Concave => "Concave", - Arrowhead::DoubleBar => "Double Bar", - Arrowhead::Feather => "Feather", - Arrowhead::DotOnBar => "Dot on Bar", - Arrowhead::Chevron => "Chevron", - Arrowhead::DoubleArrow => "Double Arrow", - Arrowhead::Target => "Target", - Arrowhead::Star => "Star", - Arrowhead::Cross => "Cross", - Arrowhead::Plus => "Plus", - Arrowhead::Hexagon => "Hexagon", - Arrowhead::HexagonOpen => "Hexagon (open)", - Arrowhead::Tag => "Tag", - Arrowhead::TagOpen => "Tag (open)", - Arrowhead::HalfCircle => "Half Circle", - Arrowhead::Drop => "Drop", - Arrowhead::Slash => "Slash", - Arrowhead::DoubleSlash => "Double Slash", - Arrowhead::DiamondOpen => "Diamond (open)", - Arrowhead::TriangleReverse => "Reverse Triangle", - Arrowhead::Swallowtail => "Swallowtail", - Arrowhead::Bracket => "Bracket", - Arrowhead::Fork => "Fork", - Arrowhead::Leaf => "Leaf", - Arrowhead::Kite => "Kite", - Arrowhead::TriangleBar => "Triangle to Bar", - Arrowhead::Oval => "Oval", - } - } -} - -/// Where an arrowhead sits relative to the end of its path. In both modes the stroke stops under -/// the head, so the line never shows through a hollow head or past its tip. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum ArrowAlign { - /// The tip extends past the end point (the path keeps its length). - #[default] - Extend, - /// The tip sits on the end point (the stroke is shortened by the head). - Tip, -} - -/// Variable-width profile: (position 0..1 along the path, left width factor, right width factor), -/// in order along the path. Two points at the same position make a discontinuous point: the -/// first is the width just before it, the second the width just after it (a step). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct WidthProfile { - pub points: Vec<(f64, f64, f64)>, -} - -/// A built-in width profile (the Stroke panel's Profile list). -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct ProfilePreset { - /// Stable id used by `stroke.set {profile}`. - pub id: &'static str, - /// Menu label. - pub label: &'static str, - /// (t, left, right) width points. - pub points: &'static [(f64, f64, f64)], -} - -impl WidthProfile { - /// (left, right) width factors at `t`, linear between points. - 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). - pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) { - if p.is_empty() { - return (1.0, 1.0); - } - if t <= p[0].0 { - return (p[0].1, p[0].2); - } - for w in p.windows(2) { - if t <= w[1].0 { - let u = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-9); - return (w[0].1 + (w[1].1 - w[0].1) * u, w[0].2 + (w[1].2 - w[0].2) * u); - } - } - p.last().map_or((1.0, 1.0), |l| (l.1, l.2)) - } - /// The built-in profiles, in menu order. "uniform" is the plain stroke (no profile). - pub const PRESETS: [ProfilePreset; 7] = [ - ProfilePreset { id: "uniform", label: "Uniform", points: &[(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)] }, - ProfilePreset { id: "lens", label: "Lens", points: &[(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)] }, - ProfilePreset { id: "taperStart", label: "Taper Start", points: &[(0.0, 0.0, 0.0), (1.0, 1.0, 1.0)] }, - ProfilePreset { id: "taperEnd", label: "Taper End", points: &[(0.0, 1.0, 1.0), (1.0, 0.0, 0.0)] }, - // Full width at both ends, pinched to a quarter in the middle. - ProfilePreset { id: "pinch", label: "Pinch", points: &[(0.0, 1.0, 1.0), (0.5, 0.25, 0.25), (1.0, 1.0, 1.0)] }, - // A round head a fifth of the way along, then a long taper to the end. - ProfilePreset { id: "teardrop", label: "Teardrop", points: &[(0.0, 0.0, 0.0), (0.2, 1.0, 1.0), (1.0, 0.0, 0.0)] }, - // 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 built-in profile with this id. - pub fn preset(id: &str) -> Option { - Self::PRESETS.iter().find(|p| p.id == id).map(|p| Self { points: p.points.to_vec() }) - } - /// The id of the built-in profile these points match, if any. - pub fn preset_id(&self) -> Option<&'static str> { - Self::PRESETS.iter().find(|p| p.points == self.points.as_slice()).map(|p| p.id) - } - /// The id of a stroke's profile: "uniform" without one, "custom" when it matches no preset. - pub fn id_of(p: Option<&Self>) -> &'static str { - p.map_or(Some("uniform"), Self::preset_id).unwrap_or("custom") - } - /// The lens profile (thin ends, full width in the middle). - pub fn lens() -> Self { - Self::preset("lens").unwrap_or_default() - } - pub fn taper_end() -> Self { - Self::preset("taperEnd").unwrap_or_default() - } - pub fn taper_start() -> Self { - Self::preset("taperStart").unwrap_or_default() - } - /// The (left, right) factors just before and just after `t`: they differ only at a - /// discontinuous point (two points at `t`, within `1e-7`). - pub fn around(&self, t: f64) -> ((f64, f64), (f64, f64)) { - let p = &self.points; - if let Some(i) = p.iter().position(|q| (q.0 - t).abs() <= 1e-7) { - let j = i + p[i..].iter().take_while(|q| (q.0 - p[i].0).abs() <= 1e-9).count() - 1; - if j > i { - return ((p[i].1, p[i].2), (p[j].1, p[j].2)); - } - } - let v = self.at(t); - (v, v) - } -} - -/// Pen pressure recorded along a stroke (the Paintbrush with a graphics tablet): (position 0..1 -/// along the path, pressure 0..1) samples in order, positions measured as a [`WidthProfile`]'s -/// are. Calligraphic brushes with Pressure variation read it; everything else ignores it. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct PressureProfile { - pub points: Vec<(f64, f64)>, -} - -impl PressureProfile { - /// The pressure of a stroke drawn without one (a mouse, or a path the brush was applied to): - /// half way, so a Pressure brush draws its own value there. - pub const MID: f64 = 0.5; - /// The most samples a stroke keeps (after simplifying them). - pub const MAX_POINTS: usize = 512; - /// How far (in pressure) simplifying may move the recorded curve. - const TOLERANCE: f64 = 0.01; - - /// The pressure at `t` (0..1), linear between samples; [`Self::MID`] without any. - pub fn at(&self, t: f64) -> f64 { - let p = &self.points; - let (Some(first), Some(last)) = (p.first(), p.last()) else { return Self::MID }; - let v = if t <= first.0 { - first.1 - } else { - p.windows(2) - .find_map(|w| match w { - [a, b] if t <= b.0 => Some(a.1 + (b.1 - a.1) * ((t - a.0) / (b.0 - a.0).max(1e-9)).clamp(0.0, 1.0)), - _ => None, - }) - .unwrap_or(last.1) - }; - if v.is_finite() { v.clamp(0.0, 1.0) } else { Self::MID } - } - - /// A profile from (position, pressure) samples in order along the stroke: values are clamped - /// into 0..1 (non-finite ones dropped), the curve is simplified to within 1 % and kept to - /// [`Self::MAX_POINTS`]. `None` without a sample. - pub fn from_samples(samples: impl IntoIterator) -> Option { - let pts: Vec<(f64, f64)> = - samples.into_iter().filter(|(t, p)| t.is_finite() && p.is_finite()).map(|(t, p)| (t.clamp(0.0, 1.0), p.clamp(0.0, 1.0))).collect(); - if pts.is_empty() { - return None; - } - // Simplifying is quadratic at worst: a huge stroke is thinned evenly first. - let mut pts = thin(pts, 16 * Self::MAX_POINTS); - // Positions only ever go forward. - let mut prev = 0.0; - for p in &mut pts { - p.0 = p.0.max(prev); - prev = p.0; - } - let keep = simplify_1d(&pts, Self::TOLERANCE); - let pts = thin(pts.iter().zip(keep).filter(|(_, k)| *k).map(|(p, _)| *p).collect(), Self::MAX_POINTS); - let round = |v: f64| (v * 1e4).round() / 1e4; - Some(Self { points: pts.into_iter().map(|(t, p)| (round(t), round(p))).collect() }) - } - - /// The pressure of a path `old_len` long (`old`; None: drawn without pressure) continued at its - /// end by a stroke `added_len` long (`added`). None when neither has pressure. - pub fn extended(old: Option<&Self>, old_len: f64, added: Option<&Self>, added_len: f64) -> Option { - if old.is_none() && added.is_none() { - return None; - } - let (old_len, added_len) = (old_len.max(0.0), added_len.max(0.0)); - let total = old_len + added_len; - if !total.is_finite() || total <= 1e-9 { - return old.or(added).cloned(); - } - let flat = Self { points: vec![(0.0, Self::MID), (1.0, Self::MID)] }; - let (old, added) = (old.unwrap_or(&flat), added.unwrap_or(&flat)); - let o = old_len / total; - let old_pts = old.points.iter().map(|&(t, p)| (t * o, p)); - Self::from_samples(old_pts.chain(added.points.iter().map(|&(u, p)| (o + u * (1.0 - o), p)))) - } - - /// The pressure of the path reversed. - pub fn reversed(&self) -> Self { - Self { points: self.points.iter().rev().map(|&(t, p)| (1.0 - t, p)).collect() } - } - - /// A light–heavy–light stroke, for previews of pressure-sensitive brushes. - pub fn sample() -> Self { - Self { points: vec![(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)] } - } -} - -/// At most `max` of `pts`, evenly spread (the ends kept). -fn thin(pts: Vec<(f64, f64)>, max: usize) -> Vec<(f64, f64)> { - let n = pts.len(); - if n <= max || max < 2 { - return pts; - } - (0..max).filter_map(|i| pts.get(i * (n - 1) / (max - 1)).copied()).collect() -} - -/// Douglas–Peucker over a function sampled at `pts`: which samples to keep so the polyline through -/// them stays within `tol` (vertically) of every sample. The ends are always kept. -fn simplify_1d(pts: &[(f64, f64)], tol: f64) -> Vec { - let mut keep = vec![false; pts.len()]; - let Some(last) = pts.len().checked_sub(1) else { return keep }; - for i in [0, last] { - if let Some(k) = keep.get_mut(i) { - *k = true; - } - } - let mut stack = vec![(0, last)]; - while let Some((i, j)) = stack.pop() { - let (Some(&a), Some(&b)) = (pts.get(i), pts.get(j)) else { continue }; - let line = |t: f64| if b.0 - a.0 > 1e-12 { a.1 + (b.1 - a.1) * (t - a.0) / (b.0 - a.0) } else { (a.1 + b.1) / 2.0 }; - let far = (i + 1..j).filter_map(|k| pts.get(k).map(|q| (k, (q.1 - line(q.0)).abs()))).max_by(|x, y| x.1.total_cmp(&y.1)); - if let Some((k, d)) = far - && d > tol - { - if let Some(f) = keep.get_mut(k) { - *f = true; - } - stack.push((i, k)); - stack.push((k, j)); - } - } - keep -} - -/// A width profile saved to the Profile list under a name (Add to Profiles), kept with the -/// preferences. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct SavedProfile { - pub name: String, - pub profile: WidthProfile, -} - -/// A live effect in an appearance stack. Parameters are interpreted by `vectorcraft-effects`. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Effect { - /// Stable id, e.g. `stylize.dropShadow`, `distort.roughen`, `path.offsetPath`, `warp.arc`. - pub id: String, - #[serde(default)] - pub params: serde_json::Value, - #[serde(default = "yes")] - pub visible: bool, -} - -fn yes() -> bool { - true -} -fn one() -> f32 { - 1.0 -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct FillLayer { - pub paint: Paint, - #[serde(default = "one", skip_serializing_if = "crate::skip::is_one")] - pub opacity: f32, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub blend: BlendMode, - #[serde(default = "yes", skip_serializing_if = "crate::skip::is_true")] - pub visible: bool, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub effects: Vec, - /// Overprint Fill: on press the fill's inks print over the inks below instead of knocking - /// them out (Overprint Preview and Separations Preview show it). - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub overprint: bool, -} - -impl FillLayer { - pub fn new(paint: Paint) -> Self { - Self { paint, opacity: 1.0, blend: BlendMode::Normal, visible: true, effects: vec![], overprint: false } - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct StrokeLayer { - pub paint: Paint, - /// Weight in points. - pub width: f64, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub cap: LineCap, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub join: LineJoin, - #[serde(default = "ten", skip_serializing_if = "is_ten")] - pub miter_limit: f64, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub align: StrokeAlign, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub dash: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub start_arrow: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub end_arrow: Option, - /// Arrowhead scale in percent (start, end). - #[serde(default = "hundreds", skip_serializing_if = "is_hundreds")] - pub arrow_scale: (f64, f64), - #[serde(default, skip_serializing_if = "Option::is_none")] - pub profile: Option, - /// Brush applied to the stroke (by brush name). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub brush: Option, - #[serde(default = "one", skip_serializing_if = "crate::skip::is_one")] - pub opacity: f32, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub blend: BlendMode, - #[serde(default = "yes", skip_serializing_if = "crate::skip::is_true")] - pub visible: bool, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub effects: Vec, - /// Arrowhead placement at both ends. - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub arrow_align: ArrowAlign, - /// Overprint Stroke (see [`FillLayer::overprint`]). - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub overprint: bool, - /// How a gradient paint maps onto the stroke (within, along or across it). - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub gradient_mode: StrokeGradientMode, - /// The pen pressure the stroke was drawn with (Paintbrush with a tablet): pressure-sensitive - /// brushes vary with it. It belongs to this path's shape, so appearances copied to other - /// art leave it behind ([`Appearance::without_pressure`]). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub pressure: Option, -} - -/// How a gradient on a stroke is laid out (the Gradient panel's Stroke buttons). Saved by variant -/// name: new modes are appended, never renamed. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum StrokeGradientMode { - /// Placed on the page like a fill's gradient and seen through the stroke. - #[default] - Within, - /// From the start of each subpath to its end, following the path. - Along, - /// From the stroke's left edge to its right edge (left of the path's direction), all along it. - Across, -} - -impl StrokeGradientMode { - pub const ALL: [StrokeGradientMode; 3] = [StrokeGradientMode::Within, StrokeGradientMode::Along, StrokeGradientMode::Across]; - /// The name commands use (`within`, `along`, `across`). - pub fn name(self) -> &'static str { - match self { - StrokeGradientMode::Within => "within", - StrokeGradientMode::Along => "along", - StrokeGradientMode::Across => "across", - } - } - /// Parse a mode name (any case). - pub fn parse(s: &str) -> Option { - Self::ALL.into_iter().find(|m| m.name().eq_ignore_ascii_case(s)) - } -} - -/// How far any arrowhead reaches from its tip, in units of its weight (the open arrow's arms are -/// cut square a little behind its 4 × 4 box). -pub(crate) const HEAD_REACH: f64 = 4.6; - -fn ten() -> f64 { - 10.0 -} -fn hundreds() -> (f64, f64) { - (100.0, 100.0) -} -fn is_ten(v: &f64) -> bool { - *v == 10.0 -} -fn is_hundreds(v: &(f64, f64)) -> bool { - *v == (100.0, 100.0) -} - -impl StrokeLayer { - pub fn new(paint: Paint, width: f64) -> Self { - Self { - paint, - width, - cap: LineCap::Butt, - join: LineJoin::Miter, - miter_limit: 10.0, - align: StrokeAlign::Center, - dash: None, - start_arrow: None, - end_arrow: None, - arrow_scale: (100.0, 100.0), - profile: None, - brush: None, - opacity: 1.0, - blend: BlendMode::Normal, - visible: true, - effects: vec![], - arrow_align: ArrowAlign::Extend, - overprint: false, - gradient_mode: StrokeGradientMode::Within, - pressure: None, - } - } - /// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least - /// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide. - pub fn arrow_weight(&self, end: bool) -> f64 { - let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 }; - (self.width * pct / 100.0).max(0.25) - } - /// 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, |_| HEAD_REACH * 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 { - self.head_reach(false).max(self.head_reach(true)) - } - /// The widest the width profile makes the stroke, as a factor of its weight (1 without one). - pub fn profile_max(&self) -> f64 { - self.profile.as_ref().and_then(|p| p.points.iter().map(|&(_, l, r)| l.max(r)).reduce(f64::max)).unwrap_or(1.0).max(0.0) - } - /// The stroke's body across a path that is `closed` or open: how far it reaches from the path - /// at full width (half the weight centred; the whole weight on one side when aligned inside or - /// outside a closed path, which open paths ignore), and for aligned strokes which side it - /// paints (`Some(true)`: inside). - pub fn body(&self, closed: bool) -> (f64, Option) { - match self.align { - StrokeAlign::Outside if closed => (self.width, Some(false)), - StrokeAlign::Inside if closed => (self.width, Some(true)), - _ => (self.width / 2.0, None), - } - } - /// How far the body paints outside a path that is `closed` or open, at the profile's widest. - pub fn side_reach(&self, closed: bool) -> f64 { - match self.body(closed) { - (_, Some(true)) => 0.0, - (half, _) => half * self.profile_max(), - } - } - /// The farthest this stroke can paint from any path: its body, miter spikes up to the miter - /// limit, projecting caps' corners and the arrowheads ([`Appearance::outset`]). - pub fn reach(&self) -> f64 { - let side = self.side_reach(true).max(self.side_reach(false)); - let miter = if self.join == LineJoin::Miter { self.miter_limit.max(1.0) } else { 1.0 }; - let cap = if self.cap == LineCap::Square { std::f64::consts::SQRT_2 } else { 1.0 }; - (side * miter.max(cap)).max(self.arrow_reach()) - } - /// The box an unplaced gradient on this stroke fits to (see [`stroke_paint_bounds`]). - pub fn paint_bounds(&self, geometric: vectorcraft_geom::Rect) -> vectorcraft_geom::Rect { - stroke_paint_bounds(geometric, self.width) - } - /// The gradient this stroke lays along or across its path: its linear or radial gradient - /// paint when [`Self::gradient_mode`] isn't Within (freeform gradients always paint within). - pub fn path_gradient(&self) -> Option<&vectorcraft_color::GradientPaint> { - match &self.paint { - Paint::Gradient(g) - if self.gradient_mode != StrokeGradientMode::Within && g.gradient.kind != vectorcraft_color::GradientKind::Freeform => - { - Some(g) - } - _ => None, - } - } -} - -/// The box an unplaced gradient on a stroke of `width` fits to: the geometric bounds grown by half -/// the weight (object strokes and type strokes alike, on screen and in exports). -pub fn stroke_paint_bounds(geometric: vectorcraft_geom::Rect, width: f64) -> vectorcraft_geom::Rect { - geometric.inflate(width / 2.0, width / 2.0) -} +pub(crate) use layers::HEAD_REACH; +pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds}; +pub use profile::{PressureProfile, ProfilePreset, SavedProfile, WidthProfile}; +pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign}; /// One entry of the appearance stack. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -1150,319 +506,105 @@ impl Appearance { } } -#[cfg(test)] -mod tests { - use super::*; +/// The most fills, strokes or effects a stack may have to be matched against another's +/// ([`align`]); a larger stack shares nothing with the others. +const MAX_ALIGNED: usize = 1024; - #[test] - fn hidden_attributes_show_again() { - let mut a = Appearance::default_art(); - assert!(!a.has_hidden() && !a.show_all()); - a.stroke_mut().unwrap().visible = false; - a.items[0].effects_mut().push(Effect { id: "distort.roughen".into(), params: serde_json::Value::Null, visible: false }); - assert!(a.has_hidden()); - assert!(a.show_all()); - assert!(!a.has_hidden() && a.items.iter().all(AppearanceItem::visible) && a.items[0].effects()[0].visible); +/// Where each entry of `first` is in `other`: the entries equal in both (`same`), matched in their +/// stacking order (a longest common subsequence, so the matches never cross), by index into +/// `other`; `None` where `other` has no equal entry left for it. +pub fn align(first: &[T], other: &[T], same: impl Fn(&T, &T) -> bool) -> Vec> { + let (n, m) = (first.len(), other.len()); + let mut out = vec![None; n]; + if n == 0 || m == 0 || n > MAX_ALIGNED || m > MAX_ALIGNED { + return out; } - - #[test] - fn basic_appearance() { - let a = Appearance::default_art(); - assert!(a.is_basic()); - assert_eq!(a.fill_paint(), Paint::solid(Color::WHITE)); - assert_eq!(a.stroke_width(), 1.0); - } - - #[test] - fn rebase_moves_fills_by_the_box_and_strokes_by_their_inflated_box() { - use vectorcraft_color::{Gradient, GradientGeom, GradientPaint}; - use vectorcraft_geom::{Point, Rect}; - let placed = |x: f64| { - let mut g = GradientPaint::new(Gradient::default()); - g.geom = Some(GradientGeom { start: Point::new(x, 0.0), end: Point::new(x + 10.0, 0.0), aspect: 1.0, focal: None }); - Paint::Gradient(Box::new(g)) - }; - let mut a = Appearance::basic(placed(0.0), placed(-5.0), 10.0); - a.rebase_gradients(Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(100.0, 0.0, 300.0, 100.0)); - let start = |p: Paint| match p { - Paint::Gradient(g) => g.geom.unwrap().start, - _ => panic!("a gradient"), - }; - // The fill's start stays on the left edge; the stroke's on its inflated box's (−5 → 95). - assert_eq!((start(a.fill_paint()), start(a.stroke_paint())), (Point::new(100.0, 0.0), Point::new(95.0, 0.0))); - } - - #[test] - fn items_by_index() { - let mut a = Appearance::default_art(); - a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::None))); - // [Fill white, Stroke black, Fill none] - assert_eq!(a.fill_at(None).unwrap().paint, Paint::None); - assert_eq!(a.fill_at(Some(0)).unwrap().paint, Paint::solid(Color::WHITE)); - assert!(a.fill_at(Some(1)).is_none() && a.stroke_at(Some(0)).is_none() && a.fill_at(Some(9)).is_none()); - assert_eq!(a.item_of_kind(Some(1), false), Some(1)); - assert_eq!(a.item_of_kind(Some(1), true), None); - assert_eq!(a.fill_for(Some(1)).unwrap().paint, Paint::None); - assert!(a.set_fill_at(Some(0), Paint::solid(Color::BLACK))); - assert!(!a.set_stroke_at(Some(0), Paint::None)); - assert_eq!(a.fill_at(Some(0)).unwrap().paint, Paint::solid(Color::BLACK)); - a.effects_mut(Some(1)).unwrap().push(Effect { id: "distort.roughen".into(), params: serde_json::Value::Null, visible: true }); - assert_eq!(a.effects_at(Some(1)).unwrap().len(), 1); - assert!(a.effects_at(None).unwrap().is_empty() && a.effects_mut(Some(3)).is_none()); - assert_eq!((a.items[1].kind_name(), a.items[2].kind_name()), ("stroke", "fill")); - } - - #[test] - fn basic_means_one_plain_fill_and_stroke() { - let stroke = || AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 1.0)); - let mut a = Appearance { items: vec![stroke(), stroke()], ..Appearance::default() }; - assert!(!a.is_basic(), "two strokes"); - a.items.pop(); - assert!(a.is_basic() && Appearance::default().is_basic()); - let mut b = Appearance::default_art(); - b.stroke_mut().unwrap().visible = false; - assert!(!b.is_basic(), "a hidden stroke"); - let mut c = Appearance::default_art(); - c.fill_mut().unwrap().opacity = 0.5; - assert!(!c.is_basic(), "fill opacity"); - let mut d = Appearance::default_art(); - d.items.push(AppearanceItem::Fill(FillLayer::new(Paint::None))); - assert!(!d.is_basic(), "two fills"); - let mut e = Appearance::default_art(); - e.effects.push(Effect { id: "distort.roughen".into(), params: serde_json::Value::Null, visible: true }); - assert!(!e.is_basic(), "an effect"); - } - - #[test] - fn set_creates_missing() { - let mut a = Appearance::default(); - a.set_fill(Paint::solid(Color::BLACK)); - a.set_stroke(Paint::solid(Color::WHITE)); - assert_eq!(a.items.len(), 2); - assert!(matches!(a.items[0], AppearanceItem::Fill(_))); - } - - /// #852: pen pressure is kept simplified along the stroke and read back by position. - #[test] - fn pressure_profile_samples_simplify_and_interpolate() { - // A steady ramp keeps only its ends; a bump keeps its peak. - let ramp = PressureProfile::from_samples((0..=100).map(|i| (i as f64 / 100.0, i as f64 / 100.0))).unwrap(); - assert_eq!(ramp.points, vec![(0.0, 0.0), (1.0, 1.0)]); - assert!((ramp.at(0.25) - 0.25).abs() < 1e-9); - let bump = PressureProfile::from_samples([(0.0, 0.2), (0.3, 0.2), (0.5, 0.9), (0.7, 0.2), (1.0, 0.2)]).unwrap(); - assert!(bump.points.contains(&(0.5, 0.9)) && (bump.at(0.4) - 0.55).abs() < 1e-9, "{bump:?}"); - // Junk is clamped or dropped; positions never go back; nothing at all is no profile. - let junk = PressureProfile::from_samples([(f64::NAN, 0.5), (0.5, 7.0), (0.2, -1.0), (2.0, f64::INFINITY)]).unwrap(); - assert_eq!(junk.points, vec![(0.5, 1.0), (0.5, 0.0)]); - assert!(PressureProfile::from_samples([(f64::NAN, 0.5)]).is_none()); - assert_eq!(PressureProfile::default().at(0.3), PressureProfile::MID); - // A long noisy stroke stays bounded. - let noisy = PressureProfile::from_samples((0..1_000_000).map(|i| (i as f64 / 1e6, (i % 2) as f64))).unwrap(); - assert!(noisy.points.len() <= PressureProfile::MAX_POINTS); - // Out-of-order points (a hand-edited file) still read within 0..1. - let odd = PressureProfile { points: vec![(1.0, 5.0), (0.0, -3.0)] }; - assert!((0.0..=1.0).contains(&odd.at(0.5))); - } - - #[test] - fn pressure_profile_extends_and_reverses() { - let old = PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }; - let added = PressureProfile { points: vec![(0.0, 1.0), (1.0, 0.0)] }; - // A 30 pt path continued by 10 pt: its ramp fills the first three quarters. - let joined = PressureProfile::extended(Some(&old), 30.0, Some(&added), 10.0).unwrap(); - assert!((joined.at(0.75) - 1.0).abs() < 1e-9 && (joined.at(0.375) - 0.5).abs() < 1e-9 && joined.at(1.0) == 0.0, "{joined:?}"); - // A side without pressure is half way. - let half = PressureProfile::extended(None, 10.0, Some(&added), 10.0).unwrap(); - assert_eq!(half.at(0.25), PressureProfile::MID); - assert!(PressureProfile::extended(None, 10.0, None, 10.0).is_none()); - assert_eq!(PressureProfile::extended(Some(&old), 0.0, None, f64::NAN), Some(old.clone())); - assert_eq!(old.reversed().points, vec![(0.0, 1.0), (1.0, 0.0)]); - } - - /// Strokes saved before pen pressure load as they were, and are written without it. - #[test] - fn strokes_without_pressure_round_trip_unchanged() { - let json = serde_json::to_value(StrokeLayer::new(Paint::None, 2.0)).unwrap(); - assert!(json.get("pressure").is_none()); - let st: StrokeLayer = serde_json::from_value(json).unwrap(); - assert_eq!(st.pressure, None); - let pressed = StrokeLayer { pressure: Some(PressureProfile::sample()), ..st }; - let back: StrokeLayer = serde_json::from_value(serde_json::to_value(&pressed).unwrap()).unwrap(); - assert_eq!(back, pressed); - let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0); - ap.stroke_mut().unwrap().pressure = Some(PressureProfile::sample()); - assert_eq!(ap.without_pressure().stroke().unwrap().pressure, None); - } - - #[test] - fn profile_interp() { - let p = WidthProfile::lens(); - assert_eq!(p.at(0.5), (1.0, 1.0)); - assert_eq!(p.at(0.25), (0.5, 0.5)); - assert_eq!(p.at(2.0), (0.0, 0.0)); - } - - #[test] - fn profile_presets_round_trip_their_ids() { - for p in WidthProfile::PRESETS { - let prof = WidthProfile::preset(p.id).unwrap(); - assert_eq!(prof.preset_id(), Some(p.id)); - assert_eq!(WidthProfile::id_of(Some(&prof)), p.id); + // `len[i][j]`: the longest match of `first[i..]` and `other[j..]`. + let w = m + 1; + let mut len = vec![0u16; (n + 1) * w]; + for i in (0..n).rev() { + for j in (0..m).rev() { + let here = match (first.get(i), other.get(j)) { + (Some(a), Some(b)) if same(a, b) => len.get((i + 1) * w + j + 1).copied().unwrap_or(0).saturating_add(1), + _ => len.get((i + 1) * w + j).copied().unwrap_or(0).max(len.get(i * w + j + 1).copied().unwrap_or(0)), + }; + if let Some(c) = len.get_mut(i * w + j) { + *c = here; + } } - assert_eq!(WidthProfile::id_of(None), "uniform"); - assert_eq!(WidthProfile::id_of(Some(&WidthProfile { points: vec![(0.0, 0.3, 0.3)] })), "custom"); - assert!(WidthProfile::preset("nope").is_none()); - assert_eq!(WidthProfile::lens().points, vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)]); } + let (mut i, mut j) = (0, 0); + while i < n && j < m { + let at = |a: usize, b: usize| len.get(a * w + b).copied().unwrap_or(0); + match (first.get(i), other.get(j)) { + (Some(a), Some(b)) if same(a, b) && at(i, j) == at(i + 1, j + 1).saturating_add(1) => { + if let Some(o) = out.get_mut(i) { + *o = Some(j); + } + i += 1; + j += 1; + } + _ if at(i + 1, j) >= at(i, j + 1) => i += 1, + _ => j += 1, + } + } + out +} - #[test] - fn arrowhead_names_are_stable_and_every_one_is_listed_once() { - // Saved files store these names: they may only ever be appended to. - const SAVED: [&str; 40] = [ - "Triangle", - "TriangleOpen", - "Circle", - "CircleOpen", - "Square", - "SquareOpen", - "Bar", - "Diamond", - "Arrow", - "ArrowOpen", - "Barbed", - "HalfArrowLeft", - "HalfArrowRight", - "Concave", - "DoubleBar", - "Feather", - "DotOnBar", - "Chevron", - "DoubleArrow", - "Target", - "Star", - "Cross", - "Plus", - "Hexagon", - "HexagonOpen", - "Tag", - "TagOpen", - "HalfCircle", - "Drop", - "Slash", - "DoubleSlash", - "DiamondOpen", - "TriangleReverse", - "Swallowtail", - "Bracket", - "Fork", - "Leaf", - "Kite", - "TriangleBar", - "Oval", - ]; - 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!(Arrowhead::ALL.iter().filter(|x| **x == a).count(), 1, "{name} in the menu once"); +/// What several objects' appearances share, as the Appearance panel lists a mixed selection: the +/// fills and strokes, and the object-level effects, that every one of them has an equal copy of, in +/// stacking order ([`align`]), each with where it is in every object's own stack. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SharedStack { + /// Each shared fill or stroke, in the first object's paint order: its index in each object's + /// `items` (the first object's first). + pub items: Vec>, + /// Each shared object-level effect: its index in each object's `effects`. + pub effects: Vec>, +} + +impl SharedStack { + /// The rows `appearances` share (see [`SharedStack`]). One appearance shares all of itself. + pub fn of(appearances: &[&Appearance]) -> Self { + let Some((first, rest)) = appearances.split_first() else { return Self::default() }; + fn shared(first: &[T], rest: Vec<&[T]>, same: impl Fn(&T, &T) -> bool + Copy) -> Vec> { + let maps: Vec>> = rest.iter().map(|o| align(first, o, same)).collect(); + (0..first.len()) + .filter_map(|i| { + let mut at = vec![i]; + for m in &maps { + at.push((*m.get(i)?)?); + } + Some(at) + }) + .collect() + } + Self { + items: shared(&first.items, rest.iter().map(|a| a.items.as_slice()).collect(), |a, b| a == b), + effects: shared(&first.effects, rest.iter().map(|a| a.effects.as_slice()).collect(), |a, b| a == b), } - let labels: std::collections::HashSet<&str> = Arrowhead::ALL.iter().map(|a| a.label()).collect(); - assert_eq!(labels.len(), Arrowhead::ALL.len(), "labels are distinct"); } - #[test] - fn arrow_align_defaults_to_extend_and_round_trips() { - let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); - assert_eq!(st.arrow_align, ArrowAlign::Extend); - // The default is not written, so older readers see the same JSON as before. - assert!(!serde_json::to_string(&st).unwrap().contains("arrow_align")); - let old: StrokeLayer = serde_json::from_str(r#"{"paint":{"type":"none"},"width":2.0}"#).unwrap(); - assert_eq!(old.arrow_align, ArrowAlign::Extend); - st.arrow_align = ArrowAlign::Tip; - let back: StrokeLayer = serde_json::from_str(&serde_json::to_string(&st).unwrap()).unwrap(); - assert_eq!(back, st); + /// Where the first object's fill or stroke `first` is in object `k`'s stack, when it is shared. + pub fn item_in(&self, first: usize, k: usize) -> Option { + self.items.iter().find(|at| at.first() == Some(&first))?.get(k).copied() } - #[test] - fn outset_covers_arrowheads() { - let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 4.0); - a.stroke_mut().unwrap().join = LineJoin::Round; - assert_eq!(a.outset(), 2.0); - let st = a.stroke_mut().unwrap(); - st.end_arrow = Some(Arrowhead::Triangle); - st.arrow_scale = (100.0, 200.0); - assert_eq!(st.arrow_weight(false), 4.0); - assert_eq!(st.arrow_weight(true), 8.0); - assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, HEAD_REACH * 8.0 + 2.0)); - // A 32 pt head whose tip sits up to its length (plus the cap) past the end point. - assert_eq!(a.outset(), HEAD_REACH * 8.0 + 2.0); - a.stroke_mut().unwrap().width = 0.01; - assert_eq!(a.stroke().unwrap().arrow_weight(true), 0.25, "heads keep a minimum size"); + /// Where the first object's object-level effect `first` is in object `k`'s effects, when shared. + pub fn effect_in(&self, first: usize, k: usize) -> Option { + self.effects.iter().find(|at| at.first() == Some(&first))?.get(k).copied() } - #[test] - fn outset_depends_on_align() { - let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0); - a.stroke_mut().unwrap().join = LineJoin::Round; - assert_eq!(a.outset(), 5.0); - a.stroke_mut().unwrap().align = StrokeAlign::Outside; - assert_eq!(a.outset(), 10.0); - // Open paths stroke inside-aligned strokes centred. - a.stroke_mut().unwrap().align = StrokeAlign::Inside; - assert_eq!(a.outset(), 5.0); - assert_eq!((a.stroke().unwrap().side_reach(true), a.stroke().unwrap().body(true)), (0.0, (10.0, Some(true)))); + /// Is the first object's fill or stroke `i` shared? + pub fn has_item(&self, i: usize) -> bool { + self.items.iter().any(|at| at.first() == Some(&i)) } - #[test] - fn outset_covers_miter_spikes_projecting_caps_and_profile_maxima() { - let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0); - // Miter joins can spike out to the limit × half the weight. - assert_eq!(a.outset(), 10.0); - let st = a.stroke_mut().unwrap(); - st.join = LineJoin::Bevel; - st.cap = LineCap::Square; - assert!((a.outset() - std::f64::consts::SQRT_2).abs() < 1e-12, "a projecting cap's corner"); - let st = a.stroke_mut().unwrap(); - st.cap = LineCap::Round; - st.profile = Some(WidthProfile { points: vec![(0.0, 0.5, 2.5), (1.0, 1.0, 1.0)] }); - assert_eq!(st.profile_max(), 2.5); - assert_eq!(a.outset(), 2.5); - a.stroke_mut().unwrap().paint = Paint::None; - assert_eq!(a.outset(), 0.0, "an unpainted stroke"); - } - - #[test] - fn contents_slot_follows_item_edits_and_round_trips() { - let fill = || AppearanceItem::Fill(FillLayer::new(Paint::None)); - let mut a = Appearance { items: vec![fill(), fill(), fill()], ..Appearance::default() }; - assert_eq!((a.contents_at(), a.split_contents().1.len()), (0, 3), "all items above by default"); - a.set_contents_at(1); - assert!(!a.is_basic()); - // [0 | 1 2]: removing below shifts the slot, removing above doesn't. - a.remove_item(2); - assert_eq!(a.contents_at(), 1); - a.remove_item(0); - assert_eq!((a.contents_at(), a.contents_index), (0, None)); - // Inserting next to the slot joins the item below it. - a.items.push(fill()); - a.set_contents_at(1); // [0 | 1] - a.insert_item(1, fill()); - assert_eq!(a.contents_at(), 2); - a.insert_item(3, fill()); // [0 1 | 2 3] - assert_eq!(a.contents_at(), 2); - // Moves keep their side when landing next to the slot, cross it otherwise. - assert_eq!(a.move_item(3, 2), Some(2)); - assert_eq!(a.contents_at(), 2, "stays above"); - a.move_item(3, 0); - assert_eq!(a.contents_at(), 3, "crossed below"); - a.move_item(0, 3); - assert_eq!(a.contents_at(), 2, "crossed above"); - assert_eq!(a.move_item(9, 0), None); - // Saved only when set; older files load with every item above. - let json = serde_json::to_string(&a).unwrap(); - assert!(json.contains("\"contents_index\":2")); - assert_eq!(serde_json::from_str::(&json).unwrap(), a); - let old: Appearance = serde_json::from_str(r#"{"items":[]}"#).unwrap(); - assert_eq!(old.contents_index, None); - assert!(!serde_json::to_string(&Appearance::default_art()).unwrap().contains("contents_index")); + /// Is the first object's object-level effect `k` shared? + pub fn has_effect(&self, k: usize) -> bool { + self.effects.iter().any(|at| at.first() == Some(&k)) } } + +#[cfg(test)] +mod tests; diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs new file mode 100644 index 0000000000..6103e7dfdc --- /dev/null +++ b/crates/doc/src/appearance/layers.rs @@ -0,0 +1,240 @@ +use super::profile::{PressureProfile, WidthProfile}; +use super::stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign}; +use super::*; + +/// A live effect in an appearance stack. Parameters are interpreted by `vectorcraft-effects`. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Effect { + /// Stable id, e.g. `stylize.dropShadow`, `distort.roughen`, `path.offsetPath`, `warp.arc`. + pub id: String, + #[serde(default)] + pub params: serde_json::Value, + #[serde(default = "yes")] + pub visible: bool, +} + +fn yes() -> bool { + true +} + +fn one() -> f32 { + 1.0 +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct FillLayer { + pub paint: Paint, + #[serde(default = "one", skip_serializing_if = "crate::skip::is_one")] + pub opacity: f32, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub blend: BlendMode, + #[serde(default = "yes", skip_serializing_if = "crate::skip::is_true")] + pub visible: bool, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub effects: Vec, + /// Overprint Fill: on press the fill's inks print over the inks below instead of knocking + /// them out (Overprint Preview and Separations Preview show it). + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub overprint: bool, +} + +impl FillLayer { + pub fn new(paint: Paint) -> Self { + Self { paint, opacity: 1.0, blend: BlendMode::Normal, visible: true, effects: vec![], overprint: false } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct StrokeLayer { + pub paint: Paint, + /// Weight in points. + pub width: f64, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub cap: LineCap, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub join: LineJoin, + #[serde(default = "ten", skip_serializing_if = "is_ten")] + pub miter_limit: f64, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub align: StrokeAlign, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub dash: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start_arrow: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end_arrow: Option, + /// Arrowhead scale in percent (start, end). + #[serde(default = "hundreds", skip_serializing_if = "is_hundreds")] + pub arrow_scale: (f64, f64), + #[serde(default, skip_serializing_if = "Option::is_none")] + pub profile: Option, + /// Brush applied to the stroke (by brush name). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub brush: Option, + #[serde(default = "one", skip_serializing_if = "crate::skip::is_one")] + pub opacity: f32, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub blend: BlendMode, + #[serde(default = "yes", skip_serializing_if = "crate::skip::is_true")] + pub visible: bool, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub effects: Vec, + /// Arrowhead placement at both ends. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub arrow_align: ArrowAlign, + /// Overprint Stroke (see [`FillLayer::overprint`]). + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub overprint: bool, + /// How a gradient paint maps onto the stroke (within, along or across it). + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub gradient_mode: StrokeGradientMode, + /// The pen pressure the stroke was drawn with (Paintbrush with a tablet): pressure-sensitive + /// brushes vary with it. It belongs to this path's shape, so appearances copied to other + /// art leave it behind ([`Appearance::without_pressure`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pressure: Option, +} + +/// How a gradient on a stroke is laid out (the Gradient panel's Stroke buttons). Saved by variant +/// name: new modes are appended, never renamed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum StrokeGradientMode { + /// Placed on the page like a fill's gradient and seen through the stroke. + #[default] + Within, + /// From the start of each subpath to its end, following the path. + Along, + /// From the stroke's left edge to its right edge (left of the path's direction), all along it. + Across, +} + +impl StrokeGradientMode { + pub const ALL: [StrokeGradientMode; 3] = [StrokeGradientMode::Within, StrokeGradientMode::Along, StrokeGradientMode::Across]; + /// The name commands use (`within`, `along`, `across`). + pub fn name(self) -> &'static str { + match self { + StrokeGradientMode::Within => "within", + StrokeGradientMode::Along => "along", + StrokeGradientMode::Across => "across", + } + } + /// Parse a mode name (any case). + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|m| m.name().eq_ignore_ascii_case(s)) + } +} + +/// How far any arrowhead reaches from its tip, in units of its weight (the open arrow's arms are +/// cut square a little behind its 4 × 4 box). +pub(crate) const HEAD_REACH: f64 = 4.6; + +fn ten() -> f64 { + 10.0 +} + +fn hundreds() -> (f64, f64) { + (100.0, 100.0) +} + +fn is_ten(v: &f64) -> bool { + *v == 10.0 +} + +fn is_hundreds(v: &(f64, f64)) -> bool { + *v == (100.0, 100.0) +} + +impl StrokeLayer { + pub fn new(paint: Paint, width: f64) -> Self { + Self { + paint, + width, + cap: LineCap::Butt, + join: LineJoin::Miter, + miter_limit: 10.0, + align: StrokeAlign::Center, + dash: None, + start_arrow: None, + end_arrow: None, + arrow_scale: (100.0, 100.0), + profile: None, + brush: None, + opacity: 1.0, + blend: BlendMode::Normal, + visible: true, + effects: vec![], + arrow_align: ArrowAlign::Extend, + overprint: false, + gradient_mode: StrokeGradientMode::Within, + pressure: None, + } + } + /// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least + /// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide. + pub fn arrow_weight(&self, end: bool) -> f64 { + let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 }; + (self.width * pct / 100.0).max(0.25) + } + /// 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, |_| HEAD_REACH * 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 { + self.head_reach(false).max(self.head_reach(true)) + } + /// The widest the width profile makes the stroke, as a factor of its weight (1 without one). + pub fn profile_max(&self) -> f64 { + self.profile.as_ref().and_then(|p| p.points.iter().map(|&(_, l, r)| l.max(r)).reduce(f64::max)).unwrap_or(1.0).max(0.0) + } + /// The stroke's body across a path that is `closed` or open: how far it reaches from the path + /// at full width (half the weight centred; the whole weight on one side when aligned inside or + /// outside a closed path, which open paths ignore), and for aligned strokes which side it + /// paints (`Some(true)`: inside). + pub fn body(&self, closed: bool) -> (f64, Option) { + match self.align { + StrokeAlign::Outside if closed => (self.width, Some(false)), + StrokeAlign::Inside if closed => (self.width, Some(true)), + _ => (self.width / 2.0, None), + } + } + /// How far the body paints outside a path that is `closed` or open, at the profile's widest. + pub fn side_reach(&self, closed: bool) -> f64 { + match self.body(closed) { + (_, Some(true)) => 0.0, + (half, _) => half * self.profile_max(), + } + } + /// The farthest this stroke can paint from any path: its body, miter spikes up to the miter + /// limit, projecting caps' corners and the arrowheads ([`Appearance::outset`]). + pub fn reach(&self) -> f64 { + let side = self.side_reach(true).max(self.side_reach(false)); + let miter = if self.join == LineJoin::Miter { self.miter_limit.max(1.0) } else { 1.0 }; + let cap = if self.cap == LineCap::Square { std::f64::consts::SQRT_2 } else { 1.0 }; + (side * miter.max(cap)).max(self.arrow_reach()) + } + /// The box an unplaced gradient on this stroke fits to (see [`stroke_paint_bounds`]). + pub fn paint_bounds(&self, geometric: vectorcraft_geom::Rect) -> vectorcraft_geom::Rect { + stroke_paint_bounds(geometric, self.width) + } + /// The gradient this stroke lays along or across its path: its linear or radial gradient + /// paint when [`Self::gradient_mode`] isn't Within (freeform gradients always paint within). + pub fn path_gradient(&self) -> Option<&vectorcraft_color::GradientPaint> { + match &self.paint { + Paint::Gradient(g) + if self.gradient_mode != StrokeGradientMode::Within && g.gradient.kind != vectorcraft_color::GradientKind::Freeform => + { + Some(g) + } + _ => None, + } + } +} + +/// The box an unplaced gradient on a stroke of `width` fits to: the geometric bounds grown by half +/// the weight (object strokes and type strokes alike, on screen and in exports). +pub fn stroke_paint_bounds(geometric: vectorcraft_geom::Rect, width: f64) -> vectorcraft_geom::Rect { + geometric.inflate(width / 2.0, width / 2.0) +} diff --git a/crates/doc/src/appearance/profile.rs b/crates/doc/src/appearance/profile.rs new file mode 100644 index 0000000000..56df51ef65 --- /dev/null +++ b/crates/doc/src/appearance/profile.rs @@ -0,0 +1,222 @@ +use super::*; + +/// Variable-width profile: (position 0..1 along the path, left width factor, right width factor), +/// in order along the path. Two points at the same position make a discontinuous point: the +/// first is the width just before it, the second the width just after it (a step). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct WidthProfile { + pub points: Vec<(f64, f64, f64)>, +} + +/// A built-in width profile (the Stroke panel's Profile list). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ProfilePreset { + /// Stable id used by `stroke.set {profile}`. + pub id: &'static str, + /// Menu label. + pub label: &'static str, + /// (t, left, right) width points. + pub points: &'static [(f64, f64, f64)], +} + +impl WidthProfile { + /// (left, right) width factors at `t`, linear between points. + 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). + pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) { + if p.is_empty() { + return (1.0, 1.0); + } + if t <= p[0].0 { + return (p[0].1, p[0].2); + } + for w in p.windows(2) { + if t <= w[1].0 { + let u = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-9); + return (w[0].1 + (w[1].1 - w[0].1) * u, w[0].2 + (w[1].2 - w[0].2) * u); + } + } + p.last().map_or((1.0, 1.0), |l| (l.1, l.2)) + } + /// The built-in profiles, in menu order. "uniform" is the plain stroke (no profile). + pub const PRESETS: [ProfilePreset; 7] = [ + ProfilePreset { id: "uniform", label: "Uniform", points: &[(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)] }, + ProfilePreset { id: "lens", label: "Lens", points: &[(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)] }, + ProfilePreset { id: "taperStart", label: "Taper Start", points: &[(0.0, 0.0, 0.0), (1.0, 1.0, 1.0)] }, + ProfilePreset { id: "taperEnd", label: "Taper End", points: &[(0.0, 1.0, 1.0), (1.0, 0.0, 0.0)] }, + // Full width at both ends, pinched to a quarter in the middle. + ProfilePreset { id: "pinch", label: "Pinch", points: &[(0.0, 1.0, 1.0), (0.5, 0.25, 0.25), (1.0, 1.0, 1.0)] }, + // A round head a fifth of the way along, then a long taper to the end. + ProfilePreset { id: "teardrop", label: "Teardrop", points: &[(0.0, 0.0, 0.0), (0.2, 1.0, 1.0), (1.0, 0.0, 0.0)] }, + // 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 built-in profile with this id. + pub fn preset(id: &str) -> Option { + Self::PRESETS.iter().find(|p| p.id == id).map(|p| Self { points: p.points.to_vec() }) + } + /// The id of the built-in profile these points match, if any. + pub fn preset_id(&self) -> Option<&'static str> { + Self::PRESETS.iter().find(|p| p.points == self.points.as_slice()).map(|p| p.id) + } + /// The id of a stroke's profile: "uniform" without one, "custom" when it matches no preset. + pub fn id_of(p: Option<&Self>) -> &'static str { + p.map_or(Some("uniform"), Self::preset_id).unwrap_or("custom") + } + /// The lens profile (thin ends, full width in the middle). + pub fn lens() -> Self { + Self::preset("lens").unwrap_or_default() + } + pub fn taper_end() -> Self { + Self::preset("taperEnd").unwrap_or_default() + } + pub fn taper_start() -> Self { + Self::preset("taperStart").unwrap_or_default() + } + /// The (left, right) factors just before and just after `t`: they differ only at a + /// discontinuous point (two points at `t`, within `1e-7`). + pub fn around(&self, t: f64) -> ((f64, f64), (f64, f64)) { + let p = &self.points; + if let Some(i) = p.iter().position(|q| (q.0 - t).abs() <= 1e-7) { + let j = i + p[i..].iter().take_while(|q| (q.0 - p[i].0).abs() <= 1e-9).count() - 1; + if j > i { + return ((p[i].1, p[i].2), (p[j].1, p[j].2)); + } + } + let v = self.at(t); + (v, v) + } +} + +/// Pen pressure recorded along a stroke (the Paintbrush with a graphics tablet): (position 0..1 +/// along the path, pressure 0..1) samples in order, positions measured as a [`WidthProfile`]'s +/// are. Calligraphic brushes with Pressure variation read it; everything else ignores it. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct PressureProfile { + pub points: Vec<(f64, f64)>, +} + +impl PressureProfile { + /// The pressure of a stroke drawn without one (a mouse, or a path the brush was applied to): + /// half way, so a Pressure brush draws its own value there. + pub const MID: f64 = 0.5; + /// The most samples a stroke keeps (after simplifying them). + pub const MAX_POINTS: usize = 512; + /// How far (in pressure) simplifying may move the recorded curve. + const TOLERANCE: f64 = 0.01; + + /// The pressure at `t` (0..1), linear between samples; [`Self::MID`] without any. + pub fn at(&self, t: f64) -> f64 { + let p = &self.points; + let (Some(first), Some(last)) = (p.first(), p.last()) else { return Self::MID }; + // (Positions go forward; a profile read from a file is searched as if they do, in log time.) + let v = if t <= first.0 { + first.1 + } else { + let i = p.partition_point(|q| q.0 < t); + match (i.checked_sub(1).and_then(|j| p.get(j)), p.get(i)) { + (Some(a), Some(b)) => a.1 + (b.1 - a.1) * ((t - a.0) / (b.0 - a.0).max(1e-9)).clamp(0.0, 1.0), + _ => last.1, + } + }; + if v.is_finite() { v.clamp(0.0, 1.0) } else { Self::MID } + } + + /// A profile from (position, pressure) samples in order along the stroke: values are clamped + /// into 0..1 (non-finite ones dropped), the curve is simplified to within 1 % and kept to + /// [`Self::MAX_POINTS`]. `None` without a sample. + pub fn from_samples(samples: impl IntoIterator) -> Option { + let pts: Vec<(f64, f64)> = + samples.into_iter().filter(|(t, p)| t.is_finite() && p.is_finite()).map(|(t, p)| (t.clamp(0.0, 1.0), p.clamp(0.0, 1.0))).collect(); + if pts.is_empty() { + return None; + } + // Simplifying is quadratic at worst: a huge stroke is thinned evenly first. + let mut pts = thin(pts, 16 * Self::MAX_POINTS); + // Positions only ever go forward. + let mut prev = 0.0; + for p in &mut pts { + p.0 = p.0.max(prev); + prev = p.0; + } + let keep = simplify_1d(&pts, Self::TOLERANCE); + let pts = thin(pts.iter().zip(keep).filter(|(_, k)| *k).map(|(p, _)| *p).collect(), Self::MAX_POINTS); + let round = |v: f64| (v * 1e4).round() / 1e4; + Some(Self { points: pts.into_iter().map(|(t, p)| (round(t), round(p))).collect() }) + } + + /// The pressure of a path `old_len` long (`old`; None: drawn without pressure) continued at its + /// end by a stroke `added_len` long (`added`). None when neither has pressure. + pub fn extended(old: Option<&Self>, old_len: f64, added: Option<&Self>, added_len: f64) -> Option { + if old.is_none() && added.is_none() { + return None; + } + let (old_len, added_len) = (old_len.max(0.0), added_len.max(0.0)); + let total = old_len + added_len; + if !total.is_finite() || total <= 1e-9 { + return old.or(added).cloned(); + } + let flat = Self { points: vec![(0.0, Self::MID), (1.0, Self::MID)] }; + let (old, added) = (old.unwrap_or(&flat), added.unwrap_or(&flat)); + let o = old_len / total; + let old_pts = old.points.iter().map(|&(t, p)| (t * o, p)); + Self::from_samples(old_pts.chain(added.points.iter().map(|&(u, p)| (o + u * (1.0 - o), p)))) + } + + /// The pressure of the path reversed. + pub fn reversed(&self) -> Self { + Self { points: self.points.iter().rev().map(|&(t, p)| (1.0 - t, p)).collect() } + } + + /// A light–heavy–light stroke, for previews of pressure-sensitive brushes. + pub fn sample() -> Self { + Self { points: vec![(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)] } + } +} + +/// At most `max` of `pts`, evenly spread (the ends kept). +fn thin(pts: Vec<(f64, f64)>, max: usize) -> Vec<(f64, f64)> { + let n = pts.len(); + if n <= max || max < 2 { + return pts; + } + (0..max).filter_map(|i| pts.get(i * (n - 1) / (max - 1)).copied()).collect() +} + +/// Douglas–Peucker over a function sampled at `pts`: which samples to keep so the polyline through +/// them stays within `tol` (vertically) of every sample. The ends are always kept. +fn simplify_1d(pts: &[(f64, f64)], tol: f64) -> Vec { + let mut keep = vec![false; pts.len()]; + let Some(last) = pts.len().checked_sub(1) else { return keep }; + for i in [0, last] { + if let Some(k) = keep.get_mut(i) { + *k = true; + } + } + let mut stack = vec![(0, last)]; + while let Some((i, j)) = stack.pop() { + let (Some(&a), Some(&b)) = (pts.get(i), pts.get(j)) else { continue }; + let line = |t: f64| if b.0 - a.0 > 1e-12 { a.1 + (b.1 - a.1) * (t - a.0) / (b.0 - a.0) } else { (a.1 + b.1) / 2.0 }; + let far = (i + 1..j).filter_map(|k| pts.get(k).map(|q| (k, (q.1 - line(q.0)).abs()))).max_by(|x, y| x.1.total_cmp(&y.1)); + if let Some((k, d)) = far + && d > tol + { + if let Some(f) = keep.get_mut(k) { + *f = true; + } + stack.push((i, k)); + stack.push((k, j)); + } + } + keep +} + +/// A width profile saved to the Profile list under a name (Add to Profiles), kept with the +/// preferences. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SavedProfile { + pub name: String, + pub profile: WidthProfile, +} diff --git a/crates/doc/src/appearance/stroke_style.rs b/crates/doc/src/appearance/stroke_style.rs new file mode 100644 index 0000000000..3e6a29a324 --- /dev/null +++ b/crates/doc/src/appearance/stroke_style.rs @@ -0,0 +1,200 @@ +use super::*; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum LineCap { + #[default] + Butt, + Round, + Square, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum LineJoin { + #[default] + Miter, + Round, + Bevel, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum StrokeAlign { + #[default] + Center, + Inside, + Outside, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Dash { + /// Dash, gap, dash, gap… (up to 6 values in the Stroke panel). + pub pattern: Vec, + #[serde(default)] + pub offset: f64, + /// "Aligns dashes to corners and path ends, adjusting lengths to fit". + #[serde(default)] + pub align_corners: bool, +} + +impl Dash { + /// Whether the pattern draws dashes. As in PDF (`d` operator) and SVG (`stroke-dasharray`), a + /// pattern with a negative or non-finite value, or whose values are all zero, is invalid and the + /// stroke is drawn solid. + pub fn is_dashed(&self) -> bool { + self.pattern.iter().all(|v| v.is_finite() && *v >= 0.0) && self.pattern.iter().any(|v| *v > 0.0) + } + /// Scale the dash and gap lengths and the offset by `s`. + pub fn scale(&mut self, s: f64) { + self.pattern.iter_mut().for_each(|v| *v *= s); + self.offset *= s; + } +} + +/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Arrowhead { + Triangle, + TriangleOpen, + Circle, + CircleOpen, + Square, + SquareOpen, + Bar, + Diamond, + Arrow, + ArrowOpen, + Barbed, + /// One barb, on the left of the direction the head points. + HalfArrowLeft, + /// One barb, on the right of the direction the head points. + HalfArrowRight, + Concave, + DoubleBar, + Feather, + DotOnBar, + Chevron, + DoubleArrow, + Target, + Star, + Cross, + Plus, + Hexagon, + HexagonOpen, + Tag, + TagOpen, + HalfCircle, + Drop, + Slash, + DoubleSlash, + DiamondOpen, + TriangleReverse, + Swallowtail, + Bracket, + Fork, + Leaf, + Kite, + TriangleBar, + Oval, +} + +impl Arrowhead { + /// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks). + pub const ALL: [Arrowhead; 40] = [ + Arrowhead::Arrow, + Arrowhead::ArrowOpen, + Arrowhead::Barbed, + Arrowhead::Concave, + Arrowhead::DoubleArrow, + Arrowhead::HalfArrowLeft, + Arrowhead::HalfArrowRight, + Arrowhead::Chevron, + Arrowhead::Feather, + Arrowhead::Swallowtail, + Arrowhead::Triangle, + Arrowhead::TriangleOpen, + Arrowhead::TriangleReverse, + Arrowhead::TriangleBar, + Arrowhead::Kite, + Arrowhead::Leaf, + Arrowhead::Drop, + Arrowhead::Circle, + Arrowhead::CircleOpen, + Arrowhead::HalfCircle, + Arrowhead::Oval, + Arrowhead::Target, + Arrowhead::Square, + Arrowhead::SquareOpen, + Arrowhead::Tag, + Arrowhead::TagOpen, + Arrowhead::Diamond, + Arrowhead::DiamondOpen, + Arrowhead::Hexagon, + Arrowhead::HexagonOpen, + Arrowhead::Star, + Arrowhead::Cross, + Arrowhead::Plus, + Arrowhead::Bar, + Arrowhead::DoubleBar, + Arrowhead::DotOnBar, + Arrowhead::Slash, + Arrowhead::DoubleSlash, + Arrowhead::Bracket, + Arrowhead::Fork, + ]; + + /// The name the arrowhead menus show. + pub fn label(self) -> &'static str { + match self { + Arrowhead::Triangle => "Triangle", + Arrowhead::TriangleOpen => "Triangle (open)", + Arrowhead::Circle => "Circle", + Arrowhead::CircleOpen => "Circle (open)", + Arrowhead::Square => "Square", + Arrowhead::SquareOpen => "Square (open)", + Arrowhead::Bar => "Bar", + Arrowhead::Diamond => "Diamond", + Arrowhead::Arrow => "Arrow", + Arrowhead::ArrowOpen => "Arrow (open)", + Arrowhead::Barbed => "Barbed", + Arrowhead::HalfArrowLeft => "Half Arrow (left)", + Arrowhead::HalfArrowRight => "Half Arrow (right)", + Arrowhead::Concave => "Concave", + Arrowhead::DoubleBar => "Double Bar", + Arrowhead::Feather => "Feather", + Arrowhead::DotOnBar => "Dot on Bar", + Arrowhead::Chevron => "Chevron", + Arrowhead::DoubleArrow => "Double Arrow", + Arrowhead::Target => "Target", + Arrowhead::Star => "Star", + Arrowhead::Cross => "Cross", + Arrowhead::Plus => "Plus", + Arrowhead::Hexagon => "Hexagon", + Arrowhead::HexagonOpen => "Hexagon (open)", + Arrowhead::Tag => "Tag", + Arrowhead::TagOpen => "Tag (open)", + Arrowhead::HalfCircle => "Half Circle", + Arrowhead::Drop => "Drop", + Arrowhead::Slash => "Slash", + Arrowhead::DoubleSlash => "Double Slash", + Arrowhead::DiamondOpen => "Diamond (open)", + Arrowhead::TriangleReverse => "Reverse Triangle", + Arrowhead::Swallowtail => "Swallowtail", + Arrowhead::Bracket => "Bracket", + Arrowhead::Fork => "Fork", + Arrowhead::Leaf => "Leaf", + Arrowhead::Kite => "Kite", + Arrowhead::TriangleBar => "Triangle to Bar", + Arrowhead::Oval => "Oval", + } + } +} + +/// Where an arrowhead sits relative to the end of its path. In both modes the stroke stops under +/// the head, so the line never shows through a hollow head or past its tip. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ArrowAlign { + /// The tip extends past the end point (the path keeps its length). + #[default] + Extend, + /// The tip sits on the end point (the stroke is shortened by the head). + Tip, +} diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs new file mode 100644 index 0000000000..3e3d610f4f --- /dev/null +++ b/crates/doc/src/appearance/tests.rs @@ -0,0 +1,349 @@ +use super::*; + +#[test] +fn hidden_attributes_show_again() { + let mut a = Appearance::default_art(); + assert!(!a.has_hidden() && !a.show_all()); + a.stroke_mut().unwrap().visible = false; + a.items[0].effects_mut().push(Effect { id: "distort.roughen".into(), params: serde_json::Value::Null, visible: false }); + assert!(a.has_hidden()); + assert!(a.show_all()); + assert!(!a.has_hidden() && a.items.iter().all(AppearanceItem::visible) && a.items[0].effects()[0].visible); +} + +#[test] +fn basic_appearance() { + let a = Appearance::default_art(); + assert!(a.is_basic()); + assert_eq!(a.fill_paint(), Paint::solid(Color::WHITE)); + assert_eq!(a.stroke_width(), 1.0); +} + +#[test] +fn rebase_moves_fills_by_the_box_and_strokes_by_their_inflated_box() { + use vectorcraft_color::{Gradient, GradientGeom, GradientPaint}; + use vectorcraft_geom::{Point, Rect}; + let placed = |x: f64| { + let mut g = GradientPaint::new(Gradient::default()); + g.geom = Some(GradientGeom { start: Point::new(x, 0.0), end: Point::new(x + 10.0, 0.0), aspect: 1.0, focal: None }); + Paint::Gradient(Box::new(g)) + }; + let mut a = Appearance::basic(placed(0.0), placed(-5.0), 10.0); + a.rebase_gradients(Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(100.0, 0.0, 300.0, 100.0)); + let start = |p: Paint| match p { + Paint::Gradient(g) => g.geom.unwrap().start, + _ => panic!("a gradient"), + }; + // The fill's start stays on the left edge; the stroke's on its inflated box's (−5 → 95). + assert_eq!((start(a.fill_paint()), start(a.stroke_paint())), (Point::new(100.0, 0.0), Point::new(95.0, 0.0))); +} + +#[test] +fn items_by_index() { + let mut a = Appearance::default_art(); + a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::None))); + // [Fill white, Stroke black, Fill none] + assert_eq!(a.fill_at(None).unwrap().paint, Paint::None); + assert_eq!(a.fill_at(Some(0)).unwrap().paint, Paint::solid(Color::WHITE)); + assert!(a.fill_at(Some(1)).is_none() && a.stroke_at(Some(0)).is_none() && a.fill_at(Some(9)).is_none()); + assert_eq!(a.item_of_kind(Some(1), false), Some(1)); + assert_eq!(a.item_of_kind(Some(1), true), None); + assert_eq!(a.fill_for(Some(1)).unwrap().paint, Paint::None); + assert!(a.set_fill_at(Some(0), Paint::solid(Color::BLACK))); + assert!(!a.set_stroke_at(Some(0), Paint::None)); + assert_eq!(a.fill_at(Some(0)).unwrap().paint, Paint::solid(Color::BLACK)); + a.effects_mut(Some(1)).unwrap().push(Effect { id: "distort.roughen".into(), params: serde_json::Value::Null, visible: true }); + assert_eq!(a.effects_at(Some(1)).unwrap().len(), 1); + assert!(a.effects_at(None).unwrap().is_empty() && a.effects_mut(Some(3)).is_none()); + assert_eq!((a.items[1].kind_name(), a.items[2].kind_name()), ("stroke", "fill")); +} + +#[test] +fn basic_means_one_plain_fill_and_stroke() { + let stroke = || AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 1.0)); + let mut a = Appearance { items: vec![stroke(), stroke()], ..Appearance::default() }; + assert!(!a.is_basic(), "two strokes"); + a.items.pop(); + assert!(a.is_basic() && Appearance::default().is_basic()); + let mut b = Appearance::default_art(); + b.stroke_mut().unwrap().visible = false; + assert!(!b.is_basic(), "a hidden stroke"); + let mut c = Appearance::default_art(); + c.fill_mut().unwrap().opacity = 0.5; + assert!(!c.is_basic(), "fill opacity"); + let mut d = Appearance::default_art(); + d.items.push(AppearanceItem::Fill(FillLayer::new(Paint::None))); + assert!(!d.is_basic(), "two fills"); + let mut e = Appearance::default_art(); + e.effects.push(Effect { id: "distort.roughen".into(), params: serde_json::Value::Null, visible: true }); + assert!(!e.is_basic(), "an effect"); +} + +#[test] +fn set_creates_missing() { + let mut a = Appearance::default(); + a.set_fill(Paint::solid(Color::BLACK)); + a.set_stroke(Paint::solid(Color::WHITE)); + assert_eq!(a.items.len(), 2); + assert!(matches!(a.items[0], AppearanceItem::Fill(_))); +} + +/// #852: pen pressure is kept simplified along the stroke and read back by position. +#[test] +fn pressure_profile_samples_simplify_and_interpolate() { + // A steady ramp keeps only its ends; a bump keeps its peak. + let ramp = PressureProfile::from_samples((0..=100).map(|i| (i as f64 / 100.0, i as f64 / 100.0))).unwrap(); + assert_eq!(ramp.points, vec![(0.0, 0.0), (1.0, 1.0)]); + assert!((ramp.at(0.25) - 0.25).abs() < 1e-9); + let bump = PressureProfile::from_samples([(0.0, 0.2), (0.3, 0.2), (0.5, 0.9), (0.7, 0.2), (1.0, 0.2)]).unwrap(); + assert!(bump.points.contains(&(0.5, 0.9)) && (bump.at(0.4) - 0.55).abs() < 1e-9, "{bump:?}"); + // Junk is clamped or dropped; positions never go back; nothing at all is no profile. + let junk = PressureProfile::from_samples([(f64::NAN, 0.5), (0.5, 7.0), (0.2, -1.0), (2.0, f64::INFINITY)]).unwrap(); + assert_eq!(junk.points, vec![(0.5, 1.0), (0.5, 0.0)]); + assert!(PressureProfile::from_samples([(f64::NAN, 0.5)]).is_none()); + assert_eq!(PressureProfile::default().at(0.3), PressureProfile::MID); + // A long noisy stroke stays bounded. + let noisy = PressureProfile::from_samples((0..1_000_000).map(|i| (i as f64 / 1e6, (i % 2) as f64))).unwrap(); + assert!(noisy.points.len() <= PressureProfile::MAX_POINTS); + // Out-of-order points (a hand-edited file) still read within 0..1. + let odd = PressureProfile { points: vec![(1.0, 5.0), (0.0, -3.0)] }; + assert!((0.0..=1.0).contains(&odd.at(0.5))); +} + +#[test] +fn pressure_profile_extends_and_reverses() { + let old = PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }; + let added = PressureProfile { points: vec![(0.0, 1.0), (1.0, 0.0)] }; + // A 30 pt path continued by 10 pt: its ramp fills the first three quarters. + let joined = PressureProfile::extended(Some(&old), 30.0, Some(&added), 10.0).unwrap(); + assert!((joined.at(0.75) - 1.0).abs() < 1e-9 && (joined.at(0.375) - 0.5).abs() < 1e-9 && joined.at(1.0) == 0.0, "{joined:?}"); + // A side without pressure is half way. + let half = PressureProfile::extended(None, 10.0, Some(&added), 10.0).unwrap(); + assert_eq!(half.at(0.25), PressureProfile::MID); + assert!(PressureProfile::extended(None, 10.0, None, 10.0).is_none()); + assert_eq!(PressureProfile::extended(Some(&old), 0.0, None, f64::NAN), Some(old.clone())); + assert_eq!(old.reversed().points, vec![(0.0, 1.0), (1.0, 0.0)]); +} + +/// Strokes saved before pen pressure load as they were, and are written without it. +#[test] +fn strokes_without_pressure_round_trip_unchanged() { + let json = serde_json::to_value(StrokeLayer::new(Paint::None, 2.0)).unwrap(); + assert!(json.get("pressure").is_none()); + let st: StrokeLayer = serde_json::from_value(json).unwrap(); + assert_eq!(st.pressure, None); + let pressed = StrokeLayer { pressure: Some(PressureProfile::sample()), ..st }; + let back: StrokeLayer = serde_json::from_value(serde_json::to_value(&pressed).unwrap()).unwrap(); + assert_eq!(back, pressed); + let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0); + ap.stroke_mut().unwrap().pressure = Some(PressureProfile::sample()); + assert_eq!(ap.without_pressure().stroke().unwrap().pressure, None); +} + +#[test] +fn profile_interp() { + let p = WidthProfile::lens(); + assert_eq!(p.at(0.5), (1.0, 1.0)); + assert_eq!(p.at(0.25), (0.5, 0.5)); + assert_eq!(p.at(2.0), (0.0, 0.0)); +} + +#[test] +fn profile_presets_round_trip_their_ids() { + for p in WidthProfile::PRESETS { + let prof = WidthProfile::preset(p.id).unwrap(); + assert_eq!(prof.preset_id(), Some(p.id)); + assert_eq!(WidthProfile::id_of(Some(&prof)), p.id); + } + assert_eq!(WidthProfile::id_of(None), "uniform"); + assert_eq!(WidthProfile::id_of(Some(&WidthProfile { points: vec![(0.0, 0.3, 0.3)] })), "custom"); + assert!(WidthProfile::preset("nope").is_none()); + assert_eq!(WidthProfile::lens().points, vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)]); +} + +#[test] +fn arrowhead_names_are_stable_and_every_one_is_listed_once() { + // Saved files store these names: they may only ever be appended to. + const SAVED: [&str; 40] = [ + "Triangle", + "TriangleOpen", + "Circle", + "CircleOpen", + "Square", + "SquareOpen", + "Bar", + "Diamond", + "Arrow", + "ArrowOpen", + "Barbed", + "HalfArrowLeft", + "HalfArrowRight", + "Concave", + "DoubleBar", + "Feather", + "DotOnBar", + "Chevron", + "DoubleArrow", + "Target", + "Star", + "Cross", + "Plus", + "Hexagon", + "HexagonOpen", + "Tag", + "TagOpen", + "HalfCircle", + "Drop", + "Slash", + "DoubleSlash", + "DiamondOpen", + "TriangleReverse", + "Swallowtail", + "Bracket", + "Fork", + "Leaf", + "Kite", + "TriangleBar", + "Oval", + ]; + 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!(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"); +} + +#[test] +fn arrow_align_defaults_to_extend_and_round_trips() { + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); + assert_eq!(st.arrow_align, ArrowAlign::Extend); + // The default is not written, so older readers see the same JSON as before. + assert!(!serde_json::to_string(&st).unwrap().contains("arrow_align")); + let old: StrokeLayer = serde_json::from_str(r#"{"paint":{"type":"none"},"width":2.0}"#).unwrap(); + assert_eq!(old.arrow_align, ArrowAlign::Extend); + st.arrow_align = ArrowAlign::Tip; + let back: StrokeLayer = serde_json::from_str(&serde_json::to_string(&st).unwrap()).unwrap(); + assert_eq!(back, st); +} + +#[test] +fn outset_covers_arrowheads() { + let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 4.0); + a.stroke_mut().unwrap().join = LineJoin::Round; + assert_eq!(a.outset(), 2.0); + let st = a.stroke_mut().unwrap(); + st.end_arrow = Some(Arrowhead::Triangle); + st.arrow_scale = (100.0, 200.0); + assert_eq!(st.arrow_weight(false), 4.0); + assert_eq!(st.arrow_weight(true), 8.0); + assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, HEAD_REACH * 8.0 + 2.0)); + // A 32 pt head whose tip sits up to its length (plus the cap) past the end point. + assert_eq!(a.outset(), HEAD_REACH * 8.0 + 2.0); + a.stroke_mut().unwrap().width = 0.01; + assert_eq!(a.stroke().unwrap().arrow_weight(true), 0.25, "heads keep a minimum size"); +} + +#[test] +fn outset_depends_on_align() { + let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0); + a.stroke_mut().unwrap().join = LineJoin::Round; + assert_eq!(a.outset(), 5.0); + a.stroke_mut().unwrap().align = StrokeAlign::Outside; + assert_eq!(a.outset(), 10.0); + // Open paths stroke inside-aligned strokes centred. + a.stroke_mut().unwrap().align = StrokeAlign::Inside; + assert_eq!(a.outset(), 5.0); + assert_eq!((a.stroke().unwrap().side_reach(true), a.stroke().unwrap().body(true)), (0.0, (10.0, Some(true)))); +} + +#[test] +fn outset_covers_miter_spikes_projecting_caps_and_profile_maxima() { + let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0); + // Miter joins can spike out to the limit × half the weight. + assert_eq!(a.outset(), 10.0); + let st = a.stroke_mut().unwrap(); + st.join = LineJoin::Bevel; + st.cap = LineCap::Square; + assert!((a.outset() - std::f64::consts::SQRT_2).abs() < 1e-12, "a projecting cap's corner"); + let st = a.stroke_mut().unwrap(); + st.cap = LineCap::Round; + st.profile = Some(WidthProfile { points: vec![(0.0, 0.5, 2.5), (1.0, 1.0, 1.0)] }); + assert_eq!(st.profile_max(), 2.5); + assert_eq!(a.outset(), 2.5); + a.stroke_mut().unwrap().paint = Paint::None; + assert_eq!(a.outset(), 0.0, "an unpainted stroke"); +} + +#[test] +fn contents_slot_follows_item_edits_and_round_trips() { + let fill = || AppearanceItem::Fill(FillLayer::new(Paint::None)); + let mut a = Appearance { items: vec![fill(), fill(), fill()], ..Appearance::default() }; + assert_eq!((a.contents_at(), a.split_contents().1.len()), (0, 3), "all items above by default"); + a.set_contents_at(1); + assert!(!a.is_basic()); + // [0 | 1 2]: removing below shifts the slot, removing above doesn't. + a.remove_item(2); + assert_eq!(a.contents_at(), 1); + a.remove_item(0); + assert_eq!((a.contents_at(), a.contents_index), (0, None)); + // Inserting next to the slot joins the item below it. + a.items.push(fill()); + a.set_contents_at(1); // [0 | 1] + a.insert_item(1, fill()); + assert_eq!(a.contents_at(), 2); + a.insert_item(3, fill()); // [0 1 | 2 3] + assert_eq!(a.contents_at(), 2); + // Moves keep their side when landing next to the slot, cross it otherwise. + assert_eq!(a.move_item(3, 2), Some(2)); + assert_eq!(a.contents_at(), 2, "stays above"); + a.move_item(3, 0); + assert_eq!(a.contents_at(), 3, "crossed below"); + a.move_item(0, 3); + assert_eq!(a.contents_at(), 2, "crossed above"); + assert_eq!(a.move_item(9, 0), None); + // Saved only when set; older files load with every item above. + let json = serde_json::to_string(&a).unwrap(); + assert!(json.contains("\"contents_index\":2")); + assert_eq!(serde_json::from_str::(&json).unwrap(), a); + let old: Appearance = serde_json::from_str(r#"{"items":[]}"#).unwrap(); + assert_eq!(old.contents_index, None); + assert!(!serde_json::to_string(&Appearance::default_art()).unwrap().contains("contents_index")); +} + +/// The issue's case (#4174): two circles with different fills, the same stroke and the same +/// effect share the stroke and the effect, not the fills; a shared stroke at another place in one +/// stack maps to its own index there; nothing shared shares nothing; equal stacks share all. +#[test] +fn mixed_appearances_share_their_equal_rows() { + let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 11.0)); + let fill = |c: Color| AppearanceItem::Fill(FillLayer::new(Paint::solid(c))); + let feather = Effect { id: "stylize.feather".into(), params: serde_json::json!({"radius": 5}), visible: true }; + let a = Appearance { items: vec![fill(Color::rgb(1.0, 1.0, 0.0)), stroke.clone()], effects: vec![feather.clone()], ..Appearance::default() }; + let b = Appearance { items: vec![fill(Color::rgb(1.0, 0.0, 0.0)), stroke.clone()], effects: vec![feather.clone()], ..Appearance::default() }; + let shared = SharedStack::of(&[&a, &b]); + assert_eq!(shared.items, vec![vec![1, 1]], "the stroke, not the fills"); + assert_eq!(shared.effects, vec![vec![0, 0]]); + // The stroke under an extra fill in the second object. + let c = + Appearance { items: vec![fill(Color::BLACK), fill(Color::WHITE), stroke.clone()], effects: vec![feather.clone()], ..Appearance::default() }; + let shared = SharedStack::of(&[&a, &c]); + assert_eq!(shared.items, vec![vec![1, 2]]); + assert_eq!(shared.item_in(1, 1), Some(2)); + assert_eq!(shared.item_in(0, 1), None); + // Nothing alike. + let d = Appearance { items: vec![fill(Color::WHITE)], ..Appearance::default() }; + let none = SharedStack::of(&[&a, &d]); + assert!(none.items.is_empty() && none.effects.is_empty()); + // Equal stacks share everything, each row where it is. + assert_eq!(SharedStack::of(&[&a, &a.clone(), &a.clone()]).items, vec![vec![0, 0, 0], vec![1, 1, 1]]); +} + +/// Matches keep their stacking order: two equal rows in the opposite order match once. +#[test] +fn aligned_rows_never_cross() { + assert_eq!(align(&[1, 2], &[2, 1], |a, b| a == b).iter().filter(|m| m.is_some()).count(), 1); + assert_eq!(align(&[1, 2, 3], &[9, 1, 3], |a, b| a == b), vec![Some(1), None, Some(2)]); + assert_eq!(align::(&[], &[1], |a, b| a == b), Vec::>::new()); +} diff --git a/crates/doc/src/artboard.rs b/crates/doc/src/artboard.rs new file mode 100644 index 0000000000..bdd20f4c8e --- /dev/null +++ b/crates/doc/src/artboard.rs @@ -0,0 +1,152 @@ +use super::*; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Artboard { + pub id: u32, + pub name: String, + /// Artboard rectangle in document points. + pub rect: Rect, + /// Locked (the Artboards panel's lock column): the Artboard tool and the artboard commands + /// don't move, resize or delete it, Rearrange leaves it where it is, and the art on it can't be + /// selected or edited ([`Document::on_locked_artboard`]), except new art while it stays + /// selected ([`Document::new_art`]). + #[serde(default, skip_serializing_if = "skip::is_default")] + pub locked: bool, + /// Show Center Mark (Artboard Options): the canvas draws a mark at the artboard's center. + /// Exports and print leave it out. Always written, as before it could be set. + #[serde(default)] + pub show_center_mark: bool, + /// Show Cross Hairs (Artboard Options): the canvas draws a line from the middle of each side + /// through the center. Exports and print leave them out. Always written, as before it could + /// be set. + #[serde(default)] + pub show_cross_hairs: bool, + /// Show Video Safe Areas (Artboard Options): the canvas draws the artboard's action-safe and + /// title-safe areas ([`Artboard::video_safe_areas`]). Exports and print leave them out. Written + /// only when on, so a document that never shows them saves as before. + #[serde(default, skip_serializing_if = "skip::is_default")] + pub show_video_safe_areas: bool, + /// Video Ruler Pixel Aspect Ratio (Artboard Options): the width of one video pixel over its + /// height, which View › Rulers › Show Video Rulers counts the artboard in: a pixel is this many + /// points wide and one point tall. 1 (square pixels) unless set, and written only when it isn't + /// 1; always within [`VIDEO_PIXEL_ASPECT_RANGE`]: the commands refuse others, and a file's is + /// brought into it as it opens. + #[serde(default = "square_pixels", deserialize_with = "pixel_aspect_within_range", skip_serializing_if = "is_square_pixels")] + pub video_ruler_pixel_aspect_ratio: f64, + /// Background color (Properties › Artboards › Fill, Artboard Options). The canvas draws the + /// artboard's paper in it, multiplied with the Simulate Colored Paper color while that is on; + /// without one the paper is white, or the Simulate Colored Paper color. Exports and print leave + /// it out. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, +} + +/// The Video Ruler Pixel Aspect Ratios an artboard takes (Artboard Options): from a pixel ten times +/// as tall as it is wide to one ten times as wide as it is tall, which holds the anamorphic and +/// standard-definition ratios video uses (0.9, 1.2, 1.33, 2) with room to spare. +pub const VIDEO_PIXEL_ASPECT_RANGE: std::ops::RangeInclusive = 0.1..=10.0; + +/// How far in from each edge of an artboard the video safe areas lie, as a share of its width +/// (left and right) and of its height (top and bottom): the action-safe area 3.5% and the +/// title-safe (graphics-safe) area 5%, as EBU R 95 sets them for 16:9 television +/// (https://tech.ebu.ch/docs/r/r095.pdf, note 5). +pub const VIDEO_SAFE_INSETS: [f64; 2] = [0.035, 0.05]; + +fn square_pixels() -> f64 { + 1.0 +} + +fn is_square_pixels(v: &f64) -> bool { + *v == 1.0 +} + +/// A file's Video Ruler Pixel Aspect Ratio, brought into [`VIDEO_PIXEL_ASPECT_RANGE`]: one that +/// isn't a number (NaN, infinite) reads as square pixels. +fn pixel_aspect_within_range<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = f64::deserialize(d)?; + let (lo, hi) = (*VIDEO_PIXEL_ASPECT_RANGE.start(), *VIDEO_PIXEL_ASPECT_RANGE.end()); + Ok(if v.is_finite() { v.clamp(lo, hi) } else { 1.0 }) +} + +impl Artboard { + /// The action-safe and the title-safe area of the artboard, in that order, each inset from its + /// edges by the share of [`VIDEO_SAFE_INSETS`] (Show Video Safe Areas). + pub fn video_safe_areas(&self) -> [Rect; 2] { + let r = self.rect; + VIDEO_SAFE_INSETS.map(|k| r.inflate(-k * r.width(), -k * r.height())) + } +} + +/// A document's locked artboards ([`Document::locked_artboards`]). +pub struct LockedArtboards<'a> { + pub(crate) rects: Vec, + pub(crate) symbols: SymbolBoxes<'a>, + /// The new art, which isn't on them ([`Document::new_art`]). + pub(crate) new_art: Arc>, + /// The objects of pattern editing mode's layer ([`Document::pattern_edit`]), which are on no + /// artboard. + pub(crate) pattern_art: std::collections::HashSet, + /// What [`LockedArtboards::overlaps`] found for each object it measured: the members of a + /// group are each answered with one measurement of the group. + pub(crate) held: std::cell::RefCell>, +} + +impl LockedArtboards<'_> { + /// No artboard is locked. + pub fn is_empty(&self) -> bool { + self.rects.is_empty() + } + /// Is `n`, an object of a layer or sublayer, on a locked artboard: shown, not a guide, and its + /// visual bounds (with its strokes, a symbol instance by its art) overlapping the artboard? An + /// object counts for every artboard it overlaps, as Fit to Artwork Bounds counts it. A layer or + /// sublayer is on none, nor is the art of pattern editing mode ([`Document::pattern_edit`]) or + /// new art while it stays selected ([`Document::new_art`]). + pub fn holds(&self, n: &Node) -> bool { + !self.new_art.contains(&n.id) && self.overlaps(n) + } + /// [`LockedArtboards::holds`] for new art too: is `n` on a locked artboard, whether or not it + /// is new art? + pub fn overlaps(&self, n: &Node) -> bool { + if self.rects.is_empty() + || !n.visible + || n.is_layer() + || matches!(n.kind, NodeKind::Path { guide: true, .. }) + || self.pattern_art.contains(&n.id) + { + return false; + } + if let Some(held) = self.held.borrow().get(&n.id) { + return *held; + } + let held = + n.visual_bounds_with(&self.symbols).is_some_and(|b| self.rects.iter().any(|r| b.x0 < r.x1 && b.x1 > r.x0 && b.y0 < r.y1 && b.y1 > r.y0)); + self.held.borrow_mut().insert(n.id, held); + held + } + /// Is node `id` on a locked artboard: is the object of a layer or sublayer that holds it (`id` + /// itself when it is one, a group counting as one object) on one ([`LockedArtboards::holds`])? + pub fn holds_id(&self, id: NodeId) -> bool { + !self.rects.is_empty() && self.symbols.document().layer_object(id).is_some_and(|n| self.holds(n)) + } +} + +/// [`Document::retired_artboard_id`]: not document content, so two documents are equal whatever it +/// holds. A clone shares the value with the document it was cloned from. +#[derive(Clone, Debug, Default)] +pub struct RetiredArtboardId(pub(crate) Arc); + +impl RetiredArtboardId { + pub fn get(&self) -> u32 { + self.0.load(std::sync::atomic::Ordering::Relaxed) + } + /// Raise the value to `id` when `id` is higher. + pub fn raise(&self, id: u32) { + self.0.fetch_max(id, std::sync::atomic::Ordering::Relaxed); + } +} + +impl PartialEq for RetiredArtboardId { + fn eq(&self, _: &Self) -> bool { + true + } +} diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 119e75abc3..7bf88ac164 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -44,23 +44,54 @@ fn lerp_f64(x: f64, y: f64, t: f64) -> f64 { x + (y - x) * t } -fn solid_gradient(c: Color, like: &Gradient) -> Gradient { +/// `like` with every stop painting `c`, linked as the solid is (`swatch` at `tint`). +fn solid_gradient(c: Color, swatch: Option<&str>, tint: f32, like: &Gradient) -> Gradient { let mut g = like.clone(); for s in &mut g.stops { s.color = c; s.opacity = 1.0; + s.swatch = swatch.map(str::to_string); + s.tint = tint; } g } +/// The swatch and tint `g` paints at `t`: a stop's own link, or the shared swatch of the two stops +/// around `t` at the tint between theirs (unlinked when they differ), as [`Gradient::sample_with`] walks. +fn link_at(g: &Gradient, t: f32) -> (Option, f32) { + let stops = &g.stops; + let link = |s: &GradientStop| (s.swatch.clone(), s.tint); + let Some(first) = stops.first() else { return (None, 1.0) }; + if t <= first.offset { + return link(first); + } + for w in stops.windows(2) { + let (a, b) = (&w[0], &w[1]); + if t <= b.offset { + let span = (b.offset - a.offset).max(1e-6); + let u = (t - a.offset) / span; + let m = a.midpoint.clamp(0.01, 0.99); + let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) }; + return match (&a.swatch, &b.swatch) { + (Some(x), Some(y)) if x == y => (Some(x.clone()), lerp_f32(a.tint, b.tint, v)), + _ if v <= 0.0 => link(a), + _ if v >= 1.0 => link(b), + _ => (None, 1.0), + }; + } + } + stops.last().map_or((None, 1.0), link) +} + /// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred). fn resample_stops(g: &Gradient, offsets: &[f32]) -> Gradient { let mut out = g.clone(); out.stops = offsets .iter() .map(|&o| { - let (color, opacity) = g.sample_with(o, lerp_color); - GradientStop { opacity, ..GradientStop::new(o, color) } + let (color, opacity) = g.sample_keep_model(o); + let (swatch, tint) = link_at(g, o); + GradientStop { opacity, swatch, tint, ..GradientStop::new(o, color) } }) .collect(); out @@ -106,10 +137,19 @@ fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option (Some(x.clone()), lerp_f32(sa.tint, sb.tint, t)), + _ => (None, 1.0), + }; + GradientStop { + opacity: lerp_f32(sa.opacity, sb.opacity, t), + midpoint: lerp_f32(sa.midpoint, sb.midpoint, t), + swatch, + tint, + ..GradientStop::new(lerp_f32(sa.offset, sb.offset, t), lerp_color(&sa.color, &sb.color, t)) + } }) .collect(); out.angle = a.angle + (b.angle - a.angle) * t as f64; @@ -131,17 +171,21 @@ fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option Paint { match (a, b) { + // Two tints of one swatch blend into tints of that swatch (a spot stays a spot on export). + (Paint::Solid { color: x, swatch: Some(sa), tint: ta }, Paint::Solid { color: y, swatch: Some(sb), tint: tb }) if sa == sb => { + Paint::Solid { color: lerp_color(x, y, t), swatch: Some(sa.clone()), tint: lerp_f32(*ta, *tb, t) } + } (Paint::Solid { color: x, .. }, Paint::Solid { color: y, .. }) => Paint::solid(lerp_color(x, y, t)), (Paint::Gradient(ga), Paint::Gradient(gb)) => match lerp_gradient(ga, gb, t) { Some(g) => Paint::Gradient(Box::new(g)), None => (if t < 0.5 { a } else { b }).clone(), }, - (Paint::Solid { color, .. }, Paint::Gradient(g)) => { - let ga = GradientPaint { gradient: solid_gradient(*color, &g.gradient), ..(**g).clone() }; + (Paint::Solid { color, swatch, tint }, Paint::Gradient(g)) => { + let ga = GradientPaint { gradient: solid_gradient(*color, swatch.as_deref(), *tint, &g.gradient), ..(**g).clone() }; Paint::Gradient(Box::new(lerp_gradient(&ga, g, t).unwrap_or_else(|| (**g).clone()))) } - (Paint::Gradient(g), Paint::Solid { color, .. }) => { - let gb = GradientPaint { gradient: solid_gradient(*color, &g.gradient), ..(**g).clone() }; + (Paint::Gradient(g), Paint::Solid { color, swatch, tint }) => { + let gb = GradientPaint { gradient: solid_gradient(*color, swatch.as_deref(), *tint, &g.gradient), ..(**g).clone() }; Paint::Gradient(Box::new(lerp_gradient(g, &gb, t).unwrap_or_else(|| (**g).clone()))) } _ => (if t < 0.5 { a } else { b }).clone(), @@ -535,11 +579,18 @@ impl Lerp { /// The object at `t` (0 = `a`, 1 = `b`), with id 0. pub fn at(&self, t: f64) -> Node { + self.at_eased(t, t) + } + + /// The object whose shape is at `t` and whose colours (fills, strokes, opacity, mesh and text + /// colours) are at `tc`: a blend with its colours eased apart from its spacing. + pub fn at_eased(&self, t: f64, tc: f64) -> Node { let (a, b) = (&self.a, &self.b); let base = if t < 0.5 { a } else { b }; let mut n = match &self.shape { Shape::Group { children, clip } => { - let mut g = Node::new(NodeId(0), NodeKind::Group { children: children.iter().map(|c| Arc::new(c.at(t))).collect(), clip: *clip }); + let mut g = + Node::new(NodeId(0), NodeKind::Group { children: children.iter().map(|c| Arc::new(c.at_eased(t, tc))).collect(), clip: *clip }); g.isolate = base.isolate; g.knockout = base.knockout; g @@ -549,8 +600,8 @@ impl Lerp { if let (NodeKind::Mesh(m), NodeKind::Mesh(ma), NodeKind::Mesh(mb)) = (&mut n.kind, &a.kind, &b.kind) { for ((p, x), y) in m.points.iter_mut().zip(&ma.points).zip(&mb.points) { p.p = x.p.lerp(y.p, t); - p.color = lerp_color(&x.color, &y.color, t as f32); - p.opacity = lerp_f32(x.opacity, y.opacity, t as f32); + p.color = lerp_color(&x.color, &y.color, tc as f32); + p.opacity = lerp_f32(x.opacity, y.opacity, tc as f32); for h in 0..4 { p.handles[h] = x.handles[h].lerp(y.handles[h], t); } @@ -576,7 +627,7 @@ impl Lerp { Shape::Placed => { let mut n = base.clone(); match (&mut n.kind, &a.kind, &b.kind) { - (NodeKind::Text(o), NodeKind::Text(x), NodeKind::Text(y)) => lerp_text(o, x, y, t), + (NodeKind::Text(o), NodeKind::Text(x), NodeKind::Text(y)) => lerp_text(o, x, y, t, tc), (NodeKind::SymbolInstance { xf: o, .. }, NodeKind::SymbolInstance { xf: x, .. }, NodeKind::SymbolInstance { xf: y, .. }) => { *o = lerp_affine(*x, *y, t) } @@ -613,8 +664,8 @@ impl Lerp { } }; n.id = NodeId(0); - n.appearance = lerp_appearance(&a.appearance, &b.appearance, t).into(); - n.opacity = lerp_f32(a.opacity, b.opacity, t as f32); + n.appearance = lerp_appearance(&a.appearance, &b.appearance, tc).into(); + n.opacity = lerp_f32(a.opacity, b.opacity, tc as f32); n.blend = base.blend; n.visible = true; n.locked = false; @@ -644,7 +695,7 @@ fn compound(path: PathData, rule: FillRule, counts: &[usize], total: usize) -> N /// Interpolate text `x` → `y` into `o` (a copy of the nearer): the transform by its parts, an /// area frame anchor by anchor, and each run's colours, stroke weight and size from the runs at /// the same place (by character) of both. -fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64) { +fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64, tc: f64) { o.xf = lerp_affine(x.xf, y.xf, t); if let (crate::text::TextKind::Area { frame: f }, crate::text::TextKind::Area { frame: fx }, crate::text::TextKind::Area { frame: fy }) = (&mut o.kind, &x.kind, &y.kind) @@ -666,7 +717,7 @@ fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64) { } let total: usize = o.runs.iter().map(|r| r.text.chars().count()).sum::().max(1); let mut start = 0usize; - let tf = t as f32; + let tf = tc as f32; let mut resized = false; for r in &mut o.runs { let len = r.text.chars().count(); @@ -1027,8 +1078,10 @@ pub fn blend_expand(keys: &[Arc], spec: &BlendSpec) -> Vec { let n = blend_step_count(a, b, spec.spacing, len); let lerp = Lerp::new(a, b, (spec.start(i), spec.start(i + 1))); for j in 1..=n { - let t = j as f64 / (n + 1) as f64; - let mut s = lerp.at(t); + // 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)); + let mut s = lerp.at_eased(t, tc); if let Some(r) = &rail { r.place(&mut s, i, t); } @@ -1090,6 +1143,55 @@ mod tests { assert_eq!(out[0].geometric_bounds().unwrap().center(), Point::new(5.0, 5.0), "keys stay put"); } + #[test] + fn easing_keeps_the_ends_and_stays_monotone() { + use crate::live::{BlendEase, BlendEaseType as K}; + for kind in [K::In, K::Out, K::InOut, K::OutIn] { + for ramp in [0.0, 0.5, 1.0, f64::NAN, f64::INFINITY] { + let e = BlendEase { kind, ramp }; + assert_eq!((e.apply(0.0), e.apply(1.0)), (0.0, 1.0)); + let ys: Vec = (0..=100).map(|i| e.apply(i as f64 / 100.0)).collect(); + assert!(ys.windows(2).all(|w| w[0] <= w[1])); + assert_eq!(e.apply(f64::NAN), 0.0); + if ramp == 0.0 { + assert_eq!(e.apply(0.25), 0.25); + } + } + } + let e = |kind| BlendEase { kind, ramp: 1.0 }; + assert!(e(K::In).apply(0.25) < 0.25); + assert!(e(K::Out).apply(0.25) > 0.25); + assert!(e(K::InOut).apply(0.25) < 0.25 && e(K::InOut).apply(0.75) > 0.75); + assert!(e(K::OutIn).apply(0.25) > 0.25 && e(K::OutIn).apply(0.75) < 0.75); + } + + #[test] + fn colour_easing_moves_colours_apart_from_positions() { + let rect = |x: f64, c: Color| { + let mut n = Node::path(NodeId(1), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default()); + n.appearance = Appearance::basic(Paint::solid(c), Paint::None, 0.0).into(); + Arc::new(n) + }; + let keys = vec![rect(0.0, Color::BLACK), rect(100.0, Color::WHITE)]; + let mid = |spec: &BlendSpec| { + let out = blend_expand(&keys, spec); + let n = &out[1]; + (n.geometric_bounds().unwrap().x0, n.appearance.fill_paint()) + }; + // Position easing runs along a spine: Align to Path gives the blend one. + let base = BlendSpec { spacing: BlendSpacing::Steps(1), orientation: BlendOrientation::AlignToPath, ..Default::default() }; + let (x0, p0) = mid(&base); + // Colour easing alone leaves the position and moves the colour. + let colour = BlendSpec { color_shift: 50.0, ..base.clone() }; + let (x1, p1) = mid(&colour); + assert!((x0 - x1).abs() < 1e-9 && p0 != p1); + // Position easing alone leaves the colour and moves the position. + let pos = BlendSpec { ease: crate::live::BlendEase { kind: crate::live::BlendEaseType::In, ramp: 1.0 }, ..base.clone() }; + let (x2, p2) = mid(&pos); + assert!((x0 - x2).abs() > 1e-3 && p0 == p2); + assert_eq!(mid(&pos).0, x2, "deterministic"); + } + #[test] fn affine_lerp_turns_the_short_way() { let x = Affine::rotate(170f64.to_radians()); @@ -1114,6 +1216,56 @@ mod tests { assert!(pair.at(0.5).bounds().unwrap().height() < 1e-6, "the clicked anchors pair up"); } + #[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 }; + let Paint::Solid { swatch, tint, .. } = lerp_paint(&tinted(0.2), &tinted(1.0), 0.5) else { panic!() }; + assert_eq!(swatch.as_deref(), Some("Spot")); + assert!((tint - 0.6).abs() < 1e-6, "{tint}"); + let other = Paint::Solid { color: Color::BLACK, swatch: Some("Other".into()), tint: 1.0 }; + assert!(matches!(lerp_paint(&tinted(0.2), &other, 0.5), Paint::Solid { swatch: None, .. })); + + // Gradient stops on tints of one swatch stay linked too; a process solid unlinks them. + let spot_gradient = |tint: f32| { + let mut stop = GradientStop::new(0.0, Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(tint)); + stop.swatch = Some("Spot".into()); + stop.tint = tint; + let stops = vec![stop.clone(), GradientStop { offset: 1.0, ..stop }]; + Paint::Gradient(Box::new(GradientPaint::new(Gradient { stops, ..Gradient::default() }))) + }; + let Paint::Gradient(m) = lerp_paint(&spot_gradient(0.2), &spot_gradient(1.0), 0.5) else { panic!() }; + assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops); + let Paint::Gradient(m) = lerp_paint(&tinted(0.2), &spot_gradient(1.0), 0.5) else { panic!() }; + assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops); + let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &spot_gradient(1.0), 0.5) else { panic!() }; + assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none()), "{:?}", m.gradient.stops); + } + + #[test] + fn resampled_gradient_stops_keep_the_swatch_link() { + let spot = |offset: f32, tint: f32| { + let mut stop = GradientStop::new(offset, Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(tint)); + stop.swatch = Some("Spot".into()); + stop.tint = tint; + stop + }; + let paint = |stops: Vec| Paint::Gradient(Box::new(GradientPaint::new(Gradient { stops, ..Gradient::default() }))); + let two = paint(vec![spot(0.0, 0.2), spot(1.0, 1.0)]); + let three = paint(vec![spot(0.0, 0.2), spot(0.5, 0.6), spot(1.0, 1.0)]); + let Paint::Gradient(m) = lerp_paint(&two, &three, 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 3); + assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops); + let tints: Vec = m.gradient.stops.iter().map(|s| s.tint).collect(); + assert!((tints[1] - 0.6).abs() < 1e-6 && (tints[2] - 1.0).abs() < 1e-6, "{tints:?}"); + + // Spot on one side, process on the other: the stops are unlinked. + let mut plain = spot(0.5, 1.0); + plain.swatch = None; + let mixed = paint(vec![spot(0.0, 1.0), plain, spot(1.0, 1.0)]); + let Paint::Gradient(m) = lerp_paint(&two, &mixed, 0.5) else { panic!() }; + assert!(m.gradient.stops.iter().any(|s| s.swatch.is_none()), "{:?}", m.gradient.stops); + } + #[test] fn gradients_with_different_stop_counts_interpolate() { let g = |stops: &[(f32, Color)]| { diff --git a/crates/doc/src/cancel.rs b/crates/doc/src/cancel.rs index bff510707f..e38b0ab817 100644 --- a/crates/doc/src/cancel.rs +++ b/crates/doc/src/cancel.rs @@ -92,6 +92,15 @@ pub fn check() -> Result<(), Cancelled> { if is_cancelled() { Err(Cancelled) } else { Ok(()) } } +/// Run `f` with this thread's token still in effect and its progress reports dropped: for work +/// that reports its own steps around calls that report theirs (each file of a batch export). +pub fn quiet(f: impl FnOnce() -> T) -> T { + match CURRENT.with(|c| c.borrow().as_ref().map(|s| s.token.clone())) { + Some(token) => scope(&token, None, f), + None => f(), + } +} + /// Report that `done` of `total` steps (0: unknown) are finished. A no-op outside a [`scope`] /// that has a sink. pub fn progress(done: u64, total: u64, what: &str) { @@ -139,4 +148,25 @@ mod tests { progress(2, 3, "after"); assert_eq!(*seen.borrow(), vec![(1, 3, "page".to_string())]); } + + #[test] + fn quiet_work_reports_nothing_and_can_still_be_cancelled() { + let seen = Rc::new(RefCell::new(vec![])); + let sink: ProgressSink = { + let seen = seen.clone(); + Rc::new(move |d, t, w| seen.borrow_mut().push((d, t, w.to_string()))) + }; + let t = CancelToken::new(); + scope(&t, Some(sink), || { + progress(0, 2, "file"); + quiet(|| { + progress(0, 1, "artboard"); + t.cancel(); + assert_eq!(check(), Err(Cancelled)); + }); + progress(1, 2, "file"); + }); + assert_eq!(*seen.borrow(), vec![(0, 2, "file".to_string()), (1, 2, "file".to_string())]); + assert_eq!(quiet(check), Ok(()), "outside a scope nothing is cancelled"); + } } diff --git a/crates/doc/src/clipnest.rs b/crates/doc/src/clipnest.rs index f77f9e0187..7d94e3b580 100644 --- a/crates/doc/src/clipnest.rs +++ b/crates/doc/src/clipnest.rs @@ -40,11 +40,18 @@ pub type Drawn = Vec<(Vec>, Node)>; /// The nodes of `items`, those under clips grouped into clipping groups and those in groups into /// groups (ids from `doc`), in order. pub fn nest(doc: &mut Document, items: Drawn) -> Vec> { - nest_at(doc, items, 0) + let mut left = MAX_CLIP_ELEMENTS; + nest_at(doc, items, 0, &mut left) } -/// [`nest`] for the clips at `depth` and deeper. -fn nest_at(doc: &mut Document, items: Drawn, depth: usize) -> Vec> { +/// Most path elements the clipping paths [`nest`] makes may have together. Each run of objects +/// under a clip gets its own copy of the clip's path, so one large clip used again around many +/// short runs (an EMF restoring one saved clip between drawings) multiplied it. Past it, runs are +/// grouped without their clip. +pub const MAX_CLIP_ELEMENTS: usize = 8_000_000; + +/// [`nest`] for the clips at `depth` and deeper, with `left` of [`MAX_CLIP_ELEMENTS`]. +fn nest_at(doc: &mut Document, items: Drawn, depth: usize, left: &mut usize) -> Vec> { let mut out: Vec> = vec![]; let mut group: Drawn = vec![]; let mut clip: Option> = None; @@ -52,7 +59,7 @@ fn nest_at(doc: &mut Document, items: Drawn, depth: usize) -> Vec> { let here = chain.get(depth).cloned(); if here.as_ref().map(|c| c.id) != clip.as_ref().map(|c| c.id) { if let Some(c) = clip.take() { - out.push(clip_group(doc, &c, std::mem::take(&mut group), depth)); + out.push(clip_group(doc, &c, std::mem::take(&mut group), depth, left)); } clip = here.clone(); } @@ -62,16 +69,23 @@ fn nest_at(doc: &mut Document, items: Drawn, depth: usize) -> Vec> { } } if let Some(c) = clip { - out.push(clip_group(doc, &c, group, depth)); + out.push(clip_group(doc, &c, group, depth, left)); } out } /// A clipping group of `items`, clipped by `c` (their clip at `depth`), or their group when `c` is /// a plain group. -fn clip_group(doc: &mut Document, c: &Clip, items: Drawn, depth: usize) -> Arc { +fn clip_group(doc: &mut Document, c: &Clip, items: Drawn, depth: usize, left: &mut usize) -> Arc { let mut children = vec![]; - if let Some((bp, r)) = &c.region { + let region = c.region.as_ref().filter(|(bp, _)| match left.checked_sub(bp.elements().len()) { + Some(rest) => { + *left = rest; + true + } + None => false, + }); + if let Some((bp, r)) = region { let mut path = Node::path(doc.alloc_id(), PathData::from_bezpath(bp), Appearance::default()); if let NodeKind::Path { clipping, rule, .. } = &mut path.kind { *clipping = true; @@ -79,6 +93,6 @@ fn clip_group(doc: &mut Document, c: &Clip, items: Drawn, depth: usize) -> Arc Vec { + if !relative { + return stored.to_vec(); + } + let corners = path_corners(base); + let mut out = stored.to_vec(); + out.resize(base.anchor_count(), 0.0); + for c in corners { + if let Some(r) = out.get_mut(c.index) { + *r = (*r).clamp(0.0, 1.0) * c.max_radius(); + } + } + out +} + +/// Turn stored absolute radii into fractions of each corner's maximum, or the other way. +pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) { + if live.radii_relative() == relative { + return; + } + let was_relative = live.radii_relative(); + let base = match live { + LiveShape::Rectangle { w, h, .. } => shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)), + LiveShape::Polygon { .. } => live.polygon_outline(), + LiveShape::Path { base, .. } => base.clone(), + LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, + }; + let corners = path_corners(&base); + let radii: &mut [f64] = match live { + LiveShape::Rectangle { radii, .. } => radii, + LiveShape::Polygon { radii, .. } => radii, + LiveShape::Path { radii, .. } => radii, + LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, + }; + for c in corners { + if let Some(r) = radii.get(c.index) { + let max = c.max_radius(); + radii[c.index] = if relative { + if max > 1e-12 && !was_relative { (*r / max).clamp(0.0, 1.0) } else { *r } + } else if was_relative { + (*r).clamp(0.0, 1.0) * max + } else { + *r + }; + } + } + match live { + LiveShape::Rectangle { radii_relative: rel, .. } + | LiveShape::Polygon { radii_relative: rel, .. } + | LiveShape::Path { radii_relative: rel, .. } => { + *rel = relative; + } + LiveShape::Ellipse { .. } | LiveShape::Line { .. } => {} + } +} + /// The Live Corners of a path. #[derive(Clone, Debug)] pub struct LiveCorners<'a> { @@ -26,6 +83,8 @@ pub struct LiveCorners<'a> { /// The radius each of `corners` is drawn with ([`fitted_radii`]). drawn: Vec, kinds: Vec, + /// Stored radii are fractions of each corner's maximum, not document lengths. + relative: bool, /// For each anchor of the path as drawn (per subpath), the anchor of `base` it comes from. sources: Vec>, } @@ -34,16 +93,21 @@ impl<'a> LiveCorners<'a> { /// The Live Corners of `path` and its live shape; `None` for shapes without corners (ellipses, /// lines). pub fn new(path: &'a PathData, live: Option<&'a LiveShape>) -> Option { - let (base, xf, radii, kinds) = match live { - None => (Cow::Borrowed(path), Affine::IDENTITY, vec![], vec![]), + let (base, xf, stored, kinds, relative) = match live { + None => (Cow::Borrowed(path), Affine::IDENTITY, vec![], vec![], false), Some(l @ LiveShape::Rectangle { .. }) => { - let LiveShape::Rectangle { w, h, radii, kinds, xf } = l.folded() else { return None }; - (Cow::Owned(shapes::rectangle(Rect::new(0.0, 0.0, w, h))), xf, radii.to_vec(), kinds.to_vec()) + let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = l.folded() else { return None }; + (Cow::Owned(shapes::rectangle(Rect::new(0.0, 0.0, w, h))), xf, radii.to_vec(), kinds.to_vec(), radii_relative) + } + Some(l @ LiveShape::Polygon { radii, kinds, radii_relative, .. }) => { + (Cow::Owned(l.polygon_outline()), Affine::IDENTITY, radii.clone(), kinds.clone(), *radii_relative) + } + Some(LiveShape::Path { base, radii, kinds, radii_relative }) => { + (Cow::Borrowed(base), Affine::IDENTITY, radii.clone(), kinds.clone(), *radii_relative) } - Some(l @ LiveShape::Polygon { radii, kinds, .. }) => (Cow::Owned(l.polygon_outline()), Affine::IDENTITY, radii.clone(), kinds.clone()), - Some(LiveShape::Path { base, radii, kinds }) => (Cow::Borrowed(base), Affine::IDENTITY, radii.clone(), kinds.clone()), Some(LiveShape::Ellipse { .. } | LiveShape::Line { .. }) => return None, }; + let radii = resolve_stored_radii(&base, &stored, relative); let sources = if radii.iter().any(|r| *r > 0.0) { cut_corners(&base, &radii, &kinds).1 } else { @@ -58,7 +122,7 @@ impl<'a> LiveCorners<'a> { }; let corners = path_corners(&base); let drawn = fitted_radii(&corners, &radii); - Some(Self { corners, base, xf, radii, drawn, kinds, sources }) + Some(Self { corners, base, xf, radii: stored, drawn, kinds, relative, sources }) } /// The Live Corners of a path object. @@ -72,7 +136,13 @@ impl<'a> LiveCorners<'a> { self.corners.binary_search_by_key(&index, |c| c.index).ok().and_then(|i| self.corners.get(i)) } - /// The radius corner `index` is set to, in document units (drawn no larger than fits). + /// Whether corner radii are stored as fractions of each corner's maximum. + pub fn radii_relative(&self) -> bool { + self.relative + } + + /// The radius corner `index` is stored at: document lengths, or a fraction in 0..1 when + /// [`LiveCorners::radii_relative`]. pub fn radius(&self, index: usize) -> f64 { self.radii.get(index).copied().unwrap_or(0.0) } @@ -119,8 +189,9 @@ impl<'a> LiveCorners<'a> { &self.sources } - /// The radius (document units) and kind `corners` share (each `None` when they differ, or - /// for no corners). + /// The radius and kind `corners` share (each `None` when they differ, or for no corners). + /// Radius is what was set ([`LiveCorners::radius`]: document lengths, or a fraction in 0..1 + /// when [`LiveCorners::radii_relative`]), not the fitted draw size ([`LiveCorners::drawn_radius`]). pub fn style(&self, corners: &BTreeSet) -> (Option, Option) { fn shared(mut it: impl Iterator, same: impl Fn(T, T) -> bool) -> Option { let first = it.next()?; @@ -137,29 +208,31 @@ impl<'a> LiveCorners<'a> { /// plain path again once no corner is cut. Ellipses and lines have no corners: they stay as they /// are. pub fn set_corners(path: &mut PathData, live: &mut Option>, corners: &BTreeSet, radius: Option, kind: Option) { - fn edit(radii: &mut [f64], kinds: &mut [CornerKind], corners: &BTreeSet, radius: Option, kind: Option) { + fn edit( + base: &PathData, + relative: bool, + radii: &mut [f64], + kinds: &mut [CornerKind], + corners: &BTreeSet, + radius: Option, + kind: Option, + ) { + let corners_on_base = path_corners(base); for k in corners { if let (Some(r), Some(slot)) = (radius, radii.get_mut(*k)) { - *slot = r.max(0.0); + *slot = if relative { + let max = corners_on_base.iter().find(|c| c.index == *k).map(|c| c.max_radius()).unwrap_or(0.0); + if max > 1e-12 { (r / max).clamp(0.0, 1.0) } else { 0.0 } + } else { + r.max(0.0) + }; } if let (Some(kind), Some(slot)) = (kind, kinds.get_mut(*k)) { *slot = kind; } } } - /// One radius and kind per corner of an outline of `n` anchors while editing; none saved - /// when all are sharp or round. - fn edit_vec( - n: usize, - radii: &mut Vec, - kinds: &mut Vec, - corners: &BTreeSet, - radius: Option, - kind: Option, - ) { - radii.resize(n, 0.0); - kinds.resize(n, CornerKind::Round); - edit(radii, kinds, corners, radius, kind); + fn trim_vec_radii(radii: &mut Vec, kinds: &mut Vec) { if radii.iter().all(|r| *r <= 0.0) { radii.clear(); } @@ -167,18 +240,35 @@ pub fn set_corners(path: &mut PathData, live: &mut Option>, corne kinds.clear(); } } - let l = live.get_or_insert_with(|| Box::new(LiveShape::Path { base: path.clone(), radii: vec![], kinds: vec![] })); + let l = live.get_or_insert_with(|| Box::new(LiveShape::Path { base: path.clone(), radii: vec![], kinds: vec![], radii_relative: false })); // Radii are document lengths and corners circular, also on a rectangle from a file that kept // an uneven scale in its transform (#442). l.fold_scale(); + let relative = l.radii_relative(); match &mut **l { - LiveShape::Rectangle { radii, kinds, .. } => edit(radii, kinds, corners, radius, kind), - LiveShape::Polygon { sides, radii, kinds, .. } => edit_vec(*sides as usize, radii, kinds, corners, radius, kind), - LiveShape::Path { base, radii, kinds } => edit_vec(base.anchor_count(), radii, kinds, corners, radius, kind), + LiveShape::Rectangle { w, h, radii, kinds, .. } => { + let base = shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)); + edit(&base, relative, radii, kinds, corners, radius, kind); + } + LiveShape::Polygon { radius: poly_r, sides, xf, radii, kinds, .. } => { + let outline = shapes::polygon(Point::ZERO, *poly_r, *sides, 0.0).transformed(*xf); + let n = *sides as usize; + radii.resize(n, 0.0); + kinds.resize(n, CornerKind::Round); + edit(&outline, relative, radii, kinds, corners, radius, kind); + trim_vec_radii(radii, kinds); + } + LiveShape::Path { base, radii, kinds, .. } => { + let n = base.anchor_count(); + radii.resize(n, 0.0); + kinds.resize(n, CornerKind::Round); + edit(base, relative, radii, kinds, corners, radius, kind); + trim_vec_radii(radii, kinds); + } LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return, } match live.as_deref_mut() { - Some(LiveShape::Path { base, radii, kinds }) if radii.is_empty() && kinds.is_empty() => { + Some(LiveShape::Path { base, radii, kinds, .. }) if radii.is_empty() && kinds.is_empty() => { *path = std::mem::take(base); *live = None; } @@ -202,7 +292,14 @@ mod tests { #[test] fn rectangle_corners_map_to_their_anchors() { - let l = LiveShape::Rectangle { w: 100.0, h: 50.0, radii: [0.0, 10.0, 0.0, 0.0], kinds: Default::default(), xf: Affine::IDENTITY }; + let l = LiveShape::Rectangle { + w: 100.0, + h: 50.0, + radii: [0.0, 10.0, 0.0, 0.0], + kinds: Default::default(), + radii_relative: false, + xf: Affine::IDENTITY, + }; let path = l.to_path(); let c = LiveCorners::new(&path, Some(&l)).unwrap(); // Anchors: top-left, the top-right corner's two, bottom-right, bottom-left. @@ -229,7 +326,7 @@ mod tests { let star = shapes::star(Point::new(100.0, 100.0), 50.0, 25.0, 5, 0.0); let (mut path, mut live) = (star.clone(), None); set_corners(&mut path, &mut live, &set(&[0, 2]), Some(5.0), None); - let Some(LiveShape::Path { base, radii, kinds }) = live.as_deref() else { panic!("live corners: {live:?}") }; + let Some(LiveShape::Path { base, radii, kinds, .. }) = live.as_deref() else { panic!("live corners: {live:?}") }; assert_eq!((base, radii.len(), kinds.len()), (&star, 10, 0)); assert_eq!(path.anchor_count(), 12, "two corners cut"); let c = LiveCorners::new(&path, live.as_deref()).unwrap(); @@ -245,7 +342,8 @@ mod tests { /// A polygon's corners are cut in the document and survive a change of sides when shared. #[test] fn polygon_corners_follow_their_sides() { - let mut l = LiveShape::Polygon { radius: 50.0, sides: 6, xf: Affine::translate((100.0, 100.0)), radii: vec![], kinds: vec![] }; + let mut l = + LiveShape::Polygon { radius: 50.0, sides: 6, xf: Affine::translate((100.0, 100.0)), radii: vec![], kinds: vec![], radii_relative: false }; let (mut path, mut live) = (l.to_path(), Some(Box::new(l.clone()))); set_corners(&mut path, &mut live, &set(&[0, 1, 2, 3, 4, 5]), Some(8.0), None); assert_eq!(path.anchor_count(), 12); @@ -265,6 +363,53 @@ mod tests { assert!(!p.transform(Affine::translate((5.0, 0.0))), "a move needs no new cuts"); } + #[test] + fn relative_radii_scale_with_rectangle_size() { + let l = LiveShape::Rectangle { + w: 100.0, + h: 100.0, + radii: [0.25, 0.25, 0.25, 0.25], + kinds: Default::default(), + radii_relative: true, + xf: Affine::IDENTITY, + }; + let path = l.to_path(); + let c = LiveCorners::new(&path, Some(&l)).unwrap(); + let r0 = c.drawn_radius(0); + let l2 = LiveShape::Rectangle { + w: 200.0, + h: 200.0, + radii: [0.25, 0.25, 0.25, 0.25], + kinds: Default::default(), + radii_relative: true, + xf: Affine::IDENTITY, + }; + let path2 = l2.to_path(); + let c2 = LiveCorners::new(&path2, Some(&l2)).unwrap(); + assert!((c2.drawn_radius(0) / r0 - 2.0).abs() < 0.05, "{r0} → {}", c2.drawn_radius(0)); + } + + #[test] + fn convert_between_relative_and_absolute_radii() { + let mut l = LiveShape::Rectangle { + w: 100.0, + h: 50.0, + radii: [10.0, 0.0, 0.0, 0.0], + kinds: Default::default(), + radii_relative: false, + xf: Affine::IDENTITY, + }; + let before = LiveCorners::new(&l.to_path(), Some(&l)).unwrap().drawn_radius(0); + convert_radii_relative(&mut l, true); + assert!(l.radii_relative()); + let mid = LiveCorners::new(&l.to_path(), Some(&l)).unwrap().drawn_radius(0); + assert!((mid - before).abs() < 0.5); + convert_radii_relative(&mut l, false); + assert!(!l.radii_relative()); + let after = LiveCorners::new(&l.to_path(), Some(&l)).unwrap().drawn_radius(0); + assert!((after - before).abs() < 0.5); + } + #[test] fn open_paths_and_curves_keep_their_ends_and_smooth_anchors() { let pen = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], false)); diff --git a/crates/doc/src/depth.rs b/crates/doc/src/depth.rs index 464eaf9d52..8e4f807282 100644 --- a/crates/doc/src/depth.rs +++ b/crates/doc/src/depth.rs @@ -25,6 +25,12 @@ use crate::{Document, Node, NodeKind}; /// can be made can be saved and opened again. pub const MAX_DEPTH: usize = 32; +/// Most objects the symbol instances drawn in one frame or written in one export may hold +/// together. Instances of symbols that hold instances of others draw every level for each instance +/// above it, so a few levels of a few instances each multiply past what [`MAX_DEPTH`] stops; past +/// it, further instances aren't drawn. +pub const MAX_SYMBOL_NODES: u64 = 16_000_000; + /// The deepest an object may be drawn: as [`MAX_DEPTH`], the art of a symbol counted under its /// instance and a pattern's tile under the object it paints (and what those use, under them). /// Symbols a few objects deep nest in one another dozens deep within it. diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs new file mode 100644 index 0000000000..a17b430be1 --- /dev/null +++ b/crates/doc/src/document.rs @@ -0,0 +1,786 @@ +use super::artboard::{Artboard, LockedArtboards}; +use super::graphic_style::default_graphic_styles; +use super::guides::{GridPrefs, RulerMode}; +use super::limits::{DocError, FORMAT_VERSION, MAX_COORD, MAX_NEXT_ID}; +use super::units::{ColorMode, Unit}; +use super::*; + +impl Document { + /// Is everything but the layers the same in `other`, as the next version of the document after + /// an edit of its art? The id counter and the id index are left out, and art outside the layers + /// (symbols, patterns, graph designs) compares by identity, which an edit keeps for what it + /// doesn't change: quick for every frame of an animation. + pub fn same_outside_layers(&self, other: &Self) -> bool { + let same_art = |a: &[Arc], b: &[Arc]| a.len() == b.len() && a.iter().zip(b).all(|(a, b)| Arc::ptr_eq(a, b)); + let same_pattern = |a: &PatternDef, b: &PatternDef| { + same_art(&a.art, &b.art) && PatternDef { art: Vec::new(), ..a.clone() } == PatternDef { art: Vec::new(), ..b.clone() } + }; + let Self { + version, + title, + template, + units, + ruler_origin, + rulers, + artboard_ruler_origins, + color_mode, + artboards, + layers: _, + swatches, + swatch_groups, + graphic_styles, + char_styles, + para_styles, + text_threads, + symbols, + graph_designs, + guides, + views, + saved_selections, + variables, + grid, + raster_effects_ppi, + images, + patterns, + pattern_edit, + mask_edit, + next_id: _, + unknown, + page_isolate, + page_knockout, + spot_use_lab, + setup, + paste_remembers_layers, + metadata, + raster_effects, + last_view, + transparency_grid, + layers_open, + color_profiles, + export_settings, + extra, + slices, + slices_clip_to_artboard, + print_setup, + assets, + svg_scripts, + puppet, + new_art, + dimensions, + retired_artboard_id: _, + index: _, + } = self; + *version == other.version + && *title == other.title + && *template == other.template + && *units == other.units + && *ruler_origin == other.ruler_origin + && *rulers == other.rulers + && *artboard_ruler_origins == other.artboard_ruler_origins + && *color_mode == other.color_mode + && *artboards == other.artboards + && *swatches == other.swatches + && *swatch_groups == other.swatch_groups + && *graphic_styles == other.graphic_styles + && *char_styles == other.char_styles + && *para_styles == other.para_styles + && *text_threads == other.text_threads + && symbols.len() == other.symbols.len() + && symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && graph_designs.len() == other.graph_designs.len() + && graph_designs.iter().zip(&other.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && *guides == other.guides + && *views == other.views + && *saved_selections == other.saved_selections + && *variables == other.variables + && *grid == other.grid + && *raster_effects_ppi == other.raster_effects_ppi + && *images == other.images + && patterns.len() == other.patterns.len() + && patterns.iter().zip(&other.patterns).all(|(a, b)| same_pattern(a, b)) + && match (pattern_edit, &other.pattern_edit) { + (Some(a), Some(b)) => { + a.pattern == b.pattern + && a.layer == b.layer + && match (&a.original, &b.original) { + (Some(a), Some(b)) => same_pattern(a, b), + (a, b) => a.is_none() && b.is_none(), + } + } + (a, b) => a.is_none() && b.is_none(), + } + && *mask_edit == other.mask_edit + && *unknown == other.unknown + && *page_isolate == other.page_isolate + && *page_knockout == other.page_knockout + && *spot_use_lab == other.spot_use_lab + && *setup == other.setup + && *paste_remembers_layers == other.paste_remembers_layers + && *metadata == other.metadata + && *raster_effects == other.raster_effects + && *last_view == other.last_view + && *transparency_grid == other.transparency_grid + && *layers_open == other.layers_open + && *color_profiles == other.color_profiles + && *export_settings == other.export_settings + && *extra == other.extra + && *slices == other.slices + && *slices_clip_to_artboard == other.slices_clip_to_artboard + && *print_setup == other.print_setup + && *assets == other.assets + && *svg_scripts == other.svg_scripts + && match (puppet, &other.puppet) { + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + (a, b) => a.is_none() && b.is_none(), + } + && *new_art == other.new_art + && *dimensions == other.dimensions + } + + /// Document Raster Effects Settings › Resolution in ppi, 1 to 2400 (72 when the stored value + /// isn't a number). + pub fn raster_ppi(&self) -> f64 { + Some(self.raster_effects_ppi).filter(|v| v.is_finite()).unwrap_or(72.0).clamp(1.0, 2400.0) + } + + /// The ruler zero point, or zero on both axes when either stored coordinate is invalid. + /// Rulers, coordinate fields and guide snapping use the same supported range. + pub fn ruler_origin_or_zero(&self) -> Point { + let origin = self.ruler_origin; + if origin.is_finite() && origin.x.abs() <= MAX_COORD && origin.y.abs() <= MAX_COORD { origin } else { Point::ZERO } + } + + /// Where the rulers measure from with artboard `index` active: [`Self::ruler_origin_or_zero`] + /// with global rulers; with artboard rulers that artboard's top-left corner moved by its own + /// offset (the first artboard's when `index` is out of range, the global zero point when the + /// document has no artboard or the result is out of the supported range). + pub fn ruler_origin_for(&self, index: usize) -> Point { + if self.rulers == RulerMode::Global { + return self.ruler_origin_or_zero(); + } + let Some(ab) = self.artboards.get(index).or_else(|| self.artboards.first()) else { return self.ruler_origin_or_zero() }; + let corner = Point::new(ab.rect.x0, ab.rect.y0); + let offset = self.artboard_ruler_origins.get(&ab.id).copied().unwrap_or(Vec2::ZERO); + let origin = corner + offset; + if origin.is_finite() && origin.x.abs() <= MAX_COORD && origin.y.abs() <= MAX_COORD { + origin + } else if corner.is_finite() && corner.x.abs() <= MAX_COORD && corner.y.abs() <= MAX_COORD { + corner + } else { + Point::ZERO + } + } + + /// A new RGB document with one artboard of `size` and one layer ("Layer 1"). + pub fn new(width: f64, height: f64) -> Self { + Self::new_with_mode(width, height, ColorMode::Rgb) + } + + /// [`Document::new`] in colour `mode`, with that mode's default swatches. + pub fn new_with_mode(width: f64, height: f64, mode: ColorMode) -> Self { + let (swatches, swatch_groups) = vectorcraft_color::default_swatches(mode.model()); + let mut d = Self { + version: FORMAT_VERSION, + title: "Untitled-1".into(), + template: false, + units: Unit::Points, + ruler_origin: Point::ZERO, + rulers: RulerMode::Artboard, + artboard_ruler_origins: BTreeMap::new(), + color_mode: mode, + artboards: vec![Artboard { + id: 1, + name: "Artboard 1".into(), + rect: Rect::new(0.0, 0.0, width, height), + locked: false, + show_center_mark: false, + show_cross_hairs: false, + show_video_safe_areas: false, + video_ruler_pixel_aspect_ratio: 1.0, + color: None, + }], + layers: vec![], + swatches: swatches.into(), + swatch_groups: swatch_groups.into(), + graphic_styles: default_graphic_styles().into(), + char_styles: Default::default(), + para_styles: Default::default(), + text_threads: vec![], + symbols: vec![], + graph_designs: vec![], + guides: vec![], + views: vec![], + saved_selections: Default::default(), + variables: Default::default(), + grid: GridPrefs::default(), + raster_effects_ppi: 72.0, + images: BTreeMap::new(), + patterns: vec![], + pattern_edit: None, + mask_edit: None, + next_id: 1, + unknown: Default::default(), + page_isolate: false, + page_knockout: false, + spot_use_lab: true, + setup: DocSetup::default(), + paste_remembers_layers: false, + metadata: DocMetadata::default(), + raster_effects: RasterEffectsSettings::default(), + last_view: None, + transparency_grid: false, + layers_open: None, + color_profiles: ColorProfiles::default(), + export_settings: Default::default(), + extra: Default::default(), + slices: vec![], + slices_clip_to_artboard: true, + print_setup: None, + assets: vec![], + svg_scripts: vec![], + puppet: None, + new_art: Default::default(), + dimensions: false, + retired_artboard_id: Default::default(), + index: Default::default(), + }; + let id = d.alloc_id(); + d.layers.push(Arc::new(Node::layer(id, "Layer 1", LayerColor::Preset(0)))); + d + } + + /// Allocate a fresh node id. + pub fn alloc_id(&mut self) -> NodeId { + let id = NodeId(self.next_id); + // Never reached from a counter [`Self::fix_next_id`] has seen (it stays under + // [`MAX_NEXT_ID`]); saturating so that no counter can overflow. + self.next_id = self.next_id.saturating_add(1); + id + } + + pub fn peek_next_id(&self) -> u64 { + self.next_id + } + + /// Ensure `next_id` is above every id in the tree (after deserializing foreign data). + 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 + // the largest would run out and hand out ids the document already uses. + let mut max = 0; + let mut see = |id: u64| { + if id < MAX_NEXT_ID { + max = max.max(id); + } + }; + for l in &self.layers { + l.walk(&mut |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)); + } + + /// Find a node anywhere in the tree. + pub fn node(&self, id: NodeId) -> Option<&Node> { + self.index_path(id).and_then(|p| self.node_at(&p)) + } + + /// [`Document::node`] without building the lookup cache when there is none: for a look at a + /// document kept in the undo history ([`Document::drop_lookup_cache`]). + pub fn node_uncached(&self, id: NodeId) -> Option<&Node> { + match self.index.is_built() { + true => self.node(id), + false => self.walk_index_path(id).and_then(|p| self.node_at(&p)), + } + } + + /// Let go of the lookup cache ([`id_index`]), as a document kept in the undo history does: a + /// table per step would add up. Lookups still work; the first one builds the cache again. + pub fn drop_lookup_cache(&self) { + self.index.clear(); + } + + /// Whether the lookup cache ([`id_index`]) is built (see [`Document::drop_lookup_cache`]). + pub fn has_lookup_cache(&self) -> bool { + self.index.is_built() + } + + /// Index path from the top-level layer list to `id` (e.g. `[0, 3, 1]`): the first place in + /// tree order where `id` appears. + pub fn index_path(&self, id: NodeId) -> Option> { + // The cached path, while the node there still has the id ([`id_index`]). + let cached = self.index.get(); + match cached.as_ref().and_then(|m| m.get(&id)) { + Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == id) => return Some(p), + Some(None) => return self.walk_index_path(id), + _ => {} + } + // A stale path (the tree changed), an id the cache doesn't have (deleted or added since), + // or no cache yet: walk, and rebuild now and then. + let found = self.walk_index_path(id); + let stale = cached.as_ref().is_some_and(|m| m.contains_key(&id)); + if cached.is_none() || ((stale || found.is_some()) && self.index.missed()) { + self.index.rebuild(&self.layers); + } + found + } + + /// [`Document::index_path`] by walking the tree. + pub(crate) fn walk_index_path(&self, id: NodeId) -> Option> { + fn find(nodes: &[Arc], id: NodeId, path: &mut Vec) -> bool { + for (i, n) in nodes.iter().enumerate() { + path.push(i); + if n.id == id { + return true; + } + if let Some(ch) = n.children() + && find(ch, id, path) + { + return true; + } + path.pop(); + } + false + } + let mut p = vec![]; + find(&self.layers, id, &mut p).then_some(p) + } + + /// [`Document::index_path`] of every id in `ids` that is in the tree, in one walk of it: an + /// edit of many objects looks them all up for the cost of one search instead of one each. Like + /// `index_path`, an id that appears twice maps to its first place in tree order. + pub fn index_paths(&self, ids: impl IntoIterator) -> std::collections::HashMap> { + use std::collections::{HashMap, HashSet}; + fn walk(nodes: &[Arc], want: &HashSet, path: &mut Vec, out: &mut HashMap>) -> bool { + for (i, n) in nodes.iter().enumerate() { + path.push(i); + if want.contains(&n.id) && !out.contains_key(&n.id) { + out.insert(n.id, path.clone()); + if out.len() == want.len() { + return true; + } + } + if let Some(ch) = n.children() + && walk(ch, want, path, out) + { + return true; + } + path.pop(); + } + false + } + let mut want: HashSet = ids.into_iter().collect(); + let mut out = HashMap::with_capacity(want.len()); + // Cached paths that still check out ([`id_index`]); the rest take one walk. For a good + // share of the document, one walk is quicker than checking each cached path. + if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { + want.retain(|id| match cache.get(id) { + Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { + out.insert(*id, p); + false + } + _ => true, + }); + } + if !want.is_empty() { + let mut rest = HashMap::with_capacity(want.len()); + walk(&self.layers, &want, &mut Vec::new(), &mut rest); + out.extend(rest); + } + out + } + + /// The node at index path `path` (as [`Document::index_path`] gives it). + pub fn node_at(&self, path: &[usize]) -> Option<&Node> { + let (first, rest) = path.split_first()?; + let mut cur: &Node = self.layers.get(*first)?; + for &i in rest { + cur = cur.children()?.get(i)?; + } + Some(cur) + } + + /// Mutable access to the node at index path `path`; clones the Arc path (copy-on-write), as + /// [`Document::node_mut`] does. + pub fn node_mut_at(&mut self, path: &[usize]) -> Option<&mut Node> { + let (first, rest) = path.split_first()?; + let mut cur: &mut Arc = self.layers.get_mut(*first)?; + for &i in rest { + cur = Arc::make_mut(cur).children_mut()?.get_mut(i)?; + } + Some(Arc::make_mut(cur)) + } + + /// [`Document::ancestry`] of the node at index path `path`. + pub fn ancestry_at(&self, path: &[usize]) -> Option> { + let mut out = Vec::with_capacity(path.len()); + let mut nodes = &self.layers; + for &i in path { + let n = nodes.get(i)?; + out.push(n.id); + if let Some(ch) = n.children() { + nodes = ch; + } + } + Some(out) + } + + /// Ids from the top-level layer down to `id` inclusive. + pub fn ancestry(&self, id: NodeId) -> Option> { + let path = self.index_path(id)?; + let mut out = Vec::with_capacity(path.len()); + let mut nodes = &self.layers; + for &i in &path { + let n = &nodes[i]; + out.push(n.id); + if let Some(ch) = n.children() { + nodes = ch; + } + } + Some(out) + } + + pub fn parent_of(&self, id: NodeId) -> Option { + let a = self.ancestry(id)?; + (a.len() >= 2).then(|| a[a.len() - 2]) + } + + /// The top-level layer that contains `id`. + pub fn layer_of(&self, id: NodeId) -> Option { + self.ancestry(id).and_then(|a| a.first().copied()) + } + + /// Mutable access to a node; clones the Arc path (copy-on-write). + pub fn node_mut(&mut self, id: NodeId) -> Option<&mut Node> { + let path = self.index_path(id)?; + let mut cur: &mut Arc = &mut self.layers[path[0]]; + for &i in &path[1..] { + cur = &mut Arc::make_mut(cur).children_mut()?[i]; + } + Some(Arc::make_mut(cur)) + } + + /// Children list of a container (or the top-level layer list for `None`). + pub fn children_mut(&mut self, parent: Option) -> Result<&mut Vec>, DocError> { + match parent { + None => Ok(&mut self.layers), + Some(p) => self.node_mut(p).ok_or(DocError::NoNode(p))?.children_mut().ok_or(DocError::NotContainer(p)), + } + } + + pub fn children(&self, parent: Option) -> Option<&Vec>> { + match parent { + None => Some(&self.layers), + Some(p) => self.node(p)?.children(), + } + } + + /// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top). + pub fn insert(&mut self, parent: Option, index: usize, node: Node) -> Result { + let id = node.id; + let ch = self.children_mut(parent)?; + let i = index.min(ch.len()); + ch.insert(i, Arc::new(node)); + Ok(id) + } + + /// Remove a node and return it. + pub fn remove(&mut self, id: NodeId) -> Result, DocError> { + let parent = self.parent_of(id); + let path = self.index_path(id).ok_or(DocError::NoNode(id))?; + let idx = *path.last().ok_or(DocError::NoNode(id))?; + let ch = self.children_mut(parent)?; + if idx >= ch.len() { + return Err(DocError::NoNode(id)); + } + Ok(ch.remove(idx)) + } + + /// Move a node to `parent` at `index` (index measured after removal). + pub fn move_node(&mut self, id: NodeId, parent: Option, index: usize) -> Result<(), DocError> { + if let Some(p) = parent + && self.ancestry(p).is_some_and(|a| a.contains(&id)) + { + return Err(DocError::Invalid("cannot move an object into itself".into())); + } + let n = self.remove(id)?; + let ch = self.children_mut(parent)?; + let i = index.min(ch.len()); + ch.insert(i, n); + Ok(()) + } + + /// Position of `id` within its parent: (parent, index, sibling count). + pub fn position(&self, id: NodeId) -> Option<(Option, usize, usize)> { + let parent = self.parent_of(id); + let idx = *self.index_path(id)?.last()?; + let n = self.children(parent)?.len(); + Some((parent, idx, n)) + } + + /// Remove the nodes `ids` names and return them in the order of `ids`, in one pass over the + /// children of each parent. Each id is listed once and none lies inside another listed node, as + /// in a list of top-level objects. For an id that is not in the tree, is listed twice or lies + /// inside another listed node, it fails with `NoNode` and leaves the document as it was. + pub fn remove_many(&mut self, ids: &[NodeId]) -> Result>, DocError> { + let places = self.places(ids)?; + let removed = self.take(places, ids.len())?; + self.index.clear(); + Ok(removed) + } + + /// Remove the nodes `ids` names, as [`Document::remove_many`] does, and put the node that `make` + /// builds from them (in the order of `ids`) in the parent of the last of them, at that node's + /// index less the number of listed nodes below it there. Returns the new node's id. + pub fn wrap(&mut self, ids: &[NodeId], make: impl FnOnce(Vec>) -> Node) -> Result { + let places = self.places(ids)?; + let last = ids.len().checked_sub(1); + let found = places.iter().find_map(|(up, kids)| kids.iter().find(|(_, k)| Some(*k) == last).map(|(i, _)| (up.clone(), *i))); + let Some((up, i)) = found else { return Err(DocError::Invalid("nothing to wrap".into())) }; + // The parent and each node it is in move down by the listed nodes before them. + let below = |parent: &[usize], index: usize| places.get(parent).map_or(0, |kids| kids.partition_point(|(j, _)| *j < index)); + let to: Vec = up.iter().enumerate().map(|(l, &j)| j.saturating_sub(below(&up[..l], j))).collect(); + let at = i.saturating_sub(below(&up, i)); + let node = make(self.take(places, ids.len())?); + let id = node.id; + let children = self.children_at(&to).ok_or_else(|| DocError::Invalid("the container of the listed objects is gone".into()))?; + let at = at.min(children.len()); + children.insert(at, Arc::new(node)); + self.index.clear(); + Ok(id) + } + + /// Put each list of nodes in `items` directly above its anchor (`replace`: in its place), in + /// list order, in one pass over the children of each parent. Each anchor is listed once and none + /// lies inside another. For an anchor that is not in the tree, is listed twice or lies inside + /// another listed anchor, it fails with `NoNode` and leaves the document as it was. + pub fn insert_beside(&mut self, items: Vec<(NodeId, Vec)>, replace: bool) -> Result<(), DocError> { + let anchors: Vec = items.iter().map(|(id, _)| *id).collect(); + let places = self.places(&anchors)?; + let mut lists: Vec> = items.into_iter().map(|(_, nodes)| nodes).collect(); + self.edit_children(places, |k, anchor, children| { + if !replace { + children.push(anchor); + } + let nodes = lists.get_mut(k).map(std::mem::take).unwrap_or_default(); + children.extend(nodes.into_iter().map(Arc::new)); + })?; + self.index.clear(); + Ok(()) + } + + /// Where each of `ids` is ([`Places`]). Fails with `NoNode` for an id that is not in the tree, + /// is listed twice or lies inside another listed node. + fn places(&self, ids: &[NodeId]) -> Result { + let paths = self.index_paths(ids.iter().copied()); + let mut places = Places::new(); + for (k, id) in ids.iter().enumerate() { + let (&i, up) = paths.get(id).and_then(|p| p.split_last()).ok_or(DocError::NoNode(*id))?; + match places.get_mut(up) { + Some(kids) => kids.push((i, k)), + None => { + places.insert(up.to_vec(), vec![(i, k)]); + } + } + } + for kids in places.values_mut() { + kids.sort_unstable(); + } + // An id listed twice has one path, so its parent lists the same child twice. A listed node + // lies inside another when its parent's path, or a part of it from the top, is the path of a + // listed node. + let twice = places.values().flat_map(|kids| kids.windows(2)).find(|w| w[0].0 == w[1].0).map(|w| w[1].1); + let listed = |path: &[usize]| { + path.split_last().is_some_and(|(i, up)| places.get(up).is_some_and(|kids| kids.binary_search_by_key(i, |(j, _)| *j).is_ok())) + }; + let nested = places.iter().find(|(up, _)| (1..=up.len()).any(|l| listed(&up[..l]))); + let inner = nested.and_then(|(_, kids)| kids.first()).map(|(_, k)| *k); + if let Some(id) = twice.or(inner).and_then(|k| ids.get(k)) { + return Err(DocError::NoNode(*id)); + } + Ok(places) + } + + /// Take the nodes `places` lists out of their parents and return them in the order of the list, + /// which is `len` long. + fn take(&mut self, places: Places, len: usize) -> Result>, DocError> { + let mut taken = vec![None; len]; + self.edit_children(places, |k, node, _| { + if let Some(t) = taken.get_mut(k) { + *t = Some(node); + } + })?; + Ok(taken.into_iter().flatten().collect()) + } + + /// Rebuild the children of each parent in `places` once, the parents later in tree order + /// first. `each` gets each listed child, its place in the list and the parent's new children, + /// onto which it pushes what takes the child's place. + fn edit_children(&mut self, places: Places, mut each: impl FnMut(usize, Arc, &mut Vec>)) -> Result<(), DocError> { + for (up, kids) in places.into_iter().rev() { + let children = self.children_at(&up).ok_or_else(|| DocError::Invalid("a container of the listed objects is gone".into()))?; + let old = std::mem::take(children); + children.reserve(old.len()); + let mut kids = kids.into_iter().peekable(); + for (i, node) in old.into_iter().enumerate() { + match kids.next_if(|(j, _)| *j == i) { + Some((_, k)) => each(k, node, children), + None => children.push(node), + } + } + } + Ok(()) + } + + /// The children of the node at index path `path`, or the top-level layers for an empty path. + fn children_at(&mut self, path: &[usize]) -> Option<&mut Vec>> { + match path { + [] => Some(&mut self.layers), + _ => self.node_mut_at(path)?.children_mut(), + } + } + + /// Default target layer: the topmost visible, unlocked layer. + pub fn default_layer(&self) -> Option { + self.layers.iter().rev().find(|l| l.visible && !l.locked).or(self.layers.last()).map(|l| l.id) + } + + /// Add a new top-level layer above all others. + pub fn add_layer(&mut self, name: Option<&str>) -> NodeId { + let id = self.alloc_id(); + let n = self.layers.len(); + let name = name.map(str::to_string).unwrap_or_else(|| self.next_layer_name()); + self.layers.push(Arc::new(Node::layer(id, &name, LayerColor::Preset((n % LAYER_COLORS.len()) as u8)))); + id + } + + /// The default name of a new layer or sublayer, "Layer N". Layers and sublayers share the + /// numbering: it starts after the number of layers there are and skips any layer's name. + pub fn next_layer_name(&self) -> String { + let (mut count, mut taken) = (0, std::collections::HashSet::new()); + self.walk(|n| { + if n.is_layer() { + count += 1; + taken.extend(n.name.as_deref()); + } + }); + (count + 1..).map(|i| format!("Layer {i}")).find(|name| !taken.contains(name.as_str())).unwrap_or_default() + } + + /// Visit every node depth first in paint order (bottom to top). + pub fn walk<'a>(&'a self, mut f: impl FnMut(&'a Node)) { + for l in &self.layers { + l.walk(&mut f); + } + } + + pub fn node_count(&self) -> usize { + self.layers.iter().map(|l| l.count()).sum() + } + + /// Is the node (and every ancestor) visible and unlocked, and not on a locked artboard + /// ([`Document::on_locked_artboard`])? + pub fn is_editable(&self, id: NodeId) -> bool { + self.is_editable_with(&self.locked_artboards(), id) + } + + /// [`Document::is_editable`] with the locked artboards `locks` of this document, measured + /// once for many ids. + pub fn is_editable_with(&self, locks: &LockedArtboards, id: NodeId) -> bool { + self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| n.visible && !n.locked))) && !locks.holds_id(id) + } + + /// [`Document::is_editable`] for many ids: the art on the locked artboards is measured once + /// for all of them, a group once for all its members. + pub fn editable(&self) -> impl Fn(NodeId) -> bool + '_ { + let locks = self.locked_artboards(); + move |id| self.is_editable_with(&locks, id) + } + + /// The locked artboards, for asking which art is on them ([`LockedArtboards::holds`]). + pub fn locked_artboards(&self) -> LockedArtboards<'_> { + self.locked_artboards_except(usize::MAX) + } + + /// [`Document::locked_artboards`] leaving out artboard `index`. + pub fn locked_artboards_except(&self, index: usize) -> LockedArtboards<'_> { + // Art flush with an edge from outside can overlap it by a rounding error, as in + // `art_bounds_on` (#1295). + let rects: Vec = + self.artboards.iter().enumerate().filter(|(i, a)| a.locked && *i != index).map(|(_, a)| a.rect.inflate(-1e-6, -1e-6)).collect(); + // The objects of pattern editing mode's layer, a sublayer's objects included. + fn objects(n: &Node, out: &mut std::collections::HashSet) { + for c in n.children().into_iter().flatten() { + if c.is_layer() { + objects(c, out); + } else { + out.insert(c.id); + } + } + } + let mut pattern_art = std::collections::HashSet::new(); + if let Some(layer) = self.pattern_edit.as_ref().filter(|_| !rects.is_empty()).and_then(|e| self.layers.iter().find(|l| l.id == e.layer)) { + objects(layer, &mut pattern_art); + } + LockedArtboards { rects, symbols: self.symbol_boxes(), new_art: self.new_art.get(), pattern_art, held: Default::default() } + } + + /// Is `id` on a locked artboard ([`LockedArtboards::holds_id`])? A layer or sublayer is on none. + pub fn on_locked_artboard(&self, id: NodeId) -> bool { + self.locked_artboards().holds_id(id) + } + + /// The object of a layer or sublayer that holds node `id`: `id` itself when it is one, else + /// the group or other object around it right inside a layer. None for a layer or sublayer. + pub fn layer_object(&self, id: NodeId) -> Option<&Node> { + self.layer_object_at(&self.index_path(id)?) + } + + /// [`Document::layer_object`] for the node at index path `path`. + pub fn layer_object_at(&self, path: &[usize]) -> Option<&Node> { + // Down the path to the first node that isn't a layer. + let mut nodes = &self.layers; + for &i in path { + let n = nodes.get(i)?; + if !n.is_layer() { + return Some(n.as_ref()); + } + nodes = n.children()?; + } + None + } + + pub fn is_visible(&self, id: NodeId) -> bool { + self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| n.visible))) + } + + /// The innermost layer or sublayer containing `id` (`id` itself when it is a layer). + pub fn layer_containing(&self, id: NodeId) -> Option { + let a = self.ancestry(id)?; + a.iter().rev().copied().find(|i| self.node(*i).is_some_and(Node::is_layer)) + } + + /// Every art object the Selection tool can reach (Select All): the visible, unlocked objects + /// of the visible, unlocked, non-template layers, looking through sublayers (bottom first), + /// except those on a locked artboard. + pub fn selectable_art(&self) -> Vec { + let locks = self.locked_artboards(); + self.layers + .iter() + .filter(|l| l.visible && !l.locked && !l.is_template()) + .flat_map(|l| l.layer_art(true)) + .filter(|id| locks.is_empty() || !self.node(*id).is_some_and(|n| locks.holds(n))) + .collect() + } + + /// Colour of the innermost layer or sublayer containing `id` (selection highlight colour). + pub fn layer_color(&self, id: NodeId) -> [u8; 3] { + let l = self.layer_containing(id).and_then(|l| self.node(l)); + match l.map(|n| &n.kind) { + Some(NodeKind::Layer { color, .. }) => color.rgb(), + _ => LAYER_COLORS[0].1, + } + } +} diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs new file mode 100644 index 0000000000..9d17f689a7 --- /dev/null +++ b/crates/doc/src/document_ext.rs @@ -0,0 +1,285 @@ +use super::graphic_style::GraphicStyle; +use super::limits::MAX_NEXT_ID; +use super::records::{ImageBlob, SavedSelection, SavedView}; +use super::*; + +impl Document { + /// The pixels image `im` shows: its own ([`ImageObject::pixels`]) or this document's. + pub fn image_blob<'a>(&'a self, im: &'a ImageObject) -> Option<&'a ImageBlob> { + im.pixels.as_deref().or_else(|| self.images.get(&im.key)) + } + + /// Take the pixels the images in `n` (its opacity masks' art included) hold themselves (art + /// made outside a document) into [`Self::images`]: under the image's key, or a free one when + /// the key shows other pixels. + pub fn adopt_pixels(&mut self, n: &mut Node) { + // Only what holds such pixels is copied out of the art it shares. + fn holds(n: &Node) -> bool { + matches!(&n.kind, NodeKind::Image(im) if im.pixels.is_some()) + || n.extras().mask.as_ref().is_some_and(|m| holds(&m.art)) + || n.children().into_iter().flatten().any(|c| holds(c)) + } + if let NodeKind::Image(im) = &mut n.kind { + self.adopt_image_pixels(im); + } + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) + && holds(&m.art) + { + self.adopt_pixels(Arc::make_mut(&mut m.art)); + } + for c in n.children_mut().into_iter().flatten() { + if holds(c) { + self.adopt_pixels(Arc::make_mut(c)); + } + } + } + + pub(crate) fn adopt_image_pixels(&mut self, im: &mut ImageObject) { + let Some(blob) = im.pixels.take() else { return }; + let mut key = im.key.clone(); + let mut i = 1; + while self.images.get(&key).is_some_and(|b| b.bytes != blob.bytes) { + i += 1; + key = format!("{}-{i}", im.key); + } + self.images.entry(key.clone()).or_insert_with(|| (*blob).clone()); + im.key = key; + } + + /// Saved selections as a file gives them, made safe to list and recall: at most + /// [`SavedSelection::MAX`], each with a clean, unique name and naming objects this document + /// has, each once. (An id it doesn't have would select whatever object takes that id later.) + pub fn tidy_saved_selections(&mut self) { + if self.saved_selections.is_empty() { + return; + } + let mut ids = std::collections::HashSet::new(); + self.walk(|n| { + ids.insert(n.id); + }); + let mut kept: Vec = vec![]; + for s in std::mem::take(&mut self.saved_selections) { + if kept.len() >= SavedSelection::MAX { + break; + } + let Some(name) = SavedSelection::clean_name(&s.name) else { continue }; + if kept.iter().any(|k| k.name == name) { + continue; + } + let mut seen = std::collections::HashSet::new(); + let objects = s.objects.into_iter().filter(|id| ids.contains(id) && seen.insert(*id)).collect(); + kept.push(SavedSelection { name, objects }); + } + self.saved_selections = kept.into(); + } + + /// Saved views as a file gives them, made safe to list and go to: at most [`SavedView::MAX`], + /// each with a clean, unique name, a finite centre and a finite, positive zoom (a rotation + /// that isn't finite becomes 0°). + pub fn tidy_views(&mut self) { + if self.views.is_empty() { + return; + } + let mut kept: Vec = vec![]; + for v in std::mem::take(&mut self.views) { + if kept.len() >= SavedView::MAX { + break; + } + let Some(name) = SavedView::clean_name(&v.name) else { continue }; + if !v.is_usable() || kept.iter().any(|k| k.name == name) { + continue; + } + let rotation = if v.rotation.is_finite() { v.rotation } else { 0.0 }; + kept.push(SavedView { name, rotation, ..v }); + } + self.views = kept; + } + + /// Leave opacity-mask editing: drop the temporary editing layer, a working copy of art the + /// mask already holds (the engine syncs it after every edit). + pub fn drop_edit_modes(&mut self) { + if let Some(me) = self.mask_edit.take() { + self.layers.retain(|l| l.id != me.layer); + } + } + + /// The document as saved and exported: without the opacity-mask editing layer. Borrowed when + /// no mask is being edited. (Pattern editing is saved: its tile layer holds unapplied edits.) + pub fn without_edit_modes(&self) -> std::borrow::Cow<'_, Document> { + if self.mask_edit.is_none() { + return std::borrow::Cow::Borrowed(self); + } + let mut d = self.clone(); + d.drop_edit_modes(); + std::borrow::Cow::Owned(d) + } +} + +/// Graphic styles. +impl Document { + /// Index of the graphic style named `name`. + pub fn graphic_style_index(&self, name: &str) -> Option { + self.graphic_styles.iter().position(|g| g.name == name) + } + + /// The graphic style named `name`. + pub fn graphic_style(&self, name: &str) -> Option<&GraphicStyle> { + self.graphic_styles.iter().find(|g| g.name == name) + } + + /// The graphic style with id `id` (0 never matches). + pub fn graphic_style_by_id(&self, id: u32) -> Option<&GraphicStyle> { + self.graphic_styles.iter().find(|g| g.id != 0 && g.id == id) + } + + /// An id no graphic style has. + pub fn next_graphic_style_id(&self) -> u32 { + free_id(self.graphic_styles.iter().map(|g| g.id)) + } + + /// The id of graphic style `index`, assigning one if it has none yet. + pub fn graphic_style_id(&mut self, index: usize) -> u32 { + if self.graphic_styles[index].id == 0 { + self.graphic_styles[index].id = self.next_graphic_style_id(); + } + self.graphic_styles[index].id + } + + /// The default name of a new graphic style: the first free "Graphic Style N", N counting on + /// from the number of styles. + pub fn new_graphic_style_name(&self) -> String { + (self.graphic_styles.len() + 1..).map(|i| format!("Graphic Style {i}")).find(|n| self.graphic_style(n).is_none()).unwrap_or_default() + } + + /// `base`, or the first free "`base` N" (N from 2) when a symbol already has that name. + pub fn unique_symbol_name(&self, base: &str) -> String { + let taken = |n: &str| self.symbols.iter().any(|s| s.name == n); + if !taken(base) { + return base.to_string(); + } + (2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| base.to_string()) + } + + /// Symbol Options › Registration for `name` (default: centre). + pub fn symbol_registration(&self, name: &str) -> SymbolRegistration { + self.unknown + .get(SYMBOL_REGISTRATION) + .and_then(|m| m.get(name)) + .and_then(|v| v.as_u64()) + .and_then(SymbolRegistration::from_u64) + .unwrap_or_default() + } + + /// Set or clear (when centre) the registration point stored for `name`. + pub fn set_symbol_registration(&mut self, name: &str, reg: SymbolRegistration) { + let m = self.unknown.entry(SYMBOL_REGISTRATION.to_string()).or_insert_with(|| serde_json::json!({})); + let Some(o) = m.as_object_mut() else { return }; + if reg.is_center() { + o.remove(name); + if o.is_empty() { + self.unknown.remove(SYMBOL_REGISTRATION); + } + } else { + o.insert(name.into(), serde_json::json!(reg.0)); + } + } + + /// Move the stored registration when a symbol is renamed. + pub fn rename_symbol_registration(&mut self, from: &str, to: &str) { + if from == to { + return; + } + let reg = self.symbol_registration(from); + self.set_symbol_registration(from, SymbolRegistration::CENTER); + self.set_symbol_registration(to, reg); + } + + /// Symbol Options › Export Type for `name` (default: Movie Clip). + pub fn symbol_export_type(&self, name: &str) -> SymbolExportType { + self.unknown.get(SYMBOL_EXPORT_TYPE).and_then(|m| m.get(name)).and_then(SymbolExportType::from_value).unwrap_or_default() + } + + /// Set or clear (when Movie Clip, the default) the export type stored for `name`. + pub fn set_symbol_export_type(&mut self, name: &str, kind: SymbolExportType) { + if kind.is_default() { + self.clear_symbol_export_type(name); + return; + } + let m = self.unknown.entry(SYMBOL_EXPORT_TYPE.to_string()).or_insert_with(|| serde_json::json!({})); + let Some(o) = m.as_object_mut() else { return }; + o.insert(name.into(), serde_json::json!(kind.id())); + } + + /// Drop any stored export type for `name` (Movie Clip default). + pub fn clear_symbol_export_type(&mut self, name: &str) { + let Some(m) = self.unknown.get_mut(SYMBOL_EXPORT_TYPE) else { return }; + let Some(o) = m.as_object_mut() else { return }; + o.remove(name); + if o.is_empty() { + self.unknown.remove(SYMBOL_EXPORT_TYPE); + } + } + + /// Move the stored export type when a symbol is renamed. + pub fn rename_symbol_export_type(&mut self, from: &str, to: &str) { + if from == to { + return; + } + let kind = self.symbol_export_type(from); + self.clear_symbol_export_type(from); + self.set_symbol_export_type(to, kind); + } + + /// Symbol Options › 9-slice guides for `name`: `None` when 9-slice scaling is off (default). + pub fn symbol_nine_slice(&self, name: &str) -> Option { + self.unknown.get(SYMBOL_NINE_SLICE).and_then(|m| m.get(name)).and_then(SymbolNineSlice::from_value) + } + + /// Turn 9-slice scaling on with `guides`, or off with `None`, for `name`. + pub fn set_symbol_nine_slice(&mut self, name: &str, guides: Option) { + let Some(g) = guides else { + let Some(o) = self.unknown.get_mut(SYMBOL_NINE_SLICE).and_then(|m| m.as_object_mut()) else { return }; + o.remove(name); + if o.is_empty() { + self.unknown.remove(SYMBOL_NINE_SLICE); + } + return; + }; + let m = self.unknown.entry(SYMBOL_NINE_SLICE.to_string()).or_insert_with(|| serde_json::json!({})); + if let Some(o) = m.as_object_mut() { + o.insert(name.into(), g.to_value()); + } + } + + /// Move the stored 9-slice guides when a symbol is renamed. + pub fn rename_symbol_nine_slice(&mut self, from: &str, to: &str) { + if from == to { + return; + } + let g = self.symbol_nine_slice(from); + self.set_symbol_nine_slice(from, None); + self.set_symbol_nine_slice(to, g); + } +} + +/// An id (never 0) none of `used` has: one past the largest, or, when that is the largest there +/// is (a damaged file), the smallest one free. +pub(crate) fn free_id(used: impl Iterator) -> u32 { + let mut used: Vec = used.collect(); + if let Some(next) = used.iter().max().copied().unwrap_or(0).checked_add(1) { + return next; + } + used.sort_unstable(); + used.dedup(); + // Ids 1, 2, 3… as far as they are all taken: the first that isn't follows them. + let taken = used.iter().filter(|&&id| id != 0).zip(1u32..).take_while(|&(&id, n)| id == n).count(); + u32::try_from(taken).map_or(u32::MAX, |n| n.saturating_add(1)) +} + +impl Document { + /// Make the next id allocated at least `next`: ids handed out outside the layer tree (such + /// as an importer's opacity mask and pattern art), which [`Document::fix_next_id`] doesn't see. + pub fn reserve_ids(&mut self, next: u64) { + self.next_id = self.next_id.max(next.min(MAX_NEXT_ID)); + } +} diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs new file mode 100644 index 0000000000..96af5c75b9 --- /dev/null +++ b/crates/doc/src/document_guides.rs @@ -0,0 +1,313 @@ +use super::document_ext::free_id; +use super::guides::Guide; +use super::*; + +impl Document { + /// Union of the geometric bounds of `ids` (their visual bounds when `visual`), with symbol + /// instances measured by their art ([`Node::geometric_bounds_with`]). + pub fn bounds_of(&self, ids: &[NodeId], visual: bool) -> Option { + let symbols = self.symbol_boxes(); + ids.iter().filter_map(|id| self.node(*id)).fold(None, |acc, n| { + vectorcraft_geom::union_opt(acc, if visual { n.visual_bounds_with(&symbols) } else { n.geometric_bounds_with(&symbols) }) + }) + } + + /// Visual bounds of all art, with symbol instances measured by their art. + pub fn art_bounds(&self) -> Option { + let symbols = self.symbol_boxes(); + self.layers.iter().fold(None, |acc, l| vectorcraft_geom::union_opt(acc, l.visual_bounds_with(&symbols))) + } + + /// Artboard index containing point `p` (topmost = last), its edges included + /// ([`Document::artboard_holding`]). + pub fn artboard_at(&self, p: Point) -> Option { + self.artboard_holding(p, true) + } + + /// Index of the artboard that holds point `p`: the first (the last when `topmost`) that holds it + /// inside or on its left or top edge, else the first (the last) that holds it by + /// [`artboard_holds`]: on its right or bottom edge, or within a millionth of a point outside an + /// edge. On an edge two artboards share, the artboard to the right of it or below it holds the + /// point, except at the end of the edge that lies on that artboard's bottom or right edge, such + /// as the point where both artboards' bottom edges meet; there the first (the last) holds it. + pub fn artboard_holding(&self, p: Point, topmost: bool) -> Option { + let pick = |on: &dyn Fn(Rect) -> bool| { + let on = |i: &usize| self.artboards.get(*i).is_some_and(|a| on(a.rect)); + let mut all = 0..self.artboards.len(); + if topmost { all.rfind(on) } else { all.find(on) } + }; + pick(&|r| r.contains(p)).or_else(|| pick(&|r| artboard_holds(r, p))) + } + + /// The art that moves with an artboard at `rect`: top-level objects (children of layers and + /// sublayers) lying entirely inside it, with symbol instances measured by their art. Locked and + /// hidden objects and layers stay put unless `locked_and_hidden` (Selection & Anchor Display › + /// Move Locked and Hidden Artwork with Artboard). + pub fn art_on_artboard(&self, rect: Rect, locked_and_hidden: bool) -> Vec { + // Art drawn flush with the artboard can end up a rounding error outside it (a background + // 3e-14 pt past the top edge, #1295): a millionth of a point is far below anything visible. + let rect = rect.inflate(1e-6, 1e-6); + fn collect(n: &Node, s: &SymbolBoxes, rect: Rect, all: bool, out: &mut Vec) { + for c in n.children().into_iter().flatten().filter(|c| c.rides_with_artboard(all)) { + if c.is_layer() { + collect(c, s, rect, all, out); + } else if let Some(b) = c.geometric_bounds_with(s) + // Inside it, edges included: art flush with the right or bottom edge is on it too + // (`Rect::contains` leaves those out, #890). + && b.x0 >= rect.x0 + && b.y0 >= rect.y0 + && b.x1 <= rect.x1 + && b.y1 <= rect.y1 + { + out.push(c.id); + } + } + } + let symbols = self.symbol_boxes(); + let mut art = vec![]; + for l in self.layers.iter().filter(|l| l.rides_with_artboard(locked_and_hidden)) { + collect(l, &symbols, rect, locked_and_hidden, &mut art); + } + art + } + + /// Does any artwork lie on `rect` (an artboard)? Artwork is any object under the layers, + /// hidden and locked ones and those on template layers included, whose visual bounds (symbol + /// instances measured by their art) meet `rect`; touching its edge counts. A group (not a clip + /// group) counts by its members, so one whose members sit on two other artboards leaves the one + /// between them empty. A clip group or clipping layer counts by its members inside its clip (and + /// by its clipping path where that paints). Guides (paths made into guides too) aren't artwork + /// (Delete Empty Artboards). + pub fn artboard_has_art(&self, rect: Rect) -> bool { + // As in `art_on_artboard`: a millionth of a point covers rounding at the edges. + let rect = rect.inflate(1e-6, 1e-6); + fn meets(b: Option, r: Rect) -> bool { + b.is_some_and(|b| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1) + } + fn has(c: &Node, s: &SymbolBoxes, rect: Rect) -> bool { + match &c.kind { + NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => { + let Some((clip, rest)) = children.split_first() else { return false }; + let paint = clip.clip_paint(); + if (paint.fill.is_some() || paint.stroke.is_some()) && meets(clip.visual_bounds_with(s), rect) { + return true; + } + // The members show only inside the clip's box. + let Some(b) = c.visual_bounds_with(s).filter(|b| meets(Some(*b), rect)) else { return false }; + let inside = Rect::new(b.x0.max(rect.x0), b.y0.max(rect.y0), b.x1.min(rect.x1), b.y1.min(rect.y1)); + rest.iter().any(|m| has(m, s, inside)) + } + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().any(|m| has(m, s, rect)), + NodeKind::Path { guide: true, .. } => false, + _ => meets(c.visual_bounds_with(s), rect), + } + } + let symbols = self.symbol_boxes(); + self.layers.iter().any(|l| has(l, &symbols, rect)) + } + + /// The art that moves, scales or is cut with artboard `index`: [`Document::art_on_artboard`] + /// without the objects on another locked artboard, which stay unless `locked_and_hidden`, as + /// locked art does. + pub fn art_moving_with(&self, index: usize, locked_and_hidden: bool) -> Vec { + let Some(rect) = self.artboards.get(index).map(|a| a.rect) else { return vec![] }; + let mut art = self.art_on_artboard(rect, locked_and_hidden); + let locks = self.locked_artboards_except(index); + if !locked_and_hidden && !locks.is_empty() { + art.retain(|id| !self.node(*id).is_some_and(|n| locks.holds(n))); + } + art + } + + /// Where ruler guide `g` runs along its line (the y range of a vertical guide): across its + /// artboard for an artboard guide, None (the whole canvas) for a canvas guide or one whose + /// artboard is gone. + pub fn guide_span(&self, g: &Guide) -> Option<(f64, f64)> { + let r = self.artboards.iter().find(|a| Some(a.id) == g.artboard)?.rect; + Some(if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) }) + } + + /// The layer (or sublayer) ruler guide `g` is on, if it is on one this document has. + fn guide_layer(&self, g: &Guide) -> Option { + g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer)) + } + + /// Is ruler guide `g` shown: on no layer, or on a layer that (with the layers around it) is + /// visible? A guide whose layer is gone shows as one on no layer. + pub fn guide_shown(&self, g: &Guide) -> bool { + self.guide_layer(g).is_none_or(|l| self.is_visible(l)) + } + + /// Can ruler guide `g` be picked, moved and deleted: shown, and its layer unlocked? + pub fn guide_editable(&self, g: &Guide) -> bool { + self.guide_layer(g).is_none_or(|l| self.is_editable(l)) + } + + /// Put the ruler guides on no layer this document has (from files saved before guides had + /// layers, or of layers merged into `layer`) on layer `layer`. Returns how many. + pub fn rehome_guides(&mut self, layer: NodeId) -> usize { + let lost: Vec = self.guides.iter().map(|g| self.guide_layer(g).is_none()).collect(); + let mut n = 0; + for (g, lost) in self.guides.iter_mut().zip(lost) { + if lost { + g.layer = Some(layer); + n += 1; + } + } + n + } + + /// Put the ruler guides on no layer (from files saved before guides had layers), or on one that + /// is gone, on the top visible, unlocked layer ([`Self::default_layer`]). Returns how many. + pub fn adopt_guides(&mut self) -> usize { + self.default_layer().map_or(0, |home| self.rehome_guides(home)) + } + + /// Delete the ruler guides whose layer was deleted (they go with it), keeping `sel`'s guides in + /// step. Guides on no layer stay. Returns how many went. + pub fn drop_guides_of_deleted_layers(&mut self, sel: &mut Selection) -> usize { + let gone: Vec = self.guides.iter().map(|g| g.layer.is_some() && self.guide_layer(g).is_none()).collect(); + self.retain_guides(sel, |i, _| !gone.get(i).copied().unwrap_or(false)) + } + + /// Copy the ruler guides of layer `from` and of its sublayers onto their copies in `copy` (made + /// from `from` by [`Self::reid`]: the same tree with fresh ids), as duplicating a layer copies + /// the objects on it. Returns how many. + pub fn copy_layer_guides(&mut self, from: &Node, copy: &Node) -> usize { + let layers = |n: &Node| { + let mut out = vec![]; + n.walk(&mut |c| { + if c.is_layer() { + out.push(c.id); + } + }); + out + }; + let pairs: Vec<(NodeId, NodeId)> = layers(from).into_iter().zip(layers(copy)).collect(); + let copies: Vec = self + .guides + .iter() + .filter_map(|g| { + let to = pairs.iter().find(|(a, _)| Some(*a) == g.layer)?.1; + Some(Guide { layer: Some(to), ..g.clone() }) + }) + .collect(); + let n = copies.len(); + self.guides.extend(copies); + n + } + + /// The ruler guides on layer `layer` (not its sublayers'), by index. + pub fn guides_on(&self, layer: NodeId) -> impl Iterator + '_ { + self.guides.iter().enumerate().filter(move |(_, g)| g.layer == Some(layer)) + } + + /// Does ruler guide `g` run past `p` (up to `tol` beyond its ends)? + pub fn guide_passes(&self, g: &Guide, p: Point, tol: f64) -> bool { + let along = if g.vertical { p.y } else { p.x }; + self.guide_span(g).is_none_or(|(a, b)| along >= a - tol && along <= b + tol) + } + + /// Keep the ruler guides `keep` accepts (by index), the selected ones left keeping their + /// place among the rest (the selected art stays selected). Returns how many went. + pub fn retain_guides(&mut self, sel: &mut Selection, keep: impl Fn(usize, &Guide) -> bool) -> usize { + let kept: Vec = self.guides.iter().enumerate().map(|(i, g)| keep(i, g)).collect(); + // Where each kept guide ends up. + let (mut to, mut n) = (Vec::with_capacity(kept.len()), 0); + for k in &kept { + to.push(k.then_some(n)); + n += usize::from(*k); + } + sel.guides = sel.guides.iter().filter_map(|i| to.get(*i).copied().flatten()).collect(); + sel.key_guide = sel.key_guide.and_then(|i| to.get(i).copied().flatten()); + let before = self.guides.len(); + let mut flags = kept.into_iter(); + self.guides.retain(|_| flags.next().unwrap_or(true)); + before - self.guides.len() + } + + /// Move the guides of artboard `id` by `d` (along with their artboard). + pub fn move_artboard_guides(&mut self, id: u32, d: Vec2) { + for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) { + *g = g.moved(d); + } + } + + /// Map the guides of artboard `id` through `xf`, an axis-aligned scale and move (Scale Artwork + /// with Artboard). + pub fn map_artboard_guides(&mut self, id: u32, xf: Affine) { + for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) { + g.pos = if g.vertical { (xf * Point::new(g.pos, 0.0)).x } else { (xf * Point::new(0.0, g.pos)).y }; + } + } + + /// Copy the guides of artboard `from` onto artboard `to`, `d` away (with a copy of their + /// artboard). + pub fn copy_artboard_guides(&mut self, from: u32, to: u32, d: Vec2) { + let copies: Vec = + self.guides.iter().filter(|g| g.artboard == Some(from)).map(|g| Guide { artboard: Some(to), ..g.moved(d) }).collect(); + self.guides.extend(copies); + } + + /// An id for a new artboard: one no artboard has, above the ids given out before and the ids of + /// the artboards deleted from the document ([`Document::retired_artboard_id`]). The id counts + /// as given out, so an artboard made after an undo does not take the id of one the undo took + /// away. + pub fn next_artboard_id(&self) -> u32 { + let id = free_id(self.artboards.iter().map(|a| a.id).chain([self.retired_artboard_id.get()])); + self.retired_artboard_id.raise(id); + 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); + } + + pub fn pattern(&self, name: &str) -> Option<&PatternDef> { + self.patterns.iter().find(|p| p.name == name) + } + + pub fn pattern_mut(&mut self, name: &str) -> Option<&mut PatternDef> { + self.patterns.iter_mut().find(|p| p.name == name) + } + + /// Deep-clone `node` with fresh ids for it and all descendants, its images' own pixels taken + /// in ([`Self::adopt_pixels`]). + pub fn reid(&mut self, node: &Node) -> Node { + let mut n = node.clone(); + n.id = self.alloc_id(); + if let NodeKind::Image(im) = &mut n.kind { + self.adopt_image_pixels(im); + } + // A copied annotation must never bind its source ids to unrelated art in a different + // document. Keep the measured geometry; new measurements can be linked after pasting. + if let Some(e) = n.extras_if_any() + && let Some(dimension) = &mut e.dimension + { + dimension.source = None; + } + // A copy of a threaded frame is in no thread, so its first paragraph starts in it and its + // layout caches are dropped. A caller that keeps the copy as an object fills them again. + if let NodeKind::Text(t) = &mut n.kind + && t.first_para_continues + { + t.first_para_continues = false; + t.cached_bounds = None; + t.cached_baselines.clear(); + } + let mut renamed = std::collections::HashMap::new(); + if let Some(ch) = n.children_mut() { + let old: Vec> = std::mem::take(ch); + *ch = old.iter().map(|c| Arc::new(self.reid(c))).collect(); + renamed.extend(old.iter().zip(ch.iter()).map(|(o, c)| (o.id, c.id))); + } + // An Objects on Path group names its path and its objects by id: the copy names the copies. + if let Some(e) = n.extras_if_any() + && let Some(on_path) = &mut e.objects_on_path + { + on_path.rename(&renamed); + } + n + } +} diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 9da5d0d0ca..34c2a1dd99 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -127,7 +127,7 @@ impl crate::Document { break; } let Some(name) = GraphDesign::clean_name(&d.name) else { continue }; - if kept.iter().any(|k| k.name == name) || d.art.count() > GraphDesign::MAX_NODES { + if kept.iter().any(|k| k.name == name) || d.art.count_with_masks() > GraphDesign::MAX_NODES { continue; } kept.push(GraphDesign { name, art: std::sync::Arc::new(GraphDesign::plain_art(&d.art)) }); diff --git a/crates/doc/src/graphic_style.rs b/crates/doc/src/graphic_style.rs new file mode 100644 index 0000000000..95c61b6ebf --- /dev/null +++ b/crates/doc/src/graphic_style.rs @@ -0,0 +1,92 @@ +use super::*; + +/// A named graphic style (Graphic Styles panel): an appearance plus the object's transparency. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct GraphicStyle { + pub name: String, + pub appearance: Appearance, + /// Stable id linked objects refer to ([`Node::graphic_style`]); 0 until first needed (styles + /// from older files get one when an object is first linked to them). + #[serde(default, skip_serializing_if = "skip::is_default")] + pub id: u32, + #[serde(default = "one", skip_serializing_if = "skip::is_one")] + pub opacity: f32, + #[serde(default, skip_serializing_if = "skip::is_default")] + pub blend: vectorcraft_color::BlendMode, + #[serde(default, skip_serializing_if = "skip::is_default")] + pub isolate: bool, + #[serde(default, skip_serializing_if = "skip::is_default")] + pub knockout: Knockout, + /// Placed gradients are stored relative to the unit box (0, 0)–(1, 1), so applying the style + /// places them on each object's own bounds. Styles saved before this kept document + /// coordinates (false). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub unit_box: bool, +} + +fn one() -> f32 { + 1.0 +} + +/// The name of the style new documents list first (Sort by Name keeps it first). +pub const DEFAULT_GRAPHIC_STYLE: &str = "Default Graphic Style"; + +impl GraphicStyle { + /// The box a style's placed gradients are stored relative to. + pub const UNIT_BOX: Rect = Rect::new(0.0, 0.0, 1.0, 1.0); + + /// A style with `appearance` (its placed gradients, if any, in unit-box space) and default + /// transparency (no id yet). + pub fn new(name: impl Into, appearance: Appearance) -> Self { + Self { + name: name.into(), + appearance, + id: 0, + opacity: 1.0, + blend: Default::default(), + isolate: false, + knockout: Knockout::Neutral, + unit_box: true, + } + } + /// A style capturing `n`'s transparency and `appearance` (in unit-box space). + pub fn of(name: impl Into, appearance: Appearance, n: &Node) -> Self { + Self { opacity: n.opacity, blend: n.blend, isolate: n.isolate, knockout: n.knockout, ..Self::new(name, appearance) } + } + /// The style's appearance as object `n` takes it: placed gradients stored in unit-box space + /// land at the same place relative to `n`'s geometric bounds. + pub fn appearance_on(&self, n: &Node) -> std::borrow::Cow<'_, Appearance> { + let placed = self.unit_box && self.appearance.has_placed_gradient(); + match n.geometric_bounds().filter(|_| placed) { + Some(b) => { + let mut ap = self.appearance.clone(); + ap.rebase_gradients(Self::UNIT_BOX, b); + std::borrow::Cow::Owned(ap) + } + None => std::borrow::Cow::Borrowed(&self.appearance), + } + } + /// Give `n` this style's transparency. + pub fn apply_transparency(&self, n: &mut Node) { + (n.opacity, n.blend, n.isolate, n.knockout) = (self.opacity, self.blend, self.isolate, self.knockout); + } + /// Does `n` have this style's transparency? + pub fn transparency_matches(&self, n: &Node) -> bool { + (n.opacity, n.blend, n.isolate, n.knockout) == (self.opacity, self.blend, self.isolate, self.knockout) + } +} + +pub(crate) fn default_graphic_styles() -> Vec { + use vectorcraft_color::{Color, Paint}; + let solid = |hex| Paint::solid(Color::from_hex(hex).unwrap_or(Color::BLACK)); + [ + GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art()), + GraphicStyle::new("Black Outline", Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)), + GraphicStyle::new("Heavy Ink", Appearance::basic(solid("#1b1464"), Paint::solid(Color::BLACK), 4.0)), + GraphicStyle::new("Sunshine", Appearance::basic(solid("#fbb03b"), solid("#f15a24"), 2.0)), + ] + .into_iter() + .zip(1..) + .map(|(g, id)| GraphicStyle { id, ..g }) + .collect() +} diff --git a/crates/doc/src/guides.rs b/crates/doc/src/guides.rs new file mode 100644 index 0000000000..0c10efff20 --- /dev/null +++ b/crates/doc/src/guides.rs @@ -0,0 +1,58 @@ +use super::*; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Guide { + /// true = vertical guide at `pos` (x), false = horizontal at `pos` (y). + pub vertical: bool, + pub pos: f64, + /// An artboard guide: the [`Artboard::id`] it belongs to. It runs across that artboard only + /// and moves, is copied and is deleted with it. None: a canvas guide, across the whole canvas. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub artboard: Option, + /// The layer (or sublayer) it is on: it shows, hides and locks with that layer and is listed + /// in it in the Layers panel, and goes when the layer is deleted. None: on no layer (guides + /// from before guides had layers, and from files that don't say), always there. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub layer: Option, +} + +impl Guide { + /// A canvas guide. + pub fn new(vertical: bool, pos: f64) -> Self { + Self { vertical, pos, artboard: None, layer: None } + } + + /// Moved by `d` (a vertical guide across, a horizontal one down). + pub fn moved(&self, d: Vec2) -> Self { + Self { pos: self.pos + if self.vertical { d.x } else { d.y }, ..self.clone() } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct GridPrefs { + pub spacing: f64, + pub subdivisions: u32, +} + +impl Default for GridPrefs { + fn default() -> Self { + Self { spacing: 72.0, subdivisions: 8 } + } +} + +/// What the rulers measure from (View › Rulers): the active artboard's origin, the default of a +/// new document, or one origin for the whole document. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum RulerMode { + #[default] + Artboard, + Global, +} + +impl RulerMode { + /// The mode of a document saved before the choice existed: global, as its rulers measured. + pub fn legacy() -> Self { + Self::Global + } +} diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 81d1d12f63..d93f923d39 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -66,11 +66,16 @@ pub struct HitOptions { /// Guide objects (paths made into guides) are not hittable: View › Guides › Lock Guides is /// on or the guides are hidden. pub skip_guides: bool, + /// The selection tools: a clip group's clipping path is hit on its outline, within the + /// tolerance, before the art it clips, so that the mask can be reached where the art covers + /// its edge. Off for the tools that act on what is drawn (sampling, type, gradients…); + /// [`hit_test_visible`] never does it. + pub clip_outlines: bool, } impl Default for HitOptions { fn default() -> Self { - Self { tol: 3.0, outline: false, path_only: false, type_path_only: false, skip_guides: false, scope: None } + Self { tol: 3.0, outline: false, path_only: false, type_path_only: false, skip_guides: false, clip_outlines: false, scope: None } } } @@ -134,6 +139,11 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option, seen: &mut HashSet) -> bool { let Some(children) = layer.children() else { return true }; - if layer.clips() && children.first().is_some_and(|clip| !clip_contains(clip, p)) { - return true; + if layer.clips() + && let Some(clip) = children.first() + { + // As the hit test does: the clipping mask's outline first, then only inside the mask. + if clip_outline_hit(layer, clip, p, opt, symbols, true).is_some() && seen.insert(clip.id) { + tops.push(clip.id); + } + if !clip_contains(clip, p) { + return true; + } } let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt }; for (i, c) in children.iter().enumerate().rev() { @@ -267,14 +285,24 @@ fn locked_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> boo } } -/// [`hit_test`] passing over the nodes `skip` names (and their contents). Symbol instances are -/// measured by their art ([`Node::geometric_bounds_with`]). +/// [`hit_test`] passing over the nodes `skip` names (and their contents), and with +/// `editable_only` over the objects of layers and sublayers on a locked artboard, and over all of +/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art +/// ([`Node::geometric_bounds_with`]). fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option { let finish = |mut h: Hit| { h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents)); h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count(); h }; + let locks = doc.locked_artboards(); + let on_locked = |id: NodeId| { + editable_only + && !locks.is_empty() + && doc.parent_of(id).and_then(|l| doc.node(l)).is_some_and(Node::is_layer) + && doc.node(id).is_some_and(|n| locks.holds(n)) + }; + let skip = &|id| skip(id) || on_locked(id); let symbols = doc.symbol_boxes(); // Isolation mode: only what is inside the isolated container hits. The art around it is // locked, and clicks pass through it (#833). @@ -283,6 +311,10 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No && let Some(isolated) = doc.node(scope) && let Some(mut chain) = doc.ancestry(scope) { + // Isolated before its artboard was locked: nothing in it hits. + if locks.holds_id(scope) { + return None; + } if isolated.is_container() { return hit_children(isolated, p, opt, &symbols, skip, &mut chain, editable_only).map(finish); } @@ -363,6 +395,31 @@ fn shaper_hides(parent: &Node, i: usize, scope: Option) -> bool { parent.extras().shaper.is_some() && (i == 0) != source_of(parent, scope) } +/// A press on the outline of clipping path `clip` (a path or a compound path; type clips by its +/// glyphs, which this crate cannot outline), within the tolerance. +fn clip_outline(clip: &Node, p: Point, opt: HitOptions) -> Option { + let bp = match &clip.kind { + NodeKind::Path { path, .. } => path.to_bezpath(), + NodeKind::Compound { .. } => clip.stroke_path()?, + _ => return None, + }; + stroke_contains(&bp, 0.0, opt.tol, p).then_some(HitKind::Outline) +} + +/// For the selection tools ([`HitOptions::clip_outlines`]), a press on the outline of `clip`, the +/// clipping path of `parent` (a clip group or a layer with a clipping mask), within the tolerance: +/// it is hit before the art it clips. There Direct Selection takes its segments, and the +/// Selection tool the clip group. The reference app reshapes a clipping path with Direct Selection +/// (); +/// without this, art drawn over the path's edge is hit first and its segments can't be dragged. +/// The clipping path must be one a click may hit ([`may_hit`]: visible, editable, within reach). +fn clip_outline_hit(parent: &Node, clip: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editable_only: bool) -> Option { + if !opt.clip_outlines || !editable_only || !may_hit(parent, 0, clip, p, opt, symbols, editable_only) { + return None; + } + clip_outline(clip, p, opt) +} + fn hit_children( parent: &Node, p: Point, @@ -373,12 +430,17 @@ fn hit_children( editable_only: bool, ) -> Option { let children = parent.children()?; - // A clip group (or a layer with a clipping mask) only hits inside its clipping path. if parent.clips() && let Some(clip) = children.first() - && !clip_contains(clip, p) { - return None; + if let Some(kind) = clip_outline_hit(parent, clip, p, opt, symbols, editable_only).filter(|_| !skip(clip.id)) { + chain.push(clip.id); + return Some(Hit { leaf: clip.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 }); + } + // Elsewhere a clip group (or a layer with a clipping mask) only hits inside it. + if !clip_contains(clip, p) { + return None; + } } for i in hit_order(parent, children, p) { let Some(c) = children.get(i) else { continue }; @@ -460,10 +522,18 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio n.geometric_bounds().filter(|b| b.inflate(opt.tol, opt.tol).contains(p))?; on_type_path(n, t, p, opt.tol).then_some(HitKind::Outline) } - // An image is hit within its frame, and where its own fills and strokes paint - // ([`image_paint`]) except in outline mode. - NodeKind::Image(_) => { - if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { + // An image is hit within its frame (on the frame's edge only with Selection by Path Only, + // #3291), and where its own fills and strokes paint ([`image_paint`]) except in outline + // mode. + NodeKind::Image(im) => { + if opt.path_only { + use vectorcraft_geom::kurbo::Shape; + let mut frame = Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1); + frame.apply_affine(im.xf); + if stroke_contains(&frame, 0.0, opt.tol, p) { + return Some(HitKind::Outline); + } + } else if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { return Some(HitKind::Bounds); } if opt.outline { @@ -477,7 +547,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } | NodeKind::Blend { .. } | NodeKind::Envelope { .. } => { n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds) } - NodeKind::Repeat(r) => r.expand().iter().find_map(|g| hit_any(g, p, opt, symbols)), + NodeKind::Repeat(r) => r.expand(Some(symbols.document())).iter().find_map(|g| hit_any(g, p, opt, symbols)), NodeKind::Mesh(m) => { let bp = m.outline().to_bezpath(); if stroke_contains(&bp, 0.0, opt.tol, p) { @@ -533,10 +603,11 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { parts.iter().filter(|(_, bp, _)| fill_contains(bp, *rule, p)).min_by(|a, b| size(&a.2).total_cmp(&size(&b.2))).map(|(id, ..)| *id) } -/// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect. Symbol -/// instances are measured by their art ([`Node::geometric_bounds_with`]). The art of a clip group -/// or of a layer with a clipping mask counts only when the marquee meets the region its clipping -/// path clips to, and then only within that region's bounds. +/// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving +/// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured +/// by their art ([`Node::geometric_bounds_with`]). The art of a clip group or of a layer with a +/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then +/// only within that region's bounds. pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> Vec { let mut out = Vec::new(); // `tops` pairs each object with the part of `r` in which the marquee can touch it. @@ -588,7 +659,7 @@ pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => marquee_in(n, r) .is_some_and(|r| children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope))), NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope)), - NodeKind::Repeat(spec) => spec.expand().iter().any(|copy| touches(copy, s, r, scope)), + NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope)), // A box with no width or no height (an instance of a symbol that draws a straight // line) is touched where the marquee crosses it. _ => n.geometric_bounds_with(s).is_some_and(|b| { @@ -615,8 +686,9 @@ pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> } } let symbols = doc.symbol_boxes(); + let locks = doc.locked_artboards(); for (t, r) in tops { - if !t.visible || t.locked { + if !t.visible || t.locked || locks.holds_id(t.id) { continue; } if leaves { @@ -659,739 +731,4 @@ fn marquee_in_clip(clip: &Node, r: Rect) -> Option { } #[cfg(test)] -mod tests { - use super::*; - use crate::{Appearance, Node}; - use std::sync::Arc; - use vectorcraft_color::{Color, Paint}; - use vectorcraft_geom::shapes; - - #[test] - fn hits_topmost() { - let mut d = Document::new(200.0, 200.0); - let l = d.layers[0].id; - let a = d.alloc_id(); - d.insert(Some(l), 9, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap(); - let b = d.alloc_id(); - d.insert(Some(l), 9, Node::path(b, shapes::rectangle(Rect::new(25.0, 25.0, 75.0, 75.0)), Appearance::default_art())).unwrap(); - let h = hit_test(&d, Point::new(30.0, 30.0), HitOptions::default()).unwrap(); - assert_eq!(h.leaf, b); - assert_eq!(h.kind, HitKind::Fill); - let h = hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).unwrap(); - assert_eq!(h.leaf, a); - assert!(hit_test(&d, Point::new(150.0, 150.0), HitOptions::default()).is_none()); - // Outline mode: interior misses. - assert!(hit_test(&d, Point::new(10.0, 10.0), HitOptions { outline: true, ..Default::default() }).is_none()); - assert!(hit_test(&d, Point::new(0.5, 10.0), HitOptions { outline: true, ..Default::default() }).is_some()); - } - - #[test] - fn unfilled_interior_misses() { - let mut d = Document::new(200.0, 200.0); - let l = d.layers[0].id; - let a = d.alloc_id(); - d.insert( - Some(l), - 9, - Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)), - ) - .unwrap(); - assert!(hit_test(&d, Point::new(25.0, 25.0), HitOptions::default()).is_none()); - assert!(hit_test(&d, Point::new(50.5, 25.0), HitOptions::default()).is_some()); - } - - /// #1103: a marquee drawn over a background picks what is on it, not the background, whose - /// outline it doesn't touch. - #[test] - fn a_marquee_inside_a_background_leaves_the_background() { - let mut d = Document::new(200.0, 200.0); - let l = d.layers[0].id; - let (back, small) = (d.alloc_id(), d.alloc_id()); - d.insert(Some(l), 0, Node::path(back, shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default_art())).unwrap(); - d.insert(Some(l), 1, Node::path(small, shapes::rectangle(Rect::new(50.0, 50.0, 60.0, 60.0)), Appearance::default_art())).unwrap(); - assert_eq!(marquee(&d, Rect::new(40.0, 40.0, 70.0, 70.0), None, false), vec![small]); - // Reaching the background's edge takes it too. - assert_eq!(marquee(&d, Rect::new(-5.0, 40.0, 70.0, 70.0), None, false), vec![back, small]); - } - - #[test] - fn group_top_object() { - let mut d = Document::new(200.0, 200.0); - let l = d.layers[0].id; - let a = d.alloc_id(); - let g = d.alloc_id(); - let p = Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art()); - d.insert(Some(l), 0, Node::group(g, vec![Arc::new(p)])).unwrap(); - let h = hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).unwrap(); - assert_eq!(h.leaf, a); - assert_eq!(h.top_object(None), g); - assert_eq!(h.top_object(Some(g)), a); - assert_eq!(marquee(&d, Rect::new(-5.0, -5.0, 5.0, 5.0), None, false), vec![g]); - assert_eq!(marquee(&d, Rect::new(-5.0, -5.0, 5.0, 5.0), None, true), vec![a]); - assert!(marquee(&d, Rect::new(100.0, 100.0, 105.0, 105.0), None, false).is_empty()); - } - - /// The art of a 200 pt wide rectangle clipped to its left half (0..100 × 0..100): the mask and - /// the art, in that order. - fn half_clipped(d: &mut Document) -> (Node, Node) { - let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default()); - let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Appearance::default_art()); - (mask, art) - } - - /// #2345: a marquee touches a clip group only where its art shows. Over the clipped-away - /// half alone it selects nothing, and around a rectangle drawn beside the group's mask it - /// takes that rectangle alone; reaching into the mask takes the group. The same holds for - /// Group Selection's leaves and in isolation mode. - #[test] - fn a_marquee_leaves_a_clip_group_by_its_clipped_away_art() { - let mut d = Document::new(300.0, 200.0); - let l = d.layers[0].id; - let (mask, art) = half_clipped(&mut d); - let (g, art_id, beside) = (d.alloc_id(), art.id, d.alloc_id()); - let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); - clip.set_clips(true); - d.insert(Some(l), 0, clip).unwrap(); - d.insert(Some(l), 1, Node::path(beside, shapes::rectangle(Rect::new(150.0, 80.0, 190.0, 130.0)), Appearance::default_art())).unwrap(); - // This marquee crosses only the hidden art's top and right edges. - let hidden = Rect::new(150.0, -10.0, 210.0, 50.0); - assert!(marquee(&d, hidden, None, false).is_empty()); - assert!(marquee(&d, hidden, None, true).is_empty()); - assert!(marquee(&d, hidden, Some(g), false).is_empty()); - assert!(marquee(&d, hidden, Some(art_id), false).is_empty()); - // This marquee surrounds the rectangle beside and crosses the hidden art's bottom edge. - assert_eq!(marquee(&d, Rect::new(140.0, 70.0, 195.0, 140.0), None, false), vec![beside]); - // This marquee crosses the shown half's top edge and goes on into the hidden half. - let shown = Rect::new(50.0, -10.0, 160.0, 10.0); - assert_eq!(marquee(&d, shown, None, false), vec![g]); - assert!(marquee(&d, shown, None, true).contains(&art_id)); - assert_eq!(marquee(&d, shown, Some(g), false).len(), 2, "the mask and the art"); - } - - /// #2345: in the corner of a diamond mask's box, outside the diamond, a marquee over the - /// clipped art's corner leaves the clip group. An open mask clips to its area closed by a - /// straight line, and a marquee across that line takes the art it reaches inside. - #[test] - fn a_marquee_must_meet_the_clipping_path_itself() { - // A clip group of a mask through `pts` (closed or open) over the art `art`. - let clipped = |pts: &[(f64, f64)], closed: bool, art: Rect| { - let mut d = Document::new(200.0, 200.0); - let l = d.layers[0].id; - let mut mask = vectorcraft_geom::BezPath::new(); - mask.move_to(pts[0]); - for &p in &pts[1..] { - mask.line_to(p); - } - if closed { - mask.close_path(); - } - let mask = Node::path(d.alloc_id(), vectorcraft_geom::PathData::from_bezpath(&mask), Appearance::default()); - let art = Node::path(d.alloc_id(), shapes::rectangle(art), Appearance::default_art()); - let g = d.alloc_id(); - let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); - clip.set_clips(true); - d.insert(Some(l), 0, clip).unwrap(); - (d, g) - }; - let (d, g) = clipped(&[(50.0, 0.0), (100.0, 50.0), (50.0, 100.0), (0.0, 50.0)], true, Rect::new(0.0, 0.0, 100.0, 100.0)); - assert!(marquee(&d, Rect::new(-10.0, -10.0, 10.0, 10.0), None, false).is_empty()); - assert_eq!(marquee(&d, Rect::new(-10.0, 40.0, 10.0, 60.0), None, false), vec![g], "over the diamond's left point"); - // The mask is the triangle above the line from (0, 0) to (100, 100), and the art lies inside it. - let (d, g) = clipped(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false, Rect::new(55.0, 40.0, 70.0, 50.0)); - assert_eq!(marquee(&d, Rect::new(40.0, 45.0, 60.0, 70.0), None, false), vec![g]); - } - - /// #2345: the objects of a layer or sublayer with a clipping mask are touched only where the - /// mask shows them, as in a clip group. - #[test] - fn a_marquee_leaves_art_a_layer_clips_away() { - for sublayer in [false, true] { - let mut d = Document::new(300.0, 200.0); - let l = d.layers[0].id; - let beside = d.alloc_id(); - d.insert(Some(l), 0, Node::path(beside, shapes::rectangle(Rect::new(150.0, 80.0, 190.0, 130.0)), Appearance::default_art())).unwrap(); - let masked = d.alloc_id(); - let mut layer = Node::layer(masked, "Masked", crate::LayerColor::Preset(2)); - layer.set_clips(true); - d.insert(sublayer.then_some(l), 9, layer).unwrap(); - let (mask, art) = half_clipped(&mut d); - let (mask_id, art_id) = (mask.id, art.id); - d.insert(Some(masked), 0, mask).unwrap(); - d.insert(Some(masked), 1, art).unwrap(); - assert!(marquee(&d, Rect::new(150.0, -10.0, 210.0, 50.0), None, false).is_empty(), "sublayer: {sublayer}"); - assert_eq!(marquee(&d, Rect::new(140.0, 70.0, 195.0, 140.0), None, false), vec![beside], "sublayer: {sublayer}"); - assert_eq!(marquee(&d, Rect::new(50.0, -10.0, 160.0, 10.0), None, false), vec![mask_id, art_id], "sublayer: {sublayer}"); - } - } - - /// A marquee touches a Shaper Group only by the art it shows, as clicks do ([`may_hit`]): over - /// the original shape of a face the group erased it selects nothing, with Group Selection's - /// leaves too, and over a face it shows it takes the group. With the original shapes isolated - /// (Construction mode) it takes the original shape it reaches. - #[test] - fn a_marquee_leaves_a_shaper_group_by_its_original_shapes() { - let mut d = Document::new(300.0, 200.0); - let l = d.layers[0].id; - // Two original squares, 0..100 and 50..150; the group shows only the first one's face. - let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0)); - let a = Node::path(d.alloc_id(), square(0.0), Appearance::default_art()); - let b = Node::path(d.alloc_id(), square(50.0), Appearance::default_art()); - let b_id = b.id; - let mut sources = Node::group(d.alloc_id(), vec![Arc::new(a), Arc::new(b)]); - sources.name = Some(crate::shaper::SOURCES.into()); - sources.opacity = 0.0; - let sources_id = sources.id; - let mut face = Node::path(d.alloc_id(), square(0.0), Appearance::default_art()); - face.name = Some(format!("{}0", crate::shaper::FILL_PREFIX)); - let face_id = face.id; - let g = d.alloc_id(); - let mut group = Node::group(g, vec![Arc::new(sources), Arc::new(face)]); - group.extras_mut().shaper = Some(Box::default()); - d.insert(Some(l), 0, group).unwrap(); - // This marquee crosses only the right edge of the second square, whose face is erased. - let erased = Rect::new(140.0, 40.0, 160.0, 60.0); - assert!(hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).is_none(), "a click there misses"); - assert!(marquee(&d, erased, None, false).is_empty()); - assert!(marquee(&d, erased, None, true).is_empty()); - assert!(marquee(&d, erased, Some(g), false).is_empty()); - // This marquee crosses the shown face's left edge. - let shown = Rect::new(-10.0, 40.0, 10.0, 60.0); - assert_eq!(marquee(&d, shown, None, false), vec![g]); - assert_eq!(marquee(&d, shown, None, true), vec![face_id]); - assert_eq!(marquee(&d, shown, Some(g), false), vec![face_id]); - // Construction mode: the original shapes are the objects. - assert_eq!(marquee(&d, erased, Some(sources_id), false), vec![b_id]); - } - - /// A marquee touches an Intertwine group by its members, as it touches a plain group (#1103) and - /// as clicks do: in the gap between two members, or inside one member's fill, it selects nothing. - /// Across a member's edge it selects the group, and with the leaves that Direct and Group - /// Selection take, or in isolation mode, it selects the member. - #[test] - fn a_marquee_meets_an_intertwine_group_by_its_members() { - let mut d = Document::new(300.0, 200.0); - let l = d.layers[0].id; - // Two squares, 0..100 and 150..250, with a gap between them inside the group's box. - let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0)); - let mut a = Node::path(d.alloc_id(), square(0.0), Appearance::default_art()); - a.extras_mut().intertwine = Some(Box::new(shapes::rectangle(Rect::new(50.0, 0.0, 100.0, 100.0)))); - let b = Node::path(d.alloc_id(), square(150.0), Appearance::default_art()); - let (a_id, g) = (a.id, d.alloc_id()); - d.insert(Some(l), 0, Node::new(g, NodeKind::Intertwine { children: vec![Arc::new(a), Arc::new(b)] })).unwrap(); - let gap = Rect::new(110.0, 40.0, 140.0, 60.0); - assert!(hit_test(&d, gap.center(), HitOptions::default()).is_none(), "a click in the gap misses"); - assert!(marquee(&d, gap, None, false).is_empty()); - assert!(marquee(&d, gap, None, true).is_empty()); - assert!(marquee(&d, gap, Some(g), false).is_empty()); - assert!(marquee(&d, Rect::new(20.0, 20.0, 40.0, 40.0), None, false).is_empty(), "inside a member's fill"); - // This marquee crosses the first square's left edge. - let edge = Rect::new(-10.0, 40.0, 10.0, 60.0); - assert_eq!(marquee(&d, edge, None, false), vec![g]); - assert_eq!(marquee(&d, edge, None, true), vec![a_id]); - assert_eq!(marquee(&d, edge, Some(g), false), vec![a_id]); - } - - /// A marquee touches a repeat by the copies it draws, as clicks do: between two copies of a - /// grid repeat it selects nothing, and across a copy's edge it takes the repeat. - #[test] - fn a_marquee_meets_a_repeat_by_its_copies() { - let mut d = Document::new(300.0, 200.0); - let l = d.layers[0].id; - let source = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art()); - // Copies at 0..20, 40..60 and 80..100. - let kind = crate::pattern::RepeatKind::Grid { - h_spacing: 20.0, - v_spacing: 20.0, - rows: 1, - cols: 3, - grid_type: crate::pattern::TileType::Grid, - flip_rows: false, - flip_cols: false, - }; - let r = d.alloc_id(); - d.insert(Some(l), 0, Node::new(r, NodeKind::Repeat(crate::pattern::RepeatSpec { kind, source: vec![Arc::new(source)] }))).unwrap(); - let gap = Rect::new(25.0, 5.0, 35.0, 15.0); - assert!(hit_test(&d, gap.center(), HitOptions::default()).is_none(), "a click between copies misses"); - assert!(marquee(&d, gap, None, false).is_empty()); - assert!(marquee(&d, gap, None, true).is_empty()); - assert_eq!(marquee(&d, Rect::new(35.0, 5.0, 45.0, 15.0), None, false), vec![r], "across the second copy's left edge"); - assert_eq!(marquee(&d, Rect::new(35.0, 5.0, 45.0, 15.0), None, true), vec![r]); - } - - /// A blend and an envelope are clicked anywhere in their box, and a marquee touches them there - /// too: inside the box, away from every key object's and the content's outline, it takes them. - #[test] - fn a_marquee_meets_blends_and_envelopes_by_their_box() { - let mut d = Document::new(300.0, 300.0); - let l = d.layers[0].id; - let square = |id, x: f64, y: f64| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), Appearance::default_art())); - let blend = d.alloc_id(); - let keys = vec![square(d.alloc_id(), 0.0, 0.0), square(d.alloc_id(), 100.0, 0.0)]; - d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Default::default() })).unwrap(); - let envelope = d.alloc_id(); - let content = vec![Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 150.0, 100.0, 250.0)), Appearance::default_art()))]; - let e = Node::new( - 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 }), - fidelity: 100.0, - editing: false, - options: Default::default(), - frame: Box::new(vectorcraft_geom::Affine::IDENTITY), - }, - ); - d.insert(Some(l), 1, e).unwrap(); - for (r, id) in [(Rect::new(50.0, 5.0, 60.0, 15.0), blend), (Rect::new(40.0, 190.0, 60.0, 210.0), envelope)] { - assert_eq!(hit_test(&d, r.center(), HitOptions::default()).map(|h| h.leaf), Some(id)); - assert_eq!(marquee(&d, r, None, false), vec![id]); - assert_eq!(marquee(&d, r, None, true), vec![id]); - } - } - - /// Art in a sublayer is an object of its own: a click or a marquee takes it, not the - /// sublayer; hidden, locked and template sublayers block both. - #[test] - fn sublayers_are_not_objects() { - let mut d = Document::new(200.0, 200.0); - let l = d.layers[0].id; - let sub = d.alloc_id(); - d.insert(Some(l), 0, Node::layer(sub, "Sub", crate::LayerColor::Preset(2))).unwrap(); - let inner = d.alloc_id(); - d.insert(Some(sub), 0, Node::layer(inner, "Inner", crate::LayerColor::Preset(3))).unwrap(); - let a = d.alloc_id(); - d.insert(Some(inner), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap(); - let g = d.alloc_id(); - let b = d.alloc_id(); - let pb = Node::path(b, shapes::rectangle(Rect::new(100.0, 0.0, 150.0, 50.0)), Appearance::default_art()); - d.insert(Some(sub), 9, Node::group(g, vec![Arc::new(pb)])).unwrap(); - let h = hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).unwrap(); - assert_eq!((h.leaf, h.top_object(None), h.layers), (a, a, 3)); - let h = hit_test(&d, Point::new(110.0, 10.0), HitOptions::default()).unwrap(); - assert_eq!((h.top_object(None), h.top_object(Some(g))), (g, b)); - let all = Rect::new(-5.0, -5.0, 200.0, 200.0); - assert_eq!(marquee(&d, all, None, false), vec![a, g]); - assert_eq!(d.layer_containing(a), Some(inner)); - assert_eq!(d.layer_color(a), crate::LayerColor::Preset(3).rgb(), "the sublayer's own colour"); - assert_eq!(d.selectable_art(), vec![a, g]); - for f in [ - |n: &mut Node| n.visible = false, - |n: &mut Node| n.locked = true, - |n: &mut Node| { - if let NodeKind::Layer { template, .. } = &mut n.kind { - *template = true; - } - }, - ] { - let mut d2 = d.clone(); - f(d2.node_mut(inner).unwrap()); - assert!(hit_test(&d2, Point::new(10.0, 10.0), HitOptions::default()).is_none()); - assert_eq!(marquee(&d2, all, None, false), vec![g]); - assert_eq!(d2.selectable_art(), vec![g]); - } - // A sublayer whose Preview is off is clicked in outline: its fill no longer hits. - if let NodeKind::Layer { preview, .. } = &mut d.node_mut(inner).unwrap().kind { - *preview = false; - } - assert!(hit_test(&d, Point::new(25.0, 25.0), HitOptions::default()).is_none()); - assert!(hit_test(&d, Point::new(0.5, 25.0), HitOptions::default()).is_some()); - } - - /// Object Selection by Path Only: a filled path or compound path hits on its outline only. - #[test] - fn path_only_leaves_out_fills() { - let mut d = Document::new(200.0, 200.0); - let l = d.layers[0].id; - let (a, c) = (d.alloc_id(), d.alloc_id()); - d.insert(Some(l), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap(); - let inner = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 0.0, 150.0, 50.0)), Appearance::default()); - let mut compound = Node::new(c, NodeKind::Compound { children: vec![Arc::new(inner)], rule: vectorcraft_geom::FillRule::NonZero }); - compound.appearance = Appearance::default_art().into(); - d.insert(Some(l), 9, compound).unwrap(); - let path_only = HitOptions { path_only: true, ..Default::default() }; - for (id, inside, edge) in [(a, Point::new(25.0, 25.0), Point::new(0.5, 25.0)), (c, Point::new(125.0, 25.0), Point::new(100.5, 25.0))] { - assert_eq!(hit_test(&d, inside, HitOptions::default()).map(|h| h.leaf), Some(id), "the fill hits"); - assert!(hit_test(&d, inside, path_only).is_none(), "path only: the fill of {id:?} doesn't hit"); - assert_eq!(hit_test(&d, edge, path_only).map(|h| h.leaf), Some(id), "path only: the outline does"); - } - } - - /// Type Object Selection by Path Only: point type is picked on its baseline, area type on its - /// frame and type on a path on its path, no longer anywhere in its bounds. - #[test] - fn type_path_only_picks_type_on_its_path() { - use crate::{CharStyle, TextKind, TextObject}; - let mut d = Document::new(400.0, 400.0); - let l = d.layers[0].id; - let mut add = |t: TextObject| { - let id = d.alloc_id(); - d.insert(Some(l), 9, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); - id - }; - // Point type at (10, 100), 20 pt: its glyphs rise above the baseline, its layout is 60 wide. - let mut point = TextObject::point(Point::new(10.0, 100.0), "Hello", CharStyle { size: 20.0, ..CharStyle::default() }); - point.cached_bounds = Some(Rect::new(0.0, -16.0, 60.0, 4.0)); - let point = add(point); - let mut area = TextObject::point(Point::new(200.0, 200.0), "Area", CharStyle::default()); - area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)) }; - let area = add(area); - let mut on_path = TextObject::point(Point::new(10.0, 300.0), "Path", CharStyle::default()); - on_path.kind = TextKind::OnPath { path: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 40.0)), start: 0.0, end: None }; - let on_path = add(on_path); - let path_only = HitOptions { type_path_only: true, ..Default::default() }; - let hit = |p: Point, opt: HitOptions| hit_test(&d, p, opt).map(|h| (h.leaf, h.kind)); - // Off: anywhere in the bounds. - assert_eq!(hit(Point::new(40.0, 90.0), HitOptions::default()), Some((point, HitKind::Bounds))); - assert_eq!(hit(Point::new(250.0, 225.0), HitOptions::default()), Some((area, HitKind::Bounds))); - assert_eq!(hit(Point::new(60.0, 320.0), HitOptions::default()), Some((on_path, HitKind::Bounds))); - // On: the glyphs and the inside of the frame or path no longer pick the type. - assert_eq!(hit(Point::new(40.0, 90.0), path_only), None, "point type: among its glyphs"); - assert_eq!(hit(Point::new(250.0, 225.0), path_only), None, "area type: inside its frame"); - assert_eq!(hit(Point::new(60.0, 320.0), path_only), None, "type on a path: inside its path"); - // The baseline (within the tolerance, across the layout's width), frame and path do. - assert_eq!(hit(Point::new(40.0, 101.5), path_only), Some((point, HitKind::Outline)), "point type: its baseline"); - assert_eq!(hit(Point::new(75.0, 100.0), path_only), None, "point type: past the end of its layout"); - assert_eq!(hit(Point::new(250.0, 200.5), path_only), Some((area, HitKind::Outline)), "area type: its frame"); - assert_eq!(hit(Point::new(60.0, 339.5), path_only), Some((on_path, HitKind::Outline)), "type on a path: its path"); - } - - /// Type Object Selection by Path Only with the layout's baselines: every line's for point type, - /// area type's besides its frame, a vertical column's centre line, and type in perspective - /// where it is drawn. - #[test] - fn type_path_only_picks_every_baseline() { - use crate::{CharStyle, PerspectiveAttachment, TextKind, TextObject}; - use vectorcraft_geom::{Affine, Homography}; - let mut d = Document::new(400.0, 400.0); - let l = d.layers[0].id; - let mut add = |t: TextObject, perspective: Option| { - let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); - n.extras_mut().perspective = perspective.map(|a| { - Box::new(PerspectiveAttachment { projection: Some(Homography::from_affine(a).to_array()), ..PerspectiveAttachment::new("left", 0.0) }) - }); - let id = n.id; - d.insert(Some(l), 9, n).unwrap(); - id - }; - let style = CharStyle { size: 20.0, ..CharStyle::default() }; - // Two lines of point type at (10, 100), 24 pt apart. - let mut point = TextObject::point( - Point::new(10.0, 100.0), - "Hello -world", - style.clone(), - ); - point.cached_bounds = Some(Rect::new(0.0, -16.0, 60.0, 28.0)); - point.cached_baselines = vec![(Point::ZERO, Point::new(60.0, 0.0)), (Point::new(0.0, 24.0), Point::new(50.0, 24.0))]; - let point = add(point, None); - // Area type: a line inside its frame. - let mut area = TextObject::point(Point::new(200.0, 50.0), "Area", style.clone()); - area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)) }; - area.cached_baselines = vec![(Point::new(0.0, 16.0), Point::new(40.0, 16.0))]; - let area = add(area, None); - // Vertical point type at (300, 200) with no baselines cached: down its first column. - let mut vertical = TextObject::point(Point::new(300.0, 200.0), "Tate", style.clone()); - vertical.vertical = true; - vertical.cached_bounds = Some(Rect::new(-10.0, 0.0, 10.0, 80.0)); - let vertical = add(vertical, None); - // Point type drawn 100 to the right of where it is laid out. - let mut moved = TextObject::point(Point::new(10.0, 350.0), "Moved", style); - moved.cached_bounds = Some(Rect::new(0.0, -16.0, 60.0, 4.0)); - let moved = add(moved, Some(Affine::translate((100.0, 0.0)))); - let path_only = HitOptions { type_path_only: true, ..Default::default() }; - let hit = |p: Point| hit_test(&d, p, path_only).map(|h| h.leaf); - assert_eq!(hit(Point::new(40.0, 100.0)), Some(point), "the first line's baseline"); - assert_eq!(hit(Point::new(40.0, 125.0)), Some(point), "the second line's"); - assert_eq!(hit(Point::new(40.0, 112.0)), None, "between the lines"); - assert_eq!(hit(Point::new(65.0, 124.0)), None, "past the end of the shorter second line"); - assert_eq!(hit(Point::new(220.0, 66.0)), Some(area), "area type: a line's baseline"); - assert_eq!(hit(Point::new(220.0, 80.0)), None, "area type: inside the frame, off the baselines"); - assert_eq!(hit(Point::new(299.0, 260.0)), Some(vertical), "vertical type: down the column"); - assert_eq!(hit(Point::new(306.0, 260.0)), None, "vertical type: beside it"); - assert_eq!(hit(Point::new(140.0, 351.0)), Some(moved), "in perspective: where it is drawn"); - assert_eq!(hit(Point::new(40.0, 351.0)), None, "in perspective: not where it is laid out"); - } - - /// `objects_at`: every object under the point, topmost first; a group counts once. - #[test] - fn objects_at_lists_the_stack() { - let mut d = Document::new(200.0, 200.0); - let l = d.layers[0].id; - let rect = - |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art()); - let a = rect(&mut d, 0.0); - let (b, c) = (rect(&mut d, 10.0), rect(&mut d, 20.0)); - let (a_id, b_id, c_id, g) = (a.id, b.id, c.id, d.alloc_id()); - d.insert(Some(l), 0, a).unwrap(); - d.insert(Some(l), 9, Node::group(g, vec![Arc::new(b), Arc::new(c)])).unwrap(); - let far = rect(&mut d, 120.0); - d.insert(Some(l), 9, far).unwrap(); - let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope); - assert_eq!(at(30.0, None), vec![g, a_id]); - assert_eq!(at(30.0, Some(g)), [c_id, b_id], "isolated: the group's own objects"); - // Isolated, the art around the group is locked: clicks pass through it (#833). - assert!(at(5.0, Some(g)).is_empty()); - assert!(at(130.0, Some(g)).is_empty()); - assert!(hit_test(&d, Point::new(5.0, 25.0), HitOptions { scope: Some(g), ..HitOptions::default() }).is_none()); - assert_eq!(at(5.0, None), vec![a_id]); - assert!(at(90.0, None).is_empty()); - } - - /// Many overlapping paths: Select Behind must list each exactly once, front to back. - /// This is quadratic with repeated full-document hit tests, but linear in tree size with - /// the per-object walk. - #[test] - fn objects_at_large_overlapping_stack() { - let mut d = Document::new(100.0, 100.0); - let layer = d.layers[0].id; - let mut ids = Vec::new(); - for _ in 0..256 { - let id = d.alloc_id(); - d.insert(Some(layer), usize::MAX, Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap(); - ids.push(id); - } - ids.reverse(); - assert_eq!(objects_at(&d, Point::new(25.0, 25.0), HitOptions::default(), None), ids); - } - - /// Match the original skip-and-retest algorithm for normal groups, sublayers, clipping, - /// invisibility, and path/outline-only settings. - #[test] - fn objects_at_one_pass_matches_repeated_hits() { - let mut d = Document::new(200.0, 200.0); - let layer = d.layers[0].id; - let add = |d: &mut Document, parent, bounds| { - let id = d.alloc_id(); - d.insert(Some(parent), usize::MAX, Node::path(id, shapes::rectangle(bounds), Appearance::default_art())).unwrap(); - id - }; - add(&mut d, layer, Rect::new(0.0, 0.0, 60.0, 60.0)); - let sub = d.alloc_id(); - d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sublayer", crate::LayerColor::Preset(2))).unwrap(); - add(&mut d, sub, Rect::new(0.0, 0.0, 60.0, 60.0)); - let group = d.alloc_id(); - d.insert(Some(layer), usize::MAX, Node::group(group, Vec::new())).unwrap(); - add(&mut d, group, Rect::new(0.0, 0.0, 60.0, 60.0)); - add(&mut d, group, Rect::new(5.0, 5.0, 60.0, 60.0)); - let clip = d.alloc_id(); - let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(5.0, 5.0, 45.0, 45.0)), Appearance::default_art()); - let content = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 80.0, 80.0)), Appearance::default_art()); - let mut clipping = Node::group(clip, vec![Arc::new(mask), Arc::new(content)]); - clipping.set_clips(true); - d.insert(Some(layer), usize::MAX, clipping).unwrap(); - for (point, opt) in [ - (Point::new(25.0, 25.0), HitOptions::default()), - (Point::new(3.0, 25.0), HitOptions::default()), - (Point::new(25.0, 25.0), HitOptions { outline: true, ..Default::default() }), - (Point::new(6.0, 25.0), HitOptions { path_only: true, ..Default::default() }), - (Point::new(100.0, 100.0), HitOptions::default()), - ] { - assert_eq!(objects_at(&d, point, opt, None), objects_at_repeated(&d, point, opt, None), "point={point:?}, opt={opt:?}"); - } - if let NodeKind::Layer { preview, .. } = &mut d.node_mut(sub).unwrap().kind { - *preview = false; - } - let p = Point::new(25.0, 25.0); - let opt = HitOptions::default(); - assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None)); - d.node_mut(group).unwrap().locked = true; - assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None)); - } - - /// Documents built at random (nested groups, sublayers, clipping groups, compound paths, blends - /// of nothing, hidden and locked objects, outline layers): Select Behind lists the same objects - /// in the same order as the hit test repeated over what is left. - #[test] - fn objects_at_matches_repeated_hits_on_random_documents() { - let mut seed = 0x9e37_79b9_u32; - let mut next = move |n: u32| { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - seed % n - }; - fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) { - for _ in 0..2 + next(4) { - let id = d.alloc_id(); - let (x, y) = (f64::from(next(60)), f64::from(next(60))); - let rect = Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50))); - let appearance = if next(4) == 0 { Appearance::default() } else { Appearance::default_art() }; - let mut n = match next(if depth < 3 { 8 } else { 4 }) { - 4 | 5 => Node::group(id, Vec::new()), - 6 => Node::layer(id, "Sublayer", crate::LayerColor::Preset(2)), - 7 => { - let mut g = Node::group(id, Vec::new()); - g.set_clips(true); - g - } - _ => Node::path(id, shapes::rectangle(rect), appearance), - }; - n.visible = next(8) != 0; - n.locked = next(8) == 0; - if let NodeKind::Layer { preview, .. } = &mut n.kind { - *preview = next(3) != 0; - } - let container = n.is_container(); - // A sublayer belongs in a layer; in a group it is a group like another to the hit test. - d.insert(Some(parent), usize::MAX, n).unwrap(); - if container { - fill(d, id, depth + 1, next); - } - } - } - for round in 0..200 { - let mut d = Document::new(120.0, 120.0); - let layer = d.layers[0].id; - fill(&mut d, layer, 0, &mut next); - for _ in 0..12 { - let p = Point::new(f64::from(next(120)), f64::from(next(120))); - let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, ..Default::default() }; - assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None), "round {round}, {p:?}, {opt:?}"); - } - } - } - - /// Select Behind finds a symbol instance by its symbol's art, as a click does: art from - /// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by - /// one instance and 100 pt lower by an instance in a group. - #[test] - fn objects_at_finds_symbol_instances_by_their_art() { - let mut d = Document::new(200.0, 200.0); - let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 60.0, 140.0, 80.0)), Appearance::default_art()); - d.symbols.push(crate::Symbol { name: "Far".into(), art: Arc::new(art) }); - let (layer, top, inner, group) = (d.layers[0].id, d.alloc_id(), d.alloc_id(), d.alloc_id()); - let instance = - |id, dy: f64| Node::new(id, NodeKind::SymbolInstance { symbol: "Far".into(), xf: vectorcraft_geom::Affine::translate((0.0, dy)) }); - d.insert(Some(layer), 0, instance(top, 0.0)).unwrap(); - d.insert(Some(layer), 1, Node::group(group, vec![Arc::new(instance(inner, 100.0))])).unwrap(); - let opt = HitOptions::default(); - for (x, y, want) in [(120.0, 70.0, vec![top]), (120.0, 170.0, vec![group]), (0.0, 0.0, vec![]), (0.0, 100.0, vec![])] { - let p = Point::new(x, y); - assert_eq!(objects_at(&d, p, opt, None), want, "{p:?}"); - assert_eq!(objects_at_repeated(&d, p, opt, None), want, "{p:?}"); - } - } - - /// Edit Contents can expose descendants of a top-level group: preserve the original - /// selection order by falling back to the general hit traversal. - #[test] - fn objects_at_edit_contents_uses_general_order() { - let mut d = Document::new(100.0, 100.0); - let layer = d.layers[0].id; - let inner = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())); - let (a, b) = (d.alloc_id(), d.alloc_id()); - let e = Node::new( - 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 }), - fidelity: 100.0, - editing: true, - options: Default::default(), - frame: Box::new(vectorcraft_geom::Affine::IDENTITY), - }, - ); - d.insert(Some(layer), usize::MAX, e).unwrap(); - let p = Point::new(25.0, 25.0); - let opt = HitOptions::default(); - assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None)); - assert_eq!(objects_at(&d, p, opt, None), vec![b, a]); - } - - #[test] - fn locked_and_hidden_skip() { - let mut d = Document::new(200.0, 200.0); - let l = d.layers[0].id; - let a = d.alloc_id(); - d.insert(Some(l), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap(); - d.node_mut(a).unwrap().locked = true; - assert!(hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).is_none()); - d.node_mut(a).unwrap().locked = false; - d.node_mut(l).unwrap().visible = false; - assert!(hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).is_none()); - } - - /// Insert `n` locked at the top of `parent`. - fn insert_locked(d: &mut Document, parent: NodeId, mut n: Node) -> NodeId { - let id = n.id; - n.locked = true; - d.insert(Some(parent), usize::MAX, n).unwrap(); - id - } - - /// `locked_objects_at`: the locked objects under the point, topmost first. A locked group is - /// listed rather than its contents, and a locked object in an unlocked group is listed itself. - /// Hidden objects, locked layers and the art outside an isolated group are left out. - #[test] - fn locked_objects_at_lists_the_locked_stack() { - let mut d = Document::new(200.0, 200.0); - let l = d.layers[0].id; - let rect = - |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art()); - let (a, b) = (rect(&mut d, 0.0), rect(&mut d, 10.0)); - let (a, b) = (insert_locked(&mut d, l, a), insert_locked(&mut d, l, b)); - let (mut inner, locked_group) = (rect(&mut d, 20.0), d.alloc_id()); - inner.locked = true; - let inner_id = inner.id; - let mut g = Node::group(locked_group, vec![Arc::new(inner)]); - g.locked = true; - d.insert(Some(l), usize::MAX, g).unwrap(); - let open_group = d.alloc_id(); - let mut child = rect(&mut d, 25.0); - child.locked = true; - let child_id = child.id; - let free = rect(&mut d, 25.0); - d.insert(Some(l), usize::MAX, Node::group(open_group, vec![Arc::new(child), Arc::new(free)])).unwrap(); - let at = |d: &Document, x: f64, scope| locked_objects_at(d, Point::new(x, 25.0), HitOptions { scope, ..HitOptions::default() }); - assert_eq!(at(&d, 30.0, None), [child_id, locked_group, b, a]); - assert!(!at(&d, 30.0, None).contains(&inner_id), "the locked group stands for what it holds"); - assert_eq!(at(&d, 5.0, None), [a]); - assert!(at(&d, 150.0, None).is_empty()); - // Isolated, only the group's own objects are looked at. - assert_eq!(at(&d, 30.0, Some(open_group)), [child_id]); - // A hidden object is left out, and nothing on a locked or hidden layer is listed. - d.node_mut(b).unwrap().visible = false; - assert_eq!(at(&d, 30.0, None), [child_id, locked_group, a]); - d.node_mut(l).unwrap().locked = true; - assert!(at(&d, 30.0, None).is_empty()); - d.node_mut(l).unwrap().locked = false; - d.node_mut(l).unwrap().visible = false; - assert!(at(&d, 30.0, None).is_empty()); - } - - /// `locked_objects_at` lists at most `MAX_LOCKED_AT` objects, the topmost ones. - #[test] - fn locked_objects_at_stops_at_its_limit() { - let mut d = Document::new(100.0, 100.0); - let l = d.layers[0].id; - let ids: Vec = (0..MAX_LOCKED_AT + 5) - .map(|_| { - let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art()); - insert_locked(&mut d, l, n) - }) - .collect(); - let found = locked_objects_at(&d, Point::new(25.0, 25.0), HitOptions::default()); - assert_eq!(found, ids.iter().rev().take(MAX_LOCKED_AT).copied().collect::>()); - } - - #[test] - fn visible_sampling_reads_locked_art_and_layers_but_excludes_hidden_art() { - let mut d = Document::new(200.0, 200.0); - let l = d.layers[0].id; - let a = d.alloc_id(); - d.insert(Some(l), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap(); - let p = Point::new(10.0, 10.0); - for lock in [a, l] { - d.node_mut(lock).unwrap().locked = true; - assert!(hit_test(&d, p, HitOptions::default()).is_none()); - assert_eq!(hit_test_visible(&d, p, HitOptions::default()).unwrap().leaf, a); - assert!(d.node(lock).unwrap().locked); - d.node_mut(lock).unwrap().locked = false; - } - d.node_mut(a).unwrap().visible = false; - assert!(hit_test_visible(&d, p, HitOptions::default()).is_none()); - d.node_mut(a).unwrap().visible = true; - d.node_mut(l).unwrap().visible = false; - assert!(hit_test_visible(&d, p, HitOptions::default()).is_none()); - } -} +mod tests; diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs new file mode 100644 index 0000000000..43db8ee167 --- /dev/null +++ b/crates/doc/src/hit/tests.rs @@ -0,0 +1,835 @@ +use super::*; +use crate::{Appearance, Node}; +use std::sync::Arc; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_geom::shapes; + +#[test] +fn hits_topmost() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let a = d.alloc_id(); + d.insert(Some(l), 9, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap(); + let b = d.alloc_id(); + d.insert(Some(l), 9, Node::path(b, shapes::rectangle(Rect::new(25.0, 25.0, 75.0, 75.0)), Appearance::default_art())).unwrap(); + let h = hit_test(&d, Point::new(30.0, 30.0), HitOptions::default()).unwrap(); + assert_eq!(h.leaf, b); + assert_eq!(h.kind, HitKind::Fill); + let h = hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).unwrap(); + assert_eq!(h.leaf, a); + assert!(hit_test(&d, Point::new(150.0, 150.0), HitOptions::default()).is_none()); + // Outline mode: interior misses. + assert!(hit_test(&d, Point::new(10.0, 10.0), HitOptions { outline: true, ..Default::default() }).is_none()); + assert!(hit_test(&d, Point::new(0.5, 10.0), HitOptions { outline: true, ..Default::default() }).is_some()); +} + +#[test] +fn unfilled_interior_misses() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let a = d.alloc_id(); + d.insert( + Some(l), + 9, + Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)), + ) + .unwrap(); + assert!(hit_test(&d, Point::new(25.0, 25.0), HitOptions::default()).is_none()); + assert!(hit_test(&d, Point::new(50.5, 25.0), HitOptions::default()).is_some()); +} + +/// #1103: a marquee drawn over a background picks what is on it, not the background, whose +/// outline it doesn't touch. +#[test] +fn a_marquee_inside_a_background_leaves_the_background() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let (back, small) = (d.alloc_id(), d.alloc_id()); + d.insert(Some(l), 0, Node::path(back, shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default_art())).unwrap(); + d.insert(Some(l), 1, Node::path(small, shapes::rectangle(Rect::new(50.0, 50.0, 60.0, 60.0)), Appearance::default_art())).unwrap(); + assert_eq!(marquee(&d, Rect::new(40.0, 40.0, 70.0, 70.0), None, false), vec![small]); + // Reaching the background's edge takes it too. + assert_eq!(marquee(&d, Rect::new(-5.0, 40.0, 70.0, 70.0), None, false), vec![back, small]); +} + +#[test] +fn group_top_object() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let a = d.alloc_id(); + let g = d.alloc_id(); + let p = Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art()); + d.insert(Some(l), 0, Node::group(g, vec![Arc::new(p)])).unwrap(); + let h = hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).unwrap(); + assert_eq!(h.leaf, a); + assert_eq!(h.top_object(None), g); + assert_eq!(h.top_object(Some(g)), a); + assert_eq!(marquee(&d, Rect::new(-5.0, -5.0, 5.0, 5.0), None, false), vec![g]); + assert_eq!(marquee(&d, Rect::new(-5.0, -5.0, 5.0, 5.0), None, true), vec![a]); + assert!(marquee(&d, Rect::new(100.0, 100.0, 105.0, 105.0), None, false).is_empty()); +} + +/// The art of a 200 pt wide rectangle clipped to its left half (0..100 × 0..100): the mask and +/// the art, in that order. +fn half_clipped(d: &mut Document) -> (Node, Node) { + let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default()); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Appearance::default_art()); + (mask, art) +} + +/// #2345: a marquee touches a clip group only where its art shows. Over the clipped-away +/// half alone it selects nothing, and around a rectangle drawn beside the group's mask it +/// takes that rectangle alone; reaching into the mask takes the group. The same holds for +/// Group Selection's leaves and in isolation mode. +#[test] +fn a_marquee_leaves_a_clip_group_by_its_clipped_away_art() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mask, art) = half_clipped(&mut d); + let (g, art_id, beside) = (d.alloc_id(), art.id, d.alloc_id()); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + d.insert(Some(l), 1, Node::path(beside, shapes::rectangle(Rect::new(150.0, 80.0, 190.0, 130.0)), Appearance::default_art())).unwrap(); + // This marquee crosses only the hidden art's top and right edges. + let hidden = Rect::new(150.0, -10.0, 210.0, 50.0); + assert!(marquee(&d, hidden, None, false).is_empty()); + assert!(marquee(&d, hidden, None, true).is_empty()); + assert!(marquee(&d, hidden, Some(g), false).is_empty()); + assert!(marquee(&d, hidden, Some(art_id), false).is_empty()); + // This marquee surrounds the rectangle beside and crosses the hidden art's bottom edge. + assert_eq!(marquee(&d, Rect::new(140.0, 70.0, 195.0, 140.0), None, false), vec![beside]); + // This marquee crosses the shown half's top edge and goes on into the hidden half. + let shown = Rect::new(50.0, -10.0, 160.0, 10.0); + assert_eq!(marquee(&d, shown, None, false), vec![g]); + assert!(marquee(&d, shown, None, true).contains(&art_id)); + assert_eq!(marquee(&d, shown, Some(g), false).len(), 2, "the mask and the art"); +} + +/// #2345: in the corner of a diamond mask's box, outside the diamond, a marquee over the +/// clipped art's corner leaves the clip group. An open mask clips to its area closed by a +/// straight line, and a marquee across that line takes the art it reaches inside. +#[test] +fn a_marquee_must_meet_the_clipping_path_itself() { + // A clip group of a mask through `pts` (closed or open) over the art `art`. + let clipped = |pts: &[(f64, f64)], closed: bool, art: Rect| { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let mut mask = vectorcraft_geom::BezPath::new(); + mask.move_to(pts[0]); + for &p in &pts[1..] { + mask.line_to(p); + } + if closed { + mask.close_path(); + } + let mask = Node::path(d.alloc_id(), vectorcraft_geom::PathData::from_bezpath(&mask), Appearance::default()); + let art = Node::path(d.alloc_id(), shapes::rectangle(art), Appearance::default_art()); + let g = d.alloc_id(); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + (d, g) + }; + let (d, g) = clipped(&[(50.0, 0.0), (100.0, 50.0), (50.0, 100.0), (0.0, 50.0)], true, Rect::new(0.0, 0.0, 100.0, 100.0)); + assert!(marquee(&d, Rect::new(-10.0, -10.0, 10.0, 10.0), None, false).is_empty()); + assert_eq!(marquee(&d, Rect::new(-10.0, 40.0, 10.0, 60.0), None, false), vec![g], "over the diamond's left point"); + // The mask is the triangle above the line from (0, 0) to (100, 100), and the art lies inside it. + let (d, g) = clipped(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false, Rect::new(55.0, 40.0, 70.0, 50.0)); + assert_eq!(marquee(&d, Rect::new(40.0, 45.0, 60.0, 70.0), None, false), vec![g]); +} + +/// #2345: the objects of a layer or sublayer with a clipping mask are touched only where the +/// mask shows them, as in a clip group. +#[test] +fn a_marquee_leaves_art_a_layer_clips_away() { + for sublayer in [false, true] { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let beside = d.alloc_id(); + d.insert(Some(l), 0, Node::path(beside, shapes::rectangle(Rect::new(150.0, 80.0, 190.0, 130.0)), Appearance::default_art())).unwrap(); + let masked = d.alloc_id(); + let mut layer = Node::layer(masked, "Masked", crate::LayerColor::Preset(2)); + layer.set_clips(true); + d.insert(sublayer.then_some(l), 9, layer).unwrap(); + let (mask, art) = half_clipped(&mut d); + let (mask_id, art_id) = (mask.id, art.id); + d.insert(Some(masked), 0, mask).unwrap(); + d.insert(Some(masked), 1, art).unwrap(); + assert!(marquee(&d, Rect::new(150.0, -10.0, 210.0, 50.0), None, false).is_empty(), "sublayer: {sublayer}"); + assert_eq!(marquee(&d, Rect::new(140.0, 70.0, 195.0, 140.0), None, false), vec![beside], "sublayer: {sublayer}"); + assert_eq!(marquee(&d, Rect::new(50.0, -10.0, 160.0, 10.0), None, false), vec![mask_id, art_id], "sublayer: {sublayer}"); + } +} + +/// A marquee touches a Shaper Group only by the art it shows, as clicks do ([`may_hit`]): over +/// the original shape of a face the group erased it selects nothing, with Group Selection's +/// leaves too, and over a face it shows it takes the group. With the original shapes isolated +/// (Construction mode) it takes the original shape it reaches. +#[test] +fn a_marquee_leaves_a_shaper_group_by_its_original_shapes() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + // Two original squares, 0..100 and 50..150; the group shows only the first one's face. + let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0)); + let a = Node::path(d.alloc_id(), square(0.0), Appearance::default_art()); + let b = Node::path(d.alloc_id(), square(50.0), Appearance::default_art()); + let b_id = b.id; + let mut sources = Node::group(d.alloc_id(), vec![Arc::new(a), Arc::new(b)]); + sources.name = Some(crate::shaper::SOURCES.into()); + sources.opacity = 0.0; + let sources_id = sources.id; + let mut face = Node::path(d.alloc_id(), square(0.0), Appearance::default_art()); + face.name = Some(format!("{}0", crate::shaper::FILL_PREFIX)); + let face_id = face.id; + let g = d.alloc_id(); + let mut group = Node::group(g, vec![Arc::new(sources), Arc::new(face)]); + group.extras_mut().shaper = Some(Box::default()); + d.insert(Some(l), 0, group).unwrap(); + // This marquee crosses only the right edge of the second square, whose face is erased. + let erased = Rect::new(140.0, 40.0, 160.0, 60.0); + assert!(hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).is_none(), "a click there misses"); + assert!(marquee(&d, erased, None, false).is_empty()); + assert!(marquee(&d, erased, None, true).is_empty()); + assert!(marquee(&d, erased, Some(g), false).is_empty()); + // This marquee crosses the shown face's left edge. + let shown = Rect::new(-10.0, 40.0, 10.0, 60.0); + assert_eq!(marquee(&d, shown, None, false), vec![g]); + assert_eq!(marquee(&d, shown, None, true), vec![face_id]); + assert_eq!(marquee(&d, shown, Some(g), false), vec![face_id]); + // Construction mode: the original shapes are the objects. + assert_eq!(marquee(&d, erased, Some(sources_id), false), vec![b_id]); +} + +/// A marquee touches an Intertwine group by its members, as it touches a plain group (#1103) and +/// as clicks do: in the gap between two members, or inside one member's fill, it selects nothing. +/// Across a member's edge it selects the group, and with the leaves that Direct and Group +/// Selection take, or in isolation mode, it selects the member. +#[test] +fn a_marquee_meets_an_intertwine_group_by_its_members() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + // Two squares, 0..100 and 150..250, with a gap between them inside the group's box. + let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0)); + let mut a = Node::path(d.alloc_id(), square(0.0), Appearance::default_art()); + a.extras_mut().intertwine = Some(Box::new(shapes::rectangle(Rect::new(50.0, 0.0, 100.0, 100.0)))); + let b = Node::path(d.alloc_id(), square(150.0), Appearance::default_art()); + let (a_id, g) = (a.id, d.alloc_id()); + d.insert(Some(l), 0, Node::new(g, NodeKind::Intertwine { children: vec![Arc::new(a), Arc::new(b)] })).unwrap(); + let gap = Rect::new(110.0, 40.0, 140.0, 60.0); + assert!(hit_test(&d, gap.center(), HitOptions::default()).is_none(), "a click in the gap misses"); + assert!(marquee(&d, gap, None, false).is_empty()); + assert!(marquee(&d, gap, None, true).is_empty()); + assert!(marquee(&d, gap, Some(g), false).is_empty()); + assert!(marquee(&d, Rect::new(20.0, 20.0, 40.0, 40.0), None, false).is_empty(), "inside a member's fill"); + // This marquee crosses the first square's left edge. + let edge = Rect::new(-10.0, 40.0, 10.0, 60.0); + assert_eq!(marquee(&d, edge, None, false), vec![g]); + assert_eq!(marquee(&d, edge, None, true), vec![a_id]); + assert_eq!(marquee(&d, edge, Some(g), false), vec![a_id]); +} + +/// A marquee touches a repeat by the copies it draws, as clicks do: between two copies of a +/// grid repeat it selects nothing, and across a copy's edge it takes the repeat. +#[test] +fn a_marquee_meets_a_repeat_by_its_copies() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let source = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art()); + // Copies at 0..20, 40..60 and 80..100. + let kind = crate::pattern::RepeatKind::Grid { + h_spacing: 20.0, + v_spacing: 20.0, + rows: 1, + cols: 3, + grid_type: crate::pattern::TileType::Grid, + flip_rows: false, + flip_cols: false, + }; + let r = d.alloc_id(); + d.insert(Some(l), 0, Node::new(r, NodeKind::Repeat(crate::pattern::RepeatSpec { kind, source: vec![Arc::new(source)] }))).unwrap(); + let gap = Rect::new(25.0, 5.0, 35.0, 15.0); + assert!(hit_test(&d, gap.center(), HitOptions::default()).is_none(), "a click between copies misses"); + assert!(marquee(&d, gap, None, false).is_empty()); + assert!(marquee(&d, gap, None, true).is_empty()); + assert_eq!(marquee(&d, Rect::new(35.0, 5.0, 45.0, 15.0), None, false), vec![r], "across the second copy's left edge"); + assert_eq!(marquee(&d, Rect::new(35.0, 5.0, 45.0, 15.0), None, true), vec![r]); +} + +/// A blend and an envelope are clicked anywhere in their box, and a marquee touches them there +/// too: inside the box, away from every key object's and the content's outline, it takes them. +#[test] +fn a_marquee_meets_blends_and_envelopes_by_their_box() { + let mut d = Document::new(300.0, 300.0); + let l = d.layers[0].id; + let square = |id, x: f64, y: f64| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), Appearance::default_art())); + let blend = d.alloc_id(); + let keys = vec![square(d.alloc_id(), 0.0, 0.0), square(d.alloc_id(), 100.0, 0.0)]; + d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Default::default() })).unwrap(); + let envelope = d.alloc_id(); + let content = vec![Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 150.0, 100.0, 250.0)), Appearance::default_art()))]; + let e = Node::new( + 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 }), + fidelity: 100.0, + editing: false, + options: Default::default(), + frame: Box::new(vectorcraft_geom::Affine::IDENTITY), + }, + ); + d.insert(Some(l), 1, e).unwrap(); + for (r, id) in [(Rect::new(50.0, 5.0, 60.0, 15.0), blend), (Rect::new(40.0, 190.0, 60.0, 210.0), envelope)] { + assert_eq!(hit_test(&d, r.center(), HitOptions::default()).map(|h| h.leaf), Some(id)); + assert_eq!(marquee(&d, r, None, false), vec![id]); + assert_eq!(marquee(&d, r, None, true), vec![id]); + } +} + +/// A rectangle (40, 40)–(140, 140) clipping a filled 200 × 200 square drawn over its edges, in a +/// clip group (or, `layer`, as the first layer's clipping mask): the group (or the layer), the +/// clipping path and the art. +fn masked_square(layer: bool) -> (Document, NodeId, NodeId, NodeId) { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut path = Node::path(clip, shapes::rectangle(Rect::new(40.0, 40.0, 140.0, 140.0)), Appearance::basic(Paint::None, Paint::None, 0.0)); + if let NodeKind::Path { clipping, .. } = &mut path.kind { + *clipping = true; + } + let picture = Node::path(art, shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default_art()); + if layer { + d.insert(Some(l), 0, path).unwrap(); + d.insert(Some(l), 1, picture).unwrap(); + d.node_mut(l).unwrap().set_clips(true); + (d, l, clip, art) + } else { + d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(path), Arc::new(picture)], clip: true })).unwrap(); + (d, g, clip, art) + } +} + +const SELECTING: HitOptions = + HitOptions { tol: 3.0, outline: false, path_only: false, type_path_only: false, skip_guides: false, clip_outlines: true, scope: None }; + +/// For the selection tools a clip group's clipping path is hit on its outline, within the +/// tolerance, before the art it clips and just outside it too; inside, the art is hit. +#[test] +fn a_clipping_path_is_hit_on_its_outline_before_its_art() { + let (d, g, clip, art) = masked_square(false); + for (x, y) in [(140.0, 90.0), (141.5, 90.0), (138.5, 90.0), (90.0, 40.0)] { + let h = hit_test(&d, Point::new(x, y), SELECTING).unwrap(); + assert_eq!((h.leaf, h.kind, h.top_object(None)), (clip, HitKind::Outline, g), "at {x}, {y}"); + } + let h = hit_test(&d, Point::new(90.0, 90.0), SELECTING).unwrap(); + assert_eq!((h.leaf, h.top_object(None)), (art, g)); + // Beyond the tolerance outside it, the clipped art is not there to hit. + assert!(hit_test(&d, Point::new(150.0, 90.0), SELECTING).is_none()); +} + +/// Without `clip_outlines` (the tools that act on what is drawn) and for read-only sampling +/// (the eyedropper), the art is hit on the mask's edge, as before: the clipping path paints +/// nothing there. +#[test] +fn only_the_selection_tools_hit_a_clipping_path_on_its_outline() { + let (d, _, clip, art) = masked_square(false); + let p = Point::new(138.5, 90.0); + assert_eq!(hit_test(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art)); + assert_eq!(hit_test_visible(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art)); + assert_eq!(hit_test_visible(&d, p, SELECTING).map(|h| h.leaf), Some(art)); + assert_eq!(hit_test(&d, p, SELECTING).map(|h| h.leaf), Some(clip)); + // A hidden or locked clipping path is passed over. + for change in [|n: &mut Node| n.visible = false, |n: &mut Node| n.locked = true] { + let mut d = d.clone(); + change(d.node_mut(clip).unwrap()); + assert_ne!(hit_test(&d, p, SELECTING).map(|h| h.leaf), Some(clip)); + } +} + +/// A layer's clipping mask is hit on its outline too, and Select Behind lists what the +/// repeated hit test finds: the mask on and just outside its edge, then the art inside it; +/// well inside, the art alone (the mask paints nothing there). +#[test] +fn select_behind_takes_a_layer_masks_outline_first() { + let (d, _, clip, art) = masked_square(true); + for (x, want) in [(140.0, vec![clip]), (141.5, vec![clip]), (138.5, vec![clip, art]), (90.0, vec![art])] { + let p = Point::new(x, 90.0); + assert_eq!(objects_at(&d, p, SELECTING, None), want, "x = {x}"); + assert_eq!(objects_at_repeated(&d, p, SELECTING, None), want, "x = {x}"); + } + // Without clip_outlines, as before. + assert_eq!(objects_at(&d, Point::new(138.5, 90.0), HitOptions::default(), None), vec![art, clip]); +} + +/// Art in a sublayer is an object of its own: a click or a marquee takes it, not the +/// sublayer; hidden, locked and template sublayers block both. +#[test] +fn sublayers_are_not_objects() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let sub = d.alloc_id(); + d.insert(Some(l), 0, Node::layer(sub, "Sub", crate::LayerColor::Preset(2))).unwrap(); + let inner = d.alloc_id(); + d.insert(Some(sub), 0, Node::layer(inner, "Inner", crate::LayerColor::Preset(3))).unwrap(); + let a = d.alloc_id(); + d.insert(Some(inner), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap(); + let g = d.alloc_id(); + let b = d.alloc_id(); + let pb = Node::path(b, shapes::rectangle(Rect::new(100.0, 0.0, 150.0, 50.0)), Appearance::default_art()); + d.insert(Some(sub), 9, Node::group(g, vec![Arc::new(pb)])).unwrap(); + let h = hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).unwrap(); + assert_eq!((h.leaf, h.top_object(None), h.layers), (a, a, 3)); + let h = hit_test(&d, Point::new(110.0, 10.0), HitOptions::default()).unwrap(); + assert_eq!((h.top_object(None), h.top_object(Some(g))), (g, b)); + let all = Rect::new(-5.0, -5.0, 200.0, 200.0); + assert_eq!(marquee(&d, all, None, false), vec![a, g]); + assert_eq!(d.layer_containing(a), Some(inner)); + assert_eq!(d.layer_color(a), crate::LayerColor::Preset(3).rgb(), "the sublayer's own colour"); + assert_eq!(d.selectable_art(), vec![a, g]); + for f in [ + |n: &mut Node| n.visible = false, + |n: &mut Node| n.locked = true, + |n: &mut Node| { + if let NodeKind::Layer { template, .. } = &mut n.kind { + *template = true; + } + }, + ] { + let mut d2 = d.clone(); + f(d2.node_mut(inner).unwrap()); + assert!(hit_test(&d2, Point::new(10.0, 10.0), HitOptions::default()).is_none()); + assert_eq!(marquee(&d2, all, None, false), vec![g]); + assert_eq!(d2.selectable_art(), vec![g]); + } + // A sublayer whose Preview is off is clicked in outline: its fill no longer hits. + if let NodeKind::Layer { preview, .. } = &mut d.node_mut(inner).unwrap().kind { + *preview = false; + } + assert!(hit_test(&d, Point::new(25.0, 25.0), HitOptions::default()).is_none()); + assert!(hit_test(&d, Point::new(0.5, 25.0), HitOptions::default()).is_some()); +} + +/// Object Selection by Path Only: a filled path or compound path hits on its outline only. +#[test] +fn path_only_leaves_out_fills() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let (a, c) = (d.alloc_id(), d.alloc_id()); + d.insert(Some(l), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap(); + let inner = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 0.0, 150.0, 50.0)), Appearance::default()); + let mut compound = Node::new(c, NodeKind::Compound { children: vec![Arc::new(inner)], rule: vectorcraft_geom::FillRule::NonZero }); + compound.appearance = Appearance::default_art().into(); + d.insert(Some(l), 9, compound).unwrap(); + let path_only = HitOptions { path_only: true, ..Default::default() }; + for (id, inside, edge) in [(a, Point::new(25.0, 25.0), Point::new(0.5, 25.0)), (c, Point::new(125.0, 25.0), Point::new(100.5, 25.0))] { + assert_eq!(hit_test(&d, inside, HitOptions::default()).map(|h| h.leaf), Some(id), "the fill hits"); + assert!(hit_test(&d, inside, path_only).is_none(), "path only: the fill of {id:?} doesn't hit"); + assert_eq!(hit_test(&d, edge, path_only).map(|h| h.leaf), Some(id), "path only: the outline does"); + } +} + +/// #3291: with Object Selection by Path Only, a placed image is picked on its frame's edge, so +/// a path under it can be picked through it. +#[test] +fn path_only_picks_paths_through_images() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let (path, image) = (d.alloc_id(), d.alloc_id()); + d.insert(Some(l), 0, Node::path(path, shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default_art())).unwrap(); + // 100×50 pixels, scaled to 100×100 and moved to (10, 10): over the whole path. + let xf = vectorcraft_geom::Affine::translate((10.0, 10.0)) * vectorcraft_geom::Affine::scale_non_uniform(1.0, 2.0); + let im = crate::ImageObject { key: "k".into(), width: 100, height: 50, xf, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(l), 1, Node::new(image, NodeKind::Image(Box::new(im)))).unwrap(); + let path_only = HitOptions { path_only: true, ..Default::default() }; + let hit = |p: Point, opt| hit_test(&d, p, opt).map(|h| h.leaf); + let (path_edge, inside, image_edge) = (Point::new(20.5, 40.0), Point::new(80.0, 80.0), Point::new(80.0, 109.5)); + assert_eq!(hit(path_edge, HitOptions::default()), Some(image), "the image covers the path"); + assert_eq!(hit(inside, HitOptions::default()), Some(image)); + assert_eq!(hit(path_edge, path_only), Some(path), "path only: the path through the image"); + assert_eq!(hit(inside, path_only), None, "path only: not inside the image"); + assert_eq!(hit(image_edge, path_only), Some(image), "path only: the image's frame"); +} + +/// Type Object Selection by Path Only: point type is picked on its baseline, area type on its +/// frame and type on a path on its path, no longer anywhere in its bounds. +#[test] +fn type_path_only_picks_type_on_its_path() { + use crate::{CharStyle, TextKind, TextObject}; + let mut d = Document::new(400.0, 400.0); + let l = d.layers[0].id; + let mut add = |t: TextObject| { + let id = d.alloc_id(); + d.insert(Some(l), 9, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); + id + }; + // Point type at (10, 100), 20 pt: its glyphs rise above the baseline, its layout is 60 wide. + let mut point = TextObject::point(Point::new(10.0, 100.0), "Hello", CharStyle { size: 20.0, ..CharStyle::default() }); + point.cached_bounds = Some(Rect::new(0.0, -16.0, 60.0, 4.0)); + let point = add(point); + let mut area = TextObject::point(Point::new(200.0, 200.0), "Area", CharStyle::default()); + area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)) }; + let area = add(area); + let mut on_path = TextObject::point(Point::new(10.0, 300.0), "Path", CharStyle::default()); + on_path.kind = TextKind::OnPath { path: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 40.0)), start: 0.0, end: None }; + let on_path = add(on_path); + let path_only = HitOptions { type_path_only: true, ..Default::default() }; + let hit = |p: Point, opt: HitOptions| hit_test(&d, p, opt).map(|h| (h.leaf, h.kind)); + // Off: anywhere in the bounds. + assert_eq!(hit(Point::new(40.0, 90.0), HitOptions::default()), Some((point, HitKind::Bounds))); + assert_eq!(hit(Point::new(250.0, 225.0), HitOptions::default()), Some((area, HitKind::Bounds))); + assert_eq!(hit(Point::new(60.0, 320.0), HitOptions::default()), Some((on_path, HitKind::Bounds))); + // On: the glyphs and the inside of the frame or path no longer pick the type. + assert_eq!(hit(Point::new(40.0, 90.0), path_only), None, "point type: among its glyphs"); + assert_eq!(hit(Point::new(250.0, 225.0), path_only), None, "area type: inside its frame"); + assert_eq!(hit(Point::new(60.0, 320.0), path_only), None, "type on a path: inside its path"); + // The baseline (within the tolerance, across the layout's width), frame and path do. + assert_eq!(hit(Point::new(40.0, 101.5), path_only), Some((point, HitKind::Outline)), "point type: its baseline"); + assert_eq!(hit(Point::new(75.0, 100.0), path_only), None, "point type: past the end of its layout"); + assert_eq!(hit(Point::new(250.0, 200.5), path_only), Some((area, HitKind::Outline)), "area type: its frame"); + assert_eq!(hit(Point::new(60.0, 339.5), path_only), Some((on_path, HitKind::Outline)), "type on a path: its path"); +} + +/// Type Object Selection by Path Only with the layout's baselines: every line's for point type, +/// area type's besides its frame, a vertical column's centre line, and type in perspective +/// where it is drawn. +#[test] +fn type_path_only_picks_every_baseline() { + use crate::{CharStyle, PerspectiveAttachment, TextKind, TextObject}; + use vectorcraft_geom::{Affine, Homography}; + let mut d = Document::new(400.0, 400.0); + let l = d.layers[0].id; + let mut add = |t: TextObject, perspective: Option| { + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.extras_mut().perspective = perspective.map(|a| { + Box::new(PerspectiveAttachment { projection: Some(Homography::from_affine(a).to_array()), ..PerspectiveAttachment::new("left", 0.0) }) + }); + let id = n.id; + d.insert(Some(l), 9, n).unwrap(); + id + }; + let style = CharStyle { size: 20.0, ..CharStyle::default() }; + // Two lines of point type at (10, 100), 24 pt apart. + let mut point = TextObject::point( + Point::new(10.0, 100.0), + "Hello +world", + style.clone(), + ); + point.cached_bounds = Some(Rect::new(0.0, -16.0, 60.0, 28.0)); + point.cached_baselines = vec![(Point::ZERO, Point::new(60.0, 0.0)), (Point::new(0.0, 24.0), Point::new(50.0, 24.0))]; + let point = add(point, None); + // Area type: a line inside its frame. + let mut area = TextObject::point(Point::new(200.0, 50.0), "Area", style.clone()); + area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)) }; + area.cached_baselines = vec![(Point::new(0.0, 16.0), Point::new(40.0, 16.0))]; + let area = add(area, None); + // Vertical point type at (300, 200) with no baselines cached: down its first column. + let mut vertical = TextObject::point(Point::new(300.0, 200.0), "Tate", style.clone()); + vertical.vertical = true; + vertical.cached_bounds = Some(Rect::new(-10.0, 0.0, 10.0, 80.0)); + let vertical = add(vertical, None); + // Point type drawn 100 to the right of where it is laid out. + let mut moved = TextObject::point(Point::new(10.0, 350.0), "Moved", style); + moved.cached_bounds = Some(Rect::new(0.0, -16.0, 60.0, 4.0)); + let moved = add(moved, Some(Affine::translate((100.0, 0.0)))); + let path_only = HitOptions { type_path_only: true, ..Default::default() }; + let hit = |p: Point| hit_test(&d, p, path_only).map(|h| h.leaf); + assert_eq!(hit(Point::new(40.0, 100.0)), Some(point), "the first line's baseline"); + assert_eq!(hit(Point::new(40.0, 125.0)), Some(point), "the second line's"); + assert_eq!(hit(Point::new(40.0, 112.0)), None, "between the lines"); + assert_eq!(hit(Point::new(65.0, 124.0)), None, "past the end of the shorter second line"); + assert_eq!(hit(Point::new(220.0, 66.0)), Some(area), "area type: a line's baseline"); + assert_eq!(hit(Point::new(220.0, 80.0)), None, "area type: inside the frame, off the baselines"); + assert_eq!(hit(Point::new(299.0, 260.0)), Some(vertical), "vertical type: down the column"); + assert_eq!(hit(Point::new(306.0, 260.0)), None, "vertical type: beside it"); + assert_eq!(hit(Point::new(140.0, 351.0)), Some(moved), "in perspective: where it is drawn"); + assert_eq!(hit(Point::new(40.0, 351.0)), None, "in perspective: not where it is laid out"); +} + +/// `objects_at`: every object under the point, topmost first; a group counts once. +#[test] +fn objects_at_lists_the_stack() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let rect = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art()); + let a = rect(&mut d, 0.0); + let (b, c) = (rect(&mut d, 10.0), rect(&mut d, 20.0)); + let (a_id, b_id, c_id, g) = (a.id, b.id, c.id, d.alloc_id()); + d.insert(Some(l), 0, a).unwrap(); + d.insert(Some(l), 9, Node::group(g, vec![Arc::new(b), Arc::new(c)])).unwrap(); + let far = rect(&mut d, 120.0); + d.insert(Some(l), 9, far).unwrap(); + let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope); + assert_eq!(at(30.0, None), vec![g, a_id]); + assert_eq!(at(30.0, Some(g)), [c_id, b_id], "isolated: the group's own objects"); + // Isolated, the art around the group is locked: clicks pass through it (#833). + assert!(at(5.0, Some(g)).is_empty()); + assert!(at(130.0, Some(g)).is_empty()); + assert!(hit_test(&d, Point::new(5.0, 25.0), HitOptions { scope: Some(g), ..HitOptions::default() }).is_none()); + assert_eq!(at(5.0, None), vec![a_id]); + assert!(at(90.0, None).is_empty()); +} + +/// Many overlapping paths: Select Behind must list each exactly once, front to back. +/// This is quadratic with repeated full-document hit tests, but linear in tree size with +/// the per-object walk. +#[test] +fn objects_at_large_overlapping_stack() { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + let mut ids = Vec::new(); + for _ in 0..256 { + let id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap(); + ids.push(id); + } + ids.reverse(); + assert_eq!(objects_at(&d, Point::new(25.0, 25.0), HitOptions::default(), None), ids); +} + +/// Match the original skip-and-retest algorithm for normal groups, sublayers, clipping, +/// invisibility, and path/outline-only settings. +#[test] +fn objects_at_one_pass_matches_repeated_hits() { + let mut d = Document::new(200.0, 200.0); + let layer = d.layers[0].id; + let add = |d: &mut Document, parent, bounds| { + let id = d.alloc_id(); + d.insert(Some(parent), usize::MAX, Node::path(id, shapes::rectangle(bounds), Appearance::default_art())).unwrap(); + id + }; + add(&mut d, layer, Rect::new(0.0, 0.0, 60.0, 60.0)); + let sub = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sublayer", crate::LayerColor::Preset(2))).unwrap(); + add(&mut d, sub, Rect::new(0.0, 0.0, 60.0, 60.0)); + let group = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::group(group, Vec::new())).unwrap(); + add(&mut d, group, Rect::new(0.0, 0.0, 60.0, 60.0)); + add(&mut d, group, Rect::new(5.0, 5.0, 60.0, 60.0)); + let clip = d.alloc_id(); + let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(5.0, 5.0, 45.0, 45.0)), Appearance::default_art()); + let content = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 80.0, 80.0)), Appearance::default_art()); + let mut clipping = Node::group(clip, vec![Arc::new(mask), Arc::new(content)]); + clipping.set_clips(true); + d.insert(Some(layer), usize::MAX, clipping).unwrap(); + for (point, opt) in [ + (Point::new(25.0, 25.0), HitOptions::default()), + (Point::new(3.0, 25.0), HitOptions::default()), + (Point::new(25.0, 25.0), HitOptions { outline: true, ..Default::default() }), + (Point::new(6.0, 25.0), HitOptions { path_only: true, ..Default::default() }), + (Point::new(100.0, 100.0), HitOptions::default()), + ] { + assert_eq!(objects_at(&d, point, opt, None), objects_at_repeated(&d, point, opt, None), "point={point:?}, opt={opt:?}"); + } + if let NodeKind::Layer { preview, .. } = &mut d.node_mut(sub).unwrap().kind { + *preview = false; + } + let p = Point::new(25.0, 25.0); + let opt = HitOptions::default(); + assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None)); + d.node_mut(group).unwrap().locked = true; + assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None)); +} + +/// Documents built at random (nested groups, sublayers, clipping groups, compound paths, blends +/// of nothing, hidden and locked objects, outline layers): Select Behind lists the same objects +/// in the same order as the hit test repeated over what is left. +#[test] +fn objects_at_matches_repeated_hits_on_random_documents() { + let mut seed = 0x9e37_79b9_u32; + let mut next = move |n: u32| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed % n + }; + fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) { + for _ in 0..2 + next(4) { + let id = d.alloc_id(); + let (x, y) = (f64::from(next(60)), f64::from(next(60))); + let rect = Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50))); + let appearance = if next(4) == 0 { Appearance::default() } else { Appearance::default_art() }; + let mut n = match next(if depth < 3 { 8 } else { 4 }) { + 4 | 5 => Node::group(id, Vec::new()), + 6 => Node::layer(id, "Sublayer", crate::LayerColor::Preset(2)), + 7 => { + let mut g = Node::group(id, Vec::new()); + g.set_clips(true); + g + } + _ => Node::path(id, shapes::rectangle(rect), appearance), + }; + n.visible = next(8) != 0; + n.locked = next(8) == 0; + if let NodeKind::Layer { preview, .. } = &mut n.kind { + *preview = next(3) != 0; + } + let container = n.is_container(); + // A sublayer belongs in a layer; in a group it is a group like another to the hit test. + d.insert(Some(parent), usize::MAX, n).unwrap(); + if container { + fill(d, id, depth + 1, next); + } + } + } + for round in 0..200 { + let mut d = Document::new(120.0, 120.0); + let layer = d.layers[0].id; + fill(&mut d, layer, 0, &mut next); + // A clipping mask on the layer, or on a sublayer, now and then. + let sublayers: Vec = d.layers[0].children().into_iter().flatten().filter(|n| n.is_layer()).map(|n| n.id).collect(); + for id in std::iter::once(layer).chain(sublayers) { + if next(3) == 0 { + d.node_mut(id).unwrap().set_clips(true); + } + } + for _ in 0..12 { + let p = Point::new(f64::from(next(120)), f64::from(next(120))); + let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() }; + assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None), "round {round}, {p:?}, {opt:?}"); + } + } +} + +/// Select Behind finds a symbol instance by its symbol's art, as a click does: art from +/// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by +/// one instance and 100 pt lower by an instance in a group. +#[test] +fn objects_at_finds_symbol_instances_by_their_art() { + let mut d = Document::new(200.0, 200.0); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 60.0, 140.0, 80.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { name: "Far".into(), art: Arc::new(art) }); + let (layer, top, inner, group) = (d.layers[0].id, d.alloc_id(), d.alloc_id(), d.alloc_id()); + let instance = |id, dy: f64| Node::new(id, NodeKind::SymbolInstance { symbol: "Far".into(), xf: vectorcraft_geom::Affine::translate((0.0, dy)) }); + d.insert(Some(layer), 0, instance(top, 0.0)).unwrap(); + d.insert(Some(layer), 1, Node::group(group, vec![Arc::new(instance(inner, 100.0))])).unwrap(); + let opt = HitOptions::default(); + for (x, y, want) in [(120.0, 70.0, vec![top]), (120.0, 170.0, vec![group]), (0.0, 0.0, vec![]), (0.0, 100.0, vec![])] { + let p = Point::new(x, y); + assert_eq!(objects_at(&d, p, opt, None), want, "{p:?}"); + assert_eq!(objects_at_repeated(&d, p, opt, None), want, "{p:?}"); + } +} + +/// Edit Contents can expose descendants of a top-level group: preserve the original +/// selection order by falling back to the general hit traversal. +#[test] +fn objects_at_edit_contents_uses_general_order() { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + let inner = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())); + let (a, b) = (d.alloc_id(), d.alloc_id()); + let e = Node::new( + 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 }), + fidelity: 100.0, + editing: true, + options: Default::default(), + frame: Box::new(vectorcraft_geom::Affine::IDENTITY), + }, + ); + d.insert(Some(layer), usize::MAX, e).unwrap(); + let p = Point::new(25.0, 25.0); + let opt = HitOptions::default(); + assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None)); + assert_eq!(objects_at(&d, p, opt, None), vec![b, a]); +} + +#[test] +fn locked_and_hidden_skip() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let a = d.alloc_id(); + d.insert(Some(l), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap(); + d.node_mut(a).unwrap().locked = true; + assert!(hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).is_none()); + d.node_mut(a).unwrap().locked = false; + d.node_mut(l).unwrap().visible = false; + assert!(hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).is_none()); +} + +/// Insert `n` locked at the top of `parent`. +fn insert_locked(d: &mut Document, parent: NodeId, mut n: Node) -> NodeId { + let id = n.id; + n.locked = true; + d.insert(Some(parent), usize::MAX, n).unwrap(); + id +} + +/// `locked_objects_at`: the locked objects under the point, topmost first. A locked group is +/// listed rather than its contents, and a locked object in an unlocked group is listed itself. +/// Hidden objects, locked layers and the art outside an isolated group are left out. +#[test] +fn locked_objects_at_lists_the_locked_stack() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let rect = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art()); + let (a, b) = (rect(&mut d, 0.0), rect(&mut d, 10.0)); + let (a, b) = (insert_locked(&mut d, l, a), insert_locked(&mut d, l, b)); + let (mut inner, locked_group) = (rect(&mut d, 20.0), d.alloc_id()); + inner.locked = true; + let inner_id = inner.id; + let mut g = Node::group(locked_group, vec![Arc::new(inner)]); + g.locked = true; + d.insert(Some(l), usize::MAX, g).unwrap(); + let open_group = d.alloc_id(); + let mut child = rect(&mut d, 25.0); + child.locked = true; + let child_id = child.id; + let free = rect(&mut d, 25.0); + d.insert(Some(l), usize::MAX, Node::group(open_group, vec![Arc::new(child), Arc::new(free)])).unwrap(); + let at = |d: &Document, x: f64, scope| locked_objects_at(d, Point::new(x, 25.0), HitOptions { scope, ..HitOptions::default() }); + assert_eq!(at(&d, 30.0, None), [child_id, locked_group, b, a]); + assert!(!at(&d, 30.0, None).contains(&inner_id), "the locked group stands for what it holds"); + assert_eq!(at(&d, 5.0, None), [a]); + assert!(at(&d, 150.0, None).is_empty()); + // Isolated, only the group's own objects are looked at. + assert_eq!(at(&d, 30.0, Some(open_group)), [child_id]); + // A hidden object is left out, and nothing on a locked or hidden layer is listed. + d.node_mut(b).unwrap().visible = false; + assert_eq!(at(&d, 30.0, None), [child_id, locked_group, a]); + d.node_mut(l).unwrap().locked = true; + assert!(at(&d, 30.0, None).is_empty()); + d.node_mut(l).unwrap().locked = false; + d.node_mut(l).unwrap().visible = false; + assert!(at(&d, 30.0, None).is_empty()); +} + +/// `locked_objects_at` lists at most `MAX_LOCKED_AT` objects, the topmost ones. +#[test] +fn locked_objects_at_stops_at_its_limit() { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let ids: Vec = (0..MAX_LOCKED_AT + 5) + .map(|_| { + let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art()); + insert_locked(&mut d, l, n) + }) + .collect(); + let found = locked_objects_at(&d, Point::new(25.0, 25.0), HitOptions::default()); + assert_eq!(found, ids.iter().rev().take(MAX_LOCKED_AT).copied().collect::>()); +} + +#[test] +fn visible_sampling_reads_locked_art_and_layers_but_excludes_hidden_art() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let a = d.alloc_id(); + d.insert(Some(l), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap(); + let p = Point::new(10.0, 10.0); + for lock in [a, l] { + d.node_mut(lock).unwrap().locked = true; + assert!(hit_test(&d, p, HitOptions::default()).is_none()); + assert_eq!(hit_test_visible(&d, p, HitOptions::default()).unwrap().leaf, a); + assert!(d.node(lock).unwrap().locked); + d.node_mut(lock).unwrap().locked = false; + } + d.node_mut(a).unwrap().visible = false; + assert!(hit_test_visible(&d, p, HitOptions::default()).is_none()); + d.node_mut(a).unwrap().visible = true; + d.node_mut(l).unwrap().visible = false; + assert!(hit_test_visible(&d, p, HitOptions::default()).is_none()); +} diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index 582e4c25db..65a6962f18 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -20,8 +20,9 @@ use std::sync::{Arc, RwLock}; use crate::{Node, NodeId}; -/// Hasher for node ids: one multiply. Ids are small counters, not attacker-chosen keys, and the -/// default SipHash dominated the cost of building the cache. +/// Hasher for node ids: one multiply, by a number chosen at random once per run (a document's ids +/// are its author's, and a fixed multiplier lets them be picked to collide). The default SipHash +/// dominated the cost of building the cache. #[derive(Default)] pub struct IdHasher(u64); @@ -32,13 +33,19 @@ impl Hasher for IdHasher { } } fn write_u64(&mut self, v: u64) { - self.0 = (self.0 ^ v).wrapping_mul(0x9e37_79b9_7f4a_7c15); + self.0 = (self.0 ^ v).wrapping_mul(multiplier()); } fn finish(&self) -> u64 { self.0 ^ (self.0 >> 29) } } +/// The odd multiplier of [`IdHasher`], random per run. +fn multiplier() -> u64 { + static KEY: std::sync::OnceLock = std::sync::OnceLock::new(); + *KEY.get_or_init(|| std::hash::BuildHasher::hash_one(&std::hash::RandomState::new(), 0x9e37_79b9_7f4a_7c15_u64) | 1) +} + /// A map keyed by node id with [`IdHasher`]. pub type IdMap = HashMap>; /// Where each node is: its parent's entry (`u32::MAX` for a top-level layer) and its index among diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 12ecf8570a..18873d6d93 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -44,6 +44,7 @@ pub mod perspective; mod pixels; pub use pixels::MAX_RASTER_ALLOC; pub mod placed_document; +pub mod plugin_data; pub mod profiles; pub mod puppet; pub mod range; @@ -67,23 +68,7 @@ use std::collections::BTreeMap; use std::sync::Arc; /// `skip_serializing_if` predicates: fields equal to their serde default are not written. -pub(crate) mod skip { - pub fn is_default(v: &T) -> bool { - *v == T::default() - } - pub fn is_true(v: &bool) -> bool { - *v - } - pub fn is_one(v: &f32) -> bool { - *v == 1.0 - } - pub fn is_empty_vec(v: &[T]) -> bool { - v.is_empty() - } - pub fn is_empty_map(v: &serde_json::Map) -> bool { - v.is_empty() - } -} +pub(crate) mod skip; pub use appearance::StrokeGradientMode; pub use appearance::{ @@ -92,24 +77,24 @@ pub use appearance::{ }; pub use assets::ExportAsset; pub use corners::LiveCorners; -pub use depth::MAX_DEPTH; +pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES}; pub use graph::{ ColumnDesign, ColumnType, Fractions, GraphDesign, GraphKind, GraphSpec, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide, }; pub use hit::{Hit, HitKind}; pub use links::{LinkInfo, PlacementOptions}; -pub use live::{BlendOrientation, BlendSpacing, BlendSpec, EnvelopeKind, GradientMesh, MeshPoint}; +pub use live::{BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, BlendSpec, EnvelopeKind, GradientMesh, MeshPoint}; pub use live_paint::{GapOptions, GapSize}; pub use metadata::{CopyrightStatus, DocMetadata}; pub use node::Knockout; pub use node::Scaling; pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask}; -pub use node::{ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS}; +pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS}; pub use orient::OrientedBox; pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType}; pub use perspective::PerspectiveAttachment; -pub use placed_document::PlacedDocument; +pub use placed_document::{PageBox, PlacedDocument}; pub use profiles::ColorProfiles; pub use puppet::{PuppetPin, PuppetPins}; pub use rastersettings::{RasterColorModel, RasterEffectsSettings}; @@ -119,8 +104,8 @@ pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOption pub use style_libs::StyleLibrary; pub use text::{ AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt, - JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, ScriptMetrics, - SingleWordJustify, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape, + JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition, + RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape, }; pub use trace::TraceView; pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables}; @@ -131,513 +116,26 @@ use serde::{Deserialize, Serialize}; use vectorcraft_color::{Swatch, SwatchGroup}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; -/// Coordinates beyond this many points exceed the supported document range. -pub const MAX_COORD: f64 = 4.0e6; +mod artboard; +mod document; +mod document_ext; +mod document_guides; +mod graphic_style; +mod guides; +mod limits; +mod records; +mod units; -#[derive(Debug, thiserror::Error, PartialEq)] -pub enum DocError { - #[error("no such object {0}")] - NoNode(NodeId), - #[error("object {0} cannot have children")] - NotContainer(NodeId), - #[error("{0}")] - Invalid(String), -} - -/// Measurement units (display only; the model is always in points). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum Unit { - #[default] - Points, - Picas, - Inches, - Millimeters, - Centimeters, - Pixels, - FeetInches, - Meters, - Yards, - Feet, -} - -impl Unit { - pub const ALL: [Unit; 10] = [ - Unit::Points, - Unit::Picas, - Unit::Inches, - Unit::Millimeters, - Unit::Centimeters, - Unit::Pixels, - Unit::FeetInches, - Unit::Meters, - Unit::Yards, - Unit::Feet, - ]; - /// Points per unit. - pub fn points(self) -> f64 { - match self { - Unit::Points | Unit::Pixels => 1.0, - Unit::Picas => 12.0, - Unit::Inches => 72.0, - Unit::Millimeters => 72.0 / 25.4, - Unit::Centimeters => 72.0 / 2.54, - Unit::Meters => 72.0 / 0.0254, - Unit::Yards => 72.0 * 36.0, - Unit::Feet | Unit::FeetInches => 72.0 * 12.0, - } - } - pub fn suffix(self) -> &'static str { - match self { - Unit::Points => "pt", - Unit::Picas => "p", - Unit::Inches => "in", - Unit::Millimeters => "mm", - Unit::Centimeters => "cm", - Unit::Pixels => "px", - Unit::FeetInches | Unit::Feet => "ft", - Unit::Meters => "m", - Unit::Yards => "yd", - } - } - pub fn label(self) -> &'static str { - match self { - Unit::Points => "Points", - Unit::Picas => "Picas", - Unit::Inches => "Inches", - Unit::Millimeters => "Millimeters", - Unit::Centimeters => "Centimeters", - Unit::Pixels => "Pixels", - Unit::FeetInches => "Feet & Inches", - Unit::Meters => "Meters", - Unit::Yards => "Yards", - Unit::Feet => "Feet", - } - } - /// The rulers' label step at `zoom` (screen pixels per point), in this unit: the first of - /// 1, 2, 5 × 10ⁿ that puts labels at least 50 pixels apart. Ticks mark every tenth of it. - pub fn ruler_step(self, zoom: f64) -> f64 { - const DECIMAL: [f64; 19] = - [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0]; - // An inch is divided in half, not in ten: a tenth of an inch is not a mark an inch ruler - // carries, so below an inch the steps are binary fractions (#2827). Labelling stops at a - // sixteenth; zooming in past that leaves the labels where they are and only the ticks - // between them grow denser, down to a hundred and twenty-eighth - // ([`Self::ruler_minor`]). A label is at most six characters that way ("0.0625"), which - // the left ruler has room for when it spells one down the ruler a character at a time. - // From an inch up the ladder is the shared one. - const BINARY: [f64; 15] = [1.0 / 16.0, 0.125, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 10000.0]; - let steps: &[f64] = if self.ruler_halves() { &BINARY } else { &DECIMAL }; - steps.iter().copied().find(|s| s * self.points() * zoom >= 50.0).unwrap_or(10000.0) - } - /// Does this unit's ruler divide a step in half rather than in ten? Inches do; the metric - /// units, points, pixels and picas are read in tenths. - fn ruler_halves(self) -> bool { - matches!(self, Unit::Inches) - } - /// The unlabelled ticks between two labels, `step` apart ([`Self::ruler_step`]): an eighth of - /// the step on an inch ruler, so every tick is a binary fraction of an inch and they stay about - /// as dense as the tenths elsewhere; a tenth of it otherwise. - pub fn ruler_minor(self, step: f64) -> f64 { - if self.ruler_halves() { step / 8.0 } else { step / 10.0 } - } - /// `v` (points) on the nearest ruler tick at `zoom` ([`Self::ruler_step`]). - pub fn snap_to_ruler_tick(self, v: f64, zoom: f64) -> f64 { - let tick = self.ruler_minor(self.ruler_step(zoom)) * self.points(); - (v / tick).round() * tick - } - pub fn from_pt(self, v: f64) -> f64 { - v / self.points() - } - pub fn to_pt(self, v: f64) -> f64 { - v * self.points() - } - /// Format a point value in this unit the way fields show it (e.g. `12.5 pt`, `3 in`). - pub fn format(self, pt: f64) -> String { - format!("{} {}", self.number(pt), self.suffix()) - } - /// [`Unit::format`] without the suffix (`12.5`), for narrow fields. - pub fn number(self, pt: f64) -> String { - // Three decimals for the small units (`595.276 pt`), four for the large ones (`8.2677 in`, - // `35.2778 mm`, the `0.0078 in` stroke preset); trailing zeros are trimmed (`1 pt` is `1`). - let decimals = if matches!(self, Unit::Points | Unit::Pixels | Unit::Picas) { 3 } else { 4 }; - let s = format!("{:.*}", decimals, self.from_pt(pt)); - let s = s.trim_end_matches('0').trim_end_matches('.'); - if s == "-0" { "0".into() } else { s.into() } - } - /// Parse `12`, `12pt`, `1in`, `3 mm`, `2p6` (picas+points), simple `+ - * /` arithmetic. - /// - /// A unit after a `*` or `/` operand measures the whole expression (`1080/2 px` is 540 px), so - /// math typed before a field's unit suffix works. After `*` or `/`, a percentage scales the term - /// before it (`3cm*50%` is 1.5 cm, `3cm/50%` is 6 cm). After `+` or `-`, it adds or takes away - /// that share of everything before it (`50pt+25%` is 62.5 pt, `100pt+20pt-50%` is 60 pt). A - /// percentage on its own (`50%`) reads as nothing. - pub fn parse(self, s: &str) -> Option { - parse_measure(s, self).filter(|v| v.is_finite()) - } - /// The value naming this unit in the Units preferences (`points`, `millimeters`, - /// `feetInches`). - pub fn key(self) -> &'static str { - match self { - Unit::Points => "points", - Unit::Picas => "picas", - Unit::Inches => "inches", - Unit::Millimeters => "millimeters", - Unit::Centimeters => "centimeters", - Unit::Pixels => "pixels", - Unit::FeetInches => "feetInches", - Unit::Meters => "meters", - Unit::Yards => "yards", - Unit::Feet => "feet", - } - } - /// The unit `name` names: its label, suffix or [`Unit::key`] in any case, ignoring spaces and - /// punctuation (`Millimeters`, `mm`, `Feet & Inches`, `feetInches`). - pub fn named(name: &str) -> Option { - let letters = |s: &'static str| s.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()); - let given = || name.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()); - // Feet and Feet & Inches share the suffix `ft`: it names the plain unit, so Feet & Inches - // is left to its label and key. - Unit::ALL - .into_iter() - .find(|u| letters(u.label()).eq(given())) - .or_else(|| Unit::ALL.into_iter().filter(|u| *u != Unit::FeetInches).find(|u| u.suffix().chars().eq(given()))) - } - /// A point value as the canvas measurement labels show it: two decimals and the suffix - /// (`12.50 mm`). - pub fn readout(self, pt: f64) -> String { - format!("{:.2} {}", self.from_pt(pt), self.suffix()) - } -} - -fn parse_measure(s: &str, default: Unit) -> Option { - let s = s.trim(); - // Simple arithmetic on the right (Illustrator fields accept "10+5", "100/2", "3in*2"). - // `+` and `-` share one precedence level, as do `*` and `/`, so each level splits at the last - // of its operators (left to right). - for ops in [&['+', '-'][..], &['*', '/'][..]] { - // Past the first character, so a leading sign isn't an operator. - let skip = s.chars().next().map_or(0, char::len_utf8); - // A `+` or `-` right after another operator is the sign of its operand (`10*-2`, `5--3`). - let is_sign = |i: usize| { - s.get(i..).and_then(|r| r.chars().next()).is_some_and(|c| matches!(c, '+' | '-')) - && s.get(..i).and_then(|l| l.trim_end().chars().last()).is_some_and(|c| "+-*/".contains(c)) - }; - let found = s.char_indices().rev().find(|&(i, c)| i >= skip && ops.contains(&c) && !is_sign(i)); - if let Some(i) = found.map(|(i, _)| i) { - let (l, r) = (&s[..i], &s[i + 1..]); - if l.trim().is_empty() { - continue; - } - let Some(op) = s[i..].chars().next() else { continue }; - return match op { - '+' | '-' => { - let a = parse_measure(l, default)?; - // A percentage added or taken away is a share of everything before it: - // `50pt+25%` is 62.5 pt, `100pt+20%-10pt` is 110 pt. - let b = match percent(r) { - Some(k) => a * k, - None => parse_measure(r, default)?, - }; - Some(if op == '+' { a + b } else { a - b }) - } - _ => { - // A factor or divisor is a plain number or a percentage (`3cm*50%` is 1.5 cm); - // a unit after it is the expression's. - let (k, unit) = match percent(r) { - Some(k) => (k, None), - None => number_unit(r)?, - }; - let a = parse_measure(l, unit.unwrap_or(default))?; - if op == '*' { - Some(a * k) - } else if k == 0.0 { - None - } else { - Some(a / k) - } - } - }; - } - } - if let Some((p, pt)) = s.split_once('p') - && !p.is_empty() - && p.trim().parse::().is_ok() - && (pt.is_empty() || pt.trim().parse::().is_ok()) - && !s.ends_with("pt") - && !s.ends_with("px") - { - // The sign belongs to the whole value: `-2p6` is -(2 picas + 6 points). - let sign = if p.trim_start().starts_with('-') { -1.0 } else { 1.0 }; - let picas = p.trim().parse::().ok()?.abs(); - return Some(sign * (picas * 12.0 + pt.trim().parse::().unwrap_or(0.0))); - } - let (v, unit) = number_unit(s)?; - Some(unit.unwrap_or(default).to_pt(v)) -} - -/// A number with an optional unit suffix (`12`, `3 mm`, `2in`) → (the number, its unit). -fn number_unit(s: &str) -> Option<(f64, Option)> { - let s = s.trim(); - let num_end = s.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).unwrap_or(s.len()); - let v: f64 = s.get(..num_end)?.trim().parse().ok()?; - let unit = match s.get(num_end..)?.trim() { - "" => None, - "pt" => Some(Unit::Points), - "px" => Some(Unit::Pixels), - "in" | "\"" => Some(Unit::Inches), - "mm" => Some(Unit::Millimeters), - "cm" => Some(Unit::Centimeters), - "m" => Some(Unit::Meters), - "ft" | "'" => Some(Unit::Feet), - "yd" => Some(Unit::Yards), - "p" | "pc" => Some(Unit::Picas), - _ => return None, - }; - Some((v, unit)) -} - -/// A number followed by `%` (`50%`, `12.5 %`) → its fraction (`0.5`, `0.125`). -fn percent(s: &str) -> Option { - match number_unit(s.trim().strip_suffix('%')?)? { - (p, None) => Some(p / 100.0), - _ => None, - } -} - -/// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as -/// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing. -pub fn parse_number(s: &str) -> Option { - if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/".contains(c)) { - return None; - } - // A leading `+` is a sign (`+5`), as a plain number read it. - let s = s.trim(); - Unit::Points.parse(s.strip_prefix('+').unwrap_or(s)) -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum ColorMode { - #[default] - Rgb, - Cmyk, -} - -impl ColorMode { - /// The colour model new colours take in a document of this mode. - pub fn model(self) -> vectorcraft_color::cms::Model { - match self { - ColorMode::Rgb => vectorcraft_color::cms::Model::Rgb, - ColorMode::Cmyk => vectorcraft_color::cms::Model::Cmyk, - } - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Artboard { - pub id: u32, - pub name: String, - /// Artboard rectangle in document points. - pub rect: Rect, - #[serde(default)] - pub show_center_mark: bool, - #[serde(default)] - pub show_cross_hairs: bool, -} - -/// Opacity-mask editing mode: `object`'s mask art lives on the temporary `layer` while editing. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct MaskEdit { - pub object: NodeId, - pub layer: NodeId, -} - -/// A saved view (View → New View…): zoom, centre and rotation, listed at the bottom of the View menu. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct SavedView { - pub name: String, - pub center: Point, - pub zoom: f64, - #[serde(default)] - pub rotation: f64, -} - -/// A saved selection (Select → Save Selection…): the objects that were selected, listed by name at -/// the bottom of the Select menu. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct SavedSelection { - pub name: String, - pub objects: Vec, -} - -impl SavedSelection { - /// Most saved selections a document keeps (the Select menu lists every one). - pub const MAX: usize = 25; - /// Longest name, in characters. - pub const MAX_NAME: usize = 255; - - /// `name` trimmed and cut to [`Self::MAX_NAME`] characters (`None` when blank). - pub fn clean_name(name: &str) -> Option { - let name: String = name.trim().chars().take(Self::MAX_NAME).collect(); - (!name.is_empty()).then_some(name) - } - - /// The first "Selection N" none of `saved` is named. - pub fn default_name(saved: &[SavedSelection]) -> String { - (1..=saved.len() + 1).map(|i| format!("Selection {i}")).find(|n| !saved.iter().any(|x| &x.name == n)).unwrap_or_default() - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Guide { - /// true = vertical guide at `pos` (x), false = horizontal at `pos` (y). - pub vertical: bool, - pub pos: f64, - /// An artboard guide: the [`Artboard::id`] it belongs to. It runs across that artboard only - /// and moves, is copied and is deleted with it. None: a canvas guide, across the whole canvas. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub artboard: Option, - /// The layer (or sublayer) it is on: it shows, hides and locks with that layer and is listed - /// in it in the Layers panel, and goes when the layer is deleted. None: on no layer (guides - /// from before guides had layers, and from files that don't say), always there. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub layer: Option, -} - -impl Guide { - /// A canvas guide. - pub fn new(vertical: bool, pos: f64) -> Self { - Self { vertical, pos, artboard: None, layer: None } - } - - /// Moved by `d` (a vertical guide across, a horizontal one down). - pub fn moved(&self, d: Vec2) -> Self { - Self { pos: self.pos + if self.vertical { d.x } else { d.y }, ..self.clone() } - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct GridPrefs { - pub spacing: f64, - pub subdivisions: u32, -} - -impl Default for GridPrefs { - fn default() -> Self { - Self { spacing: 72.0, subdivisions: 8 } - } -} - -/// A named graphic style (Graphic Styles panel): an appearance plus the object's transparency. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct GraphicStyle { - pub name: String, - pub appearance: Appearance, - /// Stable id linked objects refer to ([`Node::graphic_style`]); 0 until first needed (styles - /// from older files get one when an object is first linked to them). - #[serde(default, skip_serializing_if = "skip::is_default")] - pub id: u32, - #[serde(default = "one", skip_serializing_if = "skip::is_one")] - pub opacity: f32, - #[serde(default, skip_serializing_if = "skip::is_default")] - pub blend: vectorcraft_color::BlendMode, - #[serde(default, skip_serializing_if = "skip::is_default")] - pub isolate: bool, - #[serde(default, skip_serializing_if = "skip::is_default")] - pub knockout: Knockout, - /// Placed gradients are stored relative to the unit box (0, 0)–(1, 1), so applying the style - /// places them on each object's own bounds. Styles saved before this kept document - /// coordinates (false). - #[serde(default, skip_serializing_if = "std::ops::Not::not")] - pub unit_box: bool, -} - -fn one() -> f32 { - 1.0 -} - -/// The name of the style new documents list first (Sort by Name keeps it first). -pub const DEFAULT_GRAPHIC_STYLE: &str = "Default Graphic Style"; - -impl GraphicStyle { - /// The box a style's placed gradients are stored relative to. - pub const UNIT_BOX: Rect = Rect::new(0.0, 0.0, 1.0, 1.0); - - /// A style with `appearance` (its placed gradients, if any, in unit-box space) and default - /// transparency (no id yet). - pub fn new(name: impl Into, appearance: Appearance) -> Self { - Self { - name: name.into(), - appearance, - id: 0, - opacity: 1.0, - blend: Default::default(), - isolate: false, - knockout: Knockout::Neutral, - unit_box: true, - } - } - /// A style capturing `n`'s transparency and `appearance` (in unit-box space). - pub fn of(name: impl Into, appearance: Appearance, n: &Node) -> Self { - Self { opacity: n.opacity, blend: n.blend, isolate: n.isolate, knockout: n.knockout, ..Self::new(name, appearance) } - } - /// The style's appearance as object `n` takes it: placed gradients stored in unit-box space - /// land at the same place relative to `n`'s geometric bounds. - pub fn appearance_on(&self, n: &Node) -> std::borrow::Cow<'_, Appearance> { - let placed = self.unit_box && self.appearance.has_placed_gradient(); - match n.geometric_bounds().filter(|_| placed) { - Some(b) => { - let mut ap = self.appearance.clone(); - ap.rebase_gradients(Self::UNIT_BOX, b); - std::borrow::Cow::Owned(ap) - } - None => std::borrow::Cow::Borrowed(&self.appearance), - } - } - /// Give `n` this style's transparency. - pub fn apply_transparency(&self, n: &mut Node) { - (n.opacity, n.blend, n.isolate, n.knockout) = (self.opacity, self.blend, self.isolate, self.knockout); - } - /// Does `n` have this style's transparency? - pub fn transparency_matches(&self, n: &Node) -> bool { - (n.opacity, n.blend, n.isolate, n.knockout) == (self.opacity, self.blend, self.isolate, self.knockout) - } -} - -/// A symbol definition. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Symbol { - pub name: String, - pub art: Arc, -} - -/// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct ImageBlob { - pub mime: String, - #[serde(skip)] - pub bytes: Arc>, - /// A linked image's low-resolution preview (PNG, see [`links`]): what a save writes when only - /// linked images show this blob, and what `bytes` hold while the linked file can't be read. - #[serde(skip)] - pub proxy: Option>>, -} - -/// What the rulers measure from (View › Rulers): the active artboard's origin, the default of a -/// new document, or one origin for the whole document. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum RulerMode { - #[default] - Artboard, - Global, -} - -impl RulerMode { - /// The mode of a document saved before the choice existed: global, as its rulers measured. - pub fn legacy() -> Self { - Self::Global - } -} +pub use artboard::{Artboard, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS}; +#[cfg(test)] +use document_ext::free_id; +pub use graphic_style::{DEFAULT_GRAPHIC_STYLE, GraphicStyle}; +pub use guides::{GridPrefs, Guide, RulerMode}; +#[cfg(test)] +use limits::MAX_NEXT_ID; +pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; +pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, Symbol}; +pub use units::{ColorMode, Unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Document { @@ -691,7 +189,7 @@ pub struct Document { pub graph_designs: Vec, #[serde(default)] pub guides: Vec, - /// View → New View… (up to 25, like Illustrator). + /// View → New View… (at most [`SavedView::MAX`]); saved with the document. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub views: Vec, /// Select → Save Selection… (at most [`SavedSelection::MAX`]); saved with the document. @@ -795,6 +293,18 @@ pub struct Document { /// state, never saved. #[serde(skip)] pub puppet: Option>, + /// New art on a locked artboard: objects of layers on a locked artboard that an edit made and + /// left selected (a group with selected members counts), kept while they stay selected and on + /// one. They and their contents can be selected and edited ([`LockedArtboards::holds`]). The + /// engine sets it from the selection's ([`Selection::new_art`]). Editing state, never saved. + #[serde(skip)] + pub new_art: NewArtIds, + /// The highest artboard id given out ([`Document::next_artboard_id`]) or deleted from the + /// document ([`Document::retire_artboard_id`]): a new artboard takes a higher one. Shared by + /// every copy of the document, the undo history's included, so an undo does not lower it. + /// Never saved. + #[serde(skip)] + pub retired_artboard_id: RetiredArtboardId, /// Some object is a dimension (the Dimension tool): edits refresh dimensions only while this /// is set, so documents without any pay nothing for them. #[serde(default, skip_serializing_if = "std::ops::Not::not")] @@ -824,1333 +334,5 @@ pub fn artboard_holds(rect: Rect, p: Point) -> bool { /// of each listed child in it, in order, with the child's place in the list. type Places = BTreeMap, Vec<(usize, usize)>>; -pub const FORMAT_VERSION: u32 = 1; - -impl Document { - /// Document Raster Effects Settings › Resolution in ppi, 1 to 2400 (72 when the stored value - /// isn't a number). - pub fn raster_ppi(&self) -> f64 { - Some(self.raster_effects_ppi).filter(|v| v.is_finite()).unwrap_or(72.0).clamp(1.0, 2400.0) - } - - /// The ruler zero point, or zero on both axes when either stored coordinate is invalid. - /// Rulers, coordinate fields and guide snapping use the same supported range. - pub fn ruler_origin_or_zero(&self) -> Point { - let origin = self.ruler_origin; - if origin.is_finite() && origin.x.abs() <= MAX_COORD && origin.y.abs() <= MAX_COORD { origin } else { Point::ZERO } - } - - /// Where the rulers measure from with artboard `index` active: [`Self::ruler_origin_or_zero`] - /// with global rulers; with artboard rulers that artboard's top-left corner moved by its own - /// offset (the first artboard's when `index` is out of range, the global zero point when the - /// document has no artboard or the result is out of the supported range). - pub fn ruler_origin_for(&self, index: usize) -> Point { - if self.rulers == RulerMode::Global { - return self.ruler_origin_or_zero(); - } - let Some(ab) = self.artboards.get(index).or_else(|| self.artboards.first()) else { return self.ruler_origin_or_zero() }; - let corner = Point::new(ab.rect.x0, ab.rect.y0); - let offset = self.artboard_ruler_origins.get(&ab.id).copied().unwrap_or(Vec2::ZERO); - let origin = corner + offset; - if origin.is_finite() && origin.x.abs() <= MAX_COORD && origin.y.abs() <= MAX_COORD { - origin - } else if corner.is_finite() && corner.x.abs() <= MAX_COORD && corner.y.abs() <= MAX_COORD { - corner - } else { - Point::ZERO - } - } - - /// A new RGB document with one artboard of `size` and one layer ("Layer 1"). - pub fn new(width: f64, height: f64) -> Self { - Self::new_with_mode(width, height, ColorMode::Rgb) - } - - /// [`Document::new`] in colour `mode`, with that mode's default swatches. - pub fn new_with_mode(width: f64, height: f64, mode: ColorMode) -> Self { - let (swatches, swatch_groups) = vectorcraft_color::default_swatches(mode.model()); - let mut d = Self { - version: FORMAT_VERSION, - title: "Untitled-1".into(), - template: false, - units: Unit::Points, - ruler_origin: Point::ZERO, - rulers: RulerMode::Artboard, - artboard_ruler_origins: BTreeMap::new(), - color_mode: mode, - artboards: vec![Artboard { - id: 1, - name: "Artboard 1".into(), - rect: Rect::new(0.0, 0.0, width, height), - show_center_mark: false, - show_cross_hairs: false, - }], - layers: vec![], - swatches: swatches.into(), - swatch_groups: swatch_groups.into(), - graphic_styles: default_graphic_styles().into(), - char_styles: Default::default(), - para_styles: Default::default(), - text_threads: vec![], - symbols: vec![], - graph_designs: vec![], - guides: vec![], - views: vec![], - saved_selections: Default::default(), - variables: Default::default(), - grid: GridPrefs::default(), - raster_effects_ppi: 72.0, - images: BTreeMap::new(), - patterns: vec![], - pattern_edit: None, - mask_edit: None, - next_id: 1, - unknown: Default::default(), - page_isolate: false, - page_knockout: false, - spot_use_lab: true, - setup: DocSetup::default(), - paste_remembers_layers: false, - metadata: DocMetadata::default(), - raster_effects: RasterEffectsSettings::default(), - last_view: None, - transparency_grid: false, - layers_open: None, - color_profiles: ColorProfiles::default(), - export_settings: Default::default(), - extra: Default::default(), - slices: vec![], - slices_clip_to_artboard: true, - print_setup: None, - assets: vec![], - svg_scripts: vec![], - puppet: None, - dimensions: false, - index: Default::default(), - }; - let id = d.alloc_id(); - d.layers.push(Arc::new(Node::layer(id, "Layer 1", LayerColor::Preset(0)))); - d - } - - /// Allocate a fresh node id. - pub fn alloc_id(&mut self) -> NodeId { - let id = NodeId(self.next_id); - // Never reached from a counter [`Self::fix_next_id`] has seen (it stays under - // [`MAX_NEXT_ID`]); saturating so that no counter can overflow. - self.next_id = self.next_id.saturating_add(1); - id - } - pub fn peek_next_id(&self) -> u64 { - self.next_id - } - /// Ensure `next_id` is above every id in the tree (after deserializing foreign data). - 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 - // the largest would run out and hand out ids the document already uses. - let mut max = 0; - let mut see = |id: u64| { - if id < MAX_NEXT_ID { - max = max.max(id); - } - }; - for l in &self.layers { - l.walk(&mut |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)); - } - - /// Find a node anywhere in the tree. - pub fn node(&self, id: NodeId) -> Option<&Node> { - self.index_path(id).and_then(|p| self.node_at(&p)) - } - - /// [`Document::node`] without building the lookup cache when there is none: for a look at a - /// document kept in the undo history ([`Document::drop_lookup_cache`]). - pub fn node_uncached(&self, id: NodeId) -> Option<&Node> { - match self.index.is_built() { - true => self.node(id), - false => self.walk_index_path(id).and_then(|p| self.node_at(&p)), - } - } - - /// Let go of the lookup cache ([`id_index`]), as a document kept in the undo history does: a - /// table per step would add up. Lookups still work; the first one builds the cache again. - pub fn drop_lookup_cache(&self) { - self.index.clear(); - } - - /// Whether the lookup cache ([`id_index`]) is built (see [`Document::drop_lookup_cache`]). - pub fn has_lookup_cache(&self) -> bool { - self.index.is_built() - } - - /// Index path from the top-level layer list to `id` (e.g. `[0, 3, 1]`): the first place in - /// tree order where `id` appears. - pub fn index_path(&self, id: NodeId) -> Option> { - // The cached path, while the node there still has the id ([`id_index`]). - let cached = self.index.get(); - match cached.as_ref().and_then(|m| m.get(&id)) { - Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == id) => return Some(p), - Some(None) => return self.walk_index_path(id), - _ => {} - } - // A stale path (the tree changed), an id the cache doesn't have (deleted or added since), - // or no cache yet: walk, and rebuild now and then. - let found = self.walk_index_path(id); - let stale = cached.as_ref().is_some_and(|m| m.contains_key(&id)); - if cached.is_none() || ((stale || found.is_some()) && self.index.missed()) { - self.index.rebuild(&self.layers); - } - found - } - - /// [`Document::index_path`] by walking the tree. - fn walk_index_path(&self, id: NodeId) -> Option> { - fn find(nodes: &[Arc], id: NodeId, path: &mut Vec) -> bool { - for (i, n) in nodes.iter().enumerate() { - path.push(i); - if n.id == id { - return true; - } - if let Some(ch) = n.children() - && find(ch, id, path) - { - return true; - } - path.pop(); - } - false - } - let mut p = vec![]; - find(&self.layers, id, &mut p).then_some(p) - } - - /// [`Document::index_path`] of every id in `ids` that is in the tree, in one walk of it: an - /// edit of many objects looks them all up for the cost of one search instead of one each. Like - /// `index_path`, an id that appears twice maps to its first place in tree order. - pub fn index_paths(&self, ids: impl IntoIterator) -> std::collections::HashMap> { - use std::collections::{HashMap, HashSet}; - fn walk(nodes: &[Arc], want: &HashSet, path: &mut Vec, out: &mut HashMap>) -> bool { - for (i, n) in nodes.iter().enumerate() { - path.push(i); - if want.contains(&n.id) && !out.contains_key(&n.id) { - out.insert(n.id, path.clone()); - if out.len() == want.len() { - return true; - } - } - if let Some(ch) = n.children() - && walk(ch, want, path, out) - { - return true; - } - path.pop(); - } - false - } - let mut want: HashSet = ids.into_iter().collect(); - let mut out = HashMap::with_capacity(want.len()); - // Cached paths that still check out ([`id_index`]); the rest take one walk. For a good - // share of the document, one walk is quicker than checking each cached path. - if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { - want.retain(|id| match cache.get(id) { - Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { - out.insert(*id, p); - false - } - _ => true, - }); - } - if !want.is_empty() { - let mut rest = HashMap::with_capacity(want.len()); - walk(&self.layers, &want, &mut Vec::new(), &mut rest); - out.extend(rest); - } - out - } - - /// The node at index path `path` (as [`Document::index_path`] gives it). - pub fn node_at(&self, path: &[usize]) -> Option<&Node> { - let (first, rest) = path.split_first()?; - let mut cur: &Node = self.layers.get(*first)?; - for &i in rest { - cur = cur.children()?.get(i)?; - } - Some(cur) - } - - /// Mutable access to the node at index path `path`; clones the Arc path (copy-on-write), as - /// [`Document::node_mut`] does. - pub fn node_mut_at(&mut self, path: &[usize]) -> Option<&mut Node> { - let (first, rest) = path.split_first()?; - let mut cur: &mut Arc = self.layers.get_mut(*first)?; - for &i in rest { - cur = Arc::make_mut(cur).children_mut()?.get_mut(i)?; - } - Some(Arc::make_mut(cur)) - } - - /// [`Document::ancestry`] of the node at index path `path`. - pub fn ancestry_at(&self, path: &[usize]) -> Option> { - let mut out = Vec::with_capacity(path.len()); - let mut nodes = &self.layers; - for &i in path { - let n = nodes.get(i)?; - out.push(n.id); - if let Some(ch) = n.children() { - nodes = ch; - } - } - Some(out) - } - - /// Ids from the top-level layer down to `id` inclusive. - pub fn ancestry(&self, id: NodeId) -> Option> { - let path = self.index_path(id)?; - let mut out = Vec::with_capacity(path.len()); - let mut nodes = &self.layers; - for &i in &path { - let n = &nodes[i]; - out.push(n.id); - if let Some(ch) = n.children() { - nodes = ch; - } - } - Some(out) - } - - pub fn parent_of(&self, id: NodeId) -> Option { - let a = self.ancestry(id)?; - (a.len() >= 2).then(|| a[a.len() - 2]) - } - - /// The top-level layer that contains `id`. - pub fn layer_of(&self, id: NodeId) -> Option { - self.ancestry(id).and_then(|a| a.first().copied()) - } - - /// Mutable access to a node; clones the Arc path (copy-on-write). - pub fn node_mut(&mut self, id: NodeId) -> Option<&mut Node> { - let path = self.index_path(id)?; - let mut cur: &mut Arc = &mut self.layers[path[0]]; - for &i in &path[1..] { - cur = &mut Arc::make_mut(cur).children_mut()?[i]; - } - Some(Arc::make_mut(cur)) - } - - /// Children list of a container (or the top-level layer list for `None`). - pub fn children_mut(&mut self, parent: Option) -> Result<&mut Vec>, DocError> { - match parent { - None => Ok(&mut self.layers), - Some(p) => self.node_mut(p).ok_or(DocError::NoNode(p))?.children_mut().ok_or(DocError::NotContainer(p)), - } - } - pub fn children(&self, parent: Option) -> Option<&Vec>> { - match parent { - None => Some(&self.layers), - Some(p) => self.node(p)?.children(), - } - } - - /// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top). - pub fn insert(&mut self, parent: Option, index: usize, node: Node) -> Result { - let id = node.id; - let ch = self.children_mut(parent)?; - let i = index.min(ch.len()); - ch.insert(i, Arc::new(node)); - Ok(id) - } - - /// Remove a node and return it. - pub fn remove(&mut self, id: NodeId) -> Result, DocError> { - let parent = self.parent_of(id); - let path = self.index_path(id).ok_or(DocError::NoNode(id))?; - let idx = *path.last().ok_or(DocError::NoNode(id))?; - let ch = self.children_mut(parent)?; - if idx >= ch.len() { - return Err(DocError::NoNode(id)); - } - Ok(ch.remove(idx)) - } - - /// Move a node to `parent` at `index` (index measured after removal). - pub fn move_node(&mut self, id: NodeId, parent: Option, index: usize) -> Result<(), DocError> { - if let Some(p) = parent - && self.ancestry(p).is_some_and(|a| a.contains(&id)) - { - return Err(DocError::Invalid("cannot move an object into itself".into())); - } - let n = self.remove(id)?; - let ch = self.children_mut(parent)?; - let i = index.min(ch.len()); - ch.insert(i, n); - Ok(()) - } - - /// Position of `id` within its parent: (parent, index, sibling count). - pub fn position(&self, id: NodeId) -> Option<(Option, usize, usize)> { - let parent = self.parent_of(id); - let idx = *self.index_path(id)?.last()?; - let n = self.children(parent)?.len(); - Some((parent, idx, n)) - } - - /// Remove the nodes `ids` names and return them in the order of `ids`, in one pass over the - /// children of each parent. Each id is listed once and none lies inside another listed node, as - /// in a list of top-level objects. For an id that is not in the tree, is listed twice or lies - /// inside another listed node, it fails with `NoNode` and leaves the document as it was. - pub fn remove_many(&mut self, ids: &[NodeId]) -> Result>, DocError> { - let places = self.places(ids)?; - let removed = self.take(places, ids.len())?; - self.index.clear(); - Ok(removed) - } - - /// Remove the nodes `ids` names, as [`Document::remove_many`] does, and put the node that `make` - /// builds from them (in the order of `ids`) in the parent of the last of them, at that node's - /// index less the number of listed nodes below it there. Returns the new node's id. - pub fn wrap(&mut self, ids: &[NodeId], make: impl FnOnce(Vec>) -> Node) -> Result { - let places = self.places(ids)?; - let last = ids.len().checked_sub(1); - let found = places.iter().find_map(|(up, kids)| kids.iter().find(|(_, k)| Some(*k) == last).map(|(i, _)| (up.clone(), *i))); - let Some((up, i)) = found else { return Err(DocError::Invalid("nothing to wrap".into())) }; - // The parent and each node it is in move down by the listed nodes before them. - let below = |parent: &[usize], index: usize| places.get(parent).map_or(0, |kids| kids.partition_point(|(j, _)| *j < index)); - let to: Vec = up.iter().enumerate().map(|(l, &j)| j.saturating_sub(below(&up[..l], j))).collect(); - let at = i.saturating_sub(below(&up, i)); - let node = make(self.take(places, ids.len())?); - let id = node.id; - let children = self.children_at(&to).ok_or_else(|| DocError::Invalid("the container of the listed objects is gone".into()))?; - let at = at.min(children.len()); - children.insert(at, Arc::new(node)); - self.index.clear(); - Ok(id) - } - - /// Put each list of nodes in `items` directly above its anchor (`replace`: in its place), in - /// list order, in one pass over the children of each parent. Each anchor is listed once and none - /// lies inside another. For an anchor that is not in the tree, is listed twice or lies inside - /// another listed anchor, it fails with `NoNode` and leaves the document as it was. - pub fn insert_beside(&mut self, items: Vec<(NodeId, Vec)>, replace: bool) -> Result<(), DocError> { - let anchors: Vec = items.iter().map(|(id, _)| *id).collect(); - let places = self.places(&anchors)?; - let mut lists: Vec> = items.into_iter().map(|(_, nodes)| nodes).collect(); - self.edit_children(places, |k, anchor, children| { - if !replace { - children.push(anchor); - } - let nodes = lists.get_mut(k).map(std::mem::take).unwrap_or_default(); - children.extend(nodes.into_iter().map(Arc::new)); - })?; - self.index.clear(); - Ok(()) - } - - /// Where each of `ids` is ([`Places`]). Fails with `NoNode` for an id that is not in the tree, - /// is listed twice or lies inside another listed node. - fn places(&self, ids: &[NodeId]) -> Result { - let paths = self.index_paths(ids.iter().copied()); - let mut places = Places::new(); - for (k, id) in ids.iter().enumerate() { - let (&i, up) = paths.get(id).and_then(|p| p.split_last()).ok_or(DocError::NoNode(*id))?; - match places.get_mut(up) { - Some(kids) => kids.push((i, k)), - None => { - places.insert(up.to_vec(), vec![(i, k)]); - } - } - } - for kids in places.values_mut() { - kids.sort_unstable(); - } - // An id listed twice has one path, so its parent lists the same child twice. A listed node - // lies inside another when its parent's path, or a part of it from the top, is the path of a - // listed node. - let twice = places.values().flat_map(|kids| kids.windows(2)).find(|w| w[0].0 == w[1].0).map(|w| w[1].1); - let listed = |path: &[usize]| { - path.split_last().is_some_and(|(i, up)| places.get(up).is_some_and(|kids| kids.binary_search_by_key(i, |(j, _)| *j).is_ok())) - }; - let nested = places.iter().find(|(up, _)| (1..=up.len()).any(|l| listed(&up[..l]))); - let inner = nested.and_then(|(_, kids)| kids.first()).map(|(_, k)| *k); - if let Some(id) = twice.or(inner).and_then(|k| ids.get(k)) { - return Err(DocError::NoNode(*id)); - } - Ok(places) - } - - /// Take the nodes `places` lists out of their parents and return them in the order of the list, - /// which is `len` long. - fn take(&mut self, places: Places, len: usize) -> Result>, DocError> { - let mut taken = vec![None; len]; - self.edit_children(places, |k, node, _| { - if let Some(t) = taken.get_mut(k) { - *t = Some(node); - } - })?; - Ok(taken.into_iter().flatten().collect()) - } - - /// Rebuild the children of each parent in `places` once, the parents later in tree order - /// first. `each` gets each listed child, its place in the list and the parent's new children, - /// onto which it pushes what takes the child's place. - fn edit_children(&mut self, places: Places, mut each: impl FnMut(usize, Arc, &mut Vec>)) -> Result<(), DocError> { - for (up, kids) in places.into_iter().rev() { - let children = self.children_at(&up).ok_or_else(|| DocError::Invalid("a container of the listed objects is gone".into()))?; - let old = std::mem::take(children); - children.reserve(old.len()); - let mut kids = kids.into_iter().peekable(); - for (i, node) in old.into_iter().enumerate() { - match kids.next_if(|(j, _)| *j == i) { - Some((_, k)) => each(k, node, children), - None => children.push(node), - } - } - } - Ok(()) - } - - /// The children of the node at index path `path`, or the top-level layers for an empty path. - fn children_at(&mut self, path: &[usize]) -> Option<&mut Vec>> { - match path { - [] => Some(&mut self.layers), - _ => self.node_mut_at(path)?.children_mut(), - } - } - - /// Default target layer: the topmost visible, unlocked layer. - pub fn default_layer(&self) -> Option { - self.layers.iter().rev().find(|l| l.visible && !l.locked).or(self.layers.last()).map(|l| l.id) - } - - /// Add a new top-level layer above all others. - pub fn add_layer(&mut self, name: Option<&str>) -> NodeId { - let id = self.alloc_id(); - let n = self.layers.len(); - let name = name.map(str::to_string).unwrap_or_else(|| self.next_layer_name()); - self.layers.push(Arc::new(Node::layer(id, &name, LayerColor::Preset((n % LAYER_COLORS.len()) as u8)))); - id - } - /// The default name of a new layer or sublayer, "Layer N". Layers and sublayers share the - /// numbering: it starts after the number of layers there are and skips any layer's name. - pub fn next_layer_name(&self) -> String { - let (mut count, mut taken) = (0, std::collections::HashSet::new()); - self.walk(|n| { - if n.is_layer() { - count += 1; - taken.extend(n.name.as_deref()); - } - }); - (count + 1..).map(|i| format!("Layer {i}")).find(|name| !taken.contains(name.as_str())).unwrap_or_default() - } - - /// Visit every node depth first in paint order (bottom to top). - pub fn walk<'a>(&'a self, mut f: impl FnMut(&'a Node)) { - for l in &self.layers { - l.walk(&mut f); - } - } - pub fn node_count(&self) -> usize { - self.layers.iter().map(|l| l.count()).sum() - } - /// Is the node (and every ancestor) visible and unlocked? - pub fn is_editable(&self, id: NodeId) -> bool { - self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| n.visible && !n.locked))) - } - pub fn is_visible(&self, id: NodeId) -> bool { - self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| n.visible))) - } - /// The innermost layer or sublayer containing `id` (`id` itself when it is a layer). - pub fn layer_containing(&self, id: NodeId) -> Option { - let a = self.ancestry(id)?; - a.iter().rev().copied().find(|i| self.node(*i).is_some_and(Node::is_layer)) - } - /// Every art object the Selection tool can reach (Select All): the visible, unlocked objects - /// of the visible, unlocked, non-template layers, looking through sublayers (bottom first). - pub fn selectable_art(&self) -> Vec { - self.layers.iter().filter(|l| l.visible && !l.locked && !l.is_template()).flat_map(|l| l.layer_art(true)).collect() - } - /// Colour of the innermost layer or sublayer containing `id` (selection highlight colour). - pub fn layer_color(&self, id: NodeId) -> [u8; 3] { - let l = self.layer_containing(id).and_then(|l| self.node(l)); - match l.map(|n| &n.kind) { - Some(NodeKind::Layer { color, .. }) => color.rgb(), - _ => LAYER_COLORS[0].1, - } - } - /// Union of the geometric bounds of `ids` (their visual bounds when `visual`), with symbol - /// instances measured by their art ([`Node::geometric_bounds_with`]). - pub fn bounds_of(&self, ids: &[NodeId], visual: bool) -> Option { - let symbols = self.symbol_boxes(); - ids.iter().filter_map(|id| self.node(*id)).fold(None, |acc, n| { - vectorcraft_geom::union_opt(acc, if visual { n.visual_bounds_with(&symbols) } else { n.geometric_bounds_with(&symbols) }) - }) - } - /// Visual bounds of all art, with symbol instances measured by their art. - pub fn art_bounds(&self) -> Option { - let symbols = self.symbol_boxes(); - self.layers.iter().fold(None, |acc, l| vectorcraft_geom::union_opt(acc, l.visual_bounds_with(&symbols))) - } - /// Artboard index containing point `p` (topmost = last), its edges included - /// ([`Document::artboard_holding`]). - pub fn artboard_at(&self, p: Point) -> Option { - self.artboard_holding(p, true) - } - /// Index of the artboard that holds point `p`: the first (the last when `topmost`) that holds it - /// inside or on its left or top edge, else the first (the last) that holds it by - /// [`artboard_holds`]: on its right or bottom edge, or within a millionth of a point outside an - /// edge. On an edge two artboards share, the artboard to the right of it or below it holds the - /// point, except at the end of the edge that lies on that artboard's bottom or right edge, such - /// as the point where both artboards' bottom edges meet; there the first (the last) holds it. - pub fn artboard_holding(&self, p: Point, topmost: bool) -> Option { - let pick = |on: &dyn Fn(Rect) -> bool| { - let on = |i: &usize| self.artboards.get(*i).is_some_and(|a| on(a.rect)); - let mut all = 0..self.artboards.len(); - if topmost { all.rfind(on) } else { all.find(on) } - }; - pick(&|r| r.contains(p)).or_else(|| pick(&|r| artboard_holds(r, p))) - } - /// The art that moves with an artboard at `rect`: top-level objects (children of layers and - /// sublayers) lying entirely inside it, with symbol instances measured by their art. Locked and - /// hidden objects and layers stay put unless `locked_and_hidden` (Selection & Anchor Display › - /// Move Locked and Hidden Artwork with Artboard). - pub fn art_on_artboard(&self, rect: Rect, locked_and_hidden: bool) -> Vec { - // Art drawn flush with the artboard can end up a rounding error outside it (a background - // 3e-14 pt past the top edge, #1295): a millionth of a point is far below anything visible. - let rect = rect.inflate(1e-6, 1e-6); - fn collect(n: &Node, s: &SymbolBoxes, rect: Rect, all: bool, out: &mut Vec) { - for c in n.children().into_iter().flatten().filter(|c| c.rides_with_artboard(all)) { - if c.is_layer() { - collect(c, s, rect, all, out); - } else if let Some(b) = c.geometric_bounds_with(s) - // Inside it, edges included: art flush with the right or bottom edge is on it too - // (`Rect::contains` leaves those out, #890). - && b.x0 >= rect.x0 - && b.y0 >= rect.y0 - && b.x1 <= rect.x1 - && b.y1 <= rect.y1 - { - out.push(c.id); - } - } - } - let symbols = self.symbol_boxes(); - let mut art = vec![]; - for l in self.layers.iter().filter(|l| l.rides_with_artboard(locked_and_hidden)) { - collect(l, &symbols, rect, locked_and_hidden, &mut art); - } - art - } - /// Where ruler guide `g` runs along its line (the y range of a vertical guide): across its - /// artboard for an artboard guide, None (the whole canvas) for a canvas guide or one whose - /// artboard is gone. - pub fn guide_span(&self, g: &Guide) -> Option<(f64, f64)> { - let r = self.artboards.iter().find(|a| Some(a.id) == g.artboard)?.rect; - Some(if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) }) - } - /// The layer (or sublayer) ruler guide `g` is on, if it is on one this document has. - fn guide_layer(&self, g: &Guide) -> Option { - g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer)) - } - /// Is ruler guide `g` shown: on no layer, or on a layer that (with the layers around it) is - /// visible? A guide whose layer is gone shows as one on no layer. - pub fn guide_shown(&self, g: &Guide) -> bool { - self.guide_layer(g).is_none_or(|l| self.is_visible(l)) - } - /// Can ruler guide `g` be picked, moved and deleted: shown, and its layer unlocked? - pub fn guide_editable(&self, g: &Guide) -> bool { - self.guide_layer(g).is_none_or(|l| self.is_editable(l)) - } - /// Put the ruler guides on no layer this document has (from files saved before guides had - /// layers, or of layers merged into `layer`) on layer `layer`. Returns how many. - pub fn rehome_guides(&mut self, layer: NodeId) -> usize { - let lost: Vec = self.guides.iter().map(|g| self.guide_layer(g).is_none()).collect(); - let mut n = 0; - for (g, lost) in self.guides.iter_mut().zip(lost) { - if lost { - g.layer = Some(layer); - n += 1; - } - } - n - } - /// Put the ruler guides on no layer (from files saved before guides had layers), or on one that - /// is gone, on the top visible, unlocked layer ([`Self::default_layer`]). Returns how many. - pub fn adopt_guides(&mut self) -> usize { - self.default_layer().map_or(0, |home| self.rehome_guides(home)) - } - /// Delete the ruler guides whose layer was deleted (they go with it), keeping `sel`'s guides in - /// step. Guides on no layer stay. Returns how many went. - pub fn drop_guides_of_deleted_layers(&mut self, sel: &mut Selection) -> usize { - let gone: Vec = self.guides.iter().map(|g| g.layer.is_some() && self.guide_layer(g).is_none()).collect(); - self.retain_guides(sel, |i, _| !gone.get(i).copied().unwrap_or(false)) - } - /// Copy the ruler guides of layer `from` and of its sublayers onto their copies in `copy` (made - /// from `from` by [`Self::reid`]: the same tree with fresh ids), as duplicating a layer copies - /// the objects on it. Returns how many. - pub fn copy_layer_guides(&mut self, from: &Node, copy: &Node) -> usize { - let layers = |n: &Node| { - let mut out = vec![]; - n.walk(&mut |c| { - if c.is_layer() { - out.push(c.id); - } - }); - out - }; - let pairs: Vec<(NodeId, NodeId)> = layers(from).into_iter().zip(layers(copy)).collect(); - let copies: Vec = self - .guides - .iter() - .filter_map(|g| { - let to = pairs.iter().find(|(a, _)| Some(*a) == g.layer)?.1; - Some(Guide { layer: Some(to), ..g.clone() }) - }) - .collect(); - let n = copies.len(); - self.guides.extend(copies); - n - } - /// The ruler guides on layer `layer` (not its sublayers'), by index. - pub fn guides_on(&self, layer: NodeId) -> impl Iterator + '_ { - self.guides.iter().enumerate().filter(move |(_, g)| g.layer == Some(layer)) - } - /// Does ruler guide `g` run past `p` (up to `tol` beyond its ends)? - pub fn guide_passes(&self, g: &Guide, p: Point, tol: f64) -> bool { - let along = if g.vertical { p.y } else { p.x }; - self.guide_span(g).is_none_or(|(a, b)| along >= a - tol && along <= b + tol) - } - /// Keep the ruler guides `keep` accepts (by index), the selected ones left keeping their - /// place among the rest (the selected art stays selected). Returns how many went. - pub fn retain_guides(&mut self, sel: &mut Selection, keep: impl Fn(usize, &Guide) -> bool) -> usize { - let kept: Vec = self.guides.iter().enumerate().map(|(i, g)| keep(i, g)).collect(); - // Where each kept guide ends up. - let (mut to, mut n) = (Vec::with_capacity(kept.len()), 0); - for k in &kept { - to.push(k.then_some(n)); - n += usize::from(*k); - } - sel.guides = sel.guides.iter().filter_map(|i| to.get(*i).copied().flatten()).collect(); - sel.key_guide = sel.key_guide.and_then(|i| to.get(i).copied().flatten()); - let before = self.guides.len(); - let mut flags = kept.into_iter(); - self.guides.retain(|_| flags.next().unwrap_or(true)); - before - self.guides.len() - } - /// Move the guides of artboard `id` by `d` (along with their artboard). - pub fn move_artboard_guides(&mut self, id: u32, d: Vec2) { - for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) { - *g = g.moved(d); - } - } - /// Map the guides of artboard `id` through `xf`, an axis-aligned scale and move (Scale Artwork - /// with Artboard). - pub fn map_artboard_guides(&mut self, id: u32, xf: Affine) { - for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) { - g.pos = if g.vertical { (xf * Point::new(g.pos, 0.0)).x } else { (xf * Point::new(0.0, g.pos)).y }; - } - } - /// Copy the guides of artboard `from` onto artboard `to`, `d` away (with a copy of their - /// artboard). - pub fn copy_artboard_guides(&mut self, from: u32, to: u32, d: Vec2) { - let copies: Vec = - self.guides.iter().filter(|g| g.artboard == Some(from)).map(|g| Guide { artboard: Some(to), ..g.moved(d) }).collect(); - self.guides.extend(copies); - } - pub fn next_artboard_id(&self) -> u32 { - free_id(self.artboards.iter().map(|a| a.id)) - } - pub fn pattern(&self, name: &str) -> Option<&PatternDef> { - self.patterns.iter().find(|p| p.name == name) - } - pub fn pattern_mut(&mut self, name: &str) -> Option<&mut PatternDef> { - self.patterns.iter_mut().find(|p| p.name == name) - } - /// Deep-clone `node` with fresh ids for it and all descendants. - pub fn reid(&mut self, node: &Node) -> Node { - let mut n = node.clone(); - n.id = self.alloc_id(); - // A copied annotation must never bind its source ids to unrelated art in a different - // document. Keep the measured geometry; new measurements can be linked after pasting. - if let Some(e) = n.extras_if_any() - && let Some(dimension) = &mut e.dimension - { - dimension.source = None; - } - let mut renamed = std::collections::HashMap::new(); - if let Some(ch) = n.children_mut() { - let old: Vec> = std::mem::take(ch); - *ch = old.iter().map(|c| Arc::new(self.reid(c))).collect(); - renamed.extend(old.iter().zip(ch.iter()).map(|(o, c)| (o.id, c.id))); - } - // An Objects on Path group names its path and its objects by id: the copy names the copies. - if let Some(e) = n.extras_if_any() - && let Some(on_path) = &mut e.objects_on_path - { - on_path.rename(&renamed); - } - n - } -} - -impl Document { - /// Saved selections as a file gives them, made safe to list and recall: at most - /// [`SavedSelection::MAX`], each with a clean, unique name and naming objects this document - /// has, each once. (An id it doesn't have would select whatever object takes that id later.) - pub fn tidy_saved_selections(&mut self) { - if self.saved_selections.is_empty() { - return; - } - let mut ids = std::collections::HashSet::new(); - self.walk(|n| { - ids.insert(n.id); - }); - let mut kept: Vec = vec![]; - for s in std::mem::take(&mut self.saved_selections) { - if kept.len() >= SavedSelection::MAX { - break; - } - let Some(name) = SavedSelection::clean_name(&s.name) else { continue }; - if kept.iter().any(|k| k.name == name) { - continue; - } - let mut seen = std::collections::HashSet::new(); - let objects = s.objects.into_iter().filter(|id| ids.contains(id) && seen.insert(*id)).collect(); - kept.push(SavedSelection { name, objects }); - } - self.saved_selections = kept.into(); - } - - /// Leave opacity-mask editing: drop the temporary editing layer, a working copy of art the - /// mask already holds (the engine syncs it after every edit). - pub fn drop_edit_modes(&mut self) { - if let Some(me) = self.mask_edit.take() { - self.layers.retain(|l| l.id != me.layer); - } - } - - /// The document as saved and exported: without the opacity-mask editing layer. Borrowed when - /// no mask is being edited. (Pattern editing is saved: its tile layer holds unapplied edits.) - pub fn without_edit_modes(&self) -> std::borrow::Cow<'_, Document> { - if self.mask_edit.is_none() { - return std::borrow::Cow::Borrowed(self); - } - let mut d = self.clone(); - d.drop_edit_modes(); - std::borrow::Cow::Owned(d) - } -} - -/// Graphic styles. -impl Document { - /// Index of the graphic style named `name`. - pub fn graphic_style_index(&self, name: &str) -> Option { - self.graphic_styles.iter().position(|g| g.name == name) - } - /// The graphic style named `name`. - pub fn graphic_style(&self, name: &str) -> Option<&GraphicStyle> { - self.graphic_styles.iter().find(|g| g.name == name) - } - /// The graphic style with id `id` (0 never matches). - pub fn graphic_style_by_id(&self, id: u32) -> Option<&GraphicStyle> { - self.graphic_styles.iter().find(|g| g.id != 0 && g.id == id) - } - /// An id no graphic style has. - pub fn next_graphic_style_id(&self) -> u32 { - free_id(self.graphic_styles.iter().map(|g| g.id)) - } - /// The id of graphic style `index`, assigning one if it has none yet. - pub fn graphic_style_id(&mut self, index: usize) -> u32 { - if self.graphic_styles[index].id == 0 { - self.graphic_styles[index].id = self.next_graphic_style_id(); - } - self.graphic_styles[index].id - } - /// The default name of a new graphic style: the first free "Graphic Style N", N counting on - /// from the number of styles. - pub fn new_graphic_style_name(&self) -> String { - (self.graphic_styles.len() + 1..).map(|i| format!("Graphic Style {i}")).find(|n| self.graphic_style(n).is_none()).unwrap_or_default() - } - /// `base`, or the first free "`base` N" (N from 2) when a symbol already has that name. - pub fn unique_symbol_name(&self, base: &str) -> String { - let taken = |n: &str| self.symbols.iter().any(|s| s.name == n); - if !taken(base) { - return base.to_string(); - } - (2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| base.to_string()) - } - - /// Symbol Options › Registration for `name` (default: centre). - pub fn symbol_registration(&self, name: &str) -> SymbolRegistration { - self.unknown - .get(SYMBOL_REGISTRATION) - .and_then(|m| m.get(name)) - .and_then(|v| v.as_u64()) - .and_then(SymbolRegistration::from_u64) - .unwrap_or_default() - } - - /// Set or clear (when centre) the registration point stored for `name`. - pub fn set_symbol_registration(&mut self, name: &str, reg: SymbolRegistration) { - let m = self.unknown.entry(SYMBOL_REGISTRATION.to_string()).or_insert_with(|| serde_json::json!({})); - let Some(o) = m.as_object_mut() else { return }; - if reg.is_center() { - o.remove(name); - if o.is_empty() { - self.unknown.remove(SYMBOL_REGISTRATION); - } - } else { - o.insert(name.into(), serde_json::json!(reg.0)); - } - } - - /// Move the stored registration when a symbol is renamed. - pub fn rename_symbol_registration(&mut self, from: &str, to: &str) { - if from == to { - return; - } - let reg = self.symbol_registration(from); - self.set_symbol_registration(from, SymbolRegistration::CENTER); - self.set_symbol_registration(to, reg); - } - - /// Symbol Options › Export Type for `name` (default: Movie Clip). - pub fn symbol_export_type(&self, name: &str) -> SymbolExportType { - self.unknown.get(SYMBOL_EXPORT_TYPE).and_then(|m| m.get(name)).and_then(SymbolExportType::from_value).unwrap_or_default() - } - - /// Set or clear (when Movie Clip, the default) the export type stored for `name`. - pub fn set_symbol_export_type(&mut self, name: &str, kind: SymbolExportType) { - if kind.is_default() { - self.clear_symbol_export_type(name); - return; - } - let m = self.unknown.entry(SYMBOL_EXPORT_TYPE.to_string()).or_insert_with(|| serde_json::json!({})); - let Some(o) = m.as_object_mut() else { return }; - o.insert(name.into(), serde_json::json!(kind.id())); - } - - /// Drop any stored export type for `name` (Movie Clip default). - pub fn clear_symbol_export_type(&mut self, name: &str) { - let Some(m) = self.unknown.get_mut(SYMBOL_EXPORT_TYPE) else { return }; - let Some(o) = m.as_object_mut() else { return }; - o.remove(name); - if o.is_empty() { - self.unknown.remove(SYMBOL_EXPORT_TYPE); - } - } - - /// Move the stored export type when a symbol is renamed. - pub fn rename_symbol_export_type(&mut self, from: &str, to: &str) { - if from == to { - return; - } - let kind = self.symbol_export_type(from); - self.clear_symbol_export_type(from); - self.set_symbol_export_type(to, kind); - } - - /// Symbol Options › 9-slice guides for `name`: `None` when 9-slice scaling is off (default). - pub fn symbol_nine_slice(&self, name: &str) -> Option { - self.unknown.get(SYMBOL_NINE_SLICE).and_then(|m| m.get(name)).and_then(SymbolNineSlice::from_value) - } - - /// Turn 9-slice scaling on with `guides`, or off with `None`, for `name`. - pub fn set_symbol_nine_slice(&mut self, name: &str, guides: Option) { - let Some(g) = guides else { - let Some(o) = self.unknown.get_mut(SYMBOL_NINE_SLICE).and_then(|m| m.as_object_mut()) else { return }; - o.remove(name); - if o.is_empty() { - self.unknown.remove(SYMBOL_NINE_SLICE); - } - return; - }; - let m = self.unknown.entry(SYMBOL_NINE_SLICE.to_string()).or_insert_with(|| serde_json::json!({})); - if let Some(o) = m.as_object_mut() { - o.insert(name.into(), g.to_value()); - } - } - - /// Move the stored 9-slice guides when a symbol is renamed. - pub fn rename_symbol_nine_slice(&mut self, from: &str, to: &str) { - if from == to { - return; - } - let g = self.symbol_nine_slice(from); - self.set_symbol_nine_slice(from, None); - self.set_symbol_nine_slice(to, g); - } -} - -fn default_graphic_styles() -> Vec { - use vectorcraft_color::{Color, Paint}; - let solid = |hex| Paint::solid(Color::from_hex(hex).unwrap_or(Color::BLACK)); - [ - GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art()), - GraphicStyle::new("Black Outline", Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)), - GraphicStyle::new("Heavy Ink", Appearance::basic(solid("#1b1464"), Paint::solid(Color::BLACK), 4.0)), - GraphicStyle::new("Sunshine", Appearance::basic(solid("#fbb03b"), solid("#f15a24"), 2.0)), - ] - .into_iter() - .zip(1..) - .map(|(g, id)| GraphicStyle { id, ..g }) - .collect() -} - -/// Node, slice and asset ids are handed out below this: no document gets near it by counting, so -/// larger ids in a file are damage (or made by hand) and the counter never follows them (#1718). -const MAX_NEXT_ID: u64 = 1 << 62; - -/// An id (never 0) none of `used` has: one past the largest, or, when that is the largest there -/// is (a damaged file), the smallest one free. -fn free_id(used: impl Iterator) -> u32 { - let mut used: Vec = used.collect(); - if let Some(next) = used.iter().max().copied().unwrap_or(0).checked_add(1) { - return next; - } - used.sort_unstable(); - used.dedup(); - // Ids 1, 2, 3… as far as they are all taken: the first that isn't follows them. - let taken = used.iter().filter(|&&id| id != 0).zip(1u32..).take_while(|&(&id, n)| id == n).count(); - u32::try_from(taken).map_or(u32::MAX, |n| n.saturating_add(1)) -} - -impl Document { - /// Make the next id allocated at least `next`: ids handed out outside the layer tree (such - /// as an importer's opacity mask and pattern art), which [`Document::fix_next_id`] doesn't see. - pub fn reserve_ids(&mut self, next: u64) { - self.next_id = self.next_id.max(next.min(MAX_NEXT_ID)); - } -} - #[cfg(test)] -mod tests { - use super::*; - use vectorcraft_geom::shapes; - - /// Zooming in on an inch ruler divided the inch into tenths (#2827). Its steps below an inch - /// are binary fractions now, and the minor ticks between them stay binary too; every other - /// unit is still read in tenths. - #[test] - fn an_inch_ruler_steps_in_binary_fractions() { - let step = |u: Unit, zoom: f64| u.ruler_step(zoom); - // Every inch step at or below an inch is 1/2^k, never a tenth or a fifth. - for zoom in [1.0, 2.0, 5.0, 7.5, 10.0, 20.0, 40.0, 100.0, 400.0] { - let s = step(Unit::Inches, zoom); - if s <= 1.0 { - let k = s.recip(); - assert_eq!(k, k.round(), "{s} at zoom {zoom} is 1/k for a whole k"); - assert!((k.round() as u64).is_power_of_two(), "{s} at zoom {zoom} is 1/2^k"); - } - // A label step always leaves at least 50 px, which is what the ladder is picked for. - assert!(s * Unit::Inches.points() * zoom >= 50.0, "zoom {zoom}"); - } - // The steps the report named: tenths became quarters, eighths and sixteenths. - assert_eq!(step(Unit::Inches, 5.0), 0.25); - assert_eq!(step(Unit::Inches, 10.0), 0.125); - assert_eq!(step(Unit::Inches, 20.0), 0.0625); - // An inch and wider is unchanged. - assert_eq!(step(Unit::Inches, 1.0), 1.0); - // Labelling stops at a sixteenth, as the report says Illustrator's does, so zooming in - // further only adds ticks. A label therefore never needs more than the six characters of - // "0.0625", which the left ruler has room for when it spells one out a character per line. - for zoom in [20.0, 50.0, 100.0, 400.0, 1600.0] { - assert_eq!(step(Unit::Inches, zoom), 0.0625, "zoom {zoom}"); - } - // The unlabelled ticks go on down to a hundred and twenty-eighth: the 32nds, 64ths and - // 128ths the report expects to appear unlabelled when zoomed in close. - assert_eq!(Unit::Inches.ruler_minor(0.0625), 1.0 / 128.0); - // The minor ticks: an eighth of the step on an inch ruler, a tenth elsewhere. - assert_eq!(Unit::Inches.ruler_minor(0.25), 0.03125); - assert_eq!(Unit::Millimeters.ruler_minor(25.0), 2.5); - assert_eq!(Unit::Points.ruler_minor(100.0), 10.0); - // Other units keep the decimal ladder, so a tenth and a fifth still appear. - assert!([0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0].contains(&step(Unit::Millimeters, 5.0)), "{}", step(Unit::Millimeters, 5.0)); - } - - fn doc_with_rects() -> (Document, NodeId, NodeId) { - let mut d = Document::new(612.0, 792.0); - let layer = d.layers[0].id; - let a = d.alloc_id(); - d.insert(Some(layer), usize::MAX, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art())).unwrap(); - let b = d.alloc_id(); - d.insert(Some(layer), usize::MAX, Node::path(b, shapes::rectangle(Rect::new(20.0, 0.0, 30.0, 10.0)), Appearance::default_art())).unwrap(); - (d, a, b) - } - - #[test] - fn new_document_has_layer_and_artboard() { - let d = Document::new(612.0, 792.0); - assert_eq!(d.layers.len(), 1); - assert_eq!(d.layers[0].display_name(), "Layer 1"); - assert_eq!(d.artboards[0].rect, Rect::new(0.0, 0.0, 612.0, 792.0)); - } - - #[test] - fn art_on_artboard_takes_unlocked_objects_wholly_inside() { - let (mut d, a, b) = doc_with_rects(); - let wide = Rect::new(-1.0, -1.0, 40.0, 15.0); - assert_eq!(d.art_on_artboard(Rect::new(-1.0, -1.0, 15.0, 15.0), false), vec![a]); - assert_eq!(d.art_on_artboard(Rect::new(-1.0, -1.0, 25.0, 15.0), false), vec![a], "b only half inside"); - // Flush with the artboard's edges counts as inside: the right and bottom ones too (#890). - for board in [Rect::new(0.0, 0.0, 10.0, 10.0), Rect::new(-5.0, 0.0, 10.0, 15.0), Rect::new(0.0, -5.0, 15.0, 10.0)] { - assert_eq!(d.art_on_artboard(board, false), vec![a], "{board:?}"); - } - d.node_mut(a).unwrap().locked = true; - assert_eq!(d.art_on_artboard(wide, false), vec![b]); - // Move Locked and Hidden Artwork with Artboard (#394): hidden art stays too, unless on. - d.node_mut(b).unwrap().visible = false; - assert!(d.art_on_artboard(wide, false).is_empty()); - assert_eq!(d.art_on_artboard(wide, true), vec![a, b]); - Arc::make_mut(&mut d.layers[0]).locked = true; - assert!(d.art_on_artboard(wide, false).is_empty()); - assert_eq!(d.art_on_artboard(wide, true), vec![a, b], "a locked layer's art too"); - } - - #[test] - fn art_on_artboard_tolerates_roundoff_at_each_edge() { - let (d, a, _) = doc_with_rects(); - let roundoff = 1e-12; - for board in [ - Rect::new(roundoff, 0.0, 10.0, 10.0), - Rect::new(0.0, roundoff, 10.0, 10.0), - Rect::new(0.0, 0.0, 10.0 - roundoff, 10.0), - Rect::new(0.0, 0.0, 10.0, 10.0 - roundoff), - ] { - assert_eq!(d.art_on_artboard(board, false), vec![a], "roundoff at {board:?}"); - } - // A real overhang remains outside. - for board in - [Rect::new(0.001, 0.0, 10.0, 10.0), Rect::new(0.0, 0.001, 10.0, 10.0), Rect::new(0.0, 0.0, 9.999, 10.0), Rect::new(0.0, 0.0, 10.0, 9.999)] - { - assert!(d.art_on_artboard(board, false).is_empty(), "overhang at {board:?}"); - } - } - - #[test] - fn art_on_artboard_measures_a_symbol_instance_by_its_art() { - let mut d = Document::new(612.0, 792.0); - let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); - d.symbols.push(Symbol { name: "Box".into(), art: Arc::new(art) }); - let (layer, id) = (d.layers[0].id, d.alloc_id()); - d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Box".into(), xf: Affine::translate((2.0, 2.0)) })).unwrap(); - // The art, (2, 2) to (12, 12), lies inside; the 20 × 20 square, (-8, -8) to (12, 12), doesn't. - assert_eq!(d.art_on_artboard(Rect::new(0.0, 0.0, 15.0, 15.0), false), vec![id]); - } - - #[test] - fn artboard_at_counts_the_right_and_bottom_edges() { - // Artboard 0 is (0, 0) to (100, 100), artboard 1 is to its right and artboard 2 below it. - let mut d = Document::new(100.0, 100.0); - for rect in [Rect::new(100.0, 0.0, 200.0, 100.0), Rect::new(0.0, 100.0, 100.0, 200.0)] { - let mut a = d.artboards[0].clone(); - a.rect = rect; - d.artboards.push(a); - } - let held = |d: &Document, x: f64, y: f64| (d.artboard_at(Point::new(x, y)), d.artboard_holding(Point::new(x, y), false)); - // Each artboard's own right and bottom edges, edges with roundoff, and points beyond them. - assert_eq!(held(&d, 200.0, 50.0), (Some(1), Some(1)), "right edge"); - assert_eq!(held(&d, 150.0, 100.0), (Some(1), Some(1)), "bottom edge"); - assert_eq!(held(&d, 200.0, 100.0), (Some(1), Some(1)), "bottom right corner"); - assert_eq!(held(&d, 100.0, 150.0), (Some(2), Some(2)), "right edge"); - assert_eq!(held(&d, 50.0, 200.0 + 1e-9), (Some(2), Some(2)), "roundoff past the bottom edge"); - assert_eq!(held(&d, -1e-9, 50.0), (Some(0), Some(0)), "roundoff past the left edge"); - assert_eq!(held(&d, 200.001, 50.0), (None, None)); - assert_eq!(held(&d, 50.0, 200.001), (None, None)); - // On an edge two artboards share, the artboard to the right of it or below it holds the - // point, in either list order, except at the end of the edge that lies on that artboard's - // bottom or right edge. - assert_eq!(held(&d, 100.0, 50.0), (Some(1), Some(1))); - assert_eq!(held(&d, 50.0, 100.0), (Some(2), Some(2))); - // The bottom edges of artboards 0 and 1 meet at (100, 100), which is also artboard 2's top - // right corner: the first holds the point, or the last when `topmost`. - assert_eq!(held(&d, 100.0, 100.0), (Some(2), Some(0)), "shared corner"); - d.artboards.swap(0, 1); - assert_eq!(held(&d, 100.0, 50.0), (Some(0), Some(0))); - // Where two artboards overlap, the topmost holds the point, or the first one when not - // `topmost`. - let mut inner = d.artboards[1].clone(); - inner.rect = Rect::new(10.0, 10.0, 90.0, 90.0); - d.artboards.push(inner); - assert_eq!(held(&d, 50.0, 50.0), (Some(3), Some(1))); - assert_eq!(held(&d, 90.0, 50.0), (Some(1), Some(1)), "inside artboard 1, on the right edge of artboard 3"); - } - - #[test] - fn find_and_paths() { - let (d, a, b) = doc_with_rects(); - assert_eq!(d.index_path(b), Some(vec![0, 1])); - assert_eq!(d.parent_of(a), Some(d.layers[0].id)); - assert_eq!(d.layer_of(b), Some(d.layers[0].id)); - assert!(d.node(NodeId(999)).is_none()); - assert_eq!(d.node_count(), 3); - } - - #[test] - fn copy_on_write_shares_untouched() { - let (d, a, b) = doc_with_rects(); - let mut e = d.clone(); - e.node_mut(a).unwrap().name = Some("A".into()); - // b's Arc is shared between both versions; a's is not. - let lb = &d.layers[0].children().unwrap()[1]; - let eb = &e.layers[0].children().unwrap()[1]; - assert!(Arc::ptr_eq(lb, eb)); - assert_eq!(d.node(a).unwrap().name, None); - assert_eq!(e.node(a).unwrap().name.as_deref(), Some("A")); - let _ = b; - } - - #[test] - fn move_and_remove() { - let (mut d, a, b) = doc_with_rects(); - let layer = d.layers[0].id; - d.move_node(a, Some(layer), usize::MAX).unwrap(); - assert_eq!(d.index_path(a), Some(vec![0, 1])); - assert_eq!(d.index_path(b), Some(vec![0, 0])); - let r = d.remove(a).unwrap(); - assert_eq!(r.id, a); - assert!(d.node(a).is_none()); - assert!(d.move_node(layer, Some(layer), 0).is_err()); - } - - #[test] - fn layers_and_names() { - let mut d = Document::new(100.0, 100.0); - let l2 = d.add_layer(None); - assert_eq!(d.node(l2).unwrap().display_name(), "Layer 2"); - assert_eq!(d.default_layer(), Some(l2)); - assert_eq!(d.layer_color(l2), LAYER_COLORS[1].1); - } - - /// #1718: a file whose ids or counters are at their type's largest value still hands out ids - /// nothing in it uses (and never 0), instead of overflowing. - #[test] - fn exhausted_ids_in_a_file_dont_run_out() { - let (d, a, b) = doc_with_rects(); - let mut v = serde_json::to_value(&d).unwrap(); - v["next_id"] = serde_json::json!(u64::MAX); - // Object `a` gets the largest id there is. - fn renumber(v: &mut serde_json::Value, from: u64) { - match v { - serde_json::Value::Object(o) => { - if o.get("id").and_then(serde_json::Value::as_u64) == Some(from) { - o.insert("id".into(), serde_json::json!(u64::MAX)); - } - o.values_mut().for_each(|c| renumber(c, from)); - } - serde_json::Value::Array(a) => a.iter_mut().for_each(|c| renumber(c, from)), - _ => {} - } - } - renumber(&mut v["layers"], a.0); - let mut d: Document = serde_json::from_value(v).unwrap(); - assert!(d.node(NodeId(u64::MAX)).is_some(), "the file's largest id is kept"); - d.fix_next_id(); - let fresh: Vec = (0..3).map(|_| d.alloc_id()).collect(); - assert!(fresh.iter().all(|id| d.node(*id).is_none() && id.0 > b.0 && id.0 < MAX_NEXT_ID), "{fresh:?}"); - assert!(fresh[0] != fresh[1] && fresh[1] != fresh[2]); - // A counter left at the end by other means stays there rather than wrapping to 0. - d.next_id = u64::MAX; - assert_eq!((d.alloc_id(), d.peek_next_id()), (NodeId(u64::MAX), u64::MAX)); - d.reserve_ids(u64::MAX); - // Artboards and graphic styles: one past the largest, else the smallest id free. - assert_eq!(free_id([1, 2, 7].into_iter()), 8); - assert_eq!(free_id([u32::MAX, 0, 1, 2, 4].into_iter()), 3); - assert_eq!(free_id([u32::MAX].into_iter()), 1); - d.artboards[0].id = u32::MAX; - assert_eq!(d.next_artboard_id(), 1); - } - - #[test] - fn serde_roundtrip() { - let (d, _, _) = doc_with_rects(); - let s = serde_json::to_string(&d).unwrap(); - let back: Document = serde_json::from_str(&s).unwrap(); - assert_eq!(back.node_count(), d.node_count()); - assert_eq!(back.peek_next_id(), d.peek_next_id()); - } - - #[test] - fn reid_gives_fresh_ids() { - let (mut d, a, b) = doc_with_rects(); - let g = d.alloc_id(); - let na = (*d.remove(a).unwrap()).clone(); - let nb = (*d.remove(b).unwrap()).clone(); - let group = Node::group(g, vec![Arc::new(na), Arc::new(nb)]); - let copy = d.reid(&group); - assert_ne!(copy.id, g); - let ids: Vec = copy.children().unwrap().iter().map(|c| c.id).collect(); - assert!(!ids.contains(&a) && !ids.contains(&b)); - } - - #[test] - fn setup_round_trips_and_old_files_load() { - let (mut d, _, _) = doc_with_rects(); - // A document without a setup writes no `setup` key (old readers and files stay unchanged). - assert!(!serde_json::to_string(&d).unwrap().contains("\"setup\"")); - d.setup.bleed = [9.0, 9.0, 0.0, 18.0]; - d.setup.grid_size = GridSize::Large; - d.setup.typographers_quotes = false; - d.setup.quotes = setup::language_quotes("German").unwrap(); - d.setup.flattener_preset = Some("High Resolution".into()); - d.setup.background = Background::White; - d.setup.export_text = ExportText::Appearance; - let back: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap(); - assert_eq!(back.setup, d.setup); - // Files written before Document Setup existed load with the defaults. - let mut v = serde_json::to_value(&d).unwrap(); - v.as_object_mut().unwrap().remove("setup"); - let old: Document = serde_json::from_value(v).unwrap(); - assert_eq!(old.setup, DocSetup::default()); - } - - #[test] - fn char_position_round_trips() { - let st = CharStyle { - position: CharPosition::Subscript(ScriptMetrics { size: 50.0, position: 20.0 }), - small_caps: Some(75.0), - ..CharStyle::default() - }; - let v = serde_json::to_value(&st).unwrap(); - assert_eq!(v["position"], serde_json::json!({"kind": "subscript", "size": 50.0, "position": 20.0})); - assert_eq!(serde_json::from_value::(v).unwrap(), st); - let plain = serde_json::to_value(CharStyle::default()).unwrap(); - assert!(plain.get("position").is_none() && plain.get("small_caps").is_none()); - let (scale, shift) = CharPosition::Subscript(ScriptMetrics::DEFAULT).scale_shift(10.0); - assert!((scale - 0.583).abs() < 1e-9 && (shift + 3.33).abs() < 1e-9); - } - - #[test] - fn units() { - assert_eq!(Unit::Inches.parse("1"), Some(72.0)); - assert_eq!(Unit::Points.parse("1in"), Some(72.0)); - assert_eq!(Unit::Points.parse("10 mm").map(|v| (v * 1000.0).round()), Some(28346.0)); - assert_eq!(Unit::Points.parse("2p6"), Some(30.0)); - assert_eq!(Unit::Points.parse("10+5"), Some(15.0)); - assert_eq!(Unit::Points.parse("100/4"), Some(25.0)); - assert_eq!(Unit::Points.parse("-5"), Some(-5.0)); - assert_eq!(Unit::Points.parse("abc"), None); - assert_eq!(Unit::Points.format(12.5), "12.5 pt"); - assert_eq!(Unit::Inches.format(144.0), "2 in"); - } - - #[test] - fn negative_picas_and_points_sign_applies_to_whole_value() { - assert_eq!(Unit::Points.parse("-2p6"), Some(-30.0)); - assert_eq!(Unit::Points.parse("-0p6"), Some(-6.0)); - assert_eq!(Unit::Points.parse("-2p"), Some(-24.0)); - assert_eq!(Unit::Points.parse("2p6"), Some(30.0)); - } -} - -#[cfg(test)] -mod tests_lookups; -#[cfg(test)] -mod tests_slices; -#[cfg(test)] -mod tests_units; +mod tests; diff --git a/crates/doc/src/limits.rs b/crates/doc/src/limits.rs new file mode 100644 index 0000000000..e030f3d71a --- /dev/null +++ b/crates/doc/src/limits.rs @@ -0,0 +1,20 @@ +use super::*; + +/// Coordinates beyond this many points exceed the supported document range. +pub const MAX_COORD: f64 = 4.0e6; + +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum DocError { + #[error("no such object {0}")] + NoNode(NodeId), + #[error("object {0} cannot have children")] + NotContainer(NodeId), + #[error("{0}")] + Invalid(String), +} + +pub const FORMAT_VERSION: u32 = 1; + +/// Node, slice and asset ids are handed out below this: no document gets near it by counting, so +/// larger ids in a file are damage (or made by hand) and the counter never follows them (#1718). +pub(crate) const MAX_NEXT_ID: u64 = 1 << 62; diff --git a/crates/doc/src/links.rs b/crates/doc/src/links.rs index 7abcec7c16..04bad52c64 100644 --- a/crates/doc/src/links.rs +++ b/crates/doc/src/links.rs @@ -86,13 +86,25 @@ pub fn hash_bytes(bytes: &[u8]) -> String { } /// [`hash_bytes`] of everything `r` reads, read 64 KB at a time. -pub fn hash_reader(mut r: impl std::io::Read) -> std::io::Result { +pub fn hash_reader(r: impl std::io::Read) -> std::io::Result { + hash_reader_within(r, u64::MAX).map(|(hash, _)| hash) +} + +/// [`hash_reader`] of at most `max` bytes, and how many it read: `max` + 1 when there were more (the +/// hash then covers only the first `max` + 1). A file that grew since its size was looked at isn't +/// read to its new end. +pub fn hash_reader_within(r: impl std::io::Read, max: u64) -> std::io::Result<(String, u64)> { + use std::io::Read; + let mut r = r.take(max.saturating_add(1)); let mut buf = vec![0; 1 << 16]; - let mut h = FNV_BASIS; + let (mut h, mut read) = (FNV_BASIS, 0u64); loop { match r.read(&mut buf) { - Ok(0) => return Ok(format!("img{h:016x}")), - Ok(n) => h = fnv1a(h, buf.get(..n).unwrap_or_default()), + Ok(0) => return Ok((format!("img{h:016x}"), read)), + Ok(n) => { + h = fnv1a(h, buf.get(..n).unwrap_or_default()); + read = read.saturating_add(n as u64); + } Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} Err(e) => return Err(e), } @@ -127,7 +139,17 @@ fn proxy_png(bytes: &[u8]) -> Option> { if w.max(h) <= PROXY_SIZE { return None; } - let small = image::load_from_memory(bytes).ok()?.thumbnail(PROXY_SIZE, PROXY_SIZE); + // The proxy decodes within the project's raster cap, counted as RGBA like every other + // decode path (#3597): the header alone decides whether the pixels could ever fit, and the + // decoder gets the same budget instead of image's own default. + if u64::from(w) * u64::from(h) > crate::MAX_RASTER_ALLOC / 4 { + return None; + } + let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; + let mut limits = image::Limits::default(); + limits.max_alloc = Some(crate::MAX_RASTER_ALLOC); + reader.limits(limits); + let small = reader.decode().ok()?.thumbnail(PROXY_SIZE, PROXY_SIZE); let mut png = Vec::new(); small.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; Some(png) @@ -377,6 +399,7 @@ mod tests { xf: Affine::IDENTITY, link, placement: Default::default(), + pixels: None, })), ), ) @@ -404,6 +427,9 @@ mod tests { let bytes: Vec = (0..200_000u32).map(|i| (i * 7 % 251) as u8).collect(); assert_eq!(hash_reader(&bytes[..]).unwrap(), hash_bytes(&bytes)); assert_eq!((hash_reader(&b""[..]).unwrap(), hash_bytes(b"")), ("imgcbf29ce484222325".to_string(), "imgcbf29ce484222325".to_string())); + // Within a size: the whole file at that size; one byte past it when it is longer. + assert_eq!(hash_reader_within(&bytes[..], bytes.len() as u64).unwrap(), (hash_bytes(&bytes), bytes.len() as u64)); + assert_eq!(hash_reader_within(&bytes[..], 3).unwrap().1, 4); } #[test] @@ -416,6 +442,44 @@ mod tests { assert!(ImageBlob::new("image/png", vec![1, 2, 3]).with_proxy().proxy.is_none(), "undecodable"); } + /// PNG CRC-32 (the same polynomial ZIP uses), so a hand-written header is one a decoder accepts. + fn crc32(data: &[u8]) -> u32 { + let mut crc = !0u32; + for &b in data { + crc ^= u32::from(b); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xEDB8_8320 & u32::from(crc & 1 != 0).wrapping_neg()); + } + } + !crc + } + + /// A PNG header and nothing else, declaring `w` × `h` 8-bit gray pixels. + fn png_header_declaring(w: u32, h: u32) -> Vec { + let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; + let mut chunk = Vec::new(); + chunk.extend(b"IHDR"); + chunk.extend(w.to_be_bytes()); + chunk.extend(h.to_be_bytes()); + chunk.extend([8, 0, 0, 0, 0]); + let crc = crc32(&chunk); + out.extend(13u32.to_be_bytes()); + out.extend(&chunk); + out.extend(crc.to_be_bytes()); + out + } + + /// A linked image past the raster cap gets no proxy: the header alone decides (#3597). + #[test] + fn an_image_past_the_raster_cap_gets_no_proxy() { + // 65536 × 65536 gray pixels are 4 GiB as RGBA, past the 2 GiB cap on every target. + let huge = png_header_declaring(1 << 16, 1 << 16); + assert!(proxy_png(&huge).is_none()); + // A header within the cap but with no image data decodes to no preview, as before. + let truncated = png_header_declaring(600, 300); + assert!(proxy_png(&truncated).is_none()); + } + #[test] fn only_blobs_no_embedded_image_shows_are_linked_only() { let mut d = Document::new(100.0, 100.0); diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 9175c88c57..650361374c 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -34,233 +34,6 @@ fn fifty() -> f64 { 50.0 } -// ===================================================================================== -// Data -// ===================================================================================== - -/// Blend Options → Spacing. -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum BlendSpacing { - /// Step count chosen from the colour difference (or the distance when colours match). - #[default] - SmoothColor, - /// Specified number of steps between each pair of key objects (1–1000). - Steps(u32), - /// Specified distance (pt) between the steps. - Distance(f64), -} - -/// Blend Options → Orientation. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum BlendOrientation { - #[default] - AlignToPage, - AlignToPath, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct BlendSpec { - #[serde(default)] - pub spacing: BlendSpacing, - #[serde(default)] - pub orientation: BlendOrientation, - /// Replaced spine. `None` = the straight lines between the key objects' centres. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub spine: Option, - /// The anchor of the spine's first subpath each key object sits on (a spine edited on the - /// canvas: moving a key moves its anchor and the other way round). Empty: the keys spread - /// evenly along the spine by arc length (Replace Spine). - #[serde(default, rename = "keyAnchors", skip_serializing_if = "Vec::is_empty")] - pub key_anchors: Vec, - /// Per key object, the anchor of its first subpath the blend starts from (Blend tool clicks - /// on anchor points); `None`: chosen so closed shapes don't twist. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub starts: Vec>, -} - -impl BlendSpec { - /// The start anchor of key `i` (see [`Self::starts`]). - pub fn start(&self, i: usize) -> Option { - self.starts.get(i).copied().flatten().map(|a| a as usize) - } -} - -/// Blend Options set with no blend selected: what new blends start with. -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct BlendDefaults { - #[serde(default)] - pub spacing: BlendSpacing, - #[serde(default)] - pub orientation: BlendOrientation, -} - -/// How an envelope distorts its content. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "type", rename_all = "camelCase")] -pub enum EnvelopeKind { - /// One of the 15 warp styles (`arc`, `arcLower`, … — see [`WarpStyle::from_id`]); bend and - /// distortions in percent (-100..100). - Warp { - style: String, - #[serde(default)] - bend: f64, - #[serde(default)] - h: f64, - #[serde(default)] - v: f64, - #[serde(default = "yes")] - horizontal: bool, - }, - /// A `(rows+1)×(cols+1)` grid of points (row-major) the content's bounding box maps onto. - Mesh { - rows: u32, - cols: u32, - points: Vec, - /// Each point's bezier handles (offsets, see [`H_RIGHT`] …), row-major like `points`. - /// Empty: the smooth (Catmull-Rom) mesh through the points, as before handles existed; - /// editing the mesh's points or handles on the canvas fills them in. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - handles: Vec<[Vec2; 4]>, - }, - /// The content's bounding box maps onto the outline of this path. - TopObject { path: PathData }, -} - -/// Envelope Options → Preserve Shape Using: how a distorted raster keeps the envelope's shape. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum PreserveShape { - #[default] - ClippingMask, - Transparency, -} - -impl PreserveShape { - pub fn id(self) -> &'static str { - match self { - Self::ClippingMask => "clippingMask", - Self::Transparency => "transparency", - } - } - pub fn parse(s: &str) -> Option { - match s { - "clippingMask" => Some(Self::ClippingMask), - "transparency" => Some(Self::Transparency), - _ => None, - } - } -} - -/// Envelope Options besides Fidelity. `Default` is what envelopes saved before these options -/// existed do (their appearance applies after the distortion); new envelopes start from -/// [`EnvelopeOptions::NEW`], as in the reference app. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", default)] -pub struct EnvelopeOptions { - /// Rasters: Anti-Alias. - pub anti_alias: bool, - /// Rasters: Preserve Shape Using. - pub preserve_shape: PreserveShape, - /// Distort Appearance: strokes and live effects are applied before the distortion, so they - /// bend with the art (off: they apply to the distorted paths). - pub distort_appearance: bool, - /// Distort Linear Gradients (with Distort Appearance): placed gradients bend with the art. - pub distort_linear_gradients: bool, - /// Distort Pattern Fills (with Distort Appearance): pattern tiles bend with the art. - pub distort_pattern_fills: bool, -} - -impl Default for EnvelopeOptions { - fn default() -> Self { - Self { - anti_alias: true, - preserve_shape: PreserveShape::ClippingMask, - distort_appearance: false, - distort_linear_gradients: false, - distort_pattern_fills: false, - } - } -} - -impl EnvelopeOptions { - /// The options a new envelope gets (the reference app's defaults). - pub const NEW: Self = Self { - anti_alias: true, - preserve_shape: PreserveShape::ClippingMask, - distort_appearance: true, - distort_linear_gradients: false, - distort_pattern_fills: false, - }; - /// Do gradients bend with the art? - pub fn gradients(&self) -> bool { - self.distort_appearance && self.distort_linear_gradients - } - /// Do pattern tiles bend with the art? - pub fn patterns(&self) -> bool { - self.distort_appearance && self.distort_pattern_fills - } -} - -/// Handle slots of a [`MeshPoint`]: towards the next column, previous column, next row, previous row. -pub const H_RIGHT: usize = 0; -pub const H_LEFT: usize = 1; -pub const H_DOWN: usize = 2; -pub const H_UP: usize = 3; - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct MeshPoint { - pub p: Point, - pub color: Color, - #[serde(default = "one")] - pub opacity: f32, - /// Tangent handles as offsets from `p` (see [`H_RIGHT`] …). - #[serde(default)] - pub handles: [Vec2; 4], -} - -/// A gradient mesh: `(rows+1)×(cols+1)` points, row-major. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct GradientMesh { - pub rows: u32, - pub cols: u32, - pub points: Vec, -} - -/// One tessellated piece of a mesh (a small quad with a solid colour). -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct MeshQuad { - pub pts: [Point; 4], - pub color: Color, - pub opacity: f32, -} - -/// Create Gradient Mesh → Appearance. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum MeshAppearance { - #[default] - Flat, - ToCenter, - ToEdge, -} - -impl MeshAppearance { - pub fn parse(s: &str) -> Option { - match s.to_ascii_lowercase().as_str() { - "flat" => Some(Self::Flat), - "center" | "tocenter" | "to center" => Some(Self::ToCenter), - "edge" | "toedge" | "to edge" => Some(Self::ToEdge), - _ => None, - } - } -} - -/// Default envelope fidelity. -pub fn default_fidelity() -> f64 { - fifty() -} - // ===================================================================================== // Blends (evaluation in `crate::blend`) // ===================================================================================== @@ -270,1497 +43,70 @@ pub use crate::blend::{ steps_knockout_shows, }; -// ===================================================================================== -// Warp maps (shared with vectorcraft-effects' Warp effects) -// ===================================================================================== - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum WarpStyle { - Arc, - ArcLower, - ArcUpper, - Arch, - Bulge, - ShellLower, - ShellUpper, - Flag, - Wave, - Fish, - Rise, - Fisheye, - Inflate, - Squeeze, - Twist, -} - -impl WarpStyle { - /// From the id suffix (`arc`, `arcLower`, …). - pub fn from_id(s: &str) -> Option { - use WarpStyle::*; - Some(match s { - "arc" => Arc, - "arcLower" => ArcLower, - "arcUpper" => ArcUpper, - "arch" => Arch, - "bulge" => Bulge, - "shellLower" => ShellLower, - "shellUpper" => ShellUpper, - "flag" => Flag, - "wave" => Wave, - "fish" => Fish, - "rise" => Rise, - "fisheye" => Fisheye, - "inflate" => Inflate, - "squeeze" => Squeeze, - "twist" => Twist, - _ => return None, - }) - } -} - -/// The warp map on normalised coordinates: `b` = bend (-1..1), `dh`/`dv` = distortion (-1..1); -/// `aspect` is the box's half-height over its half-width along the warp (Arc bends in real -/// proportions). -pub fn warp_point(style: WarpStyle, b: f64, dh: f64, dv: f64, aspect: f64, x: f64, y: f64) -> (f64, f64) { - use WarpStyle::*; - let t = (y + 1.0) / 2.0; // 0 at top, 1 at bottom - let par = 1.0 - x * x; // parabola: 1 at centre, 0 at sides - let (mut x2, mut y2) = match style { - Arc => { - if b.abs() < 1e-6 { - (x, y) - } else { - // Bend the centre line into a circular arc of equal length (sweep = |b|·180°), in - // the box's real proportions (lengths in half-widths, so y counts `aspect` each): - // the edges are concentric arcs, and one that would pass the centre stops there - // instead of folding over (#1578). - let k = if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 }; - let sweep = b.abs() * PI; - let r0 = 2.0 / sweep; - let yy = if b > 0.0 { y } else { -y } * k; - let a = x / r0; - let r = (r0 - yy).max(0.0); - let (s, c) = a.sin_cos(); - let (nx, ny) = (r * s, (r0 - r * c) / k); - (nx, if b > 0.0 { ny } else { -ny }) - } - } - ArcLower => (x, y + b * par * t), - ArcUpper => (x, y - b * par * (1.0 - t)), - Arch => (x, y - b * par), - Bulge => (x, y + b * par * y), - ShellLower => (x * (1.0 - 0.5 * b * (1.0 - t)), y + b * par * t), - ShellUpper => (x * (1.0 - 0.5 * b * t), y - b * par * (1.0 - t)), - Flag => (x, y + 0.5 * b * (PI * x).sin()), - Wave => (x + 0.1 * b * (PI * y).sin(), y + 0.3 * b * (2.0 * PI * x).sin() * (0.5 + 0.5 * t)), - Fish => (x, y * (1.0 + 0.5 * b * (0.75 * PI * (x + 1.0)).sin())), - Rise => (x, y - b * ((x + 1.0) / 2.0).powi(2) * 2.0 + b), - Fisheye => { - let r2 = x * x + y * y; - let s = if r2 < 1.0 { 1.0 + 0.5 * b * (1.0 - r2) } else { 1.0 }; - (x * s, y * s) - } - Inflate => (x * (1.0 + 0.5 * b * (1.0 - y * y)), y * (1.0 + 0.5 * b * par)), - Squeeze => (x * (1.0 - 0.5 * b * (1.0 - y * y)), y * (1.0 + 0.3 * b * par)), - Twist => { - let r = (x * x + y * y).sqrt(); - let a = -b * PI * 0.5 * (1.0 - r / std::f64::consts::SQRT_2).max(0.0); - let (s, c) = a.sin_cos(); - (x * c - y * s, x * s + y * c) - } - }; - // Perspective-like distortion: horizontal narrows one side, vertical one end. - if dh != 0.0 { - y2 *= (1.0 + dh * x2 * 0.5).max(0.0); - } - if dv != 0.0 { - x2 *= (1.0 + dv * y2 * 0.5).max(0.0); - } - (x2, y2) -} - -/// 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); - if sp.segment_is_line(i) { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c } -} - -fn poly_len(c: &CubicBez) -> f64 { - c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3) -} - -/// Running length along a polyline: `0, |p0p1|, |p0p1| + |p1p2|, …` (one entry per point). -fn cumulative_lengths(pts: &[Point]) -> Vec { - let mut total = 0.0; - let mut cum = Vec::with_capacity(pts.len()); - cum.push(0.0); - for w in pts.windows(2) { - total += w[0].distance(w[1]); - cum.push(total); - } - cum -} - -/// Map every point of `path` through the non-linear function `f`. Segments are split into pieces -/// no longer than about `max_piece` (up to 64 per segment) and their control points mapped, which -/// approximates the image curve to O(h²). Closedness and subpath structure are preserved. -pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point) -> PathData { - let max_piece = max_piece.max(1e-3); - let mut subs = Vec::with_capacity(path.subpaths.len()); - for sp in &path.subpaths { - let n = sp.anchors.len(); - if n == 0 { - continue; - } - let segs = sp.segment_count(); - let mut res: Vec = Vec::new(); - let mut pending_in: Option = None; - for i in 0..n { - let a = &sp.anchors[i]; - let h_in = pending_in.take().unwrap_or_else(|| f(a.h_in)); - res.push(Anchor { p: f(a.p), h_in, h_out: f(a.h_out), kind: a.kind }); - if i < segs { - let c = seg_cubic(sp, i); - let k = ((poly_len(&c) / max_piece).ceil() as usize).clamp(1, 64); - for j in 0..k { - let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)); - if let Some(last) = res.last_mut() { - last.h_out = f(sub.p1); - } - if j + 1 < k { - res.push(Anchor { p: f(sub.p3), h_in: f(sub.p2), h_out: f(sub.p3), kind: Default::default() }); - } else { - pending_in = Some(f(sub.p2)); - } - } - } - } - if let Some(h) = pending_in - && sp.closed - && let Some(first) = res.first_mut() - { - first.h_in = h; - } - let anchors = res.into_iter().map(|a| Anchor::with_handles(a.p, a.h_in, a.h_out)).collect(); - subs.push(SubPath::new(anchors, sp.closed)); - } - PathData::new(subs) -} - -// ===================================================================================== -// Coons patches from outlines -// ===================================================================================== - -fn flatten_subpath(sp: &SubPath, tol: f64) -> Vec { - let mut bp = BezPath::new(); - sp.to_bezpath_into(&mut bp); - let mut pts: Vec = Vec::new(); - vectorcraft_geom::kurbo::flatten(bp.iter(), tol, |el| match el { - vectorcraft_geom::PathEl::MoveTo(p) | vectorcraft_geom::PathEl::LineTo(p) if pts.last().is_none_or(|q| q.distance(p) > 1e-9) => pts.push(p), - _ => {} - }); - pts -} - -fn resample(poly: &[Point], m: usize) -> Vec { - if poly.is_empty() { - return vec![Point::ZERO; m]; - } - if poly.len() == 1 { - return vec![poly[0]; m]; - } - let cum = cumulative_lengths(poly); - let total = cum.last().copied().unwrap_or(0.0); - let mut out = Vec::with_capacity(m); - let mut i = 0; - for k in 0..m { - let s = if m > 1 { total * k as f64 / (m - 1) as f64 } else { 0.0 }; - while i + 2 < cum.len() && cum[i + 1] < s { - i += 1; - } - let seg = (cum[i + 1] - cum[i]).max(1e-12); - out.push(poly[i].lerp(poly[i + 1], ((s - cum[i]) / seg).clamp(0.0, 1.0))); - } - out -} - -const SIDE: usize = 65; - -/// Four boundary curves (top TL→TR, right TR→BR, bottom BL→BR, left TL→BL), each resampled to -/// [`SIDE`] points, from the outline of a closed path split at the points nearest its bounding -/// box corners. -#[derive(Clone, Debug)] -pub struct Coons { - top: Vec, - right: Vec, - bottom: Vec, - left: Vec, -} - -impl Coons { - /// A rectangle. - pub fn rect(r: Rect) -> Self { - let line = |a: Point, b: Point| (0..SIDE).map(|i| a.lerp(b, i as f64 / (SIDE - 1) as f64)).collect::>(); - let (tl, tr, br, bl) = (Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)); - Self { top: line(tl, tr), right: line(tr, br), bottom: line(bl, br), left: line(tl, bl) } - } - - pub fn from_path(path: &PathData) -> Option { - // The largest subpath is the outline. - let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?; - let r = path.bounds()?; - let tol = (r.width() + r.height()).max(1e-6) / 2000.0; - let mut poly = flatten_subpath(sp, tol); - if poly.len() > 1 - && let (Some(a), Some(b)) = (poly.first(), poly.last()) - && a.distance(*b) < 1e-9 - { - poly.pop(); - } - if poly.len() < 3 { - return Some(Self::rect(r)); - } - // Orient clockwise in y-down (TL → TR → BR → BL). - let area: f64 = (0..poly.len()) - .map(|i| { - let (p, q) = (poly[i], poly[(i + 1) % poly.len()]); - p.x * q.y - q.x * p.y - }) - .sum(); - if area < 0.0 { - poly.reverse(); - } - let nearest = |c: Point| (0..poly.len()).min_by(|i, j| poly[*i].distance_squared(c).total_cmp(&poly[*j].distance_squared(c))).unwrap_or(0); - let tl = nearest(Point::new(r.x0, r.y0)); - let tr = nearest(Point::new(r.x1, r.y0)); - let br = nearest(Point::new(r.x1, r.y1)); - let bl = nearest(Point::new(r.x0, r.y1)); - let n = poly.len(); - let arc = |i: usize, j: usize| -> Vec { - let mut v = vec![poly[i]]; - let mut k = i; - while k != j { - k = (k + 1) % n; - v.push(poly[k]); - } - v - }; - let top = resample(&arc(tl, tr), SIDE); - let right = resample(&arc(tr, br), SIDE); - let mut bottom = resample(&arc(br, bl), SIDE); - bottom.reverse(); - let mut left = resample(&arc(bl, tl), SIDE); - left.reverse(); - Some(Self { top, right, bottom, left }) - } - - /// The point at `u` along a side; past its ends the end segments go on straight (art an - /// envelope bends can reach past the content's box: outlined strokes). - fn sample(side: &[Point], u: f64) -> Point { - let s = u * (side.len() - 1) as f64; - let i = (s.floor().max(0.0) as usize).min(side.len() - 2); - side[i].lerp(side[i + 1], s - i as f64) - } - - /// The surface point at (u, v) ∈ [0,1]². - pub fn eval(&self, u: f64, v: f64) -> Point { - let (t, b, l, r) = (Self::sample(&self.top, u), Self::sample(&self.bottom, u), Self::sample(&self.left, v), Self::sample(&self.right, v)); - let (p00, p10, p01, p11) = (self.top[0], self.top[SIDE - 1], self.bottom[0], self.bottom[SIDE - 1]); - let c = (1.0 - v) * t.to_vec2() + v * b.to_vec2() + (1.0 - u) * l.to_vec2() + u * r.to_vec2() - - ((1.0 - u) * (1.0 - v) * p00.to_vec2() + u * (1.0 - v) * p10.to_vec2() + (1.0 - u) * v * p01.to_vec2() + u * v * p11.to_vec2()); - c.to_point() - } - - /// The four corners TL, TR, BR, BL. - pub fn corners(&self) -> [Point; 4] { - [self.top[0], self.top[SIDE - 1], self.bottom[SIDE - 1], self.bottom[0]] - } -} - -// ===================================================================================== -// Gradient meshes -// ===================================================================================== - -/// `0, 1/n, …, 1` for `n` (clamped to 1..=200) even steps. -fn even_steps(n: u32) -> Vec { - let n = n.clamp(1, 200); - (0..=n).map(|i| i as f64 / n as f64).collect() -} - -/// The number of points of a `(rows+1)×(cols+1)` grid, `None` past `usize`: counts come from -/// files, and u32::MAX rows and columns (65,535 on 32-bit targets) would wrap to an empty grid. -fn grid_len(rows: u32, cols: u32) -> Option { - (rows as usize).checked_add(1)?.checked_mul((cols as usize).checked_add(1)?) -} - -impl GradientMesh { - pub fn idx(&self, r: usize, c: usize) -> usize { - r * (self.cols as usize + 1) + c - } - pub fn is_valid(&self) -> bool { - self.rows >= 1 && self.cols >= 1 && grid_len(self.rows, self.cols) == Some(self.points.len()) - } - - /// A 1×1 mesh from its four corners (bottom-left, top-left, top-right, bottom-right in u/v - /// order: row 0 is v = 0, columns follow u), each with its handles ([`H_RIGHT`] …). - fn patch(corners: [(Point, [Vec2; 4], Color); 4]) -> Self { - let point = |(p, handles, color): (Point, [Vec2; 4], Color)| MeshPoint { p, color, opacity: 1.0, handles }; - let [a, b, c, d] = corners; - Self { rows: 1, cols: 1, points: vec![point(a), point(d), point(b), point(c)] } - } - - /// A 1×1 mesh from a Coons patch's twelve boundary points (in the order PDF and PostScript - /// shadings list them: v runs cp0 → cp3 along cp1 and cp2, u runs cp0 → cp9 along cp11 and - /// cp10) and its corner colours (at cp0, cp3, cp6, cp9); `None` if a point isn't finite. - pub fn coons(cp: &[Point; 12], colors: [Color; 4]) -> Option { - if !cp.iter().all(|p| p.is_finite()) { - return None; - } - let h = |a: usize, b: usize| cp[b] - cp[a]; - let handles = |right: Vec2, left: Vec2, down: Vec2, up: Vec2| { - let mut h = [Vec2::ZERO; 4]; - (h[H_RIGHT], h[H_LEFT], h[H_DOWN], h[H_UP]) = (right, left, down, up); - h - }; - let [c0, c1, c2, c3] = colors; - Some(Self::patch([ - (cp[0], handles(h(0, 11), Vec2::ZERO, h(0, 1), Vec2::ZERO), c0), - (cp[3], handles(h(3, 4), Vec2::ZERO, Vec2::ZERO, h(3, 2)), c1), - (cp[6], handles(Vec2::ZERO, h(6, 5), Vec2::ZERO, h(6, 7)), c2), - (cp[9], handles(Vec2::ZERO, h(9, 10), h(9, 8), Vec2::ZERO), c3), - ])) - } - - /// A 1×1 mesh of a Gouraud-shaded triangle (a patch with two corners together); `None` if a - /// point isn't finite. - pub fn triangle(corners: [(Point, Color); 3]) -> Option { - if !corners.iter().all(|(p, _)| p.is_finite()) { - return None; - } - let [a, b, c] = corners.map(|(p, color)| (p, [Vec2::ZERO; 4], color)); - Some(Self::patch([a, b, c, c])) - } - - /// A mesh over surface `s` (u, v ∈ [0,1]) with handles from its partial derivatives. - pub fn from_surface(rows: u32, cols: u32, s: &dyn Fn(f64, f64) -> Point, color: &dyn Fn(f64, f64) -> Color) -> Self { - let (us, vs) = (even_steps(cols), even_steps(rows)); - Self::from_grid(&us, &vs, s, &|r, c, _| (color(us[c], vs[r]), 1.0)) - } - - /// A mesh over surface `s` (u, v ∈ [0,1]) whose column lines sit at `us` and row lines at `vs` - /// (ascending, at least two each; equal neighbours make a patch of no width, a sharp colour - /// change), with handles from its partial derivatives. `color(row, col, point)` gives each - /// point its colour and opacity. - pub fn from_grid(us: &[f64], vs: &[f64], s: &dyn Fn(f64, f64) -> Point, color: &dyn Fn(usize, usize, Point) -> (Color, f32)) -> Self { - let (rows, cols) = (vs.len().saturating_sub(1), us.len().saturating_sub(1)); - let eps = 1e-3; - let mut points = Vec::with_capacity(us.len() * vs.len()); - for (r, &v) in vs.iter().enumerate() { - for (c, &u) in us.iter().enumerate() { - let p = s(u, v); - let d_u = (s((u + eps).min(1.0), v) - s((u - eps).max(0.0), v)) / ((u + eps).min(1.0) - (u - eps).max(0.0)); - let d_v = (s(u, (v + eps).min(1.0)) - s(u, (v - eps).max(0.0))) / ((v + eps).min(1.0) - (v - eps).max(0.0)); - // A third of the way to the neighbouring line along the tangent; outward handles on - // the border are unused, so they stay at the point. - let h = |d: Vec2, from: f64, to: Option<&f64>| to.map_or(Vec2::ZERO, |to| d * ((to - from) / 3.0)); - let handles = [ - h(d_u, u, us.get(c + 1)), - h(d_u, u, c.checked_sub(1).map(|i| &us[i])), - h(d_v, v, vs.get(r + 1)), - h(d_v, v, r.checked_sub(1).map(|i| &vs[i])), - ]; - let (color, opacity) = color(r, c, p); - points.push(MeshPoint { p, color, opacity, handles }); - } - } - Self { rows: rows as u32, cols: cols as u32, points } - } - - /// Create Gradient Mesh for a path: the outline split at its corners, coloured per `appearance`. - pub fn for_path(path: &PathData, rows: u32, cols: u32, base: Color, appearance: MeshAppearance, highlight: f64) -> Option { - let mut m = Self::for_path_with(path, rows, cols, &|_| (base, 1.0))?; - m.highlight(appearance, highlight); - Some(m) - } - - /// Create Gradient Mesh for a path: the outline split at its corners, each point taking the - /// colour and opacity `color_at` gives at its position (a gradient fill's, say). - pub fn for_path_with(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option { - let coons = Coons::from_path(path)?; - Some(Self::from_grid(&even_steps(cols), &even_steps(rows), &|u, v| coons.eval(u, v), &|_, _, p| color_at(p))) - } - - /// Create Gradient Mesh → Appearance: lighten the points towards white, to the centre or to - /// the edges, by at most `highlight` %. - pub fn highlight(&mut self, appearance: MeshAppearance, highlight: f64) { - let h = (highlight / 100.0).clamp(0.0, 1.0) as f32; - let (rows, cols) = (self.rows as usize, self.cols as usize); - for r in 0..=rows { - for c in 0..=cols { - let (u, v) = (c as f64 / cols as f64, r as f64 / rows as f64); - let d = ((u - 0.5).abs().max((v - 0.5).abs()) * 2.0) as f32; // 0 centre … 1 edge - let w = match appearance { - MeshAppearance::Flat => 0.0, - MeshAppearance::ToCenter => (1.0 - d) * h, - MeshAppearance::ToEdge => d * h, - }; - if w > 0.0 { - let i = self.idx(r, c); - self.points[i].color = lerp_color(&self.points[i].color, &Color::WHITE, w); - } - } - } - } - - /// Horizontal edge from (r, c) to (r, c+1). - pub fn edge_u(&self, r: usize, c: usize) -> CubicBez { - let (a, b) = (&self.points[self.idx(r, c)], &self.points[self.idx(r, c + 1)]); - CubicBez::new(a.p, a.p + a.handles[H_RIGHT], b.p + b.handles[H_LEFT], b.p) - } - /// Vertical edge from (r, c) to (r+1, c). - pub fn edge_v(&self, r: usize, c: usize) -> CubicBez { - let (a, b) = (&self.points[self.idx(r, c)], &self.points[self.idx(r + 1, c)]); - CubicBez::new(a.p, a.p + a.handles[H_DOWN], b.p + b.handles[H_UP], b.p) - } - - /// Coons patch point of patch (r, c) at local (u, v). - pub fn eval(&self, r: usize, c: usize, u: f64, v: f64) -> Point { - let (t, b) = (self.edge_u(r, c).eval(u), self.edge_u(r + 1, c).eval(u)); - let (l, rr) = (self.edge_v(r, c).eval(v), self.edge_v(r, c + 1).eval(v)); - let p00 = self.points[self.idx(r, c)].p.to_vec2(); - let p10 = self.points[self.idx(r, c + 1)].p.to_vec2(); - let p01 = self.points[self.idx(r + 1, c)].p.to_vec2(); - let p11 = self.points[self.idx(r + 1, c + 1)].p.to_vec2(); - ((1.0 - v) * t.to_vec2() + v * b.to_vec2() + (1.0 - u) * l.to_vec2() + u * rr.to_vec2() - - ((1.0 - u) * (1.0 - v) * p00 + u * (1.0 - v) * p10 + (1.0 - u) * v * p01 + u * v * p11)) - .to_point() - } - - /// Bilinear colour and opacity of patch (r, c) at local (u, v). Corners all in CMYK (or all - /// grey) mix in that space, as a PDF shading mixes in its own colour space: the inks come out - /// exact, and a CMYK document separates no colour to draw them. Other corners mix in RGB. - pub fn color_at(&self, r: usize, c: usize, u: f64, v: f64) -> (Color, f32) { - let q = - [&self.points[self.idx(r, c)], &self.points[self.idx(r, c + 1)], &self.points[self.idx(r + 1, c)], &self.points[self.idx(r + 1, c + 1)]]; - let w = [(1.0 - u) * (1.0 - v), u * (1.0 - v), (1.0 - u) * v, u * v]; - let op = q.iter().zip(w).map(|(p, w)| p.opacity * w as f32).sum(); - let cmyk: Option> = - q.iter().map(|p| if let Color::Cmyk { c, m, y, k } = p.color { Some([c, m, y, k]) } else { None }).collect(); - if let Some(inks) = cmyk { - let mut mix = [0.0f32; 4]; - for (ink, w) in inks.iter().zip(w) { - for (m, x) in mix.iter_mut().zip(ink) { - *m += x * w as f32; - } - } - let [c, m, y, k] = mix; - return (Color::Cmyk { c, m, y, k }, op); - } - let grey: Option> = q.iter().map(|p| if let Color::Gray { k } = p.color { Some(k) } else { None }).collect(); - if let Some(ks) = grey { - return (Color::Gray { k: ks.iter().zip(w).map(|(k, w)| k * w as f32).sum() }, op); - } - let mut rgb = [0.0f32; 3]; - for (p, w) in q.iter().zip(w) { - for (ch, x) in rgb.iter_mut().zip(p.color.to_rgb()) { - *ch += x * w as f32; - } - } - (Color::rgb(rgb[0], rgb[1], rgb[2]), op) - } - - /// Tessellate into `n`×`n` quads per patch, each coloured at its centre. - pub fn quads(&self, n: usize) -> Vec { - if !self.is_valid() { - return vec![]; - } - let n = n.clamp(1, 64); - let mut out = Vec::with_capacity(self.rows as usize * self.cols as usize * n * n); - let mut grid = vec![Point::ZERO; (n + 1) * (n + 1)]; - for r in 0..self.rows as usize { - for c in 0..self.cols as usize { - for j in 0..=n { - for i in 0..=n { - grid[j * (n + 1) + i] = self.eval(r, c, i as f64 / n as f64, j as f64 / n as f64); - } - } - for j in 0..n { - for i in 0..n { - let (color, opacity) = self.color_at(r, c, (i as f64 + 0.5) / n as f64, (j as f64 + 0.5) / n as f64); - let g = |a: usize, b: usize| grid[b * (n + 1) + a]; - out.push(MeshQuad { pts: [g(i, j), g(i + 1, j), g(i + 1, j + 1), g(i, j + 1)], color, opacity }); - } - } - } - } - out - } - - /// The mesh's outer boundary as a closed path. - pub fn outline(&self) -> PathData { - if !self.is_valid() { - return PathData::default(); - } - let (rows, cols) = (self.rows as usize, self.cols as usize); - let mut segs: Vec = vec![]; - for c in 0..cols { - segs.push(self.edge_u(0, c)); - } - for r in 0..rows { - segs.push(self.edge_v(r, cols)); - } - for c in (0..cols).rev() { - let e = self.edge_u(rows, c); - segs.push(CubicBez::new(e.p3, e.p2, e.p1, e.p0)); - } - for r in (0..rows).rev() { - let e = self.edge_v(r, 0); - segs.push(CubicBez::new(e.p3, e.p2, e.p1, e.p0)); - } - let mut anchors: Vec = Vec::with_capacity(segs.len()); - for (i, s) in segs.iter().enumerate() { - let prev = &segs[(i + segs.len() - 1) % segs.len()]; - anchors.push(Anchor::with_handles(s.p0, prev.p2, s.p1)); - } - PathData::single(SubPath::new(anchors, true)) - } - - /// Mesh lines (all row and column edges) as open paths, for outline view and editing overlays. - pub fn lines(&self) -> PathData { - if !self.is_valid() { - return PathData::default(); - } - let (rows, cols) = (self.rows as usize, self.cols as usize); - let mut subs = vec![]; - let cub = |e: CubicBez| SubPath::new(vec![Anchor::with_handles(e.p0, e.p0, e.p1), Anchor::with_handles(e.p3, e.p2, e.p3)], false); - for r in 0..=rows { - for c in 0..cols { - subs.push(cub(self.edge_u(r, c))); - } - } - for c in 0..=cols { - for r in 0..rows { - subs.push(cub(self.edge_v(r, c))); - } - } - PathData::new(subs) - } - - /// Control bounds (points and handles). - pub fn bounds(&self) -> Option { - let mut it = self.points.iter().flat_map(|p| std::iter::once(p.p).chain(p.handles.iter().map(move |h| p.p + *h))); - let first = it.next()?; - Some(it.fold(Rect::from_points(first, first), |r, q| r.union_pt(q))) - } - - pub fn transform(&mut self, a: Affine) { - let lin = Affine::new({ - let c = a.as_coeffs(); - [c[0], c[1], c[2], c[3], 0.0, 0.0] - }); - for p in &mut self.points { - p.p = a * p.p; - for h in &mut p.handles { - *h = (lin * h.to_point()).to_vec2(); - } - } - } - - /// Map points (and handle ends) through a non-linear function. - pub fn map(&mut self, f: &dyn Fn(Point) -> Point) { - for p in &mut self.points { - let q = f(p.p); - for h in &mut p.handles { - *h = f(p.p + *h) - q; - } - p.p = q; - } - } - - /// Which patch and local (u, v) contains `p` (sampled search; `None` outside the mesh). - pub fn locate(&self, p: Point) -> Option<(usize, usize, f64, f64)> { - if !self.is_valid() { - return None; - } - let bp = self.outline().to_bezpath(); - if bp.winding(p) == 0 { - return None; - } - const N: usize = 16; - let mut best = (f64::INFINITY, 0, 0, 0.0, 0.0); - for r in 0..self.rows as usize { - for c in 0..self.cols as usize { - for j in 0..=N { - for i in 0..=N { - let (u, v) = (i as f64 / N as f64, j as f64 / N as f64); - let d = self.eval(r, c, u, v).distance_squared(p); - if d < best.0 { - best = (d, r, c, u, v); - } - } - } - } - } - // Refine with a few Newton-free local searches. - let (_, r, c, mut u, mut v) = best; - let mut step = 0.5 / N as f64; - for _ in 0..12 { - let mut improved = false; - for (du, dv) in [(step, 0.0), (-step, 0.0), (0.0, step), (0.0, -step)] { - let (nu, nv) = ((u + du).clamp(0.0, 1.0), (v + dv).clamp(0.0, 1.0)); - if self.eval(r, c, nu, nv).distance_squared(p) < self.eval(r, c, u, v).distance_squared(p) { - u = nu; - v = nv; - improved = true; - } - } - if !improved { - step /= 2.0; - } - } - Some((r, c, u, v)) - } - - /// Index of the mesh point within `tol` of `p`. - pub fn point_near(&self, p: Point, tol: f64) -> Option { - self.points - .iter() - .enumerate() - .filter(|(_, q)| q.p.distance(p) <= tol) - .min_by(|a, b| a.1.p.distance(p).total_cmp(&b.1.p.distance(p))) - .map(|(i, _)| i) - } - - fn surface_du(&self, r: usize, c: usize, u: f64, v: f64) -> Vec2 { - let e = 1e-3; - let (a, b) = ((u - e).max(0.0), (u + e).min(1.0)); - (self.eval(r, c, b, v) - self.eval(r, c, a, v)) / (b - a) - } - fn surface_dv(&self, r: usize, c: usize, u: f64, v: f64) -> Vec2 { - let e = 1e-3; - let (a, b) = ((v - e).max(0.0), (v + e).min(1.0)); - (self.eval(r, c, u, b) - self.eval(r, c, u, a)) / (b - a) - } - - /// Insert a mesh row through patch row `r` at local `v`. - pub fn insert_row(&mut self, r: usize, v: f64) { - let cols = self.cols as usize; - let v = v.clamp(0.01, 0.99); - let mut row = Vec::with_capacity(cols + 1); - // Split the vertical edges. - let mut ups = vec![]; - for c in 0..=cols { - let e = self.edge_v(r, c); - let (l, rr) = (e.subsegment(0.0..v), e.subsegment(v..1.0)); - ups.push((l.p1 - l.p0, rr.p2 - rr.p3)); - let pc = c.min(cols - 1); - let u = if c == cols { 1.0 } else { 0.0 }; - let (color, opacity) = self.color_at(r, pc, u, v); - // Horizontal handles: isocurve derivatives on either side. - let right = if c < cols { self.surface_du(r, c, 0.0, v) / (3.0) } else { Vec2::ZERO }; - let left = if c > 0 { -self.surface_du(r, c - 1, 1.0, v) / 3.0 } else { Vec2::ZERO }; - row.push(MeshPoint { p: l.p3, color, opacity, handles: [right, left, rr.p1 - rr.p0, l.p2 - l.p3] }); - } - for (c, (down, up)) in ups.into_iter().enumerate() { - let i0 = self.idx(r, c); - let i1 = self.idx(r + 1, c); - self.points[i0].handles[H_DOWN] = down; - self.points[i1].handles[H_UP] = up; - } - let at = self.idx(r + 1, 0); - self.points.splice(at..at, row); - self.rows += 1; - } - - /// Insert a mesh column through patch column `c` at local `u`. - pub fn insert_col(&mut self, c: usize, u: f64) { - let rows = self.rows as usize; - let u = u.clamp(0.01, 0.99); - let mut col = Vec::with_capacity(rows + 1); - for r in 0..=rows { - let e = self.edge_u(r, c); - let (l, rr) = (e.subsegment(0.0..u), e.subsegment(u..1.0)); - let pr = r.min(rows - 1); - let v = if r == rows { 1.0 } else { 0.0 }; - let (color, opacity) = self.color_at(pr, c, u, v); - let down = if r < rows { self.surface_dv(r, c, u, 0.0) / 3.0 } else { Vec2::ZERO }; - let up = if r > 0 { -self.surface_dv(r - 1, c, u, 1.0) / 3.0 } else { Vec2::ZERO }; - col.push((MeshPoint { p: l.p3, color, opacity, handles: [rr.p1 - rr.p0, l.p2 - l.p3, down, up] }, l.p1 - l.p0, rr.p2 - rr.p3)); - } - let cols = self.cols as usize; - let mut pts = Vec::with_capacity((rows + 1) * (cols + 2)); - for (r, (mp, right, left)) in col.into_iter().enumerate() { - for cc in 0..=cols { - let mut q = self.points[r * (cols + 1) + cc].clone(); - if cc == c { - q.handles[H_RIGHT] = right; - } - if cc == c + 1 { - q.handles[H_LEFT] = left; - } - pts.push(q); - if cc == c { - pts.push(mp.clone()); - } - } - } - self.points = pts; - self.cols += 1; - } - - /// Mesh tool click: add a row and a column through `p` (inside the mesh). Returns the new point index. - pub fn add_lines_at(&mut self, p: Point) -> Option { - let (r, c, u, v) = self.locate(p)?; - let mut rr = r; - let mut cc = c; - let row_new = v > 0.02 && v < 0.98; - let col_new = u > 0.02 && u < 0.98; - if row_new { - self.insert_row(r, v); - rr = r + 1; - } else if v >= 0.98 { - rr = r + 1; - } - if col_new { - self.insert_col(c, u); - cc = c + 1; - } else if u >= 0.98 { - cc = c + 1; - } - Some(self.idx(rr, cc)) - } - - /// Mesh tool Alt-click: delete the mesh lines through point `index` (interior lines only). - pub fn remove_point_lines(&mut self, index: usize) -> bool { - // A mesh from a file may not have the points its rows and columns need: it is indexed below. - if !self.is_valid() || index >= self.points.len() { - return false; - } - let w = self.cols as usize + 1; - let (r, c) = (index / w, index % w); - let mut changed = false; - if r > 0 && r < self.rows as usize { - // Merge the edges above and below: keep the outer handles. - for cc in 0..w { - let above = self.idx(r - 1, cc); - let below = self.idx(r + 1, cc); - let mid = self.idx(r, cc); - let (pa, pm, pb) = (self.points[above].p, self.points[mid].p, self.points[below].p); - let _ = pm; - self.points[above].handles[H_DOWN] = (pb - pa) / 3.0; - self.points[below].handles[H_UP] = (pa - pb) / 3.0; - } - self.points.drain(r * w..(r + 1) * w); - self.rows -= 1; - changed = true; - } - let w = self.cols as usize + 1; - if c > 0 && c < self.cols as usize { - let rows = self.rows as usize; - for rr in 0..=rows { - let (l, rt) = (rr * w + c - 1, rr * w + c + 1); - let (pl, pr) = (self.points[l].p, self.points[rt].p); - self.points[l].handles[H_RIGHT] = (pr - pl) / 3.0; - self.points[rt].handles[H_LEFT] = (pl - pr) / 3.0; - } - let mut k = 0; - self.points.retain(|_| { - let keep = k % w != c; - k += 1; - keep - }); - self.cols -= 1; - changed = true; - } - changed - } -} - -// ===================================================================================== -// Envelopes -// ===================================================================================== - -/// Union of the geometric bounds of `nodes`. -pub fn nodes_bounds(nodes: &[Arc]) -> Option { - nodes.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric_bounds())) -} - -/// A `(rows+1)×(cols+1)` grid over `r` (row-major). -pub fn grid_points(r: Rect, rows: u32, cols: u32) -> Vec { - let mut v = Vec::with_capacity(((rows + 1) * (cols + 1)) as usize); - for i in 0..=rows { - for j in 0..=cols { - v.push(Point::new(r.x0 + r.width() * j as f64 / cols.max(1) as f64, r.y0 + r.height() * i as f64 / rows.max(1) as f64)); - } - } - v -} - -fn catmull(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: f64) -> Vec2 { - let t2 = t * t; - let t3 = t2 * t; - 0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3) -} - -/// Point map from the unit square onto a point grid (tensor-product Catmull-Rom; linear -/// extrapolation at the borders so an undistorted grid is the identity, also past the square). -fn grid_eval(rows: usize, cols: usize, pts: &[Point], u: f64, v: f64) -> Point { - let at = |r: i64, c: i64| -> Vec2 { - let rr = r.clamp(0, rows as i64); - let cc = c.clamp(0, cols as i64); - let base = pts[rr as usize * (cols + 1) + cc as usize].to_vec2(); - // Linear extrapolation outside the grid. - let er = r - rr; - let ec = c - cc; - let mut p = base; - if er != 0 && rows >= 1 { - let inner = (rr - er.signum()).clamp(0, rows as i64); - p += (base - pts[inner as usize * (cols + 1) + cc as usize].to_vec2()) * er.abs() as f64; - } - if ec != 0 && cols >= 1 { - let inner = (cc - ec.signum()).clamp(0, cols as i64); - p += (base - pts[rr as usize * (cols + 1) + inner as usize].to_vec2()) * ec.abs() as f64; - } - p - }; - // Past the grid's edges the outer patches go on (art can reach past the content's box). - let (su, sv) = (u * cols as f64, v * rows as f64); - let (ci, ri) = ((su.floor() as i64).clamp(0, cols as i64 - 1), (sv.floor() as i64).clamp(0, rows as i64 - 1)); - let (fu, fv) = (su - ci as f64, sv - ri as f64); - let mut rowsv = [Vec2::ZERO; 4]; - for (k, rv) in rowsv.iter_mut().enumerate() { - let r = ri - 1 + k as i64; - *rv = catmull(at(r, ci - 1), at(r, ci), at(r, ci + 1), at(r, ci + 2), fu); - } - catmull(rowsv[0], rowsv[1], rowsv[2], rowsv[3], fv).to_point() -} - -/// The surface (u, v ∈ [0,1]) an envelope of `kind` maps content onto, for content whose bounds in -/// the envelope's own `frame` (its axes → the document) are `src`: a warp bends along the frame's -/// axes; a mesh's points and a top object's path are in the document already. -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 } => { - 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); - let c = src.center(); - let (hw, hh) = (src.width() / 2.0, src.height() / 2.0); - let horizontal = *horizontal; - Box::new(move |u: f64, v: f64| { - let (x, y) = (2.0 * u - 1.0, 2.0 * v - 1.0); - let (x2, y2) = if horizontal { - warp_point(st, b, dh, dv, hh / hw.max(1e-9), x, y) - } else { - let (a, b2) = warp_point(st, b, dh, dv, hw / hh.max(1e-9), y, x); - (b2, a) - }; - frame * Point::new(c.x + x2 * hw, c.y + y2 * hh) - }) - } - EnvelopeKind::Mesh { rows, cols, points, handles } => { - if !handles.is_empty() - && let Some(m) = envelope_grid(*rows, *cols, points, handles) - { - return Box::new(move |u: f64, v: f64| mesh_at(&m, u, v)); - } - if *rows == 0 || *cols == 0 || grid_len(*rows, *cols) != Some(points.len()) { - return Box::new(flat); - } - let (rows, cols) = (*rows as usize, *cols as usize); - Box::new(move |u: f64, v: f64| grid_eval(rows, cols, points, u, v)) - } - EnvelopeKind::TopObject { path } => match Coons::from_path(path) { - Some(co) => Box::new(move |u: f64, v: f64| co.eval(u, v)), - None => Box::new(flat), - }, - } -} - -/// The envelope's point map for content whose bounding box is `src` (page axes). -pub fn envelope_mapper<'a>(kind: &'a EnvelopeKind, src: Rect) -> Box Point + 'a> { - let s = surface_of(kind, src, Affine::IDENTITY); - let (w, h) = (src.width().max(1e-9), src.height().max(1e-9)); - Box::new(move |q: Point| s((q.x - src.x0) / w, (q.y - src.y0) / h)) -} - -/// Catmull-Rom tangents of a `(rows+1)×(cols+1)` point grid (row-major) as mesh handles, a third -/// of the tangent towards each neighbour (past the borders the grid goes on straight): the curves -/// an envelope mesh without handles of its own runs along between its points. -pub fn smooth_handles(rows: u32, cols: u32, points: &[Point]) -> Vec<[Vec2; 4]> { - let (rows, cols) = (rows as usize, cols as usize); - let at = |r: usize, c: usize| points.get(r * (cols + 1) + c).copied().unwrap_or_default(); - let tangent = |prev: Option, p: Point, next: Option| match (prev, next) { - (Some(a), Some(b)) => (b - a) / 2.0, - (None, Some(b)) => b - p, - (Some(a), None) => p - a, - (None, None) => Vec2::ZERO, - }; - let mut out = Vec::with_capacity(points.len()); - for r in 0..=rows { - for c in 0..=cols { - let p = at(r, c); - let du = tangent(c.checked_sub(1).map(|c| at(r, c)), p, (c < cols).then(|| at(r, c + 1))) / 3.0; - let dv = tangent(r.checked_sub(1).map(|r| at(r, c)), p, (r < rows).then(|| at(r + 1, c))) / 3.0; - // Handles pointing out of the grid are unused: they stay at the point. - let keep = |inside: bool, d: Vec2| if inside { d } else { Vec2::ZERO }; - let mut h = [Vec2::ZERO; 4]; - (h[H_RIGHT], h[H_LEFT], h[H_DOWN], h[H_UP]) = (keep(c < cols, du), keep(c > 0, -du), keep(r < rows, dv), keep(r > 0, -dv)); - out.push(h); - } - } - out -} - -/// A mesh envelope's grid (`rows`×`cols` patches, `points` and their `handles`; without handles -/// the smooth ones, see [`smooth_handles`]) as a gradient mesh with black points: what the -/// canvas draws and the Mesh tool and Direct Selection edit. `None` for a malformed grid. -pub fn envelope_grid(rows: u32, cols: u32, points: &[Point], handles: &[[Vec2; 4]]) -> Option { - if rows == 0 || cols == 0 || grid_len(rows, cols) != Some(points.len()) { - return None; - } - let smooth; - let handles = if handles.len() == points.len() { - handles - } else { - smooth = smooth_handles(rows, cols, points); - &smooth - }; - let points = points.iter().zip(handles).map(|(p, h)| MeshPoint { p: *p, color: Color::BLACK, opacity: 1.0, handles: *h }).collect(); - Some(GradientMesh { rows, cols, points }) -} - -/// The point of mesh `m` at (u, v) over the whole mesh (each patch an equal share; past the edges -/// the outer patches go on). -fn mesh_at(m: &GradientMesh, u: f64, v: f64) -> Point { - let (rows, cols) = (m.rows.max(1) as i64, m.cols.max(1) as i64); - let (su, sv) = (u * cols as f64, v * rows as f64); - let (c, r) = ((su.floor() as i64).clamp(0, cols - 1), (sv.floor() as i64).clamp(0, rows - 1)); - m.eval(r as usize, c as usize, su - c as f64, sv - r as f64) -} - -/// The envelope `id` is, or the innermost one it sits in. -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). -pub fn envelope_overlay(n: &Node) -> Option<(PathData, Option)> { - let NodeKind::Envelope { kind, .. } = &n.kind else { return None }; - match &**kind { - EnvelopeKind::Mesh { rows, cols, points, handles } => { - let grid = envelope_grid(*rows, *cols, points, handles)?; - Some((grid.lines(), Some(grid))) - } - EnvelopeKind::Warp { .. } => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)), - EnvelopeKind::TopObject { path } => Some((path.clone(), None)), - } -} - -/// 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. -pub fn envelope_frame(m: Affine) -> Affine { - let [a, b, c, d, _, _] = m.as_coeffs(); - if b.abs() < 1e-12 && c.abs() < 1e-12 && a > 0.0 && d > 0.0 { Affine::IDENTITY } else { m } -} - -/// An envelope's point map: content placed in the envelope's own frame maps, by its bounds there, -/// onto the unit square and from there onto the envelope's surface ([`surface_of`]). -pub struct EnvelopeMap<'a> { - src: Rect, - frame: Affine, - to_frame: Affine, - surface: Box Point + 'a>, -} - -impl<'a> EnvelopeMap<'a> { - /// The map of an envelope of `kind` around `content` with `frame`. `None` when the content - /// has no bounds. - pub fn new(content: &[Arc], kind: &'a EnvelopeKind, frame: Affine) -> Option { - let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY }; - let to_frame = frame.inverse(); - let src = if frame == Affine::IDENTITY { - nodes_bounds(content)? - } else { - content.iter().try_fold(None, |acc, c| { - let mut m = (**c).clone(); - m.transform(to_frame, false); - Some(vectorcraft_geom::union_opt(acc, m.geometric_bounds())) - })?? - }; - Some(Self { src, frame, to_frame, surface: surface_of(kind, src, frame) }) - } - - /// The map of envelope node `n` (`None` for other nodes). - pub fn of(n: &'a Node) -> Option { - match &n.kind { - NodeKind::Envelope { content, kind, frame, .. } => Self::new(content, kind, **frame), - _ => None, - } - } - - /// The content's bounds in the envelope's frame. - pub fn src(&self) -> Rect { - self.src - } - - /// The surface point at (u, v) ∈ [0,1]². - pub fn at(&self, u: f64, v: f64) -> Point { - (self.surface)(u, v) - } - - /// Where the envelope puts document point `p`. - pub fn map(&self, p: Point) -> Point { - let q = self.to_frame * p; - let (w, h) = (self.src.width().max(1e-9), self.src.height().max(1e-9)); - self.at((q.x - self.src.x0) / w, (q.y - self.src.y0) / h) - } - - /// A flat `(rows+1)×(cols+1)` grid over the content, in the envelope's frame (row-major). - pub fn grid(&self, rows: u32, cols: u32) -> Vec { - grid_points(self.src, rows, cols).into_iter().map(|p| self.frame * p).collect() - } - - /// The surface sampled on a `rows`×`cols` grid as a mesh whose handles follow it and whose - /// points are `color`: Release gives it back as the envelope's shape, Reset with Mesh starts - /// from it. - pub fn surface_mesh(&self, rows: u32, cols: u32, color: Color) -> GradientMesh { - GradientMesh::from_surface(rows, cols, &|u, v| self.at(u, v), &|_, _| color) - } - - /// The surface's bounds (sampled; a mesh's points and a top object's path bound it exactly). - fn bounds(&self) -> Option { - const N: usize = 16; - let mut r: Option = None; - for j in 0..=N { - for i in 0..=N { - let q = self.at(i as f64 / N as f64, j as f64 / N as f64); - r = Some(r.map_or(Rect::from_points(q, q), |r| r.union_pt(q))); - } - } - r - } -} - -/// Optional hook that converts nodes the pure evaluation can't map (text) to outlines. -pub type Outliner<'a> = Option<&'a dyn Fn(&Node) -> Option>; - -/// Distort Pattern Fills: the tiles pattern swatch `name` painted with placement `xf` lays over -/// `region` (see [`crate::PatternDef::instances_in`]); `None` without such a swatch. -pub type PatternTiles<'a> = &'a dyn Fn(&str, Affine, Rect) -> Option>; - -/// What live evaluation asks of the crates above this one (`vectorcraft-effects` supplies them). -#[derive(Clone, Copy, Default)] -pub struct Hooks<'a> { - /// Type as its glyph outlines, a symbol instance as its art (see [`Outliner`]). - pub outline: Outliner<'a>, - /// Distort Appearance: a path's strokes and geometry effects baked into filled art (`None` - /// when it has none to bake). - pub appearance: Outliner<'a>, - /// Distort Pattern Fills: the tiles a pattern fill lays (see [`PatternTiles`]). - pub pattern: Option>, -} - -impl<'a> From> for Hooks<'a> { - fn from(outline: Outliner<'a>) -> Self { - Self { outline, ..Default::default() } - } -} - -/// The affine map that best matches `f` near `p` (finite differences with step `eps`). -pub fn affine_near(f: &dyn Fn(Point) -> Point, p: Point, eps: f64) -> Affine { - let o = f(p); - let ex = (f(p + Vec2::new(eps, 0.0)) - f(p - Vec2::new(eps, 0.0))) / (2.0 * eps); - let ey = (f(p + Vec2::new(0.0, eps)) - f(p - Vec2::new(0.0, eps))) / (2.0 * eps); - let lin = Affine::new([ex.x, ex.y, ey.x, ey.y, 0.0, 0.0]); - Affine::translate(o.to_vec2()) * lin * Affine::translate(-p.to_vec2()) -} - -/// How deep hooks may nest art inside art (symbols in symbols, envelopes in envelopes) before -/// the rest is left as it is: a file can make a symbol contain itself. -const MAX_HOOK_DEPTH: u32 = 16; - -/// How an envelope pushes art through its point map. -#[derive(Clone, Copy)] -struct Warper<'a> { - f: &'a dyn Fn(Point) -> Point, - /// Longest piece a segment is cut into before mapping. - piece: f64, - /// Finite-difference step for the local affine maps gradients follow. - eps: f64, - /// Rows and columns of the pieces an image is cut into. - cells: usize, - hooks: Hooks<'a>, - options: EnvelopeOptions, - /// How many hooks the art being mapped came through. - depth: u32, -} - -impl Warper<'_> { - /// This warper one hook deeper (`None` past [`MAX_HOOK_DEPTH`]). - fn deeper(&self) -> Option { - (self.depth < MAX_HOOK_DEPTH).then_some(Self { depth: self.depth + 1, ..*self }) - } -} - -/// `to` (art standing in for `from`: its outlines, its art) with `from`'s name, transparency, -/// opacity mask and effects. -fn carry_look(from: &Node, mut to: Node) -> Node { - to.name = from.name.clone(); - to.opacity = from.opacity; - to.blend = from.blend; - to.isolate = from.isolate; - to.knockout = from.knockout; - to.knockout_shape = from.knockout_shape; - to.extras_mut().mask = from.extras().mask.clone(); - to.appearance.effects = from.appearance.effects.clone(); - to -} - -fn map_node(n: &Node, w: &Warper) -> Node { - let deeper = w.deeper(); - // Distort Appearance: strokes and geometry effects bend with the art. - if w.options.distort_appearance - && let Some(d) = &deeper - && let Some(o) = w.hooks.appearance.and_then(|h| h(n)) - { - return map_node(&o, d); - } - // Distort Pattern Fills: the tiles bend with the art (not the patterns inside them). - if w.options.patterns() - && let Some(d) = &deeper - && let Some(o) = w.hooks.pattern.and_then(|p| pattern_art(n, p)) - { - let inner = Warper { options: EnvelopeOptions { distort_pattern_fills: false, ..d.options }, ..*d }; - return map_node(&o, &inner); - } - let mut out = n.clone(); - // Distort Linear Gradients: the gradient vectors follow the warp where they sit. - if w.options.gradients() - && let Some(b) = n.geometric_bounds() - { - 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()) { - m.art = Arc::new(map_node(&m.art, w)); - } - match &mut out.kind { - NodeKind::Path { path, live, .. } => { - *path = map_nonlinear(path, w.piece, w.f); - *live = None; - } - NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { - for c in children.iter_mut() { - *c = Arc::new(map_node(c, w)); - } - } - NodeKind::Mesh(m) => m.map(w.f), - NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => { - if let Some(d) = &deeper { - return map_node(&expanded_group_hooks(n, w.hooks), d); - } - } - NodeKind::Text(_) | NodeKind::SymbolInstance { .. } => { - if let Some(d) = &deeper - && let Some(o) = w.hooks.outline.and_then(|h| h(n)) - { - return map_node(&carry_look(n, o), d); - } - } - NodeKind::Image(im) => { - let im = im.clone(); - return warp_image(&out, &im, w); - } - // Its art is plain, so it warps at this depth. - NodeKind::PlacedDocument(_) => return map_node(&expanded_group_hooks(n, w.hooks), w), - } - out -} - -/// The affine map taking triangle `s` to triangle `d` (`None` when `s` is degenerate). -fn affine_between(s: [Point; 3], d: [Point; 3]) -> Option { - let basis = |p: [Point; 3]| Affine::new([p[1].x - p[0].x, p[1].y - p[0].y, p[2].x - p[0].x, p[2].y - p[0].y, p[0].x, p[0].y]); - let bs = basis(s); - if bs.determinant().abs() < 1e-12 { - return None; - } - let a = basis(d) * bs.inverse(); - 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. Each piece reaches a little past its -/// edges (at most half a point) so neighbours overlap and no seams show. -fn warp_image(n: &Node, im: &ImageObject, w: &Warper) -> Node { - let k = w.cells.max(1); - 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)); - 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 }; - let c = Point::new((dt[0].x + dt[1].x + dt[2].x) / 3.0, (dt[0].y + dt[1].y + dt[2].y) / 3.0); - let grow = (dt[0].distance(dt[1]).max(dt[1].distance(dt[2])) * 0.02).min(0.5); - let tri: Vec = dt - .iter() - .map(|p| { - let v = *p - c; - let len = v.hypot(); - if len > 1e-12 { *p + v * (grow / len) } else { *p } - }) - .collect(); - let mut clip = Node::path(n.id, PathData::single(SubPath::polyline(&tri, true)), Appearance::default()); - if let NodeKind::Path { clipping, .. } = &mut clip.kind { - *clipping = true; - } - let image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() }))); - pieces.push(Arc::new(Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true }))); - } - } - } - let mut g = n.clone(); - g.kind = NodeKind::Group { children: pieces, clip: false }; - g -} - -/// Distort Pattern Fills: path or compound path `n` with each visible pattern fill turned into the -/// tiles it paints in a clip group shaped like `n` (with the fill's opacity and blend mode), its -/// other fills and strokes on copies of it, in paint order, under `n`'s transparency. `None` -/// without a pattern fill whose definition `pattern` finds. -fn pattern_art(n: &Node, tiles: PatternTiles) -> Option { - let (path, rule, _) = crate::blend::node_path(n)?; - let pattern_fill = |i: &AppearanceItem| matches!(i, AppearanceItem::Fill(f) if f.visible && matches!(f.paint, Paint::Pattern { .. })); - if !n.appearance.items.iter().any(pattern_fill) { - return None; - } - let bounds = path.bounds()?; - let def = |i: &AppearanceItem| match i { - AppearanceItem::Fill(f) if f.visible => match &f.paint { - Paint::Pattern { pattern: name, xf } => tiles(name, *xf, bounds).map(|t| (t, f.opacity, f.blend)), - _ => None, - }, - _ => None, - }; - let plain = |items: Vec| { - let mut p = Node { - appearance: Appearance { items, ..Default::default() }.into(), - opacity: 1.0, - blend: Default::default(), - isolate: false, - knockout: Default::default(), - knockout_shape: false, - name: None, - ..n.clone() - }; - p.extras_mut().mask = None; - Arc::new(p) - }; - let mut pieces = vec![]; - let mut rest = vec![]; - for i in &n.appearance.items { - let Some((tiles, opacity, blend)) = def(i) else { - rest.push(i.clone()); - continue; - }; - if !rest.is_empty() { - pieces.push(plain(std::mem::take(&mut rest))); - } - let mut clip = Node::path(n.id, path.clone(), Appearance::default()); - if let NodeKind::Path { clipping, rule: r, .. } = &mut clip.kind { - (*clipping, *r) = (true, rule); - } - let children = std::iter::once(clip).chain(tiles).map(Arc::new).collect(); - let mut g = Node::new(n.id, NodeKind::Group { children, clip: true }); - g.opacity = opacity; - g.blend = blend; - pieces.push(Arc::new(g)); - } - if !rest.is_empty() { - pieces.push(plain(rest)); - } - Some(Node { - kind: NodeKind::Group { children: pieces, clip: false }, - appearance: Appearance { effects: n.appearance.effects.clone(), ..Default::default() }.into(), - ..n.clone() - }) -} - -/// Evaluate an envelope of `kind` around `content` on the page axes with the options envelopes -/// had before Envelope Options (see [`expand_live_hooks`] for an envelope node). -pub fn envelope_expand(content: &[Arc], kind: &EnvelopeKind, fidelity: f64, outline: Outliner) -> Vec { - expand_envelope(content, kind, fidelity, EnvelopeOptions::default(), Affine::IDENTITY, outline.into()) -} - -/// An envelope's content pushed through its map: Fidelity sets how finely curves are cut (and -/// into how many pieces images are), the options what bends with the art. -fn expand_envelope(content: &[Arc], kind: &EnvelopeKind, fidelity: f64, options: EnvelopeOptions, frame: Affine, hooks: Hooks) -> Vec { - let Some(map) = EnvelopeMap::new(content, kind, frame) else { return content.iter().map(|c| (**c).clone()).collect() }; - let src = map.src(); - let fid = if fidelity.is_finite() { fidelity.clamp(0.0, 100.0) / 100.0 } else { 0.5 }; - let f = |p: Point| map.map(p); - let w = Warper { - f: &f, - piece: src.width().hypot(src.height()).max(1e-6) / (8.0 + fid * 56.0), - eps: (src.width().max(src.height()) * 0.05).max(0.5), - cells: (4.0 + fid * 12.0).round() as usize, - hooks, - options, - depth: 0, - }; - content.iter().map(|c| map_node(c, &w)).collect() -} - -/// Envelope bounds: a mesh's points, a top object's path, the warp's surface (sampled). -pub fn envelope_bounds(content: &[Arc], kind: &EnvelopeKind, frame: Affine) -> Option { - match kind { - EnvelopeKind::Mesh { rows, cols, points, handles } if !handles.is_empty() => envelope_grid(*rows, *cols, points, handles)?.outline().bounds(), - EnvelopeKind::Mesh { points, .. } => { - let first = *points.first()?; - Some(points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p))) - } - EnvelopeKind::TopObject { path } => path.bounds(), - EnvelopeKind::Warp { .. } => EnvelopeMap::new(content, kind, frame)?.bounds(), - } -} - -// ===================================================================================== -// Expansion -// ===================================================================================== - -/// Is this one of the live kinds? -pub fn is_live(n: &Node) -> bool { - matches!( - n.kind, - NodeKind::Blend { .. } - | NodeKind::Envelope { .. } - | NodeKind::Mesh(_) - | NodeKind::Repeat(_) - | NodeKind::PlacedDocument(_) - | NodeKind::Intertwine { .. } - ) -} - -/// Mesh tessellation as filled quad paths (no stroke), `n`×`n` per patch. -pub fn mesh_quad_nodes(m: &GradientMesh, n: usize) -> Vec { - m.quads(n) - .into_iter() - .map(|q| { - let mut ap = Appearance::default(); - let mut fl = FillLayer::new(Paint::solid(q.color)); - fl.opacity = q.opacity; - ap.items.push(AppearanceItem::Fill(fl)); - Node::path(NodeId(0), PathData::single(SubPath::polyline(&q.pts, true)), ap) - }) - .collect() -} - -/// One level of evaluation of a live object (non-live nodes return themselves). Blend steps and -/// envelope results may still contain live objects (e.g. a blend of two meshes). -pub fn expand_live(n: &Node) -> Vec { - expand_live_with(n, None) -} - -pub fn expand_live_with(n: &Node, outline: Outliner) -> Vec { - expand_live_hooks(n, outline.into()) -} - -/// [`expand_live_with`] with everything an envelope can ask of the crates above (see [`Hooks`]). -pub fn expand_live_hooks(n: &Node, hooks: Hooks) -> Vec { - match &n.kind { - NodeKind::Blend { children, spec } => blend_expand(children, spec), - NodeKind::Envelope { content, kind, fidelity, options, frame, .. } => expand_envelope(content, kind, *fidelity, *options, **frame, hooks), - NodeKind::Mesh(m) => mesh_quad_nodes(m, 8), - NodeKind::Repeat(r) => r.expand(), - NodeKind::PlacedDocument(p) => p.art(n), - NodeKind::Intertwine { children } => crate::intertwine::expand(children), - _ => vec![n.clone()], - } -} - -/// A live object evaluated into a plain group (keeping the object's id, name and transparency). -pub fn expanded_group(n: &Node, outline: Outliner) -> Node { - expanded_group_hooks(n, outline.into()) -} - -/// [`expanded_group`] with [`Hooks`]. -pub fn expanded_group_hooks(n: &Node, hooks: Hooks) -> Node { - let children = expand_live_hooks(n, hooks).into_iter().map(Arc::new).collect(); - let mut g = Node::new(n.id, NodeKind::Group { children, clip: false }); - g.name = n.name.clone(); - g.visible = n.visible; - g.locked = n.locked; - g.opacity = n.opacity; - g.blend = n.blend; - g.isolate = n.isolate; - g.knockout = n.knockout; - // Knocking out opaque blend steps changes nothing: don't make the outputs work for it. - if matches!(n.kind, NodeKind::Blend { .. }) && g.knockout == crate::Knockout::On && !crate::blend::knockout_shows(&g) { - g.knockout = crate::Knockout::Off; - } - g.knockout_shape = n.knockout_shape; - g.extras_mut().mask = n.extras().mask.clone(); - g -} - -/// Recursively replace every live object in `n` by plain geometry (for exporters). -pub fn expand_deep(n: &Node, outline: Outliner) -> Node { - expand_deep_hooks(n, outline.into()) -} - -/// [`expand_deep`] with [`Hooks`]. -pub fn expand_deep_hooks(n: &Node, hooks: Hooks) -> Node { - let mut out = if is_live(n) { expanded_group_hooks(n, hooks) } else { n.clone() }; - if let Some(ch) = out.children_mut() { - for c in ch.iter_mut() { - if subtree_has_live(c) { - *c = Arc::new(expand_deep_hooks(c, hooks)); - } - } - } - out -} - -/// Does `n` or any descendant need live evaluation? -pub fn subtree_has_live(n: &Node) -> bool { - let mut any = false; - n.walk(&mut |c| any |= is_live(c)); - any -} - -/// Largest stroke outset in a subtree (for visual bounds of envelopes). With `symbols`, the -/// outsets in the art of the symbols its instances show count too -/// ([`crate::symbols::ArtBox::reach`]), grown by [`crate::SymbolBoxes::brush_pad`]. In boxes made -/// by [`crate::SymbolBoxes::without_art_strokes`], the outsets in the art do not count, and the pad -/// does. -pub(crate) fn max_outset(nodes: &[Arc], symbols: Option<&crate::SymbolBoxes>) -> f64 { - let mut o = 0.0f64; - for n in nodes { - n.walk(&mut |c| { - o = o.max(c.appearance.outset()); - if let (Some(s), NodeKind::SymbolInstance { symbol, .. }) = (symbols, &c.kind) - && let Some(art) = s.art(symbol) - { - let reach = if s.art_strokes() { art.reach } else { 0.0 }; - o = o.max(reach + s.brush_pad(symbol)); - } - }); - } - o -} +mod blend_spec; +mod envelope; +mod expand; +mod mesh; +mod warp; + +pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, BlendSpec}; +#[cfg(test)] +use blend_spec::{blend_color_shift, blend_ramp}; +pub use envelope::{ + EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, envelope_bounds, envelope_expand, envelope_frame, + envelope_grid, envelope_mapper, envelope_of, envelope_overlay, smooth_handles, +}; +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, +}; +#[cfg(test)] +use mesh::grid_eval; +pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; +pub use warp::{WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, warp_point}; #[cfg(test)] mod tests { use super::*; + /// A bad Ramp or Shift in a file clamps (non-finite values take the default) instead of + /// failing the whole document. + #[test] + fn blend_easing_numbers_clamp_when_read() { + use serde::de::value::{Error, F64Deserializer}; + let spec: BlendSpec = serde_json::from_str(r#"{"ease":{"kind":"out","ramp":7.5},"colorShift":-900}"#).unwrap(); + assert_eq!((spec.ease.ramp, spec.color_shift), (1.0, -100.0)); + let spec: BlendSpec = serde_json::from_str(r#"{"ease":{"ramp":-3},"colorShift":250}"#).unwrap(); + assert_eq!((spec.ease.ramp, spec.color_shift), (0.0, 100.0)); + let spec: BlendSpec = serde_json::from_str(r#"{"ease":{"ramp":null},"colorShift":"NaN"}"#).unwrap(); + assert_eq!((spec.ease.ramp, spec.color_shift), (0.0, 0.0)); + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert_eq!(blend_ramp(F64Deserializer::::new(bad)).unwrap(), 0.0); + assert_eq!(blend_color_shift(F64Deserializer::::new(bad)).unwrap(), 0.0); + } + } + + /// #3578: a non-linear map within an anchor budget splits its segments into longer pieces, + /// down to one a segment, and matches the plain map where the budget leaves room. + #[test] + fn map_nonlinear_within_keeps_to_its_anchor_budget() { + let square = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); + let f = |p: Point| Point::new(p.x + (p.y / 10.0).sin(), p.y); + let full = map_nonlinear(&square, 1.0, f); + assert_eq!(full.anchor_count(), 4 * 64); + assert_eq!(map_nonlinear_within(&square, 1.0, 4 * 64, f), full); + // Every side takes the same pieces: of 400 / (max - 4) pt, so 12 a side for 50 anchors. + for (max, want) in [(0, 4), (4, 4), (5, 4), (50, 4 * 12), (255, 4 * 63)] { + assert_eq!(map_nonlinear_within(&square, 1.0, max, f).anchor_count(), want, "{max}"); + } + // Lengths that are not numbers stay one piece; with no room every segment is one piece. + assert_eq!(fit_piece(&[f64::NAN, 10.0], 1.0, 64, 5), 2.0); + assert_eq!(fit_piece(&[f64::INFINITY, 10.0], 1.0, 64, 0), f64::INFINITY); + assert_eq!(pieces(f64::INFINITY, f64::INFINITY, 64), 1); + assert_eq!(pieces(10.0, 1.0, 0), 1); + } + /// #1578: Arc bends in the box's real proportions. In half-width units (y scaled by the /// aspect), the top and bottom edges are concentric circles about the bend's centre, at their /// real distance from the centre line; an inner edge that would pass the centre stops there. diff --git a/crates/doc/src/live/blend_spec.rs b/crates/doc/src/live/blend_spec.rs new file mode 100644 index 0000000000..79c1290303 --- /dev/null +++ b/crates/doc/src/live/blend_spec.rs @@ -0,0 +1,157 @@ +use super::*; + +// ===================================================================================== +// Data +// ===================================================================================== + +/// Blend Options → Spacing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BlendSpacing { + /// Step count chosen from the colour difference (or the distance when colours match). + #[default] + SmoothColor, + /// Specified number of steps between each pair of key objects (1–1000). + Steps(u32), + /// Specified distance (pt) between the steps. + Distance(f64), +} + +/// Blend Options → Orientation. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BlendOrientation { + #[default] + AlignToPage, + AlignToPath, +} + +/// Distribution of blend steps, as offered by the Blend panel's Type menu. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BlendEaseType { + #[default] + In, + Out, + InOut, + OutIn, +} + +impl BlendEaseType { + pub fn id(self) -> &'static str { + match self { + Self::In => "easeIn", + Self::Out => "easeOut", + Self::InOut => "easeInOut", + Self::OutIn => "easeOutIn", + } + } +} + +/// Blend panel Type and Ramp. Ramp is a fraction from 0 (even) to 1. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct BlendEase { + #[serde(default)] + pub kind: BlendEaseType, + #[serde(default, deserialize_with = "blend_ramp")] + pub ramp: f64, +} + +impl BlendEase { + pub fn is_linear(&self) -> bool { + self.ramp <= 0.0 + } + + /// Only the default Type and Ramp can be omitted without losing a chosen Type at Ramp 0. + pub fn is_default(&self) -> bool { + self.kind == BlendEaseType::In && self.ramp == 0.0 + } + + /// A monotone polynomial distribution, blended with even spacing by Ramp. Public help + /// describes the four distributions, not their numeric curves; these curves are original. + pub fn apply(&self, u: f64) -> f64 { + let u = if u.is_finite() { u.clamp(0.0, 1.0) } else { 0.0 }; + let r = if self.ramp.is_finite() { self.ramp.clamp(0.0, 1.0) } else { 0.0 }; + let eased = match self.kind { + BlendEaseType::In => u * u, + BlendEaseType::Out => u * (2.0 - u), + BlendEaseType::InOut => u * u * (3.0 - 2.0 * u), + BlendEaseType::OutIn if u < 0.5 => 2.0 * u * (1.0 - u), + BlendEaseType::OutIn => 0.5 + 2.0 * (u - 0.5) * (u - 0.5), + }; + u + r * (eased - u) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct BlendSpec { + #[serde(default)] + pub spacing: BlendSpacing, + #[serde(default)] + pub orientation: BlendOrientation, + /// Acceleration of the steps' shapes and positions along the spine between two keys. + #[serde(default, skip_serializing_if = "BlendEase::is_default")] + pub ease: BlendEase, + /// Independent color acceleration. -100..100, with 0 preserving the even color ramp. + #[serde(default, rename = "colorShift", skip_serializing_if = "is_zero", deserialize_with = "blend_color_shift")] + pub color_shift: f64, + /// Replaced spine. `None` = the straight lines between the key objects' centres. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub spine: Option, + /// The anchor of the spine's first subpath each key object sits on (a spine edited on the + /// canvas: moving a key moves its anchor and the other way round). Empty: the keys spread + /// evenly along the spine by arc length (Replace Spine). + #[serde(default, rename = "keyAnchors", skip_serializing_if = "Vec::is_empty")] + pub key_anchors: Vec, + /// Per key object, the anchor of its first subpath the blend starts from (Blend tool clicks + /// on anchor points); `None`: chosen so closed shapes don't twist. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub starts: Vec>, +} + +impl BlendSpec { + /// The start anchor of key `i` (see [`Self::starts`]). + pub fn start(&self, i: usize) -> Option { + self.starts.get(i).copied().flatten().map(|a| a as usize) + } +} + +/// Blend Options set with no blend selected: what new blends start with. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct BlendDefaults { + #[serde(default)] + pub spacing: BlendSpacing, + #[serde(default)] + pub orientation: BlendOrientation, +} + +/// Reading a native file never fails over one bad blend number: out-of-range values clamp, +/// and anything that is not a finite number (NaN, null, text) becomes the default. The +/// commands still refuse such input (`ease_param`). +fn blend_number<'de, D: serde::Deserializer<'de>>(d: D, min: f64, max: f64) -> Result { + let v = serde_json::Value::deserialize(d)?; + Ok(v.as_f64().filter(|n| n.is_finite()).map_or(0.0, |n| n.clamp(min, max))) +} + +pub(super) fn blend_ramp<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + blend_number(d, 0.0, 1.0) +} + +pub(super) fn blend_color_shift<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + blend_number(d, -100.0, 100.0) +} + +/// Whether an optional stored color shift has its unchanged default. +fn is_zero(v: &f64) -> bool { + *v == 0.0 +} + +impl BlendSpec { + /// Shift the color transition independently of shape placement. The exponential curve is + /// original; the documented behavior specifies the direction, not numeric sample values. + pub fn color_position(&self, u: f64) -> f64 { + let u = if u.is_finite() { u.clamp(0.0, 1.0) } else { 0.0 }; + let shift = if self.color_shift.is_finite() { self.color_shift.clamp(-100.0, 100.0) } else { 0.0 }; + if shift == 0.0 { u } else { u.powf(2.0f64.powf(shift / 50.0)) } + } +} diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs new file mode 100644 index 0000000000..13d30cef0a --- /dev/null +++ b/crates/doc/src/live/envelope.rs @@ -0,0 +1,332 @@ +use super::expand::{Hooks, Outliner, Warper, map_node}; +use super::mesh::{GradientMesh, MeshPoint, grid_len, grid_points, nodes_bounds, surface_of}; +use super::*; + +/// How an envelope distorts its content. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "camelCase")] +pub enum EnvelopeKind { + /// One of the 15 warp styles (`arc`, `arcLower`, … — see [`WarpStyle::from_id`]); bend and + /// distortions in percent (-100..100). + Warp { + style: String, + #[serde(default)] + bend: f64, + #[serde(default)] + h: f64, + #[serde(default)] + v: f64, + #[serde(default = "yes")] + horizontal: bool, + }, + /// A `(rows+1)×(cols+1)` grid of points (row-major) the content's bounding box maps onto. + Mesh { + rows: u32, + cols: u32, + points: Vec, + /// Each point's bezier handles (offsets, see [`H_RIGHT`] …), row-major like `points`. + /// Empty: the smooth (Catmull-Rom) mesh through the points, as before handles existed; + /// editing the mesh's points or handles on the canvas fills them in. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + handles: Vec<[Vec2; 4]>, + }, + /// The content's bounding box maps onto the outline of this path. + TopObject { path: PathData }, +} + +/// Envelope Options → Preserve Shape Using: how a distorted raster keeps the envelope's shape. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum PreserveShape { + #[default] + ClippingMask, + Transparency, +} + +impl PreserveShape { + pub fn id(self) -> &'static str { + match self { + Self::ClippingMask => "clippingMask", + Self::Transparency => "transparency", + } + } + pub fn parse(s: &str) -> Option { + match s { + "clippingMask" => Some(Self::ClippingMask), + "transparency" => Some(Self::Transparency), + _ => None, + } + } +} + +/// Envelope Options besides Fidelity. `Default` is what envelopes saved before these options +/// existed do (their appearance applies after the distortion); new envelopes start from +/// [`EnvelopeOptions::NEW`], as in the reference app. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct EnvelopeOptions { + /// Rasters: Anti-Alias. + pub anti_alias: bool, + /// Rasters: Preserve Shape Using. + pub preserve_shape: PreserveShape, + /// Distort Appearance: strokes and live effects are applied before the distortion, so they + /// bend with the art (off: they apply to the distorted paths). + pub distort_appearance: bool, + /// Distort Linear Gradients (with Distort Appearance): placed gradients bend with the art. + pub distort_linear_gradients: bool, + /// Distort Pattern Fills (with Distort Appearance): pattern tiles bend with the art. + pub distort_pattern_fills: bool, +} + +impl Default for EnvelopeOptions { + fn default() -> Self { + Self { + anti_alias: true, + preserve_shape: PreserveShape::ClippingMask, + distort_appearance: false, + distort_linear_gradients: false, + distort_pattern_fills: false, + } + } +} + +impl EnvelopeOptions { + /// The options a new envelope gets (the reference app's defaults). + pub const NEW: Self = Self { + anti_alias: true, + preserve_shape: PreserveShape::ClippingMask, + distort_appearance: true, + distort_linear_gradients: false, + distort_pattern_fills: false, + }; + /// Do gradients bend with the art? + pub fn gradients(&self) -> bool { + self.distort_appearance && self.distort_linear_gradients + } + /// Do pattern tiles bend with the art? + pub fn patterns(&self) -> bool { + self.distort_appearance && self.distort_pattern_fills + } +} + +/// Handle slots of a [`MeshPoint`]: towards the next column, previous column, next row, previous row. +pub const H_RIGHT: usize = 0; + +pub const H_LEFT: usize = 1; + +pub const H_DOWN: usize = 2; + +pub const H_UP: usize = 3; + +/// The envelope's point map for content whose bounding box is `src` (page axes). +pub fn envelope_mapper<'a>(kind: &'a EnvelopeKind, src: Rect) -> Box Point + 'a> { + let s = surface_of(kind, src, Affine::IDENTITY); + let (w, h) = (src.width().max(1e-9), src.height().max(1e-9)); + Box::new(move |q: Point| s((q.x - src.x0) / w, (q.y - src.y0) / h)) +} + +/// Catmull-Rom tangents of a `(rows+1)×(cols+1)` point grid (row-major) as mesh handles, a third +/// of the tangent towards each neighbour (past the borders the grid goes on straight): the curves +/// an envelope mesh without handles of its own runs along between its points. +pub fn smooth_handles(rows: u32, cols: u32, points: &[Point]) -> Vec<[Vec2; 4]> { + let (rows, cols) = (rows as usize, cols as usize); + let at = |r: usize, c: usize| points.get(r * (cols + 1) + c).copied().unwrap_or_default(); + let tangent = |prev: Option, p: Point, next: Option| match (prev, next) { + (Some(a), Some(b)) => (b - a) / 2.0, + (None, Some(b)) => b - p, + (Some(a), None) => p - a, + (None, None) => Vec2::ZERO, + }; + let mut out = Vec::with_capacity(points.len()); + for r in 0..=rows { + for c in 0..=cols { + let p = at(r, c); + let du = tangent(c.checked_sub(1).map(|c| at(r, c)), p, (c < cols).then(|| at(r, c + 1))) / 3.0; + let dv = tangent(r.checked_sub(1).map(|r| at(r, c)), p, (r < rows).then(|| at(r + 1, c))) / 3.0; + // Handles pointing out of the grid are unused: they stay at the point. + let keep = |inside: bool, d: Vec2| if inside { d } else { Vec2::ZERO }; + let mut h = [Vec2::ZERO; 4]; + (h[H_RIGHT], h[H_LEFT], h[H_DOWN], h[H_UP]) = (keep(c < cols, du), keep(c > 0, -du), keep(r < rows, dv), keep(r > 0, -dv)); + out.push(h); + } + } + out +} + +/// A mesh envelope's grid (`rows`×`cols` patches, `points` and their `handles`; without handles +/// the smooth ones, see [`smooth_handles`]) as a gradient mesh with black points: what the +/// canvas draws and the Mesh tool and Direct Selection edit. `None` for a malformed grid. +pub fn envelope_grid(rows: u32, cols: u32, points: &[Point], handles: &[[Vec2; 4]]) -> Option { + if rows == 0 || cols == 0 || grid_len(rows, cols) != Some(points.len()) { + return None; + } + let smooth; + let handles = if handles.len() == points.len() { + handles + } else { + smooth = smooth_handles(rows, cols, points); + &smooth + }; + let points = points.iter().zip(handles).map(|(p, h)| MeshPoint { p: *p, color: Color::BLACK, opacity: 1.0, handles: *h }).collect(); + Some(GradientMesh { rows, cols, points }) +} + +/// The point of mesh `m` at (u, v) over the whole mesh (each patch an equal share; past the edges +/// the outer patches go on). +pub(super) fn mesh_at(m: &GradientMesh, u: f64, v: f64) -> Point { + let (rows, cols) = (m.rows.max(1) as i64, m.cols.max(1) as i64); + let (su, sv) = (u * cols as f64, v * rows as f64); + let (c, r) = ((su.floor() as i64).clamp(0, cols - 1), (sv.floor() as i64).clamp(0, rows - 1)); + m.eval(r as usize, c as usize, su - c as f64, sv - r as f64) +} + +/// The envelope `id` is, or the innermost one it sits in. +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). +pub fn envelope_overlay(n: &Node) -> Option<(PathData, Option)> { + let NodeKind::Envelope { kind, .. } = &n.kind else { return None }; + match &**kind { + EnvelopeKind::Mesh { rows, cols, points, handles } => { + let grid = envelope_grid(*rows, *cols, points, handles)?; + Some((grid.lines(), Some(grid))) + } + EnvelopeKind::Warp { .. } => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)), + EnvelopeKind::TopObject { path } => Some((path.clone(), None)), + } +} + +/// 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. +pub fn envelope_frame(m: Affine) -> Affine { + let [a, b, c, d, _, _] = m.as_coeffs(); + if b.abs() < 1e-12 && c.abs() < 1e-12 && a > 0.0 && d > 0.0 { Affine::IDENTITY } else { m } +} + +/// An envelope's point map: content placed in the envelope's own frame maps, by its bounds there, +/// onto the unit square and from there onto the envelope's surface ([`surface_of`]). +pub struct EnvelopeMap<'a> { + src: Rect, + frame: Affine, + to_frame: Affine, + surface: Box Point + 'a>, +} + +impl<'a> EnvelopeMap<'a> { + /// The map of an envelope of `kind` around `content` with `frame`. `None` when the content + /// has no bounds. + pub fn new(content: &[Arc], kind: &'a EnvelopeKind, frame: Affine) -> Option { + let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY }; + let to_frame = frame.inverse(); + let src = if frame == Affine::IDENTITY { + nodes_bounds(content)? + } else { + content.iter().try_fold(None, |acc, c| { + let mut m = (**c).clone(); + m.transform(to_frame, false); + Some(vectorcraft_geom::union_opt(acc, m.geometric_bounds())) + })?? + }; + Some(Self { src, frame, to_frame, surface: surface_of(kind, src, frame) }) + } + + /// The map of envelope node `n` (`None` for other nodes). + pub fn of(n: &'a Node) -> Option { + match &n.kind { + NodeKind::Envelope { content, kind, frame, .. } => Self::new(content, kind, **frame), + _ => None, + } + } + + /// The content's bounds in the envelope's frame. + pub fn src(&self) -> Rect { + self.src + } + + /// The surface point at (u, v) ∈ [0,1]². + pub fn at(&self, u: f64, v: f64) -> Point { + (self.surface)(u, v) + } + + /// Where the envelope puts document point `p`. + pub fn map(&self, p: Point) -> Point { + let q = self.to_frame * p; + let (w, h) = (self.src.width().max(1e-9), self.src.height().max(1e-9)); + self.at((q.x - self.src.x0) / w, (q.y - self.src.y0) / h) + } + + /// A flat `(rows+1)×(cols+1)` grid over the content, in the envelope's frame (row-major). + pub fn grid(&self, rows: u32, cols: u32) -> Vec { + grid_points(self.src, rows, cols).into_iter().map(|p| self.frame * p).collect() + } + + /// The surface sampled on a `rows`×`cols` grid as a mesh whose handles follow it and whose + /// points are `color`: Release gives it back as the envelope's shape, Reset with Mesh starts + /// from it. + pub fn surface_mesh(&self, rows: u32, cols: u32, color: Color) -> GradientMesh { + GradientMesh::from_surface(rows, cols, &|u, v| self.at(u, v), &|_, _| color) + } + + /// The surface's bounds (sampled; a mesh's points and a top object's path bound it exactly). + fn bounds(&self) -> Option { + const N: usize = 16; + let mut r: Option = None; + for j in 0..=N { + for i in 0..=N { + let q = self.at(i as f64 / N as f64, j as f64 / N as f64); + r = Some(r.map_or(Rect::from_points(q, q), |r| r.union_pt(q))); + } + } + r + } +} + +/// Evaluate an envelope of `kind` around `content` on the page axes with the options envelopes +/// had before Envelope Options (see [`expand_live_hooks`] for an envelope node). +pub fn envelope_expand(content: &[Arc], kind: &EnvelopeKind, fidelity: f64, outline: Outliner) -> Vec { + expand_envelope(content, kind, fidelity, EnvelopeOptions::default(), Affine::IDENTITY, outline.into()) +} + +/// An envelope's content pushed through its map: Fidelity sets how finely curves are cut (and +/// into how many pieces images are), the options what bends with the art. +pub(super) fn expand_envelope( + content: &[Arc], + kind: &EnvelopeKind, + fidelity: f64, + options: EnvelopeOptions, + frame: Affine, + hooks: Hooks, +) -> Vec { + let Some(map) = EnvelopeMap::new(content, kind, frame) else { return content.iter().map(|c| (**c).clone()).collect() }; + let src = map.src(); + let fid = if fidelity.is_finite() { fidelity.clamp(0.0, 100.0) / 100.0 } else { 0.5 }; + let f = |p: Point| map.map(p); + let w = Warper { + f: &f, + piece: src.width().hypot(src.height()).max(1e-6) / (8.0 + fid * 56.0), + eps: (src.width().max(src.height()) * 0.05).max(0.5), + cells: (4.0 + fid * 12.0).round() as usize, + hooks, + options, + depth: 0, + }; + content.iter().map(|c| map_node(c, &w)).collect() +} + +/// Envelope bounds: a mesh's points, a top object's path, the warp's surface (sampled). +pub fn envelope_bounds(content: &[Arc], kind: &EnvelopeKind, frame: Affine) -> Option { + match kind { + EnvelopeKind::Mesh { rows, cols, points, handles } if !handles.is_empty() => envelope_grid(*rows, *cols, points, handles)?.outline().bounds(), + EnvelopeKind::Mesh { points, .. } => { + let first = *points.first()?; + Some(points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p))) + } + EnvelopeKind::TopObject { path } => path.bounds(), + EnvelopeKind::Warp { .. } => EnvelopeMap::new(content, kind, frame)?.bounds(), + } +} diff --git a/crates/doc/src/live/expand.rs b/crates/doc/src/live/expand.rs new file mode 100644 index 0000000000..09eada113a --- /dev/null +++ b/crates/doc/src/live/expand.rs @@ -0,0 +1,444 @@ +use super::envelope::{EnvelopeOptions, expand_envelope}; +use super::mesh::GradientMesh; +use super::warp::map_nonlinear; +use super::*; + +/// Optional hook that converts nodes the pure evaluation can't map (text) to outlines. +pub type Outliner<'a> = Option<&'a dyn Fn(&Node) -> Option>; + +/// Distort Pattern Fills: the tiles pattern swatch `name` painted with placement `xf` lays over +/// `region` (see [`crate::PatternDef::instances_in`]); `None` without such a swatch. +pub type PatternTiles<'a> = &'a dyn Fn(&str, Affine, Rect) -> Option>; + +/// What live evaluation asks of the crates above this one (`vectorcraft-effects` supplies them). +#[derive(Clone, Copy, Default)] +pub struct Hooks<'a> { + /// Type as its glyph outlines, a symbol instance as its art (see [`Outliner`]). + pub outline: Outliner<'a>, + /// Distort Appearance: a path's strokes and geometry effects baked into filled art (`None` + /// when it has none to bake). + pub appearance: Outliner<'a>, + /// Distort Pattern Fills: the tiles a pattern fill lays (see [`PatternTiles`]). + pub pattern: Option>, + /// The document whose symbols' art counts toward the instance budget of a Repeat of their + /// instances ([`crate::RepeatSpec::expand`]). + pub symbols: Option<&'a crate::Document>, +} + +impl<'a> From> for Hooks<'a> { + fn from(outline: Outliner<'a>) -> Self { + Self { outline, ..Default::default() } + } +} + +/// The affine map that best matches `f` near `p` (finite differences with step `eps`). +pub fn affine_near(f: &dyn Fn(Point) -> Point, p: Point, eps: f64) -> Affine { + let o = f(p); + let ex = (f(p + Vec2::new(eps, 0.0)) - f(p - Vec2::new(eps, 0.0))) / (2.0 * eps); + let ey = (f(p + Vec2::new(0.0, eps)) - f(p - Vec2::new(0.0, eps))) / (2.0 * eps); + let lin = Affine::new([ex.x, ex.y, ey.x, ey.y, 0.0, 0.0]); + Affine::translate(o.to_vec2()) * lin * Affine::translate(-p.to_vec2()) +} + +/// How deep hooks may nest art inside art (symbols in symbols, envelopes in envelopes) before +/// the rest is left as it is: a file can make a symbol contain itself. +const MAX_HOOK_DEPTH: u32 = 16; + +/// How an envelope pushes art through its point map. +#[derive(Clone, Copy)] +pub(super) struct Warper<'a> { + pub(super) f: &'a dyn Fn(Point) -> Point, + /// Longest piece a segment is cut into before mapping. + pub(super) piece: f64, + /// Finite-difference step for the local affine maps gradients follow. + pub(super) eps: f64, + /// Rows and columns of the pieces an image is cut into. + pub(super) cells: usize, + pub(super) hooks: Hooks<'a>, + pub(super) options: EnvelopeOptions, + /// How many hooks the art being mapped came through. + pub(super) depth: u32, +} + +impl Warper<'_> { + /// This warper one hook deeper (`None` past [`MAX_HOOK_DEPTH`]). + fn deeper(&self) -> Option { + (self.depth < MAX_HOOK_DEPTH).then_some(Self { depth: self.depth + 1, ..*self }) + } +} + +/// `to` (art standing in for `from`: its outlines, its art) with `from`'s name, transparency, +/// opacity mask and effects. +fn carry_look(from: &Node, mut to: Node) -> Node { + to.name = from.name.clone(); + to.opacity = from.opacity; + to.blend = from.blend; + to.isolate = from.isolate; + to.knockout = from.knockout; + to.knockout_shape = from.knockout_shape; + to.extras_mut().mask = from.extras().mask.clone(); + to.appearance.effects = from.appearance.effects.clone(); + to +} + +pub(super) fn map_node(n: &Node, w: &Warper) -> Node { + let deeper = w.deeper(); + // Distort Appearance: strokes and geometry effects bend with the art. + if w.options.distort_appearance + && let Some(d) = &deeper + && let Some(o) = w.hooks.appearance.and_then(|h| h(n)) + { + return map_node(&o, d); + } + // Distort Pattern Fills: the tiles bend with the art (not the patterns inside them). + if w.options.patterns() + && let Some(d) = &deeper + && let Some(o) = w.hooks.pattern.and_then(|p| pattern_art(n, p)) + { + let inner = Warper { options: EnvelopeOptions { distort_pattern_fills: false, ..d.options }, ..*d }; + return map_node(&o, &inner); + } + let mut out = n.clone(); + // Distort Linear Gradients: the gradient vectors follow the warp where they sit. + if w.options.gradients() + && let Some(b) = n.geometric_bounds() + { + 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()) { + m.art = Arc::new(map_node(&m.art, w)); + } + match &mut out.kind { + NodeKind::Path { path, live, .. } => { + *path = map_nonlinear(path, w.piece, w.f); + *live = None; + } + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { + for c in children.iter_mut() { + *c = Arc::new(map_node(c, w)); + } + } + NodeKind::Mesh(m) => m.map(w.f), + NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => { + if let Some(d) = &deeper { + return map_node(&expanded_group_hooks(n, w.hooks), d); + } + } + NodeKind::Text(_) | NodeKind::SymbolInstance { .. } => { + if let Some(d) = &deeper + && let Some(o) = w.hooks.outline.and_then(|h| h(n)) + { + return map_node(&carry_look(n, o), d); + } + } + NodeKind::Image(im) => { + let im = im.clone(); + return warp_image(&out, &im, w); + } + // Its art is plain, so it warps at this depth. + NodeKind::PlacedDocument(_) => return map_node(&expanded_group_hooks(n, w.hooks), w), + } + out +} + +/// The affine map taking triangle `s` to triangle `d` (`None` when `s` is degenerate). +fn affine_between(s: [Point; 3], d: [Point; 3]) -> Option { + let basis = |p: [Point; 3]| Affine::new([p[1].x - p[0].x, p[1].y - p[0].y, p[2].x - p[0].x, p[2].y - p[0].y, p[0].x, p[0].y]); + let bs = basis(s); + if bs.determinant().abs() < 1e-12 { + return None; + } + let a = basis(d) * bs.inverse(); + 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. Each piece reaches a little past its +/// edges (at most half a point) so neighbours overlap and no seams show. +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)) { + let mut g = n.clone(); + g.kind = NodeKind::Group { children: vec![], clip: false }; + return g; + } + 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)); + 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 }; + let c = Point::new((dt[0].x + dt[1].x + dt[2].x) / 3.0, (dt[0].y + dt[1].y + dt[2].y) / 3.0); + let grow = (dt[0].distance(dt[1]).max(dt[1].distance(dt[2])) * 0.02).min(0.5); + let tri: Vec = dt + .iter() + .map(|p| { + let v = *p - c; + let len = v.hypot(); + if len > 1e-12 { *p + v * (grow / len) } else { *p } + }) + .collect(); + let mut clip = Node::path(n.id, PathData::single(SubPath::polyline(&tri, true)), Appearance::default()); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() }))); + pieces.push(Arc::new(Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true }))); + } + } + } + let mut g = n.clone(); + g.kind = NodeKind::Group { children: pieces, clip: false }; + g +} + +/// Distort Pattern Fills: path or compound path `n` with each visible pattern fill turned into the +/// tiles it paints in a clip group shaped like `n` (with the fill's opacity and blend mode), its +/// other fills and strokes on copies of it, in paint order, under `n`'s transparency. `None` +/// without a pattern fill whose definition `pattern` finds. +fn pattern_art(n: &Node, tiles: PatternTiles) -> Option { + let (path, rule, _) = crate::blend::node_path(n)?; + let pattern_fill = |i: &AppearanceItem| matches!(i, AppearanceItem::Fill(f) if f.visible && matches!(f.paint, Paint::Pattern { .. })); + if !n.appearance.items.iter().any(pattern_fill) { + return None; + } + let bounds = path.bounds()?; + let def = |i: &AppearanceItem| match i { + AppearanceItem::Fill(f) if f.visible => match &f.paint { + Paint::Pattern { pattern: name, xf } => tiles(name, *xf, bounds).map(|t| (t, f.opacity, f.blend)), + _ => None, + }, + _ => None, + }; + let plain = |items: Vec| { + let mut p = Node { + appearance: Appearance { items, ..Default::default() }.into(), + opacity: 1.0, + blend: Default::default(), + isolate: false, + knockout: Default::default(), + knockout_shape: false, + name: None, + ..n.clone() + }; + p.extras_mut().mask = None; + Arc::new(p) + }; + let mut pieces = vec![]; + let mut rest = vec![]; + for i in &n.appearance.items { + let Some((tiles, opacity, blend)) = def(i) else { + rest.push(i.clone()); + continue; + }; + if !rest.is_empty() { + pieces.push(plain(std::mem::take(&mut rest))); + } + let mut clip = Node::path(n.id, path.clone(), Appearance::default()); + if let NodeKind::Path { clipping, rule: r, .. } = &mut clip.kind { + (*clipping, *r) = (true, rule); + } + let children = std::iter::once(clip).chain(tiles).map(Arc::new).collect(); + let mut g = Node::new(n.id, NodeKind::Group { children, clip: true }); + g.opacity = opacity; + g.blend = blend; + pieces.push(Arc::new(g)); + } + if !rest.is_empty() { + pieces.push(plain(rest)); + } + Some(Node { + kind: NodeKind::Group { children: pieces, clip: false }, + appearance: Appearance { effects: n.appearance.effects.clone(), ..Default::default() }.into(), + ..n.clone() + }) +} + +// ===================================================================================== +// Expansion +// ===================================================================================== + +/// Is this one of the live kinds? +pub fn is_live(n: &Node) -> bool { + matches!( + n.kind, + NodeKind::Blend { .. } + | NodeKind::Envelope { .. } + | NodeKind::Mesh(_) + | NodeKind::Repeat(_) + | NodeKind::PlacedDocument(_) + | NodeKind::Intertwine { .. } + ) +} + +/// Mesh tessellation as filled quad paths (no stroke), `n`×`n` per patch. +pub fn mesh_quad_nodes(m: &GradientMesh, n: usize) -> Vec { + m.quads(n) + .into_iter() + .map(|q| { + let mut ap = Appearance::default(); + let mut fl = FillLayer::new(Paint::solid(q.color)); + fl.opacity = q.opacity; + ap.items.push(AppearanceItem::Fill(fl)); + Node::path(NodeId(0), PathData::single(SubPath::polyline(&q.pts, true)), ap) + }) + .collect() +} + +/// One level of evaluation of a live object (non-live nodes return themselves). Blend steps and +/// envelope results may still contain live objects (e.g. a blend of two meshes). +pub fn expand_live(n: &Node) -> Vec { + expand_live_with(n, None) +} + +pub fn expand_live_with(n: &Node, outline: Outliner) -> Vec { + expand_live_hooks(n, outline.into()) +} + +/// [`expand_live_with`] with everything an envelope can ask of the crates above (see [`Hooks`]). +pub fn expand_live_hooks(n: &Node, hooks: Hooks) -> Vec { + let _generating = Generating::enter(); + match &n.kind { + NodeKind::Blend { children, spec } => blend_expand(children, spec), + NodeKind::Envelope { content, kind, fidelity, options, frame, .. } => expand_envelope(content, kind, *fidelity, *options, **frame, hooks), + NodeKind::Mesh(m) => mesh_quad_nodes(m, 8), + NodeKind::Repeat(r) => r.expand(hooks.symbols), + NodeKind::PlacedDocument(p) => p.art(n), + NodeKind::Intertwine { children } => crate::intertwine::expand(children), + _ => vec![n.clone()], + } +} + +/// A live object evaluated into a plain group (keeping the object's id, name and transparency). +pub fn expanded_group(n: &Node, outline: Outliner) -> Node { + expanded_group_hooks(n, outline.into()) +} + +/// [`expanded_group`] with [`Hooks`]. +pub fn expanded_group_hooks(n: &Node, hooks: Hooks) -> Node { + let _generating = Generating::enter(); + let children = expand_live_hooks(n, hooks).into_iter().map(Arc::new).collect(); + let mut g = Node::new(n.id, NodeKind::Group { children, clip: false }); + g.name = n.name.clone(); + g.visible = n.visible; + g.locked = n.locked; + g.opacity = n.opacity; + g.blend = n.blend; + g.isolate = n.isolate; + g.knockout = n.knockout; + // Knocking out opaque blend steps changes nothing: don't make the outputs work for it. + if matches!(n.kind, NodeKind::Blend { .. }) && g.knockout == crate::Knockout::On && !crate::blend::knockout_shows(&g) { + g.knockout = crate::Knockout::Off; + } + g.knockout_shape = n.knockout_shape; + g.extras_mut().mask = n.extras().mask.clone(); + g +} + +/// Recursively replace every live object in `n` by plain geometry (for exporters). +pub fn expand_deep(n: &Node, outline: Outliner) -> Node { + expand_deep_hooks(n, outline.into()) +} + +/// [`expand_deep`] with [`Hooks`]. The objects live art makes here count against one +/// [`MAX_GENERATED`] ([`Generating`]): blends of blends kept their inner blends live, and each +/// copy expanded on its own, so step counts capped one by one multiplied. Past it, live art +/// expands to nothing. +pub fn expand_deep_hooks(n: &Node, hooks: Hooks) -> Node { + let _generating = Generating::enter(); + let mut out = if is_live(n) { + let g = expanded_group_hooks(n, hooks); + if !Generating::charge(g.count()) { + return Node::new(n.id, NodeKind::Group { children: vec![], clip: false }); + } + g + } else { + n.clone() + }; + if let Some(ch) = out.children_mut() { + for c in ch.iter_mut() { + if subtree_has_live(c) { + *c = Arc::new(expand_deep_hooks(c, hooks)); + } + } + } + out +} + +/// Most objects one evaluation of live art (an expansion, an envelope's mapping and everything +/// inside them) may make. +pub const MAX_GENERATED: usize = 4_000_000; + +std::thread_local! { + /// What is left of [`MAX_GENERATED`] for the evaluation running on this thread; `None` outside + /// one. + static GENERATED_LEFT: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// The outermost live evaluation on this thread: it starts [`GENERATED_LEFT`] and ends it. +struct Generating(bool); + +impl Generating { + fn enter() -> Self { + let outermost = GENERATED_LEFT.get().is_none(); + if outermost { + GENERATED_LEFT.set(Some(MAX_GENERATED)); + } + Self(outermost) + } + + /// Spend `n` objects; `false` (and nothing left) when there aren't that many. + fn charge(n: usize) -> bool { + match GENERATED_LEFT.get() { + None => true, + Some(left) => { + GENERATED_LEFT.set(Some(left.saturating_sub(n))); + n <= left + } + } + } +} + +impl Drop for Generating { + fn drop(&mut self) { + if self.0 { + GENERATED_LEFT.set(None); + } + } +} + +/// Does `n` or any descendant need live evaluation? +pub fn subtree_has_live(n: &Node) -> bool { + let mut any = false; + n.walk(&mut |c| any |= is_live(c)); + any +} + +/// Largest stroke outset in a subtree (for visual bounds of envelopes). With `symbols`, the +/// outsets in the art of the symbols its instances show count too +/// ([`crate::symbols::ArtBox::reach`]), grown by [`crate::SymbolBoxes::brush_pad`]. In boxes made +/// by [`crate::SymbolBoxes::without_art_strokes`], the outsets in the art do not count, and the pad +/// does. +pub(crate) fn max_outset(nodes: &[Arc], symbols: Option<&crate::SymbolBoxes>) -> f64 { + let mut o = 0.0f64; + for n in nodes { + n.walk(&mut |c| { + o = o.max(c.appearance.outset()); + if let (Some(s), NodeKind::SymbolInstance { symbol, .. }) = (symbols, &c.kind) + && let Some(art) = s.art(symbol) + { + let reach = if s.art_strokes() { art.reach } else { 0.0 }; + o = o.max(reach + s.brush_pad(symbol)); + } + }); + } + o +} diff --git a/crates/doc/src/live/mesh.rs b/crates/doc/src/live/mesh.rs new file mode 100644 index 0000000000..2cbe7602c4 --- /dev/null +++ b/crates/doc/src/live/mesh.rs @@ -0,0 +1,761 @@ +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::*; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct MeshPoint { + pub p: Point, + pub color: Color, + #[serde(default = "one")] + pub opacity: f32, + /// Tangent handles as offsets from `p` (see [`H_RIGHT`] …). + #[serde(default)] + pub handles: [Vec2; 4], +} + +/// A gradient mesh: `(rows+1)×(cols+1)` points, row-major. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct GradientMesh { + pub rows: u32, + pub cols: u32, + pub points: Vec, +} + +/// One tessellated piece of a mesh: a small quad, its colour at the centre, and its colour and +/// opacity at each corner (in `pts` order), which a renderer shades between so neighbouring quads +/// meet without a step. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeshQuad { + pub pts: [Point; 4], + pub color: Color, + pub opacity: f32, + pub corners: [(Color, f32); 4], +} + +/// Create Gradient Mesh → Appearance. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum MeshAppearance { + #[default] + Flat, + ToCenter, + ToEdge, +} + +impl MeshAppearance { + pub fn parse(s: &str) -> Option { + match s.to_ascii_lowercase().as_str() { + "flat" => Some(Self::Flat), + "center" | "tocenter" | "to center" => Some(Self::ToCenter), + "edge" | "toedge" | "to edge" => Some(Self::ToEdge), + _ => None, + } + } +} + +/// Default envelope fidelity. +pub fn default_fidelity() -> f64 { + fifty() +} + +const SIDE: usize = 65; + +/// Four boundary curves (top TL→TR, right TR→BR, bottom BL→BR, left TL→BL), each resampled to +/// [`SIDE`] points, from the outline of a closed path split at the points nearest its bounding +/// box corners. +#[derive(Clone, Debug)] +pub struct Coons { + top: Vec, + right: Vec, + bottom: Vec, + left: Vec, +} + +impl Coons { + /// A rectangle. + pub fn rect(r: Rect) -> Self { + let line = |a: Point, b: Point| (0..SIDE).map(|i| a.lerp(b, i as f64 / (SIDE - 1) as f64)).collect::>(); + let (tl, tr, br, bl) = (Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)); + Self { top: line(tl, tr), right: line(tr, br), bottom: line(bl, br), left: line(tl, bl) } + } + + pub fn from_path(path: &PathData) -> Option { + // The largest subpath is the outline. + let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?; + let r = path.bounds()?; + let tol = (r.width() + r.height()).max(1e-6) / 2000.0; + let mut poly = flatten_subpath(sp, tol); + if poly.len() > 1 + && let (Some(a), Some(b)) = (poly.first(), poly.last()) + && a.distance(*b) < 1e-9 + { + poly.pop(); + } + if poly.len() < 3 { + return Some(Self::rect(r)); + } + // Orient clockwise in y-down (TL → TR → BR → BL). + let area: f64 = (0..poly.len()) + .map(|i| { + let (p, q) = (poly[i], poly[(i + 1) % poly.len()]); + p.x * q.y - q.x * p.y + }) + .sum(); + if area < 0.0 { + poly.reverse(); + } + let nearest = |c: Point| (0..poly.len()).min_by(|i, j| poly[*i].distance_squared(c).total_cmp(&poly[*j].distance_squared(c))).unwrap_or(0); + let tl = nearest(Point::new(r.x0, r.y0)); + let tr = nearest(Point::new(r.x1, r.y0)); + let br = nearest(Point::new(r.x1, r.y1)); + let bl = nearest(Point::new(r.x0, r.y1)); + let n = poly.len(); + let arc = |i: usize, j: usize| -> Vec { + let mut v = vec![poly[i]]; + let mut k = i; + while k != j { + k = (k + 1) % n; + v.push(poly[k]); + } + v + }; + let top = resample(&arc(tl, tr), SIDE); + let right = resample(&arc(tr, br), SIDE); + let mut bottom = resample(&arc(br, bl), SIDE); + bottom.reverse(); + let mut left = resample(&arc(bl, tl), SIDE); + left.reverse(); + Some(Self { top, right, bottom, left }) + } + + /// The point at `u` along a side; past its ends the end segments go on straight (art an + /// envelope bends can reach past the content's box: outlined strokes). + fn sample(side: &[Point], u: f64) -> Point { + let s = u * (side.len() - 1) as f64; + let i = (s.floor().max(0.0) as usize).min(side.len() - 2); + side[i].lerp(side[i + 1], s - i as f64) + } + + /// The surface point at (u, v) ∈ [0,1]². + pub fn eval(&self, u: f64, v: f64) -> Point { + let (t, b, l, r) = (Self::sample(&self.top, u), Self::sample(&self.bottom, u), Self::sample(&self.left, v), Self::sample(&self.right, v)); + let (p00, p10, p01, p11) = (self.top[0], self.top[SIDE - 1], self.bottom[0], self.bottom[SIDE - 1]); + let c = (1.0 - v) * t.to_vec2() + v * b.to_vec2() + (1.0 - u) * l.to_vec2() + u * r.to_vec2() + - ((1.0 - u) * (1.0 - v) * p00.to_vec2() + u * (1.0 - v) * p10.to_vec2() + (1.0 - u) * v * p01.to_vec2() + u * v * p11.to_vec2()); + c.to_point() + } + + /// The four corners TL, TR, BR, BL. + pub fn corners(&self) -> [Point; 4] { + [self.top[0], self.top[SIDE - 1], self.bottom[SIDE - 1], self.bottom[0]] + } +} + +// ===================================================================================== +// Gradient meshes +// ===================================================================================== + +/// `0, 1/n, …, 1` for `n` (clamped to 1..=200) even steps. +fn even_steps(n: u32) -> Vec { + let n = n.clamp(1, 200); + (0..=n).map(|i| i as f64 / n as f64).collect() +} + +/// The number of points of a `(rows+1)×(cols+1)` grid, `None` past `usize`: counts come from +/// files, and u32::MAX rows and columns (65,535 on 32-bit targets) would wrap to an empty grid. +pub(super) fn grid_len(rows: u32, cols: u32) -> Option { + (rows as usize).checked_add(1)?.checked_mul((cols as usize).checked_add(1)?) +} + +impl GradientMesh { + pub fn idx(&self, r: usize, c: usize) -> usize { + r * (self.cols as usize + 1) + c + } + pub fn is_valid(&self) -> bool { + self.rows >= 1 && self.cols >= 1 && grid_len(self.rows, self.cols) == Some(self.points.len()) + } + + /// A 1×1 mesh from its four corners (bottom-left, top-left, top-right, bottom-right in u/v + /// order: row 0 is v = 0, columns follow u), each with its handles ([`H_RIGHT`] …). + fn patch(corners: [(Point, [Vec2; 4], Color); 4]) -> Self { + let point = |(p, handles, color): (Point, [Vec2; 4], Color)| MeshPoint { p, color, opacity: 1.0, handles }; + let [a, b, c, d] = corners; + Self { rows: 1, cols: 1, points: vec![point(a), point(d), point(b), point(c)] } + } + + /// A 1×1 mesh from a Coons patch's twelve boundary points (in the order PDF and PostScript + /// shadings list them: v runs cp0 → cp3 along cp1 and cp2, u runs cp0 → cp9 along cp11 and + /// cp10) and its corner colours (at cp0, cp3, cp6, cp9); `None` if a point isn't finite. + pub fn coons(cp: &[Point; 12], colors: [Color; 4]) -> Option { + if !cp.iter().all(|p| p.is_finite()) { + return None; + } + let h = |a: usize, b: usize| cp[b] - cp[a]; + let handles = |right: Vec2, left: Vec2, down: Vec2, up: Vec2| { + let mut h = [Vec2::ZERO; 4]; + (h[H_RIGHT], h[H_LEFT], h[H_DOWN], h[H_UP]) = (right, left, down, up); + h + }; + let [c0, c1, c2, c3] = colors; + Some(Self::patch([ + (cp[0], handles(h(0, 11), Vec2::ZERO, h(0, 1), Vec2::ZERO), c0), + (cp[3], handles(h(3, 4), Vec2::ZERO, Vec2::ZERO, h(3, 2)), c1), + (cp[6], handles(Vec2::ZERO, h(6, 5), Vec2::ZERO, h(6, 7)), c2), + (cp[9], handles(Vec2::ZERO, h(9, 10), h(9, 8), Vec2::ZERO), c3), + ])) + } + + /// A 1×1 mesh of a Gouraud-shaded triangle (a patch with two corners together); `None` if a + /// point isn't finite. + pub fn triangle(corners: [(Point, Color); 3]) -> Option { + if !corners.iter().all(|(p, _)| p.is_finite()) { + return None; + } + let [a, b, c] = corners.map(|(p, color)| (p, [Vec2::ZERO; 4], color)); + Some(Self::patch([a, b, c, c])) + } + + /// A mesh over surface `s` (u, v ∈ [0,1]) with handles from its partial derivatives. + pub fn from_surface(rows: u32, cols: u32, s: &dyn Fn(f64, f64) -> Point, color: &dyn Fn(f64, f64) -> Color) -> Self { + let (us, vs) = (even_steps(cols), even_steps(rows)); + Self::from_grid(&us, &vs, s, &|r, c, _| (color(us[c], vs[r]), 1.0)) + } + + /// A mesh over surface `s` (u, v ∈ [0,1]) whose column lines sit at `us` and row lines at `vs` + /// (ascending, at least two each; equal neighbours make a patch of no width, a sharp colour + /// change), with handles from its partial derivatives. `color(row, col, point)` gives each + /// point its colour and opacity. + pub fn from_grid(us: &[f64], vs: &[f64], s: &dyn Fn(f64, f64) -> Point, color: &dyn Fn(usize, usize, Point) -> (Color, f32)) -> Self { + let (rows, cols) = (vs.len().saturating_sub(1), us.len().saturating_sub(1)); + let eps = 1e-3; + let mut points = Vec::with_capacity(us.len() * vs.len()); + for (r, &v) in vs.iter().enumerate() { + for (c, &u) in us.iter().enumerate() { + let p = s(u, v); + let d_u = (s((u + eps).min(1.0), v) - s((u - eps).max(0.0), v)) / ((u + eps).min(1.0) - (u - eps).max(0.0)); + let d_v = (s(u, (v + eps).min(1.0)) - s(u, (v - eps).max(0.0))) / ((v + eps).min(1.0) - (v - eps).max(0.0)); + // A third of the way to the neighbouring line along the tangent; outward handles on + // the border are unused, so they stay at the point. + let h = |d: Vec2, from: f64, to: Option<&f64>| to.map_or(Vec2::ZERO, |to| d * ((to - from) / 3.0)); + let handles = [ + h(d_u, u, us.get(c + 1)), + h(d_u, u, c.checked_sub(1).map(|i| &us[i])), + h(d_v, v, vs.get(r + 1)), + h(d_v, v, r.checked_sub(1).map(|i| &vs[i])), + ]; + let (color, opacity) = color(r, c, p); + points.push(MeshPoint { p, color, opacity, handles }); + } + } + Self { rows: rows as u32, cols: cols as u32, points } + } + + /// Create Gradient Mesh for a path: the outline split at its corners, coloured per `appearance`. + pub fn for_path(path: &PathData, rows: u32, cols: u32, base: Color, appearance: MeshAppearance, highlight: f64) -> Option { + let mut m = Self::for_path_with(path, rows, cols, &|_| (base, 1.0))?; + m.highlight(appearance, highlight); + Some(m) + } + + /// Create Gradient Mesh for a path: the outline split at its corners, each point taking the + /// colour and opacity `color_at` gives at its position (a gradient fill's, say). + pub fn for_path_with(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option { + let coons = Coons::from_path(path)?; + Some(Self::from_grid(&even_steps(cols), &even_steps(rows), &|u, v| coons.eval(u, v), &|_, _, p| color_at(p))) + } + + /// Create Gradient Mesh → Appearance: lighten the points towards white, to the centre or to + /// the edges, by at most `highlight` %. + pub fn highlight(&mut self, appearance: MeshAppearance, highlight: f64) { + let h = (highlight / 100.0).clamp(0.0, 1.0) as f32; + let (rows, cols) = (self.rows as usize, self.cols as usize); + for r in 0..=rows { + for c in 0..=cols { + let (u, v) = (c as f64 / cols as f64, r as f64 / rows as f64); + let d = ((u - 0.5).abs().max((v - 0.5).abs()) * 2.0) as f32; // 0 centre … 1 edge + let w = match appearance { + MeshAppearance::Flat => 0.0, + MeshAppearance::ToCenter => (1.0 - d) * h, + MeshAppearance::ToEdge => d * h, + }; + if w > 0.0 { + let i = self.idx(r, c); + self.points[i].color = lerp_color(&self.points[i].color, &Color::WHITE, w); + } + } + } + } + + /// Horizontal edge from (r, c) to (r, c+1). + pub fn edge_u(&self, r: usize, c: usize) -> CubicBez { + let (a, b) = (&self.points[self.idx(r, c)], &self.points[self.idx(r, c + 1)]); + CubicBez::new(a.p, a.p + a.handles[H_RIGHT], b.p + b.handles[H_LEFT], b.p) + } + /// Vertical edge from (r, c) to (r+1, c). + pub fn edge_v(&self, r: usize, c: usize) -> CubicBez { + let (a, b) = (&self.points[self.idx(r, c)], &self.points[self.idx(r + 1, c)]); + CubicBez::new(a.p, a.p + a.handles[H_DOWN], b.p + b.handles[H_UP], b.p) + } + + /// Coons patch point of patch (r, c) at local (u, v). + pub fn eval(&self, r: usize, c: usize, u: f64, v: f64) -> Point { + let (t, b) = (self.edge_u(r, c).eval(u), self.edge_u(r + 1, c).eval(u)); + let (l, rr) = (self.edge_v(r, c).eval(v), self.edge_v(r, c + 1).eval(v)); + let p00 = self.points[self.idx(r, c)].p.to_vec2(); + let p10 = self.points[self.idx(r, c + 1)].p.to_vec2(); + let p01 = self.points[self.idx(r + 1, c)].p.to_vec2(); + let p11 = self.points[self.idx(r + 1, c + 1)].p.to_vec2(); + ((1.0 - v) * t.to_vec2() + v * b.to_vec2() + (1.0 - u) * l.to_vec2() + u * rr.to_vec2() + - ((1.0 - u) * (1.0 - v) * p00 + u * (1.0 - v) * p10 + (1.0 - u) * v * p01 + u * v * p11)) + .to_point() + } + + /// Bilinear colour and opacity of patch (r, c) at local (u, v). Corners all in CMYK (or all + /// grey) mix in that space, as a PDF shading mixes in its own colour space: the inks come out + /// exact, and a CMYK document separates no colour to draw them. Other corners mix in RGB. + pub fn color_at(&self, r: usize, c: usize, u: f64, v: f64) -> (Color, f32) { + let q = + [&self.points[self.idx(r, c)], &self.points[self.idx(r, c + 1)], &self.points[self.idx(r + 1, c)], &self.points[self.idx(r + 1, c + 1)]]; + let w = [(1.0 - u) * (1.0 - v), u * (1.0 - v), (1.0 - u) * v, u * v]; + let op = q.iter().zip(w).map(|(p, w)| p.opacity * w as f32).sum(); + let cmyk: Option> = + q.iter().map(|p| if let Color::Cmyk { c, m, y, k } = p.color { Some([c, m, y, k]) } else { None }).collect(); + if let Some(inks) = cmyk { + let mut mix = [0.0f32; 4]; + for (ink, w) in inks.iter().zip(w) { + for (m, x) in mix.iter_mut().zip(ink) { + *m += x * w as f32; + } + } + let [c, m, y, k] = mix; + return (Color::Cmyk { c, m, y, k }, op); + } + let grey: Option> = q.iter().map(|p| if let Color::Gray { k } = p.color { Some(k) } else { None }).collect(); + if let Some(ks) = grey { + return (Color::Gray { k: ks.iter().zip(w).map(|(k, w)| k * w as f32).sum() }, op); + } + let mut rgb = [0.0f32; 3]; + for (p, w) in q.iter().zip(w) { + for (ch, x) in rgb.iter_mut().zip(p.color.to_rgb()) { + *ch += x * w as f32; + } + } + (Color::rgb(rgb[0], rgb[1], rgb[2]), op) + } + + /// Tessellate into `n`×`n` quads per patch, each coloured at its centre and its corners. + pub fn quads(&self, n: usize) -> Vec { + if !self.is_valid() { + return vec![]; + } + let n = n.clamp(1, 64); + let mut out = Vec::with_capacity(self.rows as usize * self.cols as usize * n * n); + let mut grid = vec![Point::ZERO; (n + 1) * (n + 1)]; + let mut colors = vec![(Color::default(), 0.0f32); (n + 1) * (n + 1)]; + for r in 0..self.rows as usize { + for c in 0..self.cols as usize { + for j in 0..=n { + for i in 0..=n { + let (u, v) = (i as f64 / n as f64, j as f64 / n as f64); + grid[j * (n + 1) + i] = self.eval(r, c, u, v); + colors[j * (n + 1) + i] = self.color_at(r, c, u, v); + } + } + for j in 0..n { + for i in 0..n { + let (color, opacity) = self.color_at(r, c, (i as f64 + 0.5) / n as f64, (j as f64 + 0.5) / n as f64); + let g = |a: usize, b: usize| grid[b * (n + 1) + a]; + let k = |a: usize, b: usize| colors[b * (n + 1) + a]; + out.push(MeshQuad { + pts: [g(i, j), g(i + 1, j), g(i + 1, j + 1), g(i, j + 1)], + color, + opacity, + corners: [k(i, j), k(i + 1, j), k(i + 1, j + 1), k(i, j + 1)], + }); + } + } + } + } + out + } + + /// The mesh's outer boundary as a closed path. + pub fn outline(&self) -> PathData { + if !self.is_valid() { + return PathData::default(); + } + let (rows, cols) = (self.rows as usize, self.cols as usize); + let mut segs: Vec = vec![]; + for c in 0..cols { + segs.push(self.edge_u(0, c)); + } + for r in 0..rows { + segs.push(self.edge_v(r, cols)); + } + for c in (0..cols).rev() { + let e = self.edge_u(rows, c); + segs.push(CubicBez::new(e.p3, e.p2, e.p1, e.p0)); + } + for r in (0..rows).rev() { + let e = self.edge_v(r, 0); + segs.push(CubicBez::new(e.p3, e.p2, e.p1, e.p0)); + } + let mut anchors: Vec = Vec::with_capacity(segs.len()); + for (i, s) in segs.iter().enumerate() { + let prev = &segs[(i + segs.len() - 1) % segs.len()]; + anchors.push(Anchor::with_handles(s.p0, prev.p2, s.p1)); + } + PathData::single(SubPath::new(anchors, true)) + } + + /// Mesh lines (all row and column edges) as open paths, for outline view and editing overlays. + pub fn lines(&self) -> PathData { + if !self.is_valid() { + return PathData::default(); + } + let (rows, cols) = (self.rows as usize, self.cols as usize); + let mut subs = vec![]; + let cub = |e: CubicBez| SubPath::new(vec![Anchor::with_handles(e.p0, e.p0, e.p1), Anchor::with_handles(e.p3, e.p2, e.p3)], false); + for r in 0..=rows { + for c in 0..cols { + subs.push(cub(self.edge_u(r, c))); + } + } + for c in 0..=cols { + for r in 0..rows { + subs.push(cub(self.edge_v(r, c))); + } + } + PathData::new(subs) + } + + /// Control bounds (points and handles). + pub fn bounds(&self) -> Option { + let mut it = self.points.iter().flat_map(|p| std::iter::once(p.p).chain(p.handles.iter().map(move |h| p.p + *h))); + let first = it.next()?; + Some(it.fold(Rect::from_points(first, first), |r, q| r.union_pt(q))) + } + + pub fn transform(&mut self, a: Affine) { + let lin = Affine::new({ + let c = a.as_coeffs(); + [c[0], c[1], c[2], c[3], 0.0, 0.0] + }); + for p in &mut self.points { + p.p = a * p.p; + for h in &mut p.handles { + *h = (lin * h.to_point()).to_vec2(); + } + } + } + + /// Map points (and handle ends) through a non-linear function. + pub fn map(&mut self, f: &dyn Fn(Point) -> Point) { + for p in &mut self.points { + let q = f(p.p); + for h in &mut p.handles { + *h = f(p.p + *h) - q; + } + p.p = q; + } + } + + /// Which patch and local (u, v) contains `p` (sampled search; `None` outside the mesh). + pub fn locate(&self, p: Point) -> Option<(usize, usize, f64, f64)> { + if !self.is_valid() { + return None; + } + let bp = self.outline().to_bezpath(); + if bp.winding(p) == 0 { + return None; + } + const N: usize = 16; + let mut best = (f64::INFINITY, 0, 0, 0.0, 0.0); + for r in 0..self.rows as usize { + for c in 0..self.cols as usize { + for j in 0..=N { + for i in 0..=N { + let (u, v) = (i as f64 / N as f64, j as f64 / N as f64); + let d = self.eval(r, c, u, v).distance_squared(p); + if d < best.0 { + best = (d, r, c, u, v); + } + } + } + } + } + // Refine with a few Newton-free local searches. + let (_, r, c, mut u, mut v) = best; + let mut step = 0.5 / N as f64; + for _ in 0..12 { + let mut improved = false; + for (du, dv) in [(step, 0.0), (-step, 0.0), (0.0, step), (0.0, -step)] { + let (nu, nv) = ((u + du).clamp(0.0, 1.0), (v + dv).clamp(0.0, 1.0)); + if self.eval(r, c, nu, nv).distance_squared(p) < self.eval(r, c, u, v).distance_squared(p) { + u = nu; + v = nv; + improved = true; + } + } + if !improved { + step /= 2.0; + } + } + Some((r, c, u, v)) + } + + /// Index of the mesh point within `tol` of `p`. + pub fn point_near(&self, p: Point, tol: f64) -> Option { + self.points + .iter() + .enumerate() + .filter(|(_, q)| q.p.distance(p) <= tol) + .min_by(|a, b| a.1.p.distance(p).total_cmp(&b.1.p.distance(p))) + .map(|(i, _)| i) + } + + fn surface_du(&self, r: usize, c: usize, u: f64, v: f64) -> Vec2 { + let e = 1e-3; + let (a, b) = ((u - e).max(0.0), (u + e).min(1.0)); + (self.eval(r, c, b, v) - self.eval(r, c, a, v)) / (b - a) + } + fn surface_dv(&self, r: usize, c: usize, u: f64, v: f64) -> Vec2 { + let e = 1e-3; + let (a, b) = ((v - e).max(0.0), (v + e).min(1.0)); + (self.eval(r, c, u, b) - self.eval(r, c, u, a)) / (b - a) + } + + /// Insert a mesh row through patch row `r` at local `v`. + pub fn insert_row(&mut self, r: usize, v: f64) { + let cols = self.cols as usize; + let v = v.clamp(0.01, 0.99); + let mut row = Vec::with_capacity(cols + 1); + // Split the vertical edges. + let mut ups = vec![]; + for c in 0..=cols { + let e = self.edge_v(r, c); + let (l, rr) = (e.subsegment(0.0..v), e.subsegment(v..1.0)); + ups.push((l.p1 - l.p0, rr.p2 - rr.p3)); + let pc = c.min(cols - 1); + let u = if c == cols { 1.0 } else { 0.0 }; + let (color, opacity) = self.color_at(r, pc, u, v); + // Horizontal handles: isocurve derivatives on either side. + let right = if c < cols { self.surface_du(r, c, 0.0, v) / (3.0) } else { Vec2::ZERO }; + let left = if c > 0 { -self.surface_du(r, c - 1, 1.0, v) / 3.0 } else { Vec2::ZERO }; + row.push(MeshPoint { p: l.p3, color, opacity, handles: [right, left, rr.p1 - rr.p0, l.p2 - l.p3] }); + } + for (c, (down, up)) in ups.into_iter().enumerate() { + let i0 = self.idx(r, c); + let i1 = self.idx(r + 1, c); + self.points[i0].handles[H_DOWN] = down; + self.points[i1].handles[H_UP] = up; + } + let at = self.idx(r + 1, 0); + self.points.splice(at..at, row); + self.rows += 1; + } + + /// Insert a mesh column through patch column `c` at local `u`. + pub fn insert_col(&mut self, c: usize, u: f64) { + let rows = self.rows as usize; + let u = u.clamp(0.01, 0.99); + let mut col = Vec::with_capacity(rows + 1); + for r in 0..=rows { + let e = self.edge_u(r, c); + let (l, rr) = (e.subsegment(0.0..u), e.subsegment(u..1.0)); + let pr = r.min(rows - 1); + let v = if r == rows { 1.0 } else { 0.0 }; + let (color, opacity) = self.color_at(pr, c, u, v); + let down = if r < rows { self.surface_dv(r, c, u, 0.0) / 3.0 } else { Vec2::ZERO }; + let up = if r > 0 { -self.surface_dv(r - 1, c, u, 1.0) / 3.0 } else { Vec2::ZERO }; + col.push((MeshPoint { p: l.p3, color, opacity, handles: [rr.p1 - rr.p0, l.p2 - l.p3, down, up] }, l.p1 - l.p0, rr.p2 - rr.p3)); + } + let cols = self.cols as usize; + let mut pts = Vec::with_capacity((rows + 1) * (cols + 2)); + for (r, (mp, right, left)) in col.into_iter().enumerate() { + for cc in 0..=cols { + let mut q = self.points[r * (cols + 1) + cc].clone(); + if cc == c { + q.handles[H_RIGHT] = right; + } + if cc == c + 1 { + q.handles[H_LEFT] = left; + } + pts.push(q); + if cc == c { + pts.push(mp.clone()); + } + } + } + self.points = pts; + self.cols += 1; + } + + /// Mesh tool click: add a row and a column through `p` (inside the mesh). Returns the new point index. + pub fn add_lines_at(&mut self, p: Point) -> Option { + let (r, c, u, v) = self.locate(p)?; + let mut rr = r; + let mut cc = c; + let row_new = v > 0.02 && v < 0.98; + let col_new = u > 0.02 && u < 0.98; + if row_new { + self.insert_row(r, v); + rr = r + 1; + } else if v >= 0.98 { + rr = r + 1; + } + if col_new { + self.insert_col(c, u); + cc = c + 1; + } else if u >= 0.98 { + cc = c + 1; + } + Some(self.idx(rr, cc)) + } + + /// Mesh tool Alt-click: delete the mesh lines through point `index` (interior lines only). + pub fn remove_point_lines(&mut self, index: usize) -> bool { + // A mesh from a file may not have the points its rows and columns need: it is indexed below. + if !self.is_valid() || index >= self.points.len() { + return false; + } + let w = self.cols as usize + 1; + let (r, c) = (index / w, index % w); + let mut changed = false; + if r > 0 && r < self.rows as usize { + // Merge the edges above and below: keep the outer handles. + for cc in 0..w { + let above = self.idx(r - 1, cc); + let below = self.idx(r + 1, cc); + let mid = self.idx(r, cc); + let (pa, pm, pb) = (self.points[above].p, self.points[mid].p, self.points[below].p); + let _ = pm; + self.points[above].handles[H_DOWN] = (pb - pa) / 3.0; + self.points[below].handles[H_UP] = (pa - pb) / 3.0; + } + self.points.drain(r * w..(r + 1) * w); + self.rows -= 1; + changed = true; + } + let w = self.cols as usize + 1; + if c > 0 && c < self.cols as usize { + let rows = self.rows as usize; + for rr in 0..=rows { + let (l, rt) = (rr * w + c - 1, rr * w + c + 1); + let (pl, pr) = (self.points[l].p, self.points[rt].p); + self.points[l].handles[H_RIGHT] = (pr - pl) / 3.0; + self.points[rt].handles[H_LEFT] = (pl - pr) / 3.0; + } + let mut k = 0; + self.points.retain(|_| { + let keep = k % w != c; + k += 1; + keep + }); + self.cols -= 1; + changed = true; + } + changed + } +} + +// ===================================================================================== +// Envelopes +// ===================================================================================== + +/// Union of the geometric bounds of `nodes`. +pub fn nodes_bounds(nodes: &[Arc]) -> Option { + nodes.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric_bounds())) +} + +/// A `(rows+1)×(cols+1)` grid over `r` (row-major). +pub fn grid_points(r: Rect, rows: u32, cols: u32) -> Vec { + let mut v = Vec::with_capacity(((rows + 1) * (cols + 1)) as usize); + for i in 0..=rows { + for j in 0..=cols { + v.push(Point::new(r.x0 + r.width() * j as f64 / cols.max(1) as f64, r.y0 + r.height() * i as f64 / rows.max(1) as f64)); + } + } + v +} + +fn catmull(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: f64) -> Vec2 { + let t2 = t * t; + let t3 = t2 * t; + 0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3) +} + +/// Point map from the unit square onto a point grid (tensor-product Catmull-Rom; linear +/// extrapolation at the borders so an undistorted grid is the identity, also past the square). +pub(super) fn grid_eval(rows: usize, cols: usize, pts: &[Point], u: f64, v: f64) -> Point { + let at = |r: i64, c: i64| -> Vec2 { + let rr = r.clamp(0, rows as i64); + let cc = c.clamp(0, cols as i64); + let base = pts[rr as usize * (cols + 1) + cc as usize].to_vec2(); + // Linear extrapolation outside the grid. + let er = r - rr; + let ec = c - cc; + let mut p = base; + if er != 0 && rows >= 1 { + let inner = (rr - er.signum()).clamp(0, rows as i64); + p += (base - pts[inner as usize * (cols + 1) + cc as usize].to_vec2()) * er.abs() as f64; + } + if ec != 0 && cols >= 1 { + let inner = (cc - ec.signum()).clamp(0, cols as i64); + p += (base - pts[rr as usize * (cols + 1) + inner as usize].to_vec2()) * ec.abs() as f64; + } + p + }; + // Past the grid's edges the outer patches go on (art can reach past the content's box). + let (su, sv) = (u * cols as f64, v * rows as f64); + let (ci, ri) = ((su.floor() as i64).clamp(0, cols as i64 - 1), (sv.floor() as i64).clamp(0, rows as i64 - 1)); + let (fu, fv) = (su - ci as f64, sv - ri as f64); + let mut rowsv = [Vec2::ZERO; 4]; + for (k, rv) in rowsv.iter_mut().enumerate() { + let r = ri - 1 + k as i64; + *rv = catmull(at(r, ci - 1), at(r, ci), at(r, ci + 1), at(r, ci + 2), fu); + } + catmull(rowsv[0], rowsv[1], rowsv[2], rowsv[3], fv).to_point() +} + +/// The surface (u, v ∈ [0,1]) an envelope of `kind` maps content onto, for content whose bounds in +/// the envelope's own `frame` (its axes → the document) are `src`: a warp bends along the frame's +/// axes; a mesh's points and a top object's path are in the document already. +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 } => { + 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); + let c = src.center(); + let (hw, hh) = (src.width() / 2.0, src.height() / 2.0); + let horizontal = *horizontal; + Box::new(move |u: f64, v: f64| { + let (x, y) = (2.0 * u - 1.0, 2.0 * v - 1.0); + let (x2, y2) = if horizontal { + warp_point(st, b, dh, dv, hh / hw.max(1e-9), x, y) + } else { + let (a, b2) = warp_point(st, b, dh, dv, hw / hh.max(1e-9), y, x); + (b2, a) + }; + frame * Point::new(c.x + x2 * hw, c.y + y2 * hh) + }) + } + EnvelopeKind::Mesh { rows, cols, points, handles } => { + if !handles.is_empty() + && let Some(m) = envelope_grid(*rows, *cols, points, handles) + { + return Box::new(move |u: f64, v: f64| mesh_at(&m, u, v)); + } + if *rows == 0 || *cols == 0 || grid_len(*rows, *cols) != Some(points.len()) { + return Box::new(flat); + } + let (rows, cols) = (*rows as usize, *cols as usize); + Box::new(move |u: f64, v: f64| grid_eval(rows, cols, points, u, v)) + } + EnvelopeKind::TopObject { path } => match Coons::from_path(path) { + Some(co) => Box::new(move |u: f64, v: f64| co.eval(u, v)), + None => Box::new(flat), + }, + } +} diff --git a/crates/doc/src/live/warp.rs b/crates/doc/src/live/warp.rs new file mode 100644 index 0000000000..cacf26ec53 --- /dev/null +++ b/crates/doc/src/live/warp.rs @@ -0,0 +1,253 @@ +use super::*; + +// ===================================================================================== +// Warp maps (shared with vectorcraft-effects' Warp effects) +// ===================================================================================== + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WarpStyle { + Arc, + ArcLower, + ArcUpper, + Arch, + Bulge, + ShellLower, + ShellUpper, + Flag, + Wave, + Fish, + Rise, + Fisheye, + Inflate, + Squeeze, + Twist, +} + +impl WarpStyle { + /// From the id suffix (`arc`, `arcLower`, …). + pub fn from_id(s: &str) -> Option { + use WarpStyle::*; + Some(match s { + "arc" => Arc, + "arcLower" => ArcLower, + "arcUpper" => ArcUpper, + "arch" => Arch, + "bulge" => Bulge, + "shellLower" => ShellLower, + "shellUpper" => ShellUpper, + "flag" => Flag, + "wave" => Wave, + "fish" => Fish, + "rise" => Rise, + "fisheye" => Fisheye, + "inflate" => Inflate, + "squeeze" => Squeeze, + "twist" => Twist, + _ => return None, + }) + } +} + +/// The warp map on normalised coordinates: `b` = bend (-1..1), `dh`/`dv` = distortion (-1..1); +/// `aspect` is the box's half-height over its half-width along the warp (Arc bends in real +/// proportions). +pub fn warp_point(style: WarpStyle, b: f64, dh: f64, dv: f64, aspect: f64, x: f64, y: f64) -> (f64, f64) { + use WarpStyle::*; + let t = (y + 1.0) / 2.0; // 0 at top, 1 at bottom + let par = 1.0 - x * x; // parabola: 1 at centre, 0 at sides + let (mut x2, mut y2) = match style { + Arc => { + if b.abs() < 1e-6 { + (x, y) + } else { + // Bend the centre line into a circular arc of equal length (sweep = |b|·180°), in + // the box's real proportions (lengths in half-widths, so y counts `aspect` each): + // the edges are concentric arcs, and one that would pass the centre stops there + // instead of folding over (#1578). + let k = if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 }; + let sweep = b.abs() * PI; + let r0 = 2.0 / sweep; + let yy = if b > 0.0 { y } else { -y } * k; + let a = x / r0; + let r = (r0 - yy).max(0.0); + let (s, c) = a.sin_cos(); + let (nx, ny) = (r * s, (r0 - r * c) / k); + (nx, if b > 0.0 { ny } else { -ny }) + } + } + ArcLower => (x, y + b * par * t), + ArcUpper => (x, y - b * par * (1.0 - t)), + Arch => (x, y - b * par), + Bulge => (x, y + b * par * y), + ShellLower => (x * (1.0 - 0.5 * b * (1.0 - t)), y + b * par * t), + ShellUpper => (x * (1.0 - 0.5 * b * t), y - b * par * (1.0 - t)), + Flag => (x, y + 0.5 * b * (PI * x).sin()), + Wave => (x + 0.1 * b * (PI * y).sin(), y + 0.3 * b * (2.0 * PI * x).sin() * (0.5 + 0.5 * t)), + Fish => (x, y * (1.0 + 0.5 * b * (0.75 * PI * (x + 1.0)).sin())), + Rise => (x, y - b * ((x + 1.0) / 2.0).powi(2) * 2.0 + b), + Fisheye => { + let r2 = x * x + y * y; + let s = if r2 < 1.0 { 1.0 + 0.5 * b * (1.0 - r2) } else { 1.0 }; + (x * s, y * s) + } + Inflate => (x * (1.0 + 0.5 * b * (1.0 - y * y)), y * (1.0 + 0.5 * b * par)), + Squeeze => (x * (1.0 - 0.5 * b * (1.0 - y * y)), y * (1.0 + 0.3 * b * par)), + Twist => { + let r = (x * x + y * y).sqrt(); + let a = -b * PI * 0.5 * (1.0 - r / std::f64::consts::SQRT_2).max(0.0); + let (s, c) = a.sin_cos(); + (x * c - y * s, x * s + y * c) + } + }; + // Perspective-like distortion: horizontal narrows one side, vertical one end. + if dh != 0.0 { + y2 *= (1.0 + dh * x2 * 0.5).max(0.0); + } + if dv != 0.0 { + x2 *= (1.0 + dv * y2 * 0.5).max(0.0); + } + (x2, y2) +} + +/// 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); + if sp.segment_is_line(i) { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c } +} + +fn poly_len(c: &CubicBez) -> f64 { + c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3) +} + +/// Running length along a polyline: `0, |p0p1|, |p0p1| + |p1p2|, …` (one entry per point). +fn cumulative_lengths(pts: &[Point]) -> Vec { + let mut total = 0.0; + let mut cum = Vec::with_capacity(pts.len()); + cum.push(0.0); + for w in pts.windows(2) { + total += w[0].distance(w[1]); + cum.push(total); + } + cum +} + +/// Most pieces [`map_nonlinear`] splits one segment into. +const MAX_PIECES: usize = 64; + +/// How many pieces of about `piece` a segment of length `len` is split into: one to `most`. +pub fn pieces(len: f64, piece: f64, most: usize) -> usize { + ((len / piece).ceil() as usize).clamp(1, most.max(1)) +} + +/// The piece length to split segments of lengths `lens` with ([`pieces`], at most `most` each) so +/// that the pieces past each segment's first number at most `room`: `piece` when they already do, +/// longer pieces otherwise. A segment of `n` pieces adds `n - 1 ≤ len / piece` points to a path, +/// so pieces of the total length over `room` fit; with no room every segment stays one piece. +pub fn fit_piece(lens: &[f64], piece: f64, most: usize, room: usize) -> f64 { + let added = lens.iter().map(|&len| pieces(len, piece, most) - 1).fold(0, usize::saturating_add); + if added <= room { + return piece; + } + if room == 0 { + return f64::INFINITY; + } + // A NaN length is always one piece. + piece.max(lens.iter().filter(|len| !len.is_nan()).sum::() / room as f64) +} + +/// Map every point of `path` through the non-linear function `f`. Segments are split into pieces +/// no longer than about `max_piece` (up to 64 per segment) and their control points mapped, which +/// approximates the image curve to O(h²). Closedness and subpath structure are preserved. +pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point) -> PathData { + map_nonlinear_within(path, max_piece, usize::MAX, f) +} + +/// [`map_nonlinear`] whose result has at most `max` anchors, or `path`'s count when that is more: +/// where pieces of `max_piece` would make more, the pieces grow until they don't ([`fit_piece`]), +/// a coarser approximation of the image curve. Geometry effects map within their anchor budget. +pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData { + let mut max_piece = max_piece.max(1e-3); + // Each segment adds one anchor per piece past its first. + let room = max.saturating_sub(path.anchor_count()); + let segs = path.subpaths.iter().map(SubPath::segment_count).fold(0, usize::saturating_add); + if segs.saturating_mul(MAX_PIECES - 1) > room { + let lens: Vec = path.subpaths.iter().flat_map(|sp| (0..sp.segment_count()).map(|i| poly_len(&seg_cubic(sp, i)))).collect(); + max_piece = fit_piece(&lens, max_piece, MAX_PIECES, room); + } + let mut subs = Vec::with_capacity(path.subpaths.len()); + for sp in &path.subpaths { + let n = sp.anchors.len(); + if n == 0 { + continue; + } + let segs = sp.segment_count(); + let mut res: Vec = Vec::new(); + let mut pending_in: Option = None; + for i in 0..n { + let a = &sp.anchors[i]; + let h_in = pending_in.take().unwrap_or_else(|| f(a.h_in)); + res.push(Anchor { p: f(a.p), h_in, h_out: f(a.h_out), kind: a.kind }); + if i < segs { + let c = seg_cubic(sp, i); + let k = pieces(poly_len(&c), max_piece, MAX_PIECES); + for j in 0..k { + let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)); + if let Some(last) = res.last_mut() { + last.h_out = f(sub.p1); + } + if j + 1 < k { + res.push(Anchor { p: f(sub.p3), h_in: f(sub.p2), h_out: f(sub.p3), kind: Default::default() }); + } else { + pending_in = Some(f(sub.p2)); + } + } + } + } + if let Some(h) = pending_in + && sp.closed + && let Some(first) = res.first_mut() + { + first.h_in = h; + } + let anchors = res.into_iter().map(|a| Anchor::with_handles(a.p, a.h_in, a.h_out)).collect(); + subs.push(SubPath::new(anchors, sp.closed)); + } + PathData::new(subs) +} + +// ===================================================================================== +// Coons patches from outlines +// ===================================================================================== + +pub(super) fn flatten_subpath(sp: &SubPath, tol: f64) -> Vec { + let mut bp = BezPath::new(); + sp.to_bezpath_into(&mut bp); + let mut pts: Vec = Vec::new(); + vectorcraft_geom::kurbo::flatten(bp.iter(), tol, |el| match el { + vectorcraft_geom::PathEl::MoveTo(p) | vectorcraft_geom::PathEl::LineTo(p) if pts.last().is_none_or(|q| q.distance(p) > 1e-9) => pts.push(p), + _ => {} + }); + pts +} + +pub(super) fn resample(poly: &[Point], m: usize) -> Vec { + if poly.is_empty() { + return vec![Point::ZERO; m]; + } + if poly.len() == 1 { + return vec![poly[0]; m]; + } + let cum = cumulative_lengths(poly); + let total = cum.last().copied().unwrap_or(0.0); + let mut out = Vec::with_capacity(m); + let mut i = 0; + for k in 0..m { + let s = if m > 1 { total * k as f64 / (m - 1) as f64 } else { 0.0 }; + while i + 2 < cum.len() && cum[i + 1] < s { + i += 1; + } + let seg = (cum[i + 1] - cum[i]).max(1e-12); + out.push(poly[i].lerp(poly[i + 1], ((s - cum[i]) / seg).clamp(0.0, 1.0))); + } + out +} diff --git a/crates/doc/src/metadata.rs b/crates/doc/src/metadata.rs index 708cb82e8f..151365c5d2 100644 --- a/crates/doc/src/metadata.rs +++ b/crates/doc/src/metadata.rs @@ -3,6 +3,7 @@ //! document title is [`crate::Document::title`]. Every field is defaulted, so documents saved //! before File Info existed load unchanged. +use chrono::{Datelike, Timelike}; use serde::{Deserialize, Serialize}; /// File Info → Copyright Status. @@ -104,7 +105,13 @@ fn pinned_or(get: impl Fn(&str) -> Option, clock: impl Fn() -> Option Option) -> Option { - get("SOURCE_DATE_EPOCH")?.trim().parse::().ok().filter(|t| *t >= 0) + let value = get("SOURCE_DATE_EPOCH")?; + let value = value.trim(); + // `i64::from_str` also takes a leading `+`, which `date +%s` never prints. + if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + value.parse::().ok() } /// The current time as Unix seconds (UTC); `None` where the platform has no clock (the web build). @@ -118,23 +125,26 @@ pub fn now_unix() -> Option { None } -/// Unix seconds (UTC) → `[year, month, day, hour, minute, second]` (civil-from-days, proleptic -/// Gregorian; years clamped to 0–9999). +/// Unix seconds (UTC) → `[year, month, day, hour, minute, second]` (proleptic Gregorian; years +/// clamped to 0–9999). pub fn civil(t: i64) -> [i64; 6] { - // Clamp first so every step stays in range for any input. + // Clamp the input first so every input maps to a representable date (0000-01-01 .. 9999-12-31), + // exactly as the old code did. The clamped instant is always inside chrono's range, so the + // conversion below never falls back; the trailing `clamp(0, 9999)` is the old year clamp. let t = t.clamp(-62_167_219_200, 253_402_300_799); - let days = t.div_euclid(86_400); - let secs = t.rem_euclid(86_400); - let z = days + 719_468; - let era = z.div_euclid(146_097); - let doe = z - era * 146_097; - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let day = doy - (153 * mp + 2) / 5 + 1; - let month = if mp < 10 { mp + 3 } else { mp - 9 }; - let year = yoe + era * 400 + i64::from(month <= 2); - [year.clamp(0, 9999), month, day, secs / 3600, secs / 60 % 60, secs % 60] + let (days, sod) = (t.div_euclid(86_400), t.rem_euclid(86_400)); + let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097)); + // `rest + 719_163` (1970-01-01 is CE day 719_163) is always a valid CE day, and `sod` < 86_400. + let date = i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt); + let time = u32::try_from(sod).ok().and_then(|s| chrono::NaiveTime::from_num_seconds_from_midnight_opt(s, 0)); + match (date, time) { + (Some(d), Some(tm)) => { + let year = i128::from(d.year()) + i128::from(cycles) * 400; + let year = i64::try_from(year).unwrap_or(if year < 0 { i64::MIN } else { i64::MAX }); + [year.clamp(0, 9999), i64::from(d.month()), i64::from(d.day()), i64::from(tm.hour()), i64::from(tm.minute()), i64::from(tm.second())] + } + _ => [1970, 1, 1, 0, 0, 0], // unreachable: the clamped `t` is always a valid date + } } /// Unix seconds → `2026-10-05T14:03:00Z`. @@ -151,8 +161,15 @@ mod tests { fn dates_and_statuses() { assert_eq!(iso8601(0), "1970-01-01T00:00:00Z"); assert_eq!(iso8601(1_791_208_980), "2026-10-05T14:03:00Z"); + // The input is clamped to 0000-01-01..9999-12-31, then the year is clamped to 0..=9999, + // exactly as the old code did: inputs far past chrono's range land on the clamp bounds, + // never on the epoch. assert_eq!(civil(i64::MIN)[0], 0); assert_eq!(civil(i64::MAX)[0], 9999); + assert_eq!(iso8601(i64::MIN), "0000-01-01T00:00:00Z"); + assert_eq!(iso8601(i64::MAX), "9999-12-31T23:59:59Z"); + assert_eq!(iso8601(10_000_000_000_000), "9999-12-31T23:59:59Z"); + assert_eq!(iso8601(-10_000_000_000_000), "0000-01-01T00:00:00Z"); assert_eq!(CopyrightStatus::parse("Public Domain"), Some(CopyrightStatus::PublicDomain)); assert_eq!(CopyrightStatus::parse("publicdomain"), Some(CopyrightStatus::PublicDomain)); assert_eq!(CopyrightStatus::parse("maybe"), None); @@ -182,7 +199,7 @@ mod tests { assert_eq!(stamp_from_env(env(Some("1791208980"))), Some(1_791_208_980)); assert_eq!(stamp_from_env(env(Some("0"))), Some(0)); assert_eq!(stamp_from_env(env(Some(" 1791208980 "))), Some(1_791_208_980)); - for bad in ["", " ", "-1", "later", "1791208980.5", "1e9", "99999999999999999999"] { + for bad in ["", " ", "-1", "later", "1791208980.5", "1e9", "+1791208980", "+0", "99999999999999999999"] { assert_eq!(stamp_from_env(env(Some(bad))), None, "{bad:?}"); } assert_eq!(stamp_from_env(env(None)), None, "unset"); diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 1bfabf9c19..2be25e0b10 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -14,493 +14,24 @@ use crate::pattern::RepeatSpec; use crate::symbols::{SYMBOL_SQUARE, SymbolBoxes}; use crate::text::TextObject; -/// Stable per-document object id. Never reused. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(transparent)] -pub struct NodeId(pub u64); +mod attributes; +mod clip; +mod extras; +mod ids; +mod kind; +mod live_shape; +mod opacity; +mod ops; +mod wire; -impl std::fmt::Display for NodeId { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "#{}", self.0) - } -} - -/// Layer colours used for selection highlighting (index into [`LAYER_COLORS`]) or a custom RGB. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum LayerColor { - Preset(u8), - Custom([u8; 3]), -} - -/// Layer highlight colours, assigned in sequence to new layers. First is Illustrator-like light blue. -pub const LAYER_COLORS: [(&str, [u8; 3]); 27] = [ - ("Light Blue", [0x4f, 0x80, 0xff]), - ("Red", [0xff, 0x4f, 0x4f]), - ("Green", [0x4f, 0xff, 0x4f]), - ("Blue", [0x4f, 0x4f, 0xff]), - ("Yellow", [0xff, 0xff, 0x4f]), - ("Magenta", [0xff, 0x4f, 0xff]), - ("Cyan", [0x4f, 0xff, 0xff]), - ("Gray", [0x80, 0x80, 0x80]), - ("Black", [0x00, 0x00, 0x00]), - ("Orange", [0xff, 0x66, 0x00]), - ("Dark Green", [0x00, 0x80, 0x00]), - ("Teal", [0x00, 0x80, 0x80]), - ("Tan", [0xcc, 0x99, 0x66]), - ("Brown", [0x99, 0x33, 0x00]), - ("Violet", [0x99, 0x33, 0xff]), - ("Gold", [0xff, 0x99, 0x00]), - ("Dark Blue", [0x00, 0x00, 0x80]), - ("Pink", [0xff, 0x99, 0xcc]), - ("Lavender", [0x99, 0x99, 0xff]), - ("Brick Red", [0x99, 0x00, 0x00]), - ("Olive Green", [0x66, 0x66, 0x00]), - ("Peach", [0xff, 0x99, 0x99]), - ("Burgundy", [0x99, 0x00, 0x33]), - ("Grass Green", [0x99, 0xcc, 0x00]), - ("Ochre", [0x99, 0x66, 0x00]), - ("Purple", [0x66, 0x00, 0x99]), - ("Light Gray", [0xbb, 0xbb, 0xbb]), -]; - -impl LayerColor { - pub fn rgb(self) -> [u8; 3] { - match self { - LayerColor::Preset(i) => LAYER_COLORS[i as usize % LAYER_COLORS.len()].1, - LayerColor::Custom(c) => c, - } - } -} - -/// Live shape parameters (Illustrator's "Live Shapes"). The node's path is regenerated from these -/// while the shape stays live; editing anchors directly converts it to a plain path. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "shape", rename_all = "lowercase")] -pub enum LiveShape { - Rectangle { - /// Untransformed width/height. Transforms fold their scale into these (see - /// [`LiveShape::transform`]), so they are document lengths unless `xf` shears. - w: f64, - h: f64, - /// Corner radii: top-left, top-right, bottom-right, bottom-left. In the same units as - /// `w`/`h`: the corners are circular arcs in the document whenever `xf` doesn't scale. - radii: [f64; 4], - /// Corner kinds, in the same order (Live Corners' corner types). - #[serde(default, skip_serializing_if = "all_round")] - kinds: [CornerKind; 4], - /// Maps the untransformed shape (origin at its top-left) into the document. A rotation - /// or reflection plus a move, unless a shear (or a file saved before transforms folded - /// their scale into `w`/`h`) put more in it. - xf: Affine, - }, - Ellipse { - w: f64, - h: f64, - /// Pie start/end angles in degrees (0/360 = full ellipse). - pie: (f64, f64), - xf: Affine, - }, - Polygon { - radius: f64, - /// 3–1000, as [`LiveShape::set_sides`] gives it; a file's count is clamped when read. - #[serde(deserialize_with = "de_sides")] - sides: u32, - xf: Affine, - /// Corner radii in document units, by vertex from the first one clockwise (none: sharp). - #[serde(default, skip_serializing_if = "Vec::is_empty")] - radii: Vec, - /// Corner kinds, in the same order (none: round). - #[serde(default, skip_serializing_if = "all_round")] - kinds: Vec, - }, - Line { - a: Point, - b: Point, - }, - /// Any other path whose corners Live Corners cut (a star, a pen path): it keeps its uncut - /// outline so the corners stay editable. Without a cut corner it is a plain path again. - Path { - /// The path with its corners uncut, in the document. - base: PathData, - /// Corner radii in document units, by anchor index of `base` (counting every subpath's - /// anchors in order; missing: sharp). - #[serde(default, skip_serializing_if = "Vec::is_empty")] - radii: Vec, - /// Corner kinds, in the same order (missing: round). - #[serde(default, skip_serializing_if = "all_round")] - kinds: Vec, - }, -} - -impl LiveShape { - pub fn label(&self) -> &'static str { - match self { - LiveShape::Rectangle { radii, .. } if radii.iter().any(|r| *r > 0.0) => "Rounded Rectangle", - LiveShape::Rectangle { .. } => "Rectangle", - LiveShape::Ellipse { .. } => "Ellipse", - LiveShape::Polygon { .. } => "Polygon", - LiveShape::Line { .. } => "Line", - LiveShape::Path { .. } => "Path", - } - } - /// Regenerate the path. - pub fn to_path(&self) -> PathData { - match self { - LiveShape::Rectangle { w, h, radii, kinds, xf } => { - shapes::rectangle_with_corners(Rect::new(0.0, 0.0, *w, *h), *radii, *kinds).transformed(*xf) - } - LiveShape::Ellipse { w, h, pie, xf } => shapes::ellipse_pie(Rect::new(0.0, 0.0, *w, *h), pie.0, pie.1).transformed(*xf), - LiveShape::Polygon { radii, kinds, .. } => cut_corners(&self.polygon_outline(), radii, kinds).0, - LiveShape::Line { a, b } => shapes::line(*a, *b), - LiveShape::Path { base, radii, kinds } => cut_corners(base, radii, kinds).0, - } - } - /// A polygon's outline with its corners uncut, in the document (empty for other shapes). - pub fn polygon_outline(&self) -> PathData { - match self { - LiveShape::Polygon { radius, sides, xf, .. } => shapes::polygon(Point::ZERO, *radius, *sides, 0.0).transformed(*xf), - _ => PathData::default(), - } - } - /// Give a polygon `n` sides (3–1000). Its corners keep the radius and kind they shared; else - /// the corners past the old last one are sharp. - pub fn set_sides(&mut self, n: u64) { - let LiveShape::Polygon { sides, radii, kinds, .. } = self else { return }; - *sides = n.clamp(3, 1000) as u32; - fn spread(v: &mut Vec, n: usize) { - match v.first().copied() { - Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n], - Some(_) => v.resize(n, T::default()), - None => {} - } - } - spread(radii, *sides as usize); - spread(kinds, *sides as usize); - } - /// A polygon's radius in the document, centre to vertex: its own radius by the mean scale of - /// `xf` (exact while its sides are equal). None for other shapes. - pub fn polygon_radius(&self) -> Option { - let LiveShape::Polygon { radius, xf, .. } = self else { return None }; - Some(radius * xf.determinant().abs().sqrt()) - } - /// A polygon's angle: the counterclockwise degrees in [0, 360) its first vertex is turned by - /// from straight up (the Rotate field's sense). None for other shapes. - pub fn polygon_angle(&self) -> Option { - let LiveShape::Polygon { .. } = self else { return None }; - // No −0° or 360° from rounding: a polygon drawn upright reads 0°. - let a = (-self.angle_deg()).rem_euclid(360.0); - Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) - } - /// Whether a polygon's sides are all as long: `xf` scales it evenly and doesn't shear it. True - /// for other shapes. - pub fn polygon_sides_equal(&self) -> bool { - let LiveShape::Polygon { xf, .. } = self else { return true }; - let [a, b, c, d, _, _] = xf.as_coeffs(); - let (sx, sy) = (a.hypot(b), c.hypot(d)); - (sx - sy).abs() <= 1e-9 * sx.max(sy) && (a * c + b * d).abs() <= 1e-9 * sx * sy - } - /// Give a polygon the document radius `r` (centre to vertex, see [`LiveShape::polygon_radius`]). - pub fn set_polygon_radius(&mut self, r: f64) { - let LiveShape::Polygon { radius, xf, .. } = self else { return }; - let k = xf.determinant().abs().sqrt(); - if k > 1e-12 && r.is_finite() { - *radius = r.max(0.0) / k; - } - } - /// The document radius that makes a polygon's sides `side` long (with its sides equal). - pub fn polygon_radius_for_side(&self, side: f64) -> Option { - let LiveShape::Polygon { sides, .. } = self else { return None }; - Some(side / (2.0 * (std::f64::consts::PI / f64::from((*sides).max(3))).sin())) - } - /// Turn a polygon about its centre to `angle` (degrees, as [`LiveShape::polygon_angle`]). - pub fn set_polygon_angle(&mut self, angle: f64) { - let Some(now) = self.polygon_angle() else { return }; - if let LiveShape::Polygon { xf, .. } = self - && angle.is_finite() - { - let centre = *xf * Point::ZERO; - *xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf; - } - } - /// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from - /// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`]. - pub fn make_sides_equal(&mut self) { - let Some(r) = self.polygon_radius() else { return }; - let LiveShape::Polygon { radius, xf, .. } = self else { return }; - let [a, b, _, _, e, f] = xf.as_coeffs(); - let flip = if xf.determinant() < 0.0 { Affine::FLIP_Y } else { Affine::IDENTITY }; - *xf = Affine::translate((e, f)) * Affine::rotate(b.atan2(a)) * flip; - *radius = r; - } - /// Apply `a` to the shape. True when the shape is no longer `a` applied to the old path, so - /// the caller must regenerate the path with [`LiveShape::to_path`]. - /// - /// A rectangle keeps round corners whatever its proportions: when `a` scales it along its own - /// sides (any rotation or reflection, no shear), the scale goes into `w`/`h` and `xf` keeps - /// only the rotation, reflection and position. The radii scale by the mean scale (the square - /// root of the determinant), which [`LiveShape::keep_corners`] undoes for Scale Corners off. - /// A shear can't keep circular corners: `xf` takes it, as do moves (so files saved with a - /// scale in `xf` keep their exact geometry until they're next transformed). A polygon's or a - /// path's corner radii are document lengths: they scale by the mean scale and the corners are - /// cut again, circular whatever `a` does. - pub fn transform(&mut self, a: Affine) -> bool { - match self { - LiveShape::Rectangle { xf, .. } => { - *xf = a * *xf; - !moves_only(a) && self.fold_scale() - } - LiveShape::Ellipse { xf, .. } => { - *xf = a * *xf; - false - } - LiveShape::Polygon { xf, radii, .. } => { - *xf = a * *xf; - scale_radii(radii, a) - } - LiveShape::Path { base, radii, .. } => { - base.transform(a); - scale_radii(radii, a) - } - LiveShape::Line { a: p, b } => { - *p = a * *p; - *b = a * *b; - false - } - } - } - /// Move the scale of a rectangle's `xf` into `w`/`h` (and its radii, by the mean scale), so - /// `xf` keeps only a rotation or reflection plus a move and the corners are circular in the - /// document. False (and nothing changes) when there is no scale to move, when `xf` shears or - /// isn't finite, and for other shapes. Files saved before transforms did this (#291) carry an - /// uneven scale in `xf`: their corners are elliptical until this runs. - pub fn fold_scale(&mut self) -> bool { - let LiveShape::Rectangle { w, h, radii, xf, .. } = self else { return false }; - let [m0, m1, m2, m3, m4, m5] = xf.as_coeffs(); - let (sx, sy) = (m0.hypot(m1), m2.hypot(m3)); - let orthogonal = sx > 1e-12 && sy > 1e-12 && (m0 * m2 + m1 * m3).abs() <= 1e-9 * sx * sy; - let finite = xf.as_coeffs().iter().all(|c| c.is_finite()) && w.is_finite() && h.is_finite(); - let unscaled = (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12; - if !orthogonal || !finite || unscaled { - return false; - } - let k = (sx * sy).sqrt(); - radii.iter_mut().for_each(|r| *r *= k); - *w *= sx; - *h *= sy; - *xf = Affine::new([m0 / sx, m1 / sx, m2 / sy, m3 / sy, m4, m5]); - true - } - /// This shape with [`LiveShape::fold_scale`] applied: a rectangle's size and radii in document - /// units (what Live Corners show and edit). - pub fn folded(&self) -> Self { - let mut s = self.clone(); - s.fold_scale(); - s - } - /// Divide live corner radii by `k`, the mean scale of a transform just applied, so the corners - /// keep their size (Scale Corners off). False when nothing changed. - pub fn keep_corners(&mut self, k: f64) -> bool { - let radii: &mut [f64] = match self { - LiveShape::Rectangle { radii, .. } => radii, - LiveShape::Polygon { radii, .. } | LiveShape::Path { radii, .. } => radii, - LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return false, - }; - if !radii.iter().any(|r| *r > 0.0) || k <= 1e-12 { - return false; - } - radii.iter_mut().for_each(|r| *r /= k); - true - } - /// Rotation angle of the live shape in degrees, clockwise on the page (y points down). - pub fn angle_deg(&self) -> f64 { - match self { - LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } => { - let c = xf.as_coeffs(); - c[1].atan2(c[0]).to_degrees() - } - LiveShape::Line { a, b } => (b.y - a.y).atan2(b.x - a.x).to_degrees(), - LiveShape::Path { .. } => 0.0, - } - } -} - -fn all_round(kinds: &[CornerKind]) -> bool { - kinds.iter().all(|k| *k == CornerKind::Round) -} - -/// A polygon's side count read from a file, clamped as the commands clamp it: the outline and its -/// corner lists hold one entry per side, so a huge count would allocate gigabytes. -fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result { - u32::deserialize(d).map(|n| n.clamp(3, 1000)) -} - -/// Whether `a` only moves (no rotation, scale, shear or reflection). -fn moves_only(a: Affine) -> bool { - let [a0, a1, a2, a3, _, _] = a.as_coeffs(); - (a0 - 1.0).abs() < 1e-12 && a1.abs() < 1e-12 && a2.abs() < 1e-12 && (a3 - 1.0).abs() < 1e-12 -} - -/// Scale corner radii in document units by the mean scale of `a`, applied to their path. True -/// when the path must be cut again: some corner is cut and `a` does more than move it (an -/// uneven scale would otherwise make the cuts elliptical). -fn scale_radii(radii: &mut [f64], a: Affine) -> bool { - if moves_only(a) || !radii.iter().any(|r| *r > 0.0) { - return false; - } - let k = a.determinant().abs().sqrt(); - radii.iter_mut().for_each(|r| *r *= k); - true -} - -/// What a transform scales besides geometry, by its mean scale (the square root of its -/// determinant). `Scaling::default()` (and `false`) scales nothing else; `true` scales stroke -/// weights and dashes only. Transforms the user asks for take theirs from Scale Strokes & Effects -/// and Scale Corners. -#[derive(Clone, Copy, Debug, Default)] -pub struct Scaling { - /// Stroke weights, dash lengths and dash offsets scale. - pub strokes: bool, - /// With `strokes`: scales an effect's distance parameters (the effects catalogue's). - pub effects: Option, - /// Type keeps its character strokes' weight (they otherwise scale with the type). - pub keep_type_strokes: bool, - /// Live corner radii keep their size. - pub keep_corners: bool, - /// Pattern fills and strokes move with the art (Transform Patterns; General › Transform - /// Pattern Tiles is its default): their tiles transform too, instead of staying put. - pub patterns: bool, -} - -impl Scaling { - /// The mean scale of `a` when it scales (isn't 1): what strokes, effects and corners scale by. - pub fn factor(a: Affine) -> Option { - let k = a.determinant().abs().sqrt(); - ((k - 1.0).abs() > 1e-9).then_some(k) - } -} - -impl From for Scaling { - fn from(strokes: bool) -> Self { - Self { strokes, ..Self::default() } - } -} - -/// Embedded or linked raster image. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct ImageObject { - /// Key into [`crate::Document::images`]. - pub key: String, - pub width: u32, - pub height: u32, - /// Maps pixel space (0..w, 0..h) into the document. - pub xf: Affine, - /// The file a linked image shows (File → Place with Link); `None`: embedded. Files saved - /// before links had details hold just the path. - #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::links::de_link")] - pub link: Option, - /// Links panel → Placement Options: how a file read again takes this image's place. - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub placement: crate::links::PlacementOptions, -} - -/// Written with its `type` first, then its fields (an internally tagged enum); read by -/// [`kind_de`], which takes the fields straight from the file when `type` comes first. -#[derive(Clone, Debug, PartialEq, Serialize)] -#[serde(tag = "type", rename_all = "lowercase")] -pub enum NodeKind { - /// A top-level layer or sublayer. - Layer { - color: LayerColor, - #[serde(default)] - template: bool, - #[serde(default = "yes")] - printable: bool, - children: Vec>, - /// Layer clipping mask: the first (bottom-most) child clips the others, as in a clip group. - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - clip: bool, - /// Layer Options → Preview: off, the layer's art is drawn (and clicked) in outline on screen - /// (Ctrl-click its eye in the Layers panel). - #[serde(default = "yes", skip_serializing_if = "crate::skip::is_true")] - preview: bool, - /// Layer Options → Dim Images to: on screen, images on the layer show faded to this - /// percentage (0–100); `None`: not dimmed. - #[serde(default, skip_serializing_if = "Option::is_none")] - dim_images: Option, - }, - /// A group. With `clip`, the first (bottom-most) child is the clipping path. - Group { - children: Vec>, - #[serde(default)] - clip: bool, - }, - Path { - path: PathData, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - rule: FillRule, - /// Boxed: few paths are live shapes, and the shape is larger than the rest of the variant. - #[serde(default, skip_serializing_if = "Option::is_none")] - live: Option>, - /// This path acts as a clipping path inside a clip group. - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - clipping: bool, - /// Guide (non-printing) path. - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - guide: bool, - }, - /// Compound path: children are paths painted as one with the compound's appearance. - Compound { - children: Vec>, - #[serde(default)] - rule: FillRule, - }, - Text(Box), - /// Boxed, as the other large kinds: a node is as large as its largest kind. - Image(Box), - SymbolInstance { - symbol: String, - xf: Affine, - }, - /// Live blend: the key objects (paint order) plus spacing/orientation/spine; the intermediate - /// steps are evaluated on demand (`live::blend_expand`). - Blend { - children: Vec>, - #[serde(default)] - spec: Box, - }, - /// Live envelope distortion of `content`. - Envelope { - content: Vec>, - kind: Box, - /// Envelope Options → Fidelity (0–100). - #[serde(default = "crate::live::default_fidelity")] - fidelity: f64, - /// Edit Contents mode (the content, not the envelope, is edited). - #[serde(default)] - editing: bool, - /// Envelope Options besides Fidelity. - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - options: crate::live::EnvelopeOptions, - /// The envelope's own axes (→ the document): the transforms it took since it was made that - /// the page axes can't stand for (rotation, shear, reflection). The content maps from its - /// bounds in this frame, and a warp bends along it. - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - frame: Box, - }, - /// Gradient mesh. - Mesh(GradientMesh), - /// Live Repeat (radial / grid / mirror) of source art. - Repeat(RepeatSpec), - /// A placed document: an artboard of another VectorCraft file, linked and locked (see - /// [`crate::placed_document`]). - PlacedDocument(Box), - /// Object › Intertwine: the objects keep their own stacking order, except where one of them - /// is drawn over the others: the area [`NodeExtras::intertwine`] of that member (see - /// [`crate::intertwine`]). - Intertwine { - children: Vec>, - }, -} +pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS}; +pub use clip::{ClipPaint, Uniter}; +pub use extras::{Extras, ExtrasMut, NodeExtras}; +pub use ids::{LAYER_COLORS, LayerColor, NodeId}; +pub use kind::{ImageObject, NodeKind}; +pub use live_shape::{LiveShape, Scaling}; +pub use opacity::{Knockout, OpacityMask, whiten}; +use wire::NodeWire; fn yes() -> bool { true @@ -541,1975 +72,5 @@ pub struct Node { pub extras: Extras, } -/// The parts of a [`Node`] that few objects have: kept out of line, so that the nodes without -/// them stay small ([`Node::extras`]). -#[derive(Clone, Debug, Default, PartialEq)] -pub struct NodeExtras { - /// Opacity mask (Transparency panel). Its art lives here, outside the layer tree. - pub mask: Option>, - /// Image Trace object: `{preset, params, view?}` it was traced with (the Image Trace panel shows - /// them; `view` is its [`crate::TraceView`] id, absent for the tracing result). - pub trace: Option>, - /// Object → Text Wrap: area type below this object (in the same layer) flows around it. - pub wrap: Option, - /// Graph object: the group's children are generated from this spec (Object → Graph). - pub graph: Option>, - /// Index of the graph series this generated group belongs to. Axes, the legend and other - /// children leave it unset, so a series named "Legend" or "Axes" is not mistaken for them. - pub series_index: Option, - /// The group holds the glyph outlines of type. Geometry effects that reshape it move and scale - /// the placed gradients in it with the outlines. - pub type_outlines: bool, - /// Editable Shaper composition; the original art is retained in its source child. - pub shaper: Option>, - /// The [`crate::GraphicStyle::id`] last applied to this object. It stays linked while it keeps - /// that style's look: editing its appearance or transparency breaks the link. - pub graphic_style: Option, - /// Attributes panel: centre point display, image map, URL and note (`None`: all defaults). - pub attrs: Option>, - /// Object → Slice → Make: the object is an object slice (its slice follows its bounds) with - /// these options. - pub slice: Option>, - /// Object › Perspective: the perspective grid plane the object is attached to. - pub perspective: Option>, - /// Dimension object: the live measurement it draws; its ordinary group children hold its - /// exportable appearance (Object › Dimensions, the Dimension tool). - pub dimension: Option>, - /// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates, - /// filled non-zero) where this object is drawn over the group's other members. - pub intertwine: Option>, - /// Live Paint group: its Gap Options (Object › Live Paint › Gap Options; `None`: the defaults). - pub live_paint_gaps: Option>, - /// Object › Objects on Path: the group's path and the objects attached to it (see - /// [`crate::objects_on_path`]). - pub objects_on_path: Option>, -} - -/// No extras: what [`Node::extras`] gives for a node without any. -static NO_EXTRAS: NodeExtras = NodeExtras { - mask: None, - trace: None, - wrap: None, - graph: None, - series_index: None, - type_outlines: false, - shaper: None, - graphic_style: None, - attrs: None, - slice: None, - perspective: None, - dimension: None, - intertwine: None, - live_paint_gaps: None, - objects_on_path: None, -}; - -/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal -/// none. -#[derive(Clone, Debug, Default)] -pub struct Extras(Option>); - -impl Extras { - fn get(&self) -> &NodeExtras { - self.0.as_deref().unwrap_or(&NO_EXTRAS) - } -} - -impl PartialEq for Extras { - fn eq(&self, other: &Self) -> bool { - match (&self.0, &other.0) { - (Some(a), Some(b)) => a == b, - _ => self.get() == other.get(), - } - } -} - -impl Node { - /// The rarely set parts of this node (all unset when it has none). - #[inline] - pub fn extras(&self) -> &NodeExtras { - self.extras.get() - } - /// The rarely set parts of this node, to change: when the change is done (the guard dropped), - /// extras that were set are allocated and extras left all unset are let go. Setting one to - /// `None` on a node without extras allocates nothing. - #[inline] - pub fn extras_mut(&mut self) -> ExtrasMut<'_> { - ExtrasMut { slot: &mut self.extras.0, local: NodeExtras::default() } - } - /// The rarely set parts of this node, if it has any: to change what is there in place. - #[inline] - pub fn extras_if_any(&mut self) -> Option<&mut NodeExtras> { - self.extras.0.as_deref_mut() - } - /// The live shape of a path object, if it is one. - pub fn live_shape(&self) -> Option<&LiveShape> { - match &self.kind { - NodeKind::Path { live, .. } => live.as_deref(), - _ => None, - } - } - /// The live shape of a path object, if it is one, to change. - pub fn live_shape_mut(&mut self) -> Option<&mut LiveShape> { - match &mut self.kind { - NodeKind::Path { live, .. } => live.as_deref_mut(), - _ => None, - } - } - /// This node with opacity mask `mask` (or none). - pub fn with_mask(mut self, mask: Option>) -> Self { - self.extras_mut().mask = mask; - self - } - /// The extras, if this node has them allocated (for [`crate::mem`]'s estimate). - pub(crate) fn extras_box(&self) -> Option<&NodeExtras> { - self.extras.0.as_deref() - } -} - -/// [`Node::extras_mut`]: the node's extras while they change. -pub struct ExtrasMut<'a> { - slot: &'a mut Option>, - /// Stands for the extras of a node without any, boxed into it when dropped if one was set. - local: NodeExtras, -} - -impl std::ops::Deref for ExtrasMut<'_> { - type Target = NodeExtras; - fn deref(&self) -> &NodeExtras { - self.slot.as_deref().unwrap_or(&self.local) - } -} - -impl std::ops::DerefMut for ExtrasMut<'_> { - fn deref_mut(&mut self) -> &mut NodeExtras { - match self.slot.as_deref_mut() { - Some(e) => e, - None => &mut self.local, - } - } -} - -impl Drop for ExtrasMut<'_> { - fn drop(&mut self) { - match self.slot.as_deref() { - Some(e) if *e == NO_EXTRAS => *self.slot = None, - Some(_) => {} - None if self.local != NO_EXTRAS => *self.slot = Some(Box::new(std::mem::take(&mut self.local))), - None => {} - } - } -} - -/// How a [`Node`] is written: the flat field list of the file format, in its order, borrowed from -/// the node and its extras (nothing is copied). The node reads back through `NodeWire`. -impl Serialize for Node { - fn serialize(&self, s: S) -> Result { - use crate::skip::{is_default, is_one, is_true}; - use serde::ser::SerializeStruct; - let e = self.extras(); - // As the derive did: the fields written, then each field written or skipped in order. - let skips = [ - false, - self.name.is_none(), - is_true(&self.visible), - is_default(&self.locked), - is_one(&self.opacity), - is_default(&self.blend), - is_default(&self.isolate), - is_default(&self.knockout), - is_default(&self.knockout_shape), - is_default(&self.appearance), - e.mask.is_none(), - e.trace.is_none(), - e.wrap.is_none(), - e.graph.is_none(), - e.series_index.is_none(), - is_default(&e.type_outlines), - e.shaper.is_none(), - false, - e.graphic_style.is_none(), - e.attrs.is_none(), - e.slice.is_none(), - is_default(&self.bbox_angle), - e.perspective.is_none(), - e.dimension.is_none(), - e.intertwine.is_none(), - e.live_paint_gaps.is_none(), - e.objects_on_path.is_none(), - ]; - let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?; - let mut skip = skips.into_iter(); - macro_rules! field { - ($name:literal, $v:expr) => { - if skip.next().unwrap_or(false) { - st.skip_field($name)?; - } else { - st.serialize_field($name, $v)?; - } - }; - } - field!("id", &self.id); - field!("name", &self.name); - field!("visible", &self.visible); - field!("locked", &self.locked); - field!("opacity", &self.opacity); - field!("blend", &self.blend); - field!("isolate", &self.isolate); - field!("knockout", &self.knockout); - field!("knockout_shape", &self.knockout_shape); - field!("appearance", &self.appearance); - field!("mask", &e.mask); - field!("trace", &e.trace); - field!("wrap", &e.wrap); - field!("graph", &e.graph); - field!("series_index", &e.series_index); - field!("type_outlines", &e.type_outlines); - field!("shaper", &e.shaper); - field!("kind", &self.kind); - field!("graphic_style", &e.graphic_style); - field!("attrs", &e.attrs); - field!("slice", &e.slice); - field!("bbox_angle", &self.bbox_angle); - field!("perspective", &e.perspective); - field!("dimension", &e.dimension); - field!("intertwine", &e.intertwine); - field!("live_paint_gaps", &e.live_paint_gaps); - field!("objects_on_path", &e.objects_on_path); - st.end() - } -} - -/// How a [`Node`] is read: the flat field list of the file format. Fields move into the node -/// (and its extras, allocated only when one is set) without a copy of what they own. -#[derive(Deserialize)] -#[serde(rename = "Node")] -struct NodeWire { - id: NodeId, - #[serde(default)] - name: Option, - #[serde(default = "yes")] - visible: bool, - #[serde(default)] - locked: bool, - #[serde(default = "one")] - opacity: f32, - #[serde(default)] - blend: BlendMode, - #[serde(default)] - isolate: bool, - #[serde(default)] - knockout: Knockout, - #[serde(default)] - knockout_shape: bool, - #[serde(default)] - appearance: crate::Shared, - #[serde(default)] - mask: Option>, - #[serde(default)] - trace: Option>, - #[serde(default)] - wrap: Option, - #[serde(default)] - graph: Option>, - #[serde(default)] - series_index: Option, - #[serde(default)] - type_outlines: bool, - #[serde(default)] - shaper: Option>, - kind: NodeKind, - #[serde(default)] - graphic_style: Option, - #[serde(default)] - attrs: Option>, - #[serde(default)] - slice: Option>, - #[serde(default)] - bbox_angle: f64, - #[serde(default)] - perspective: Option>, - #[serde(default)] - dimension: Option>, - #[serde(default)] - intertwine: Option>, - #[serde(default)] - live_paint_gaps: Option>, - #[serde(default)] - objects_on_path: Option>, -} - -impl From for Node { - fn from(w: NodeWire) -> Self { - let extras = NodeExtras { - mask: w.mask, - trace: w.trace, - wrap: w.wrap, - graph: w.graph, - series_index: w.series_index, - type_outlines: w.type_outlines, - shaper: w.shaper, - graphic_style: w.graphic_style, - attrs: w.attrs, - slice: w.slice, - perspective: w.perspective, - dimension: w.dimension, - intertwine: w.intertwine, - live_paint_gaps: w.live_paint_gaps, - objects_on_path: w.objects_on_path, - }; - Node { - id: w.id, - name: w.name, - visible: w.visible, - locked: w.locked, - opacity: w.opacity, - blend: w.blend, - isolate: w.isolate, - knockout: w.knockout, - knockout_shape: w.knockout_shape, - appearance: w.appearance, - kind: w.kind, - bbox_angle: w.bbox_angle, - extras: Extras((extras != NO_EXTRAS).then(|| Box::new(extras))), - } - } -} - -/// Opacity mask: the luminance of the mask art sets the object's opacity (white = opaque). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct OpacityMask { - /// Mask art in document coordinates. - pub art: Arc, - /// Clip: outside the mask art is hidden. Off: outside the mask art stays visible. - #[serde(default = "yes")] - pub clip: bool, - /// Invert the mask's luminance. - #[serde(default)] - pub invert: bool, - /// Disabled masks are kept but not applied. - #[serde(default)] - pub disabled: bool, - /// Linked masks move with the object. - #[serde(default = "yes")] - pub linked: bool, -} - -impl OpacityMask { - pub fn new(art: Node, clip: bool) -> Self { - Self { art: Arc::new(art), clip, invert: false, disabled: false, linked: true } - } -} - -/// Every paint of `n` (and its children) white, opacities kept: an alpha mask's art as an opacity -/// mask's, whose luminance over the black outside the art is then the art's alpha. -pub fn whiten(n: &mut Node) { - let white = |p: &mut Paint| match p { - Paint::Solid { color, swatch, tint } => { - (*color, *swatch, *tint) = (Color::WHITE, None, 1.0); - } - Paint::Gradient(g) => { - for s in &mut g.gradient.stops { - (s.color, s.swatch, s.tint) = (Color::WHITE, None, 1.0); - } - } - Paint::None | Paint::Pattern { .. } => {} - }; - for item in &mut n.appearance.items { - white(item.paint_mut()); - } - match &mut n.kind { - NodeKind::Mesh(m) => m.points.iter_mut().for_each(|p| p.color = Color::WHITE), - NodeKind::Text(t) => t.runs.iter_mut().for_each(|r| { - white(&mut r.style.fill); - white(&mut r.style.stroke); - }), - _ => {} - } - if let Some(ch) = n.children_mut() { - for c in ch { - whiten(Arc::make_mut(c)); - } - } -} - -impl Node { - pub fn new(id: NodeId, kind: NodeKind) -> Self { - Self { - id, - name: None, - visible: true, - locked: false, - opacity: 1.0, - blend: BlendMode::Normal, - isolate: false, - knockout: Knockout::Neutral, - knockout_shape: false, - appearance: Appearance::default().into(), - kind, - bbox_angle: 0.0, - extras: Extras::default(), - } - } - pub fn path(id: NodeId, path: PathData, appearance: Appearance) -> Self { - let mut n = Self::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }); - n.appearance = appearance.into(); - n - } - pub fn group(id: NodeId, children: Vec>) -> Self { - Self::new(id, NodeKind::Group { children, clip: false }) - } - pub fn layer(id: NodeId, name: &str, color: LayerColor) -> Self { - let mut n = Self::new( - id, - NodeKind::Layer { color, template: false, printable: true, children: vec![], clip: false, preview: true, dim_images: None }, - ); - n.name = Some(name.to_string()); - n - } - pub fn children(&self) -> Option<&Vec>> { - match &self.kind { - NodeKind::Layer { children, .. } - | NodeKind::Group { children, .. } - | NodeKind::Compound { children, .. } - | NodeKind::Blend { children, .. } - | NodeKind::Envelope { content: children, .. } - | NodeKind::Repeat(RepeatSpec { source: children, .. }) - | NodeKind::Intertwine { children } => Some(children), - _ => None, - } - } - pub fn children_mut(&mut self) -> Option<&mut Vec>> { - match &mut self.kind { - NodeKind::Layer { children, .. } - | NodeKind::Group { children, .. } - | NodeKind::Compound { children, .. } - | NodeKind::Blend { children, .. } - | NodeKind::Envelope { content: children, .. } - | NodeKind::Repeat(RepeatSpec { source: children, .. }) - | NodeKind::Intertwine { children } => Some(children), - _ => None, - } - } - /// Does this object or layer move with its artboard? Locked and hidden ones only with - /// `locked_and_hidden` (Selection & Anchor Display › Move Locked and Hidden Artwork with - /// Artboard). - pub fn rides_with_artboard(&self, locked_and_hidden: bool) -> bool { - locked_and_hidden || (!self.locked && self.visible) - } - pub fn is_layer(&self) -> bool { - matches!(self.kind, NodeKind::Layer { .. }) - } - /// A template layer (Layer Options → Template). - pub fn is_template(&self) -> bool { - matches!(self.kind, NodeKind::Layer { template: true, .. }) - } - /// The art objects of this container: its children, looking through sublayers, which are not - /// objects (bottom first). With `editable`, only the visible, unlocked objects in visible, - /// unlocked, non-template sublayers. - pub fn layer_art(&self, editable: bool) -> Vec { - fn visit(n: &Node, editable: bool, out: &mut Vec) { - for c in n.children().into_iter().flatten() { - if editable && (!c.visible || c.locked || c.is_template()) { - continue; - } - if c.is_layer() { - visit(c, editable, out); - } else { - out.push(c.id); - } - } - } - let mut out = vec![]; - visit(self, editable, &mut out); - out - } - pub fn is_container(&self) -> bool { - self.children().is_some() - } - /// Full opacity, Normal blending, no isolation, knockout or opacity mask (the Layers panel - /// fills an object's target circle otherwise). - pub fn has_default_transparency(&self) -> bool { - self.opacity >= 1.0 - && self.blend == BlendMode::Normal - && !self.isolate - && self.knockout == Knockout::Neutral - && !self.knockout_shape - && self.extras().mask.is_none() - } - /// Kind name as the Layers panel / Properties panel shows it. - pub fn kind_label(&self) -> &'static str { - match &self.kind { - NodeKind::Layer { .. } => "Layer", - NodeKind::Group { clip: true, .. } => "Clip Group", - NodeKind::Group { .. } if self.extras().objects_on_path.is_some() => "Objects on Path", - NodeKind::Group { .. } => "Group", - NodeKind::Path { live: Some(l), .. } => l.label(), - NodeKind::Path { guide: true, .. } => "Guide", - NodeKind::Path { .. } => "Path", - NodeKind::Compound { .. } => "Compound Path", - NodeKind::Text(_) => "Type", - NodeKind::Image(_) => "Image", - NodeKind::SymbolInstance { .. } => "Symbol", - NodeKind::Blend { .. } => "Blend", - NodeKind::Envelope { .. } => "Envelope", - NodeKind::Mesh(_) => "Mesh", - NodeKind::Repeat(r) => r.kind.label(), - NodeKind::PlacedDocument(_) => "Placed Document", - NodeKind::Intertwine { .. } => "Intertwine", - } - } - /// Name shown in the Layers panel: explicit name or ``. - pub fn display_name(&self) -> String { - if let Some(n) = &self.name { - return n.clone(); - } - match &self.kind { - NodeKind::Text(t) => { - let s: String = t.plain_text().chars().take(32).collect(); - if s.is_empty() { "".into() } else { s } - } - _ => format!("<{}>", self.kind_label()), - } - } - - /// [`Self::display_name`], or its XML id when Preferences › Units › Identify Objects By is XML ID. - pub fn identify_label(&self, xml_id: bool) -> String { - let name = self.display_name(); - if xml_id { crate::xml_id::from_object_name(&name) } else { name } - } - /// Path data for path nodes. - pub fn path_data(&self) -> Option<&PathData> { - match &self.kind { - NodeKind::Path { path, .. } => Some(path), - _ => None, - } - } - pub fn path_data_mut(&mut self) -> Option<&mut PathData> { - match &mut self.kind { - NodeKind::Path { path, .. } => Some(path), - _ => None, - } - } - /// The path a path's or compound path's own strokes follow (a compound's members' together). - pub fn stroke_path(&self) -> Option { - match &self.kind { - NodeKind::Path { path, .. } => Some(path.to_bezpath()), - NodeKind::Compound { children, .. } => { - let mut bp = vectorcraft_geom::BezPath::new(); - children.iter().filter_map(|c| c.path_data()).for_each(|pd| bp.extend(pd.to_bezpath())); - Some(bp) - } - _ => None, - } - } - /// A quick box round everything the object can paint, for culling clicks: paths and compound - /// paths grow their geometric bounds by the farthest their strokes can reach from any path - /// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in - /// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers - /// without a clipping mask and Intertwine groups take in their members' boxes, grown by their - /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. - pub fn reach_bounds(&self) -> Option { - self.reach(None) - } - /// [`Node::reach_bounds`] with symbol instances measured by their symbol's art box from - /// `symbols`. An instance that only moves its art is measured as the art's visual box moved, - /// and any other instance is measured as its geometric box ([`Node::geometric_bounds_with`]) - /// grown by the farthest a stroke in the art can reach. - pub fn reach_bounds_with(&self, symbols: &SymbolBoxes) -> Option { - symbols.quickly(|| self.reach(Some(symbols))) - } - /// The box of [`Node::reach_bounds`], or of [`Node::reach_bounds_with`] when `symbols` is given. - pub(crate) fn reach(&self, symbols: Option<&SymbolBoxes>) -> Option { - match &self.kind { - NodeKind::Path { .. } | NodeKind::Compound { .. } => { - let o = self.appearance.outset(); - self.geometric(symbols).map(|b| b.inflate(o, o)) - } - // The members' reach, grown by the container's own strokes. - NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => { - let o = self.appearance.outset(); - children - .iter() - .skip(usize::from(self.extras().shaper.is_some())) - .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))) - .map(|b| b.inflate(o, o)) - } - NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))), - // The frame and each shape the image's own fills and strokes paint, a stroke's grown by - // the farthest it can reach from its shape. - NodeKind::Image(_) => crate::hit::image_paint(self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| { - let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; - vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) - }), - _ => self.visual(symbols), - } - } - /// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path. A - /// symbol instance is measured as its transform applied to the 20 × 20 square around the origin - /// that symbols made in the app keep their art in ([`Node::geometric_bounds_with`] measures - /// its art). - pub fn geometric_bounds(&self) -> Option { - self.geometric(None) - } - /// [`Node::geometric_bounds`] with each symbol instance measured as its transform applied to - /// its symbol's art box from `symbols`. An instance is measured as the square when its symbol - /// is missing, when its symbol or a symbol nested in its art holds an instance of itself, and - /// when symbols nest 32 deep in its art. - pub fn geometric_bounds_with(&self, symbols: &SymbolBoxes) -> Option { - self.geometric(Some(symbols)) - } - /// The box of [`Node::geometric_bounds`], or of [`Node::geometric_bounds_with`] when `symbols` - /// is given. - pub(crate) fn geometric(&self, symbols: Option<&SymbolBoxes>) -> Option { - let union = |nodes: &[Arc]| nodes.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric(symbols))); - match &self.kind { - NodeKind::Path { path, .. } => path.bounds(), - NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => { - children.first().and_then(|c| c.geometric(symbols)) - } - NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => children - .iter() - .skip(usize::from(self.extras().shaper.is_some())) - .filter(|c| c.visible || !matches!(self.kind, NodeKind::Layer { .. })) - .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric(symbols))), - NodeKind::Text(t) => self.projected(t.bounds()), - NodeKind::Image(im) => Some(im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, im.width as f64, im.height as f64))), - NodeKind::SymbolInstance { symbol, xf } => { - let art = symbols.and_then(|s| s.art(symbol)).map_or(SYMBOL_SQUARE, |a| a.geometric); - self.projected(Some(xf.transform_rect_bbox(art))) - } - NodeKind::Blend { children, spec } => vectorcraft_geom::union_opt(union(children), spec.spine.as_ref().and_then(|s| s.bounds())), - NodeKind::Envelope { content, kind, frame, .. } => crate::live::envelope_bounds(content, kind, **frame), - NodeKind::Mesh(m) => m.bounds(), - // Each copy is measured where the repeat draws it: `RepeatSpec::transforms` lays the - // copies out by the source's bounds measured without the document. - NodeKind::Repeat(r) => r.copies_bounds(union(&r.source)?), - NodeKind::PlacedDocument(p) => Some(p.bounds()), - // The members drawn over the others are drawn where they are. - NodeKind::Intertwine { children } => union(children), - } - } - /// Visual bounds: what the object paints, its strokes included (paths and compound paths - /// measure theirs along their own shape, see [`Appearance::stroked_bounds`]). An image is - /// measured by its frame. A symbol instance is measured as in [`Node::geometric_bounds`], - /// grown by its own strokes' reach ([`Node::visual_bounds_with`] measures its art). - pub fn visual_bounds(&self) -> Option { - self.visual(None) - } - /// [`Node::visual_bounds`] with symbol instances measured by their symbol's art from - /// `symbols`, the strokes in it included. An instance that only moves its art is measured as - /// the art's visual box moved. Any other instance is measured as its art transformed by it with - /// the strokes at their own weight, as the renderer draws it, and never smaller than its - /// geometric box ([`Node::geometric_bounds_with`]). Instances inside symbol art are measured as - /// in [`Node::reach_bounds_with`]. In boxes made by [`SymbolBoxes::with_brush_art`], the box of - /// an instance whose art holds brushed strokes grows by as far as their brush art can paint. In - /// boxes made by [`SymbolBoxes::without_art_strokes`], an instance is measured as its art's - /// geometric box placed by its transform, grown by its own strokes. - pub fn visual_bounds_with(&self, symbols: &SymbolBoxes) -> Option { - self.visual(Some(symbols)) - } - /// The box of [`Node::visual_bounds`], or of [`Node::visual_bounds_with`] when `symbols` is - /// given. - pub(crate) fn visual(&self, symbols: Option<&SymbolBoxes>) -> Option { - match &self.kind { - NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => { - // A clipping path that paints (see `clip_paint`) strokes over the clip edge. - let clip = children.first()?; - if matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)) { - clip.visual(symbols) - } else { - clip.geometric(symbols) - } - } - NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))), - NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => { - // The container's own strokes paint around its members. - let o = self.appearance.outset(); - children - .iter() - .skip(usize::from(self.extras().shaper.is_some())) - .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))) - .map(|b| b.inflate(o, o)) - } - NodeKind::Blend { children, spec } => { - let b = children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))); - let o = crate::live::max_outset(children, symbols); - vectorcraft_geom::union_opt(b, spec.spine.as_ref().and_then(|s| s.bounds()).map(|r| r.inflate(o, o))) - } - NodeKind::Envelope { content, .. } | NodeKind::Repeat(RepeatSpec { source: content, .. }) => { - let o = crate::live::max_outset(content, symbols); - self.geometric(symbols).map(|b| b.inflate(o, o)) - } - NodeKind::Path { .. } | NodeKind::Compound { .. } => { - let b = self.geometric(symbols)?; - Some(self.appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default())) - } - NodeKind::SymbolInstance { symbol, xf } => { - let b = match symbols.and_then(|s| Some((s, s.art(symbol)?))) { - Some((s, art)) if !s.art_strokes() => xf.transform_rect_bbox(art.geometric), - Some((_, art)) if moves_only(*xf) => xf.transform_rect_bbox(art.visual), - Some((s, art)) => { - let placed = xf.transform_rect_bbox(art.geometric); - match s.placed_visual(symbol, *xf) { - Some(v) => v.union(placed), - None => placed.inflate(art.reach, art.reach), - } - } - None => xf.transform_rect_bbox(SYMBOL_SQUARE), - }; - let o = self.appearance.outset() + symbols.map_or(0.0, |s| s.brush_pad(symbol)); - self.projected(Some(b)).map(|b| b.inflate(o, o)) - } - NodeKind::Text(t) => { - // The characters' strokes paint around the glyphs, scaled with the type. - let k = Scaling::factor(t.xf).unwrap_or(1.0); - let chars = t.runs.iter().map(|r| r.style.stroke_outset()).fold(0.0, f64::max) * k; - let o = self.appearance.outset().max(chars); - self.geometric(symbols).map(|b| b.inflate(o, o)) - } - // An image is measured by its frame, without its own fills and strokes. - NodeKind::Image(_) => self.geometric(symbols), - _ => { - let o = self.appearance.outset(); - self.geometric(symbols).map(|b| b.inflate(o, o)) - } - } - } - /// Apply an affine transform to the geometry (and gradients) of this node and its descendants. - /// `scaling` says what else scales by the transform's mean scale (a bool: stroke weights - /// only, see [`Scaling`]). - pub fn transform(&mut self, a: Affine, scaling: impl Into) { - self.transform_scaled(a, &scaling.into()); - } - fn transform_scaled(&mut self, a: Affine, sc: &Scaling) { - // A dimension's measurement moves with it. - if let Some(e) = self.extras_if_any() - && let Some(dimension) = &mut e.dimension - { - dimension.transform(a); - } - // The frames of the objects attached to a path move with them. - if let Some(e) = self.extras_if_any() - && let Some(on_path) = &mut e.objects_on_path - { - on_path.transform(a); - } - if !self.is_layer() { - self.bbox_angle = crate::orient::transformed_angle(self.bbox_angle, a); - } - // Type and symbols in perspective keep looking the same, moved by `a`. - self.transform_projection(a); - // Refitting an unplaced gradient only reproduces moves and uniform scales. - if !keeps_gradient_fit(a) { - self.pin_gradients(); - } - let k = Scaling::factor(a); - if let Some(k) = k - && sc.strokes - { - self.appearance.scale_strokes(k); - if let Some(f) = sc.effects { - self.appearance.scale_effects(k, f); - } - } - // Only through `DerefMut` when there is something to change: the appearance is shared - // copy-on-write (`Shared`), and a move must not copy what it leaves as it is. - if self.appearance.gradients().next().is_some() { - self.appearance.transform_gradients(a); - } - if sc.patterns { - crate::pattern::transform_pattern_paints(self, a); - } - match &mut self.kind { - NodeKind::Path { path, live, .. } => { - path.transform(a); - if let Some(l) = live { - // A rectangle scaled unevenly keeps circular corners: its path is regenerated. - let reshaped = l.transform(a); - let kept = sc.keep_corners && k.is_some_and(|k| l.keep_corners(k)); - if reshaped || kept { - *path = l.to_path(); - } - } - } - NodeKind::Layer { children, .. } - | NodeKind::Group { children, .. } - | NodeKind::Compound { children, .. } - | NodeKind::Intertwine { children } => { - for c in children.iter_mut() { - Arc::make_mut(c).transform_scaled(a, sc); - } - } - NodeKind::Text(t) => { - t.transform(a); - // Character strokes scale with the type: undo that when strokes keep their weight. - if sc.keep_type_strokes - && let Some(k) = k.filter(|k| *k > 1e-12) - { - t.scale_char_strokes(1.0 / k); - } - } - NodeKind::Image(im) => im.xf = a * im.xf, - NodeKind::PlacedDocument(p) => p.xf = a * p.xf, - NodeKind::SymbolInstance { xf, .. } => *xf = a * *xf, - NodeKind::Blend { children, spec } => { - for c in children.iter_mut() { - Arc::make_mut(c).transform_scaled(a, sc); - } - if let Some(s) = &mut spec.spine { - s.transform(a); - } - } - NodeKind::Envelope { content, kind, frame, .. } => { - for c in content.iter_mut() { - Arc::make_mut(c).transform_scaled(a, sc); - } - **frame = crate::live::envelope_frame(a * **frame); - match &mut **kind { - EnvelopeKind::Mesh { points, handles, .. } => { - for p in points.iter_mut() { - *p = a * *p; - } - // Handles are offsets: they take the linear part. - let [m0, m1, m2, m3, _, _] = a.as_coeffs(); - let lin = Affine::new([m0, m1, m2, m3, 0.0, 0.0]); - for h in handles.iter_mut().flatten() { - *h = (lin * h.to_point()).to_vec2(); - } - } - EnvelopeKind::TopObject { path } => path.transform(a), - EnvelopeKind::Warp { .. } => {} - } - } - NodeKind::Mesh(m) => m.transform(a), - NodeKind::Repeat(r) => r.transform(a, *sc), - } - if let Some(m) = self.extras_if_any().and_then(|e| e.mask.as_mut()) - && m.linked - { - Arc::make_mut(&mut m.art).transform_scaled(a, sc); - } - // The area where an Intertwine member is drawn over the others moves with it. - if let Some(area) = self.extras_if_any().and_then(|e| e.intertwine.as_mut()) { - area.transform(a); - } - } - /// Visit this node and all descendants depth first (paint order). - pub fn walk<'a>(&'a self, f: &mut impl FnMut(&'a Node)) { - f(self); - if let Some(ch) = self.children() { - for c in ch { - c.walk(f); - } - } - } - /// Count of nodes in this subtree. - pub fn count(&self) -> usize { - let mut n = 0; - self.walk(&mut |_| n += 1); - n - } - /// Fix this node's unplaced gradients to their fit on its current bounds (before a transform - /// or warp that refitting wouldn't reproduce). Descendants pin their own when transformed. - pub fn pin_gradients(&mut self) { - if self.appearance.has_unplaced_gradient() - && let Some(b) = self.geometric_bounds() - { - self.appearance.pin_gradients(b); - } - } - /// The paint behind the Fill (or Stroke) proxy, the map from its space to the document and - /// the box (in that space) an unplaced gradient fits. `item` (the Appearance panel's active - /// item) stands in for the topmost fill or stroke when it is of the proxy's kind. Otherwise - /// type objects paint their runs (the first run speaks for all) in text space, fitted to the - /// layout bounds; everything else paints its fill or stroke in the document, fitted to the - /// geometric bounds. Strokes fit the box grown by half their weight. - pub fn proxy_paint(&self, stroke: bool, item: Option) -> Option<(&vectorcraft_color::Paint, Affine, Rect)> { - let item = self.appearance.item_of_kind(item, !stroke); - if item.is_none() - && let NodeKind::Text(t) = &self.kind - { - let st = &t.runs.first()?.style; - let b = t.local_bounds(); - return Some(if stroke { (&st.stroke, t.xf, crate::appearance::stroke_paint_bounds(b, st.stroke_width)) } else { (&st.fill, t.xf, b) }); - } - // An object without bounds (an empty path) still shows its paints, fitted to an empty box. - let b = self.geometric_bounds().unwrap_or(Rect::ZERO); - if stroke { - self.appearance.stroke_at(item).map(|s| (&s.paint, Affine::IDENTITY, s.paint_bounds(b))) - } else { - self.appearance.fill_at(item).map(|f| (&f.paint, Affine::IDENTITY, b)) - } - } - /// The gradient behind the Fill (or Stroke) proxy and its placement in document coordinates - /// (see [`Node::proxy_paint`]): what the gradient annotator shows and edits. - pub fn proxy_gradient(&self, stroke: bool, item: Option) -> Option<(&vectorcraft_color::GradientPaint, vectorcraft_color::GradientGeom)> { - let (paint, to_doc, b) = self.proxy_paint(stroke, item)?; - let vectorcraft_color::Paint::Gradient(g) = paint else { return None }; - let mut geom = g.resolve(b); - if to_doc != Affine::IDENTITY { - geom.transform(to_doc, g.gradient.kind); - } - Some((g, geom)) - } - /// The freeform gradient behind the Fill (or Stroke) proxy, its points in document coordinates - /// (the automatic ones while unplaced), and the length its spreads are fractions of there - /// (see [`Node::proxy_paint`]): what the Gradient tool's freeform annotator shows and edits. - pub fn proxy_freeform(&self, stroke: bool, item: Option) -> Option<(vectorcraft_color::Freeform, f64)> { - let (paint, to_doc, b) = self.proxy_paint(stroke, item)?; - let vectorcraft_color::Paint::Gradient(g) = paint else { return None }; - if g.gradient.kind != vectorcraft_color::GradientKind::Freeform { - return None; - } - let mut f = g.freeform_on(b).into_owned(); - let mut scale = vectorcraft_color::freeform::spread_scale(b); - if to_doc != Affine::IDENTITY { - f.transform(to_doc); - scale *= to_doc.determinant().abs().sqrt(); - } - Some((f, scale)) - } -} - -/// Unites filled regions (each under its own fill rule) into one path filled non-zero. Booleans -/// live above this crate (`vectorcraft-pathops`), so callers supply it. -pub type Uniter<'a> = &'a dyn Fn(&[(BezPath, FillRule)]) -> BezPath; - -impl Node { - /// The filled regions this object clips to as the clipping path of a clip group, in document - /// space, each with its fill rule: a path, a compound path (with its holes), an image's frame, - /// text outlined by `text` (glyph outlines need the font engine, above this crate), the visible - /// members of a group (their union) and the clipping path of a nested clip group. Live objects - /// are evaluated first. Guides and symbol instances add nothing. - pub fn clip_shapes(&self, text: Outliner) -> Vec<(BezPath, FillRule)> { - let mut out = vec![]; - self.push_clip_shapes(text, &mut out); - out - } - - fn push_clip_shapes(&self, text: Outliner, out: &mut Vec<(BezPath, FillRule)>) { - match &self.kind { - NodeKind::Path { guide: true, .. } | NodeKind::SymbolInstance { .. } => {} - NodeKind::Path { path, rule, .. } => out.push((path.to_bezpath(), *rule)), - NodeKind::Compound { children, rule } => { - let mut bp = BezPath::new(); - for p in children.iter().filter_map(|c| c.path_data()) { - bp.extend(p.to_bezpath()); - } - out.push((bp, *rule)); - } - NodeKind::Group { children, clip: true } => { - if let Some(c) = children.first() { - c.push_clip_shapes(text, out); - } - } - NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { - for c in children.iter().skip(usize::from(self.extras().shaper.is_some())).filter(|c| c.visible) { - c.push_clip_shapes(text, out); - } - } - NodeKind::Text(_) => { - if let Some(o) = text.and_then(|f| f(self)) { - o.push_clip_shapes(None, out); - } - } - NodeKind::Image(im) => { - let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf); - out.push((frame.to_bezpath(), FillRule::NonZero)); - } - NodeKind::PlacedDocument(p) => { - let frame = shapes::rectangle(p.natural()).transformed(p.xf); - out.push((frame.to_bezpath(), FillRule::NonZero)); - } - NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => { - crate::live::expand_deep(self, text).push_clip_shapes(text, out); - } - } - } - - /// The region this object clips to as one path and fill rule ([`Self::clip_shapes`]), shared - /// by the renderer and the SVG and PDF writers so every output clips alike. One shape keeps its - /// own rule; several are united by `unite` (filled non-zero). `None` when there is nothing to - /// clip by: the clipped art is then hidden. - pub fn clip_outline(&self, text: Outliner, unite: Uniter) -> Option<(BezPath, FillRule)> { - let mut shapes = self.clip_shapes(text); - match shapes.len() { - 0 => None, - 1 => shapes.pop(), - _ => Some((unite(&shapes), FillRule::NonZero)), - } - } - - /// What this object paints as the clipping path of a clip group, shared by the renderer and - /// the SVG and PDF writers: its fills, painted behind the clipped art, and its strokes, painted - /// over it (unclipped). Each part is this object keeping only those appearance items (type: - /// also only its characters' fills or strokes); `None` where it paints nothing, as right after - /// Make Clipping Mask. Only paths, compound paths and type paint as clipping paths. - pub fn clip_paint(&self) -> ClipPaint { - use crate::appearance::AppearanceItem; - let runs = match &self.kind { - NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => None, - NodeKind::Text(t) => Some(&t.runs), - _ => return ClipPaint::default(), - }; - let paints = |fill: bool| { - let item = |i: &AppearanceItem| match i { - AppearanceItem::Fill(f) => fill && f.visible && !f.paint.is_none(), - AppearanceItem::Stroke(s) => !fill && s.visible && !s.paint.is_none() && s.width > 0.0, - }; - let run = |r: &crate::text::TextRun| if fill { !r.style.fill.is_none() } else { !r.style.stroke.is_none() && r.style.stroke_width > 0.0 }; - self.appearance.items.iter().any(item) || runs.is_some_and(|rs| rs.iter().any(run)) - }; - let part = |fill: bool| { - paints(fill).then(|| { - let mut n = self.clone(); - for i in (0..n.appearance.items.len()).rev() { - if matches!(n.appearance.items[i], AppearanceItem::Fill(_)) != fill { - n.appearance.remove_item(i); - } - } - if let NodeKind::Text(t) = &mut n.kind { - for r in &mut t.runs { - *(if fill { &mut r.style.stroke } else { &mut r.style.fill }) = vectorcraft_color::Paint::None; - } - } - n - }) - }; - ClipPaint { fill: part(true), stroke: part(false) } - } -} - -/// What a clipping path paints ([`Node::clip_paint`]). -#[derive(Clone, Debug, Default)] -pub struct ClipPaint { - /// The clipping path with only its fills: painted behind the clipped art (inside the clip). - pub fill: Option, - /// The clipping path with only its strokes: painted over the clipped art, not clipped. - pub stroke: Option, -} - -/// Knockout Group state of a container (the Transparency panel's three-state checkbox). In a -/// knockout group each child composites against the group's backdrop, so it hides the children -/// below it instead of showing them through its transparency. Neutral passes the enclosing -/// group's setting through to the children. Files from before the three states stored a bool: -/// `true` loads as On, `false` as Neutral. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub enum Knockout { - #[default] - Neutral, - Off, - On, -} - -impl Knockout { - pub const ALL: [Knockout; 3] = [Knockout::Neutral, Knockout::Off, Knockout::On]; - - /// Name in files and command parameters. - pub fn label(self) -> &'static str { - match self { - Knockout::Neutral => "neutral", - Knockout::Off => "off", - Knockout::On => "on", - } - } - /// A name ([`Self::label`], any case) or a bool as older files and commands wrote it. - pub fn from_value(v: &serde_json::Value) -> Option { - match v { - serde_json::Value::Bool(b) => Some(Self::from(*b)), - serde_json::Value::String(s) => Self::ALL.into_iter().find(|k| k.label().eq_ignore_ascii_case(s.trim())), - _ => None, - } - } - /// The state a click on the checkbox moves to: on → neutral → off → on. - pub fn cycle(self) -> Self { - match self { - Knockout::On => Knockout::Neutral, - Knockout::Neutral => Knockout::Off, - Knockout::Off => Knockout::On, - } - } - /// Whether children of a group with this state knock each other out, inside a group (or page) - /// where that is `enclosing`. - pub fn resolve(self, enclosing: bool) -> bool { - match self { - Knockout::Neutral => enclosing, - Knockout::Off => false, - Knockout::On => true, - } - } -} - -impl From for Knockout { - fn from(b: bool) -> Self { - if b { Knockout::On } else { Knockout::Neutral } - } -} - -impl Serialize for Knockout { - fn serialize(&self, s: S) -> Result { - s.serialize_str(self.label()) - } -} - -impl<'de> Deserialize<'de> for Knockout { - fn deserialize>(d: D) -> Result { - let v = serde_json::Value::deserialize(d)?; - Self::from_value(&v).ok_or_else(|| serde::de::Error::custom(format!("invalid knockout {v}"))) - } -} - -impl Node { - /// Whether the children of this group or layer knock each other out, inside a group (or page) - /// where that is `enclosing`. - pub fn knocks_out(&self, enclosing: bool) -> bool { - matches!(self.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && self.knockout.resolve(enclosing) - } - - /// A plain group or layer that is neutral to knockout and has no transparency or appearance - /// of its own: inside a knockout group its children composite as the group's own children. - pub fn passes_knockout_through(&self) -> bool { - matches!(self.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { template: false, clip: false, .. }) - && self.has_default_transparency() - && self.appearance.items.is_empty() - && self.appearance.effects.is_empty() - } - - /// The visible elements of a knockout group made of `children` (bottom first): neutral plain - /// groups ([`Self::passes_knockout_through`]) contribute their children instead of themselves. - pub fn knockout_elements(children: &[Arc]) -> Vec<&Arc> { - fn push<'a>(children: &'a [Arc], out: &mut Vec<&'a Arc>) { - for c in children.iter().filter(|c| c.visible) { - match c.children() { - Some(ch) if c.passes_knockout_through() => push(ch, out), - _ => out.push(c), - } - } - } - let mut out = Vec::with_capacity(children.len()); - push(children, &mut out); - out - } - - /// Whether this is a clip group or a layer with a clipping mask: its first child clips the rest. - pub fn clips(&self) -> bool { - matches!(self.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }) - } - - /// Make this group or layer clip its children by its first child, or stop it. - pub fn set_clips(&mut self, on: bool) { - if let NodeKind::Group { clip, .. } | NodeKind::Layer { clip, .. } = &mut self.kind { - *clip = on; - } - } - - /// Whether blending inside this object reaches the art below it unless the object isolates - /// it: a blend mode other than Normal on a child (or, in a leaf, on a fill or stroke), - /// directly or through children that don't isolate their own blending. - pub fn blends_through(&self) -> bool { - self.blends_through_with(&mut |c| c.blends_through()) - } - - /// [`Self::blends_through`], with `inner` answering it for the children (e.g. from a cache). - pub fn blends_through_with(&self, inner: &mut dyn FnMut(&Arc) -> bool) -> bool { - match self.children() { - Some(ch) if !matches!(self.kind, NodeKind::Compound { .. }) => Self::children_blend(ch, inner), - _ => self.appearance.items.iter().any(|i| i.visible() && i.blend() != BlendMode::Normal), - } - } - - /// [`Self::blends_through`] of a group made of `children` (`inner` answers it for each child). - pub fn children_blend(children: &[Arc], inner: &mut dyn FnMut(&Arc) -> bool) -> bool { - children.iter().any(|c| c.visible && (c.blend != BlendMode::Normal || (!c.isolate && inner(c)))) - } -} - -impl Node { - /// The Appearance panel's row for what this object's own fills and strokes paint around: - /// "Contents" for a group or layer (its members) and for an image (its pixels), "Characters" - /// for type; `None` for objects whose fills and strokes paint their own geometry. - pub fn contents_label(&self) -> Option<&'static str> { - match self.kind { - NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Image(_) => Some("Contents"), - NodeKind::Text(_) => Some("Characters"), - _ => None, - } - } -} - -/// Window → Attributes: an object's settings that don't change how it prints. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ObjectAttributes { - /// Show Center / Don't Show Center (`None`: the object kind's default, [`Node::shows_center`]). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub show_center: Option, - /// Image Map: the clickable area the URL covers in web output. - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub image_map: ImageMap, - /// URL the object links to (SVG ``; empty: none). - #[serde(default, skip_serializing_if = "String::is_empty")] - pub url: String, - /// The note shown in the Attributes panel. - #[serde(default, skip_serializing_if = "String::is_empty")] - pub note: String, - /// The object's own data, in order: SVG's `data-*` attributes (`data-pivot="100,180"` is - /// `("pivot", "100,180")`), kept from import to export (`object.setProps {data}`). - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub data: Vec<(String, String)>, - /// Window › SVG Interactivity: the JavaScript each event runs, in the panel's order - /// (`("onclick", "alert(1)")`, one entry per event of [`SVG_EVENTS`]). SVG export writes them as - /// the element's event attributes; nothing in VectorCraft runs them. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub events: Vec<(String, String)>, -} - -/// The events the SVG Interactivity panel attaches JavaScript to, by the names of the SVG event -/// attributes that run it. -pub const SVG_EVENTS: [&str; 19] = [ - "onfocusin", - "onfocusout", - "onactivate", - "onmousedown", - "onmouseup", - "onclick", - "onmouseover", - "onmousemove", - "onmouseout", - "onkeydown", - "onkeypress", - "onkeyup", - "onload", - "onerror", - "onabort", - "onunload", - "onzoom", - "onresize", - "onscroll", -]; - -/// The most JavaScript files a document links (`Document::svg_scripts`): SVG import keeps the -/// first ones and warns about the rest, and `svgInteractivity.addFile` refuses another. -pub const MAX_SVG_SCRIPTS: usize = 64; - -/// The Attributes panel's Image Map shapes. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum ImageMap { - #[default] - None, - Rectangle, - Polygon, -} - -impl ImageMap { - pub const ALL: [ImageMap; 3] = [ImageMap::None, ImageMap::Rectangle, ImageMap::Polygon]; - - pub fn label(self) -> &'static str { - match self { - ImageMap::None => "None", - ImageMap::Rectangle => "Rectangle", - ImageMap::Polygon => "Polygon", - } - } - - /// Parse a label or serialized name, ignoring case. - pub fn parse(s: &str) -> Option { - Self::ALL.into_iter().find(|m| m.label().eq_ignore_ascii_case(s)) - } -} - -impl Node { - /// The URL this object links to, if any. - pub fn url(&self) -> Option<&str> { - self.extras().attrs.as_deref().map(|a| a.url.as_str()).filter(|u| !u.is_empty()) - } - - /// Whether the canvas shows this object's centre point when it is selected: as set in the - /// Attributes panel, else [`Self::shows_center_by_default`]. - pub fn shows_center(&self) -> bool { - self.extras().attrs.as_deref().and_then(|a| a.show_center).unwrap_or_else(|| self.shows_center_by_default()) - } - - /// Shapes drawn with the shape tools (live rectangles, ellipses and polygons) show their centre. - pub fn shows_center_by_default(&self) -> bool { - matches!(&self.kind, NodeKind::Path { live: Some(l), .. } if !matches!(**l, LiveShape::Line { .. } | LiveShape::Path { .. })) - } - - /// Change this object's attributes with `f`; all-default attributes are dropped. - pub fn edit_attrs(&mut self, f: impl FnOnce(&mut ObjectAttributes) -> R) -> R { - let mut a = self.extras_mut().attrs.take().unwrap_or_default(); - let r = f(&mut a); - self.extras_mut().attrs = (*a != ObjectAttributes::default()).then_some(a); - r - } -} - -impl Node { - /// Whether this object shows any transparency, itself or anything inside it: object, fill or - /// stroke opacity below 100%, a blend mode, an opacity mask, effects or transparent gradient - /// stops. Hidden objects show none. - pub fn shows_transparency(&self) -> bool { - use vectorcraft_color::Paint; - let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0)); - 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) - || 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()))) - } -} - -/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)? -fn keeps_gradient_fit(a: Affine) -> bool { - let [m0, m1, m2, m3, _, _] = a.as_coeffs(); - let eps = 1e-12 * m0.abs().max(1.0); - m0 > 0.0 && m1.abs() <= eps && m2.abs() <= eps && (m0 - m3).abs() <= eps -} - -impl Node { - /// Whether a document point lies in this object's filled regions ([`Node::clip_shapes`]; true - /// everywhere for objects without them, such as type, whose boxes stand in). - pub fn contains_fn(&self) -> impl Fn(Point) -> bool + use<> { - let shapes = self.clip_shapes(None); - move |p| shapes.is_empty() || shapes.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p)) - } -} - -/// Reading a [`NodeKind`]. Derived, an internally tagged enum buffers each kind (with every -/// object inside a group, again at each level of nesting) before reading it, since `type` may come -/// anywhere among its fields. Files have it first (it is written first): then the kind is read -/// straight from the file. Otherwise (hand-written files, values whose keys are sorted) the -/// fields before `type` are buffered, and only those. -mod kind_de { - use std::fmt; - use std::sync::Arc; - - use serde::de::value::{MapAccessDeserializer, StringDeserializer}; - use serde::de::{self, DeserializeSeed, Deserializer, EnumAccess, IntoDeserializer, MapAccess, VariantAccess, Visitor}; - use serde::{Deserialize, forward_to_deserialize_any}; - use vectorcraft_geom::{Affine, FillRule, PathData}; - - use super::{LayerColor, LiveShape, Node, NodeKind, yes}; - use crate::live::{BlendSpec, EnvelopeKind, GradientMesh}; - use crate::pattern::RepeatSpec; - use crate::text::TextObject; - - /// The kinds and their fields as [`NodeKind`] has them, with the defaults its field attributes - /// note (the compiler checks that every field is here), read externally tagged: the kind from - /// `type`, its fields from the rest of the object ([`Tagged`]). - #[derive(Deserialize)] - #[serde(remote = "NodeKind", rename_all = "lowercase")] - enum KindDef { - Layer { - color: LayerColor, - #[serde(default)] - template: bool, - #[serde(default = "yes")] - printable: bool, - children: Vec>, - #[serde(default)] - clip: bool, - #[serde(default = "yes")] - preview: bool, - #[serde(default)] - dim_images: Option, - }, - Group { - children: Vec>, - #[serde(default)] - clip: bool, - }, - Path { - path: PathData, - #[serde(default)] - rule: FillRule, - #[serde(default)] - live: Option>, - #[serde(default)] - clipping: bool, - #[serde(default)] - guide: bool, - }, - Compound { - children: Vec>, - #[serde(default)] - rule: FillRule, - }, - Text(Box), - Image(Box), - SymbolInstance { - symbol: String, - xf: Affine, - }, - Blend { - children: Vec>, - #[serde(default)] - spec: Box, - }, - Envelope { - content: Vec>, - kind: Box, - #[serde(default = "crate::live::default_fidelity")] - fidelity: f64, - #[serde(default)] - editing: bool, - #[serde(default)] - options: crate::live::EnvelopeOptions, - #[serde(default)] - frame: Box, - }, - Mesh(GradientMesh), - Repeat(RepeatSpec), - PlacedDocument(Box), - Intertwine { - children: Vec>, - }, - } - - impl<'de> Deserialize<'de> for NodeKind { - fn deserialize>(d: D) -> Result { - d.deserialize_map(KindVisitor) - } - } - - struct KindVisitor; - - impl<'de> Visitor<'de> for KindVisitor { - type Value = NodeKind; - - fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str("an object kind (a map with `type`)") - } - - fn visit_map>(self, mut map: A) -> Result { - let mut before = vec![]; - while let Some(key) = map.next_key::()? { - if key == "type" { - let tag: String = map.next_value()?; - return KindDef::deserialize(Tagged { tag, map: Buffered { before: before.into_iter(), value: None, map } }); - } - before.push((key, map.next_value::()?)); - } - Err(de::Error::missing_field("type")) - } - } - - /// The fields read before `type` (buffered), then the rest of the object. - struct Buffered { - before: std::vec::IntoIter<(String, serde_json::Value)>, - value: Option, - map: A, - } - - impl<'de, A: MapAccess<'de>> MapAccess<'de> for Buffered { - type Error = A::Error; - - fn next_key_seed>(&mut self, seed: K) -> Result, A::Error> { - match self.before.next() { - Some((key, value)) => { - self.value = Some(value); - seed.deserialize(StringDeserializer::::new(key)).map(Some) - } - None => self.map.next_key_seed(seed), - } - } - - fn next_value_seed>(&mut self, seed: V) -> Result { - match self.value.take() { - Some(value) => seed.deserialize(value).map_err(de::Error::custom), - None => self.map.next_value_seed(seed), - } - } - } - - /// An object whose `type` was read: the kind is `tag`, its fields are the rest of `map`. - struct Tagged { - tag: String, - map: A, - } - - impl<'de, A: MapAccess<'de>> Deserializer<'de> for Tagged { - type Error = A::Error; - - fn deserialize_any>(self, visitor: V) -> Result { - visitor.visit_enum(self) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf - option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum - identifier ignored_any - } - } - - impl<'de, A: MapAccess<'de>> EnumAccess<'de> for Tagged { - type Error = A::Error; - type Variant = Fields; - - fn variant_seed>(self, seed: V) -> Result<(V::Value, Fields), A::Error> { - let kind = seed.deserialize(self.tag.into_deserializer())?; - Ok((kind, Fields(self.map))) - } - } - - /// A kind's fields: the rest of the object. - struct Fields(A); - - impl<'de, A: MapAccess<'de>> VariantAccess<'de> for Fields { - type Error = A::Error; - - fn unit_variant(self) -> Result<(), A::Error> { - Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"an object kind with fields")) - } - - fn newtype_variant_seed>(self, seed: T) -> Result { - seed.deserialize(MapAccessDeserializer::new(self.0)) - } - - fn tuple_variant>(self, _: usize, _: V) -> Result { - Err(de::Error::invalid_type(de::Unexpected::TupleVariant, &"an object kind with fields")) - } - - fn struct_variant>(self, _: &'static [&'static str], visitor: V) -> Result { - visitor.visit_map(self.0) - } - } -} - #[cfg(test)] -mod tests { - use super::*; - - /// A node writes its rarely set parts among the others, in the file's field order, and reads - /// them back into its extras; a node without any keeps none. - #[test] - fn extras_are_written_flat_in_order() { - let mut n = Node::path(NodeId(7), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art()); - n.name = Some("n".into()); - n.knockout_shape = true; - n.bbox_angle = 30.0; - { - let mut e = n.extras_mut(); - e.mask = Some(Box::new(OpacityMask::new(Node::group(NodeId(8), vec![]), true))); - e.trace = Some(Box::new(serde_json::json!({"preset": "p"}))); - e.series_index = Some(2); - e.type_outlines = true; - e.graphic_style = Some(3); - e.attrs = Some(Box::default()); - e.slice = Some(Box::default()); - e.perspective = Some(Box::new(crate::PerspectiveAttachment::new("left", 1.0))); - e.live_paint_gaps = Some(Box::default()); - } - /// The top-level keys of a JSON object, in the order written. - struct Keys(Vec); - impl<'de> Deserialize<'de> for Keys { - fn deserialize>(d: D) -> Result { - struct V; - impl<'de> serde::de::Visitor<'de> for V { - type Value = Keys; - fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.write_str("an object") - } - fn visit_map>(self, mut a: A) -> Result { - let mut out = vec![]; - while let Some(k) = a.next_key::()? { - a.next_value::()?; - out.push(k); - } - Ok(Keys(out)) - } - } - d.deserialize_map(V) - } - } - let text = serde_json::to_string(&n).unwrap(); - let keys = serde_json::from_str::(&text).unwrap().0; - let v: serde_json::Value = serde_json::from_str(&text).unwrap(); - let order = [ - "id", - "name", - "knockout_shape", - "appearance", - "mask", - "trace", - "series_index", - "type_outlines", - "kind", - "graphic_style", - "attrs", - "slice", - "bbox_angle", - "perspective", - "live_paint_gaps", - ]; - assert_eq!(keys, order); - assert_eq!(serde_json::from_value::(v).unwrap(), n); - let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art()); - let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap(); - assert!(back.extras_box().is_none()); - // Clearing the last extra lets them go; clearing one a node doesn't have allocates none. - n.extras_mut().mask = None; - assert!(n.extras_box().is_some()); - *n.extras_mut() = NodeExtras::default(); - assert!(n.extras_box().is_none()); - n.extras_mut().mask = None; - assert!(n.extras_box().is_none()); - assert_eq!(n.extras(), &NodeExtras::default()); - } - - #[test] - fn rect_live_shape_roundtrip() { - let l = LiveShape::Rectangle { w: 10.0, h: 20.0, radii: [0.0; 4], kinds: Default::default(), xf: Affine::translate((5.0, 5.0)) }; - assert_eq!(l.to_path().bounds(), Some(Rect::new(5.0, 5.0, 15.0, 25.0))); - assert_eq!(l.label(), "Rectangle"); - } - - #[test] - fn corner_kinds_save_only_when_some_corner_isnt_round() { - let mut l = LiveShape::Rectangle { w: 100.0, h: 50.0, radii: [0.0, 10.0, 0.0, 0.0], kinds: Default::default(), xf: Affine::IDENTITY }; - // Older files read as round. - let json = serde_json::to_value(&l).unwrap(); - assert!(json.get("kinds").is_none(), "{json}"); - assert_eq!(serde_json::from_value::(json).unwrap(), l); - if let LiveShape::Rectangle { kinds, .. } = &mut l { - kinds[1] = CornerKind::Chamfer; - } - let json = serde_json::to_value(&l).unwrap(); - assert_eq!(json["kinds"], serde_json::json!(["round", "chamfer", "round", "round"])); - assert_eq!(serde_json::from_value::(json).unwrap(), l); - // Polygons saved before Live Corners cut theirs read as sharp; a live path round-trips. - let p: LiveShape = - serde_json::from_value(serde_json::json!({"shape": "polygon", "radius": 10.0, "sides": 5, "xf": [1, 0, 0, 1, 0, 0]})).unwrap(); - assert_eq!(p, LiveShape::Polygon { radius: 10.0, sides: 5, xf: Affine::IDENTITY, radii: vec![], kinds: vec![] }); - let star = shapes::star(Point::new(0.0, 0.0), 20.0, 10.0, 5, 0.0); - let path = LiveShape::Path { base: star, radii: vec![2.0; 10], kinds: vec![] }; - let json = serde_json::to_value(&path).unwrap(); - assert_eq!((json["shape"].as_str(), json.get("kinds")), (Some("path"), None)); - assert_eq!(serde_json::from_value::(json).unwrap(), path); - assert_eq!(path.label(), "Path"); - } - - /// A polygon read from a file has 3 to 1000 sides, as the commands give it: selecting one - /// with four billion made its outline and corner lists allocate tens of gigabytes. - #[test] - fn a_polygon_from_a_file_has_3_to_1000_sides() { - let read = |sides: u32| { - let json = serde_json::json!({"shape": "polygon", "radius": 10.0, "sides": sides, "xf": [1, 0, 0, 1, 0, 0]}); - serde_json::from_value::(json).unwrap() - }; - let sides_of = |l: &LiveShape| match l { - LiveShape::Polygon { sides, .. } => *sides, - _ => panic!("not a polygon: {l:?}"), - }; - let huge = read(4_000_000_000); - assert_eq!([0, 5, 1000].map(|n| sides_of(&read(n))), [3, 5, 1000]); - assert_eq!(sides_of(&huge), 1000); - assert_eq!(huge.polygon_outline().anchor_count(), 1000); - } - - #[test] - fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() { - let close = |a: f64, b: f64| (a - b).abs() < 1e-9; - // A hexagon of radius 10 at (50, 50), drawn 2× and turned 30° clockwise on the page. - let xf = Affine::translate((50.0, 50.0)) * Affine::rotate(30f64.to_radians()) * Affine::scale(2.0); - let mut p = LiveShape::Polygon { radius: 10.0, sides: 6, xf, radii: vec![], kinds: vec![] }; - assert!(close(p.polygon_radius().unwrap(), 20.0) && close(p.polygon_angle().unwrap(), 330.0) && p.polygon_sides_equal()); - p.set_polygon_angle(45.0); - assert!(close(p.polygon_angle().unwrap(), 45.0)); - let centre = p.to_path().bounds().unwrap().center(); - assert!(close(centre.x, 50.0) && close(centre.y, 50.0), "turned about its centre: {centre:?}"); - p.set_polygon_radius(30.0); - assert!(close(p.polygon_radius().unwrap(), 30.0)); - // A hexagon's side is as long as its radius. - assert!(close(p.polygon_radius_for_side(12.0).unwrap(), 12.0)); - // Stretched, its sides differ; Make Sides Equal keeps its centre, angle and mean radius. - p.transform(Affine::scale_non_uniform(2.0, 1.0)); - assert!(!p.polygon_sides_equal()); - let (r, a) = (p.polygon_radius().unwrap(), p.polygon_angle().unwrap()); - p.make_sides_equal(); - assert!(p.polygon_sides_equal() && close(p.polygon_radius().unwrap(), r) && close(p.polygon_angle().unwrap(), a)); - let LiveShape::Polygon { xf, .. } = &p else { panic!("polygon") }; - assert_eq!(*xf * Point::ZERO, Point::new(100.0, 50.0)); - // Other shapes have none of it. - let e = LiveShape::Ellipse { w: 1.0, h: 1.0, pie: (0.0, 360.0), xf: Affine::IDENTITY }; - assert_eq!((e.polygon_radius(), e.polygon_angle()), (None, None)); - } - - /// A node holding a live rectangle (`w` × `h`, all radii `r`, placed by `xf`) and its path. - fn live_rect(w: f64, h: f64, r: f64, xf: Affine) -> Node { - let live = LiveShape::Rectangle { w, h, radii: [r; 4], kinds: Default::default(), xf }; - let mut n = Node::path(NodeId(1), live.to_path(), Appearance::default_art()); - if let NodeKind::Path { live: slot, .. } = &mut n.kind { - *slot = Some(Box::new(live)); - } - n - } - - fn live_of(n: &Node) -> (f64, f64, [f64; 4], Affine) { - let NodeKind::Path { live: Some(l), .. } = &n.kind else { panic!("not a live shape") }; - let LiveShape::Rectangle { w, h, radii, xf, .. } = &**l else { panic!("not a live rectangle") }; - (*w, *h, *radii, *xf) - } - - fn near(a: f64, b: f64) -> bool { - (a - b).abs() < 1e-9 - } - - fn near_xf(a: Affine, b: Affine) -> bool { - a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| near(*x, y)) - } - - /// Size and radius of a live rectangle, within rounding. - fn assert_live(n: &Node, w: f64, h: f64, r: f64) { - let (lw, lh, radii, _) = live_of(n); - assert!(near(lw, w) && near(lh, h) && radii.iter().all(|x| near(*x, r)), "{lw} × {lh} r {radii:?}, want {w} × {h} r {r}"); - } - - /// Each corner arc of a rounded rectangle's path, mapped by `back` (to undo a rotation), - /// spans `r` along x and y: the corner is a circular arc of radius `r`. - fn assert_round_corners(n: &Node, back: Affine, r: f64) { - let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") }; - let a: Vec = path.subpaths[0].anchors.iter().map(|a| back * a.p).collect(); - assert_eq!(a.len(), 8, "a rounded rectangle"); - // Anchors 1→2, 3→4, 5→6 and 7→0 are the arcs. - for (i, j) in [(1, 2), (3, 4), (5, 6), (7, 0)] { - let (x, y) = ((a[j].x - a[i].x).abs(), (a[j].y - a[i].y).abs()); - assert!(near(x, r) && near(y, r), "corner spans {x} × {y}, want {r} × {r}"); - } - } - - const KEEP_CORNERS: Scaling = Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: true, patterns: false }; - - #[test] - fn uneven_scales_keep_live_corners_circular() { - // A 100 pt rounded square at (10, 10) stretched to 300 × 100 (#291). - let mut n = live_rect(100.0, 100.0, 20.0, Affine::translate((10.0, 10.0))); - let stretch = Affine::translate((10.0, 10.0)) * Affine::scale_non_uniform(3.0, 1.0) * Affine::translate((-10.0, -10.0)); - n.transform(stretch, KEEP_CORNERS); - assert_live(&n, 300.0, 100.0, 20.0); - assert!(near_xf(live_of(&n).3, Affine::translate((10.0, 10.0))), "the scale went into the size"); - let b = n.geometric_bounds().unwrap(); - assert!(near(b.x0, 10.0) && near(b.y0, 10.0) && near(b.x1, 310.0) && near(b.y1, 110.0), "{b:?}"); - assert_round_corners(&n, Affine::IDENTITY, 20.0); - // Scale Corners on: the radius scales by the mean scale, still circular. - let mut n = live_rect(100.0, 100.0, 20.0, Affine::IDENTITY); - n.transform(Affine::scale_non_uniform(4.0, 1.0), Scaling::default()); - assert_live(&n, 400.0, 100.0, 40.0); - assert_round_corners(&n, Affine::IDENTITY, 40.0); - // Squashed below the radius, the short sides are fully round; stretched back, it returns. - n.transform(Affine::scale_non_uniform(1.0, 0.5), KEEP_CORNERS); - assert_round_corners(&n, Affine::IDENTITY, 25.0); - n.transform(Affine::scale_non_uniform(1.0, 2.0), KEEP_CORNERS); - assert_round_corners(&n, Affine::IDENTITY, 40.0); - } - - #[test] - fn rotated_and_reflected_live_rectangles_scale_along_their_own_sides() { - let place = Affine::translate((200.0, 100.0)) * Affine::rotate(30f64.to_radians()); - let mut n = live_rect(100.0, 50.0, 10.0, place); - // Stretched along its own width, as a bounding-box drag of a rotated shape does. - n.transform(place * Affine::scale_non_uniform(2.0, 1.0) * place.inverse(), KEEP_CORNERS); - assert_live(&n, 200.0, 50.0, 10.0); - assert!(near_xf(live_of(&n).3, place)); - assert_round_corners(&n, place.inverse(), 10.0); - // A reflection stays in `xf`; the corners stay as they were. - n.transform(Affine::scale_non_uniform(-1.0, 1.0), KEEP_CORNERS); - assert_live(&n, 200.0, 50.0, 10.0); - let xf = live_of(&n).3; - assert!(near(xf.determinant(), -1.0)); - assert_round_corners(&n, xf.inverse(), 10.0); - } - - #[test] - fn shears_and_moves_keep_the_old_transform() { - // Scaling a rotated rectangle along the page axes shears it: `xf` takes it all, as before. - let rot = Affine::rotate(30f64.to_radians()); - let mut n = live_rect(100.0, 50.0, 10.0, rot); - let before = n.clone(); - let a = Affine::scale_non_uniform(2.0, 1.0); - n.transform(a, Scaling::default()); - assert_eq!(live_of(&n), (100.0, 50.0, [10.0; 4], a * rot)); - let (NodeKind::Path { path, .. }, NodeKind::Path { path: old, .. }) = (&n.kind, &before.kind) else { panic!() }; - assert_eq!(*path, old.transformed(a)); - // A file saved with an uneven scale in `xf` keeps its exact geometry when moved... - let legacy = Affine::translate((5.0, 5.0)) * Affine::scale_non_uniform(2.0, 1.0); - let mut n = live_rect(100.0, 100.0, 20.0, legacy); - n.transform(Affine::translate((10.0, 0.0)), KEEP_CORNERS); - assert_eq!(live_of(&n), (100.0, 100.0, [20.0; 4], Affine::translate((10.0, 0.0)) * legacy)); - // ...and once scaled, has document units and circular corners of its mean radius. - n.transform(Affine::scale(2.0), Scaling::default()); - assert_live(&n, 400.0, 200.0, 20.0 * 2f64.sqrt() * 2.0); - assert!(near(live_of(&n).3.determinant(), 1.0)); - assert_round_corners(&n, Affine::IDENTITY, 20.0 * 2f64.sqrt() * 2.0); - } - - /// A rectangle saved with an uneven scale in `xf` (before #291) has elliptical corners; Live - /// Corners see and edit it in document units, with circular corners (#442). - #[test] - fn a_scale_left_in_the_transform_folds_into_the_size() { - let legacy = Affine::translate((5.0, 5.0)) * Affine::scale_non_uniform(4.0, 1.0); - let n = live_rect(50.0, 80.0, 20.0, legacy); - let NodeKind::Path { live: Some(live), .. } = &n.kind else { panic!("not live") }; - let folded = live.folded(); - assert_eq!(live_of(&n).3, legacy, "folded() leaves the shape alone"); - let LiveShape::Rectangle { w, h, radii, xf, .. } = &folded else { panic!("not a rectangle") }; - // Drawn 200 × 80 with 80 × 20 corners; folded, the corners are circles of the mean radius. - assert!(near(*w, 200.0) && near(*h, 80.0) && radii.iter().all(|r| near(*r, 40.0)), "{w} × {h} r {radii:?}"); - assert!(near_xf(*xf, Affine::translate((5.0, 5.0)))); - let (a, b) = (folded.to_path().bounds().unwrap(), live.to_path().bounds().unwrap()); - assert!(near(a.x0, b.x0) && near(a.y0, b.y0) && near(a.x1, b.x1) && near(a.y1, b.y1), "same place and size: {a:?} {b:?}"); - let corners = crate::LiveCorners::of(&n).unwrap(); - assert_eq!(corners.style(&corners.all()).0, Some(40.0), "the radius in document units"); - // Nothing to fold: a moved, rotated or reflected rectangle and a sheared one stay as they are. - let place = Affine::translate((5.0, 5.0)) * Affine::rotate(0.5) * Affine::scale_non_uniform(-1.0, 1.0); - let shear = Affine::new([1.0, 0.0, 0.5, 1.0, 0.0, 0.0]); - for xf in [place, shear] { - let mut l = live_rect(100.0, 160.0, 20.0, xf); - let NodeKind::Path { live: Some(live), .. } = &mut l.kind else { panic!("not live") }; - assert!(!live.fold_scale()); - assert_eq!(live_of(&l), (100.0, 160.0, [20.0; 4], xf)); - } - } - - #[test] - fn default_transparency() { - let p = || Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); - assert!(p().has_default_transparency()); - let tweaks: [fn(&mut Node); 7] = [ - |n| n.opacity = 0.5, - |n| n.blend = BlendMode::Multiply, - |n| n.isolate = true, - |n| n.knockout = Knockout::On, - |n| n.knockout = Knockout::Off, - |n| n.knockout_shape = true, - |n| n.extras_mut().mask = Some(Box::new(OpacityMask::new(n.clone(), true))), - ]; - for tweak in tweaks { - let mut n = p(); - tweak(&mut n); - assert!(!n.has_default_transparency(), "{n:?}"); - } - } - - #[test] - fn transform_group_recurses() { - let p = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); - let mut g = Node::group(NodeId(1), vec![Arc::new(p)]); - g.transform(Affine::scale(2.0), true); - assert_eq!(g.geometric_bounds(), Some(Rect::new(0.0, 0.0, 20.0, 20.0))); - let child = &g.children().unwrap()[0]; - assert_eq!(child.appearance.stroke_width(), 2.0); - } - - #[test] - fn unplaced_gradients_pin_only_when_a_refit_would_differ() { - use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, Paint}; - let grad = || Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); - let fresh = || Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), Appearance::basic(grad(), grad(), 2.0)); - let geoms = |n: &Node| match (n.appearance.fill_paint(), n.appearance.stroke_paint()) { - (Paint::Gradient(f), Paint::Gradient(s)) => (f.geom, s.geom), - _ => panic!("gradient fill and stroke"), - }; - let mut n = fresh(); - n.transform(Affine::translate((10.0, 5.0)) * Affine::scale(2.0), true); - assert_eq!(geoms(&n), (None, None), "moves and uniform scales keep refitting"); - let mut n = fresh(); - n.transform(Affine::rotate(std::f64::consts::FRAC_PI_2), false); - let (f, s) = geoms(&n); - // Fitted on the old bounds (strokes on the stroke-inflated box), then rotated: vertical. - let mut want = GradientGeom::fit(GradientKind::Linear, Rect::new(0.0, 0.0, 100.0, 50.0), 0.0); - want.transform(Affine::rotate(std::f64::consts::FRAC_PI_2), GradientKind::Linear); - let f = f.unwrap(); - assert!(f.start.distance(want.start) < 1e-9 && f.end.distance(want.end) < 1e-9, "{f:?}"); - assert!((s.unwrap().length() - 102.0).abs() < 1e-9); - } - - #[test] - fn display_names() { - let p = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); - assert_eq!(p.display_name(), ""); - let l = Node::layer(NodeId(1), "Layer 1", LayerColor::Preset(0)); - assert_eq!(l.display_name(), "Layer 1"); - } - - #[test] - fn visual_bounds_include_stroke() { - let mut p = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); - p.appearance.stroke_mut().unwrap().join = crate::appearance::LineJoin::Round; - assert_eq!(p.visual_bounds(), Some(Rect::new(-0.5, -0.5, 10.5, 10.5))); - } - - /// Type's visual bounds grow by how far its character strokes paint past the glyphs: half the - /// weight centred, the whole weight outside, nothing inside; scaled with the type. - #[test] - fn type_visual_bounds_grow_with_the_character_stroke() { - use crate::appearance::StrokeAlign; - use crate::text::{CharStyle, TextObject}; - let style = CharStyle { stroke: vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), stroke_width: 4.0, ..Default::default() }; - let mut t = TextObject::point(vectorcraft_geom::Point::new(0.0, 0.0), "Ab", style); - t.xf = Affine::scale(2.0) * t.xf; - let node = |t: &TextObject| Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))); - let g = node(&t).geometric_bounds().unwrap(); - for (align, grow) in [(StrokeAlign::Center, 4.0), (StrokeAlign::Outside, 8.0), (StrokeAlign::Inside, 0.0)] { - t.runs[0].style.stroke_align = align; - assert_eq!(node(&t).visual_bounds(), Some(g.inflate(grow, grow)), "{align:?}"); - } - t.runs[0].style.stroke = vectorcraft_color::Paint::None; - assert_eq!(node(&t).visual_bounds(), Some(g), "no stroke, no growth"); - } - - /// A group holding a path, a compound, an image and a nested group, as a file writes it. - fn nested_group() -> Node { - let path = |id| Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); - let image = ImageObject { key: "k".into(), width: 2, height: 3, xf: Affine::IDENTITY, link: None, placement: Default::default() }; - let inner = Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(path(6))], clip: true }); - let compound = Node::new(NodeId(3), NodeKind::Compound { children: vec![Arc::new(path(4))], rule: FillRule::EvenOdd }); - let kids = vec![Arc::new(path(2)), Arc::new(compound), Arc::new(Node::new(NodeId(7), NodeKind::Image(Box::new(image)))), Arc::new(inner)]; - Node::new(NodeId(1), NodeKind::Group { children: kids, clip: false }) - } - - #[test] - fn kinds_read_back_with_type_first_or_anywhere() { - let n = nested_group(); - let json = serde_json::to_string(&n).unwrap(); - assert!(json.contains(r#""kind":{"type":"group","children":["#), "written with `type` first: {json}"); - assert_eq!(serde_json::from_str::(&json).unwrap(), n); - // Through a JSON value, whose keys are sorted: `type` comes after `children`. - let v = serde_json::to_value(&n).unwrap(); - assert_eq!(serde_json::from_value::(v.clone()).unwrap(), n); - assert_eq!(serde_json::from_str::(&v.to_string()).unwrap(), n); - // `type` last, in the middle, and keys a newer version added (ignored, as before). - let kind = r#"{"children":[],"x":{"deep":[1,2]},"clip":true,"type":"group"}"#; - assert_eq!(serde_json::from_str::(kind).unwrap(), NodeKind::Group { children: vec![], clip: true }); - let kind = r#"{"symbol":"S","type":"symbolinstance","later":1,"xf":[1,0,0,1,5,6]}"#; - assert_eq!( - serde_json::from_str::(kind).unwrap(), - NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::translate((5.0, 6.0)) } - ); - let kind = r#"{"width":2,"type":"image","key":"k","height":3,"xf":[1,0,0,1,0,0]}"#; - assert!(matches!(serde_json::from_str::(kind).unwrap(), NodeKind::Image(i) if i.key == "k" && i.height == 3)); - // Defaults as before. - let NodeKind::Layer { printable, preview, template, .. } = - serde_json::from_str(r#"{"type":"layer","color":{"Preset":0},"children":[]}"#).unwrap() - else { - panic!("a layer") - }; - assert!(printable && preview && !template); - } - - #[test] - fn bad_kinds_are_errors() { - for bad in [r#"{"children":[]}"#, r#"{"type":"nothing"}"#, r#"{"type":"group"}"#, r#"{"type":3,"children":[]}"#, r#"[]"#, r#""group""#] { - assert!(serde_json::from_str::(bad).is_err(), "{bad}"); - } - } -} +mod tests; diff --git a/crates/doc/src/node/attributes.rs b/crates/doc/src/node/attributes.rs new file mode 100644 index 0000000000..70653d7789 --- /dev/null +++ b/crates/doc/src/node/attributes.rs @@ -0,0 +1,133 @@ +use super::kind::NodeKind; +use super::live_shape::LiveShape; +use super::*; + +/// Window → Attributes: an object's settings that don't change how it prints. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ObjectAttributes { + /// Show Center / Don't Show Center (`None`: the object kind's default, [`Node::shows_center`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub show_center: Option, + /// Image Map: the clickable area the URL covers in web output. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub image_map: ImageMap, + /// URL the object links to (SVG ``; empty: none). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub url: String, + /// The note shown in the Attributes panel. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub note: String, + /// The object's own data, in order: SVG's `data-*` attributes (`data-pivot="100,180"` is + /// `("pivot", "100,180")`), kept from import to export (`object.setProps {data}`). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub data: Vec<(String, String)>, + /// Window › SVG Interactivity: the JavaScript each event runs, in the panel's order + /// (`("onclick", "alert(1)")`, one entry per event of [`SVG_EVENTS`]). SVG export writes them as + /// the element's event attributes; nothing in VectorCraft runs them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub events: Vec<(String, String)>, + /// Attributes in other applications' XML namespaces, in order, kept from SVG import to SVG + /// export: what another tool notes on an object (a plotter's pen, a cutter's passes) survives + /// a round trip through VectorCraft. Nothing in VectorCraft reads them. They are the object's, + /// as `data` is, so copies, duplicates and pastes keep them and a deleted object takes them + /// with it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub foreign: Vec, +} + +/// An attribute in another application's XML namespace: `plotter:pen="2"` with `xmlns:plotter= +/// "https://example.org/plotter"` is `{ns: "https://example.org/plotter", prefix: "plotter", name: +/// "pen", value: "2"}`. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ForeignAttribute { + /// The namespace's URI, which names it. + pub ns: String, + /// The prefix the file gave the namespace, which export reuses where it can. + pub prefix: String, + /// The attribute's local name. + pub name: String, + /// The attribute's value, as the file had it. + pub value: String, +} + +/// The events the SVG Interactivity panel attaches JavaScript to, by the names of the SVG event +/// attributes that run it. +pub const SVG_EVENTS: [&str; 19] = [ + "onfocusin", + "onfocusout", + "onactivate", + "onmousedown", + "onmouseup", + "onclick", + "onmouseover", + "onmousemove", + "onmouseout", + "onkeydown", + "onkeypress", + "onkeyup", + "onload", + "onerror", + "onabort", + "onunload", + "onzoom", + "onresize", + "onscroll", +]; + +/// The most JavaScript files a document links (`Document::svg_scripts`): SVG import keeps the +/// first ones and warns about the rest, and `svgInteractivity.addFile` refuses another. +pub const MAX_SVG_SCRIPTS: usize = 64; + +/// The Attributes panel's Image Map shapes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ImageMap { + #[default] + None, + Rectangle, + Polygon, +} + +impl ImageMap { + pub const ALL: [ImageMap; 3] = [ImageMap::None, ImageMap::Rectangle, ImageMap::Polygon]; + + pub fn label(self) -> &'static str { + match self { + ImageMap::None => "None", + ImageMap::Rectangle => "Rectangle", + ImageMap::Polygon => "Polygon", + } + } + + /// Parse a label or serialized name, ignoring case. + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|m| m.label().eq_ignore_ascii_case(s)) + } +} + +impl Node { + /// The URL this object links to, if any. + pub fn url(&self) -> Option<&str> { + self.extras().attrs.as_deref().map(|a| a.url.as_str()).filter(|u| !u.is_empty()) + } + + /// Whether the canvas shows this object's centre point when it is selected: as set in the + /// Attributes panel, else [`Self::shows_center_by_default`]. + pub fn shows_center(&self) -> bool { + self.extras().attrs.as_deref().and_then(|a| a.show_center).unwrap_or_else(|| self.shows_center_by_default()) + } + + /// Shapes drawn with the shape tools (live rectangles, ellipses and polygons) show their centre. + pub fn shows_center_by_default(&self) -> bool { + matches!(&self.kind, NodeKind::Path { live: Some(l), .. } if !matches!(**l, LiveShape::Line { .. } | LiveShape::Path { .. })) + } + + /// Change this object's attributes with `f`; all-default attributes are dropped. + pub fn edit_attrs(&mut self, f: impl FnOnce(&mut ObjectAttributes) -> R) -> R { + let mut a = self.extras_mut().attrs.take().unwrap_or_default(); + let r = f(&mut a); + self.extras_mut().attrs = (*a != ObjectAttributes::default()).then_some(a); + r + } +} diff --git a/crates/doc/src/node/clip.rs b/crates/doc/src/node/clip.rs new file mode 100644 index 0000000000..959b20a5bb --- /dev/null +++ b/crates/doc/src/node/clip.rs @@ -0,0 +1,120 @@ +use super::kind::NodeKind; +use super::*; + +/// Unites filled regions (each under its own fill rule) into one path filled non-zero. Booleans +/// live above this crate (`vectorcraft-pathops`), so callers supply it. +pub type Uniter<'a> = &'a dyn Fn(&[(BezPath, FillRule)]) -> BezPath; + +impl Node { + /// The filled regions this object clips to as the clipping path of a clip group, in document + /// space, each with its fill rule: a path, a compound path (with its holes), an image's frame, + /// text outlined by `text` (glyph outlines need the font engine, above this crate), the visible + /// members of a group (their union) and the clipping path of a nested clip group. Live objects + /// are evaluated first. Guides and symbol instances add nothing. + pub fn clip_shapes(&self, text: Outliner) -> Vec<(BezPath, FillRule)> { + let mut out = vec![]; + self.push_clip_shapes(text, &mut out); + out + } + + fn push_clip_shapes(&self, text: Outliner, out: &mut Vec<(BezPath, FillRule)>) { + match &self.kind { + NodeKind::Path { guide: true, .. } | NodeKind::SymbolInstance { .. } => {} + NodeKind::Path { path, rule, .. } => out.push((path.to_bezpath(), *rule)), + NodeKind::Compound { children, rule } => { + let mut bp = BezPath::new(); + for p in children.iter().filter_map(|c| c.path_data()) { + bp.extend(p.to_bezpath()); + } + out.push((bp, *rule)); + } + NodeKind::Group { children, clip: true } => { + if let Some(c) = children.first() { + c.push_clip_shapes(text, out); + } + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + for c in children.iter().skip(usize::from(self.extras().shaper.is_some())).filter(|c| c.visible) { + c.push_clip_shapes(text, out); + } + } + NodeKind::Text(_) => { + if let Some(o) = text.and_then(|f| f(self)) { + o.push_clip_shapes(None, out); + } + } + NodeKind::Image(im) => { + let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf); + out.push((frame.to_bezpath(), FillRule::NonZero)); + } + NodeKind::PlacedDocument(p) => { + let frame = shapes::rectangle(p.natural()).transformed(p.xf); + out.push((frame.to_bezpath(), FillRule::NonZero)); + } + NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => { + crate::live::expand_deep(self, text).push_clip_shapes(text, out); + } + } + } + + /// The region this object clips to as one path and fill rule ([`Self::clip_shapes`]), shared + /// by the renderer and the SVG and PDF writers so every output clips alike. One shape keeps its + /// own rule; several are united by `unite` (filled non-zero). `None` when there is nothing to + /// clip by: the clipped art is then hidden. + pub fn clip_outline(&self, text: Outliner, unite: Uniter) -> Option<(BezPath, FillRule)> { + let mut shapes = self.clip_shapes(text); + match shapes.len() { + 0 => None, + 1 => shapes.pop(), + _ => Some((unite(&shapes), FillRule::NonZero)), + } + } + + /// What this object paints as the clipping path of a clip group, shared by the renderer and + /// the SVG and PDF writers: its fills, painted behind the clipped art, and its strokes, painted + /// over it (unclipped). Each part is this object keeping only those appearance items (type: + /// also only its characters' fills or strokes); `None` where it paints nothing, as right after + /// Make Clipping Mask. Only paths, compound paths and type paint as clipping paths. + pub fn clip_paint(&self) -> ClipPaint { + use crate::appearance::AppearanceItem; + let runs = match &self.kind { + NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => None, + NodeKind::Text(t) => Some(&t.runs), + _ => return ClipPaint::default(), + }; + let paints = |fill: bool| { + let item = |i: &AppearanceItem| match i { + AppearanceItem::Fill(f) => fill && f.visible && !f.paint.is_none(), + AppearanceItem::Stroke(s) => !fill && s.visible && !s.paint.is_none() && s.width > 0.0, + }; + let run = |r: &crate::text::TextRun| if fill { !r.style.fill.is_none() } else { !r.style.stroke.is_none() && r.style.stroke_width > 0.0 }; + self.appearance.items.iter().any(item) || runs.is_some_and(|rs| rs.iter().any(run)) + }; + let part = |fill: bool| { + paints(fill).then(|| { + let mut n = self.clone(); + for i in (0..n.appearance.items.len()).rev() { + if matches!(n.appearance.items[i], AppearanceItem::Fill(_)) != fill { + n.appearance.remove_item(i); + } + } + if let NodeKind::Text(t) = &mut n.kind { + for r in &mut t.runs { + *(if fill { &mut r.style.stroke } else { &mut r.style.fill }) = vectorcraft_color::Paint::None; + } + } + n + }) + }; + ClipPaint { fill: part(true), stroke: part(false) } + } +} + +/// What a clipping path paints ([`Node::clip_paint`]). +#[derive(Clone, Debug, Default)] +pub struct ClipPaint { + /// The clipping path with only its fills: painted behind the clipped art (inside the clip). + pub fill: Option, + /// The clipping path with only its strokes: painted over the clipped art, not clipped. + pub stroke: Option, +} diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs new file mode 100644 index 0000000000..ee11653037 --- /dev/null +++ b/crates/doc/src/node/extras.rs @@ -0,0 +1,171 @@ +use super::attributes::ObjectAttributes; +use super::kind::NodeKind; +use super::live_shape::LiveShape; +use super::opacity::OpacityMask; +use super::*; + +/// The parts of a [`Node`] that few objects have: kept out of line, so that the nodes without +/// them stay small ([`Node::extras`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct NodeExtras { + /// Opacity mask (Transparency panel). Its art lives here, outside the layer tree. + pub mask: Option>, + /// Image Trace object: `{preset, params, view?}` it was traced with (the Image Trace panel shows + /// them; `view` is its [`crate::TraceView`] id, absent for the tracing result). + pub trace: Option>, + /// Object → Text Wrap: area type below this object (in the same layer) flows around it. + pub wrap: Option, + /// Graph object: the group's children are generated from this spec (Object → Graph). + pub graph: Option>, + /// Index of the graph series this generated group belongs to. Axes, the legend and other + /// children leave it unset, so a series named "Legend" or "Axes" is not mistaken for them. + pub series_index: Option, + /// The group holds the glyph outlines of type. Geometry effects that reshape it move and scale + /// the placed gradients in it with the outlines. + pub type_outlines: bool, + /// Editable Shaper composition; the original art is retained in its source child. + pub shaper: Option>, + /// The [`crate::GraphicStyle::id`] last applied to this object. It stays linked while it keeps + /// that style's look: editing its appearance or transparency breaks the link. + pub graphic_style: Option, + /// Attributes panel: centre point display, image map, URL and note (`None`: all defaults). + pub attrs: Option>, + /// Object → Slice → Make: the object is an object slice (its slice follows its bounds) with + /// these options. + pub slice: Option>, + /// Object › Perspective: the perspective grid plane the object is attached to. + pub perspective: Option>, + /// Dimension object: the live measurement it draws; its ordinary group children hold its + /// exportable appearance (Object › Dimensions, the Dimension tool). + pub dimension: Option>, + /// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates, + /// filled non-zero) where this object is drawn over the group's other members. + pub intertwine: Option>, + /// Live Paint group: its Gap Options (Object › Live Paint › Gap Options; `None`: the defaults). + pub live_paint_gaps: Option>, + /// Object › Objects on Path: the group's path and the objects attached to it (see + /// [`crate::objects_on_path`]). + pub objects_on_path: Option>, +} + +/// No extras: what [`Node::extras`] gives for a node without any. +pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { + mask: None, + trace: None, + wrap: None, + graph: None, + series_index: None, + type_outlines: false, + shaper: None, + graphic_style: None, + attrs: None, + slice: None, + perspective: None, + dimension: None, + intertwine: None, + live_paint_gaps: None, + objects_on_path: None, +}; + +/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal +/// none. +#[derive(Clone, Debug, Default)] +pub struct Extras(pub(crate) Option>); + +impl Extras { + fn get(&self) -> &NodeExtras { + self.0.as_deref().unwrap_or(&NO_EXTRAS) + } +} + +impl PartialEq for Extras { + fn eq(&self, other: &Self) -> bool { + match (&self.0, &other.0) { + (Some(a), Some(b)) => a == b, + _ => self.get() == other.get(), + } + } +} + +impl Node { + /// The rarely set parts of this node (all unset when it has none). + #[inline] + pub fn extras(&self) -> &NodeExtras { + self.extras.get() + } + + /// The rarely set parts of this node, to change: when the change is done (the guard dropped), + /// extras that were set are allocated and extras left all unset are let go. Setting one to + /// `None` on a node without extras allocates nothing. + #[inline] + pub fn extras_mut(&mut self) -> ExtrasMut<'_> { + ExtrasMut { slot: &mut self.extras.0, local: NodeExtras::default() } + } + + /// The rarely set parts of this node, if it has any: to change what is there in place. + #[inline] + pub fn extras_if_any(&mut self) -> Option<&mut NodeExtras> { + self.extras.0.as_deref_mut() + } + + /// The live shape of a path object, if it is one. + pub fn live_shape(&self) -> Option<&LiveShape> { + match &self.kind { + NodeKind::Path { live, .. } => live.as_deref(), + _ => None, + } + } + + /// The live shape of a path object, if it is one, to change. + pub fn live_shape_mut(&mut self) -> Option<&mut LiveShape> { + match &mut self.kind { + NodeKind::Path { live, .. } => live.as_deref_mut(), + _ => None, + } + } + + /// This node with opacity mask `mask` (or none). + pub fn with_mask(mut self, mask: Option>) -> Self { + self.extras_mut().mask = mask; + self + } + + /// The extras, if this node has them allocated (for [`crate::mem`]'s estimate). + pub(crate) fn extras_box(&self) -> Option<&NodeExtras> { + self.extras.0.as_deref() + } +} + +/// [`Node::extras_mut`]: the node's extras while they change. +pub struct ExtrasMut<'a> { + slot: &'a mut Option>, + /// Stands for the extras of a node without any, boxed into it when dropped if one was set. + local: NodeExtras, +} + +impl std::ops::Deref for ExtrasMut<'_> { + type Target = NodeExtras; + fn deref(&self) -> &NodeExtras { + self.slot.as_deref().unwrap_or(&self.local) + } +} + +impl std::ops::DerefMut for ExtrasMut<'_> { + fn deref_mut(&mut self) -> &mut NodeExtras { + match self.slot.as_deref_mut() { + Some(e) => e, + None => &mut self.local, + } + } +} + +impl Drop for ExtrasMut<'_> { + fn drop(&mut self) { + match self.slot.as_deref() { + Some(e) if *e == NO_EXTRAS => *self.slot = None, + Some(_) => {} + None if self.local != NO_EXTRAS => *self.slot = Some(Box::new(std::mem::take(&mut self.local))), + None => {} + } + } +} diff --git a/crates/doc/src/node/ids.rs b/crates/doc/src/node/ids.rs new file mode 100644 index 0000000000..ea4b1b4847 --- /dev/null +++ b/crates/doc/src/node/ids.rs @@ -0,0 +1,59 @@ +use super::*; + +/// Stable per-document object id. Never reused. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(transparent)] +pub struct NodeId(pub u64); + +impl std::fmt::Display for NodeId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "#{}", self.0) + } +} + +/// Layer colours used for selection highlighting (index into [`LAYER_COLORS`]) or a custom RGB. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum LayerColor { + Preset(u8), + Custom([u8; 3]), +} + +/// Layer highlight colours, assigned in sequence to new layers. First is Illustrator-like light blue. +pub const LAYER_COLORS: [(&str, [u8; 3]); 27] = [ + ("Light Blue", [0x4f, 0x80, 0xff]), + ("Red", [0xff, 0x4f, 0x4f]), + ("Green", [0x4f, 0xff, 0x4f]), + ("Blue", [0x4f, 0x4f, 0xff]), + ("Yellow", [0xff, 0xff, 0x4f]), + ("Magenta", [0xff, 0x4f, 0xff]), + ("Cyan", [0x4f, 0xff, 0xff]), + ("Gray", [0x80, 0x80, 0x80]), + ("Black", [0x00, 0x00, 0x00]), + ("Orange", [0xff, 0x66, 0x00]), + ("Dark Green", [0x00, 0x80, 0x00]), + ("Teal", [0x00, 0x80, 0x80]), + ("Tan", [0xcc, 0x99, 0x66]), + ("Brown", [0x99, 0x33, 0x00]), + ("Violet", [0x99, 0x33, 0xff]), + ("Gold", [0xff, 0x99, 0x00]), + ("Dark Blue", [0x00, 0x00, 0x80]), + ("Pink", [0xff, 0x99, 0xcc]), + ("Lavender", [0x99, 0x99, 0xff]), + ("Brick Red", [0x99, 0x00, 0x00]), + ("Olive Green", [0x66, 0x66, 0x00]), + ("Peach", [0xff, 0x99, 0x99]), + ("Burgundy", [0x99, 0x00, 0x33]), + ("Grass Green", [0x99, 0xcc, 0x00]), + ("Ochre", [0x99, 0x66, 0x00]), + ("Purple", [0x66, 0x00, 0x99]), + ("Light Gray", [0xbb, 0xbb, 0xbb]), +]; + +impl LayerColor { + pub fn rgb(self) -> [u8; 3] { + match self { + LayerColor::Preset(i) => LAYER_COLORS[i as usize % LAYER_COLORS.len()].1, + LayerColor::Custom(c) => c, + } + } +} diff --git a/crates/doc/src/node/kind.rs b/crates/doc/src/node/kind.rs new file mode 100644 index 0000000000..5bebc4379c --- /dev/null +++ b/crates/doc/src/node/kind.rs @@ -0,0 +1,326 @@ +use super::ids::LayerColor; +use super::live_shape::LiveShape; +use super::*; + +/// Embedded or linked raster image. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ImageObject { + /// Key into [`crate::Document::images`]. + pub key: String, + pub width: u32, + pub height: u32, + /// Maps pixel space (0..w, 0..h) into the document. + pub xf: Affine, + /// The file a linked image shows (File → Place with Link); `None`: embedded. Files saved + /// before links had details hold just the path. + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::links::de_link")] + pub link: Option, + /// Links panel → Placement Options: how a file read again takes this image's place. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub placement: crate::links::PlacementOptions, + /// The pixels of an image in art made outside a document (type's outlines, a glyph's art), + /// which has no [`crate::Document::images`] to keep them in. A document takes them in + /// ([`crate::Document::adopt_pixels`]): no image in one holds its own. + #[serde(skip)] + pub pixels: Option>, +} + +/// Written with its `type` first, then its fields (an internally tagged enum); read by +/// [`kind_de`], which takes the fields straight from the file when `type` comes first. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(tag = "type", rename_all = "lowercase")] +pub enum NodeKind { + /// A top-level layer or sublayer. + Layer { + color: LayerColor, + #[serde(default)] + template: bool, + #[serde(default = "yes")] + printable: bool, + children: Vec>, + /// Layer clipping mask: the first (bottom-most) child clips the others, as in a clip group. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + clip: bool, + /// Layer Options → Preview: off, the layer's art is drawn (and clicked) in outline on screen + /// (Ctrl-click its eye in the Layers panel). + #[serde(default = "yes", skip_serializing_if = "crate::skip::is_true")] + preview: bool, + /// Layer Options → Dim Images to: on screen, images on the layer show faded to this + /// percentage (0–100); `None`: not dimmed. + #[serde(default, skip_serializing_if = "Option::is_none")] + dim_images: Option, + }, + /// A group. With `clip`, the first (bottom-most) child is the clipping path. + Group { + children: Vec>, + #[serde(default)] + clip: bool, + }, + Path { + path: PathData, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + rule: FillRule, + /// Boxed: few paths are live shapes, and the shape is larger than the rest of the variant. + #[serde(default, skip_serializing_if = "Option::is_none")] + live: Option>, + /// This path acts as a clipping path inside a clip group. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + clipping: bool, + /// Guide (non-printing) path. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + guide: bool, + }, + /// Compound path: children are paths painted as one with the compound's appearance. + Compound { + children: Vec>, + #[serde(default)] + rule: FillRule, + }, + Text(Box), + /// Boxed, as the other large kinds: a node is as large as its largest kind. + Image(Box), + SymbolInstance { + symbol: String, + xf: Affine, + }, + /// Live blend: the key objects (paint order) plus spacing/orientation/spine; the intermediate + /// steps are evaluated on demand (`live::blend_expand`). + Blend { + children: Vec>, + #[serde(default)] + spec: Box, + }, + /// Live envelope distortion of `content`. + Envelope { + content: Vec>, + kind: Box, + /// Envelope Options → Fidelity (0–100). + #[serde(default = "crate::live::default_fidelity")] + fidelity: f64, + /// Edit Contents mode (the content, not the envelope, is edited). + #[serde(default)] + editing: bool, + /// Envelope Options besides Fidelity. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + options: crate::live::EnvelopeOptions, + /// The envelope's own axes (→ the document): the transforms it took since it was made that + /// the page axes can't stand for (rotation, shear, reflection). The content maps from its + /// bounds in this frame, and a warp bends along it. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + frame: Box, + }, + /// Gradient mesh. + Mesh(GradientMesh), + /// Live Repeat (radial / grid / mirror) of source art. + Repeat(RepeatSpec), + /// A placed document: an artboard of another VectorCraft file, or a page of a PDF or `.ai` + /// file, linked and locked (see [`crate::placed_document`]). + PlacedDocument(Box), + /// Object › Intertwine: the objects keep their own stacking order, except where one of them + /// is drawn over the others: the area [`NodeExtras::intertwine`] of that member (see + /// [`crate::intertwine`]). + Intertwine { + children: Vec>, + }, +} + +/// Reading a [`NodeKind`]. Derived, an internally tagged enum buffers each kind (with every +/// object inside a group, again at each level of nesting) before reading it, since `type` may come +/// anywhere among its fields. Files have it first (it is written first): then the kind is read +/// straight from the file. Otherwise (hand-written files, values whose keys are sorted) the +/// fields before `type` are buffered, and only those. +mod kind_de { + use std::fmt; + use std::sync::Arc; + + use serde::de::value::{MapAccessDeserializer, StringDeserializer}; + use serde::de::{self, DeserializeSeed, Deserializer, EnumAccess, IntoDeserializer, MapAccess, VariantAccess, Visitor}; + use serde::{Deserialize, forward_to_deserialize_any}; + use vectorcraft_geom::{Affine, FillRule, PathData}; + + use super::{LayerColor, LiveShape, Node, NodeKind, yes}; + use crate::live::{BlendSpec, EnvelopeKind, GradientMesh}; + use crate::pattern::RepeatSpec; + use crate::text::TextObject; + + /// The kinds and their fields as [`NodeKind`] has them, with the defaults its field attributes + /// note (the compiler checks that every field is here), read externally tagged: the kind from + /// `type`, its fields from the rest of the object ([`Tagged`]). + #[derive(Deserialize)] + #[serde(remote = "NodeKind", rename_all = "lowercase")] + enum KindDef { + Layer { + color: LayerColor, + #[serde(default)] + template: bool, + #[serde(default = "yes")] + printable: bool, + children: Vec>, + #[serde(default)] + clip: bool, + #[serde(default = "yes")] + preview: bool, + #[serde(default)] + dim_images: Option, + }, + Group { + children: Vec>, + #[serde(default)] + clip: bool, + }, + Path { + path: PathData, + #[serde(default)] + rule: FillRule, + #[serde(default)] + live: Option>, + #[serde(default)] + clipping: bool, + #[serde(default)] + guide: bool, + }, + Compound { + children: Vec>, + #[serde(default)] + rule: FillRule, + }, + Text(Box), + Image(Box), + SymbolInstance { + symbol: String, + xf: Affine, + }, + Blend { + children: Vec>, + #[serde(default)] + spec: Box, + }, + Envelope { + content: Vec>, + kind: Box, + #[serde(default = "crate::live::default_fidelity")] + fidelity: f64, + #[serde(default)] + editing: bool, + #[serde(default)] + options: crate::live::EnvelopeOptions, + #[serde(default)] + frame: Box, + }, + Mesh(GradientMesh), + Repeat(RepeatSpec), + PlacedDocument(Box), + Intertwine { + children: Vec>, + }, + } + + impl<'de> Deserialize<'de> for NodeKind { + fn deserialize>(d: D) -> Result { + d.deserialize_map(KindVisitor) + } + } + + struct KindVisitor; + + impl<'de> Visitor<'de> for KindVisitor { + type Value = NodeKind; + + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("an object kind (a map with `type`)") + } + + fn visit_map>(self, mut map: A) -> Result { + let mut before = vec![]; + while let Some(key) = map.next_key::()? { + if key == "type" { + let tag: String = map.next_value()?; + return KindDef::deserialize(Tagged { tag, map: Buffered { before: before.into_iter(), value: None, map } }); + } + before.push((key, map.next_value::()?)); + } + Err(de::Error::missing_field("type")) + } + } + + /// The fields read before `type` (buffered), then the rest of the object. + struct Buffered { + before: std::vec::IntoIter<(String, serde_json::Value)>, + value: Option, + map: A, + } + + impl<'de, A: MapAccess<'de>> MapAccess<'de> for Buffered { + type Error = A::Error; + + fn next_key_seed>(&mut self, seed: K) -> Result, A::Error> { + match self.before.next() { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize(StringDeserializer::::new(key)).map(Some) + } + None => self.map.next_key_seed(seed), + } + } + + fn next_value_seed>(&mut self, seed: V) -> Result { + match self.value.take() { + Some(value) => seed.deserialize(value).map_err(de::Error::custom), + None => self.map.next_value_seed(seed), + } + } + } + + /// An object whose `type` was read: the kind is `tag`, its fields are the rest of `map`. + struct Tagged { + tag: String, + map: A, + } + + impl<'de, A: MapAccess<'de>> Deserializer<'de> for Tagged { + type Error = A::Error; + + fn deserialize_any>(self, visitor: V) -> Result { + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf + option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum + identifier ignored_any + } + } + + impl<'de, A: MapAccess<'de>> EnumAccess<'de> for Tagged { + type Error = A::Error; + type Variant = Fields; + + fn variant_seed>(self, seed: V) -> Result<(V::Value, Fields), A::Error> { + let kind = seed.deserialize(self.tag.into_deserializer())?; + Ok((kind, Fields(self.map))) + } + } + + /// A kind's fields: the rest of the object. + struct Fields(A); + + impl<'de, A: MapAccess<'de>> VariantAccess<'de> for Fields { + type Error = A::Error; + + fn unit_variant(self) -> Result<(), A::Error> { + Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"an object kind with fields")) + } + + fn newtype_variant_seed>(self, seed: T) -> Result { + seed.deserialize(MapAccessDeserializer::new(self.0)) + } + + fn tuple_variant>(self, _: usize, _: V) -> Result { + Err(de::Error::invalid_type(de::Unexpected::TupleVariant, &"an object kind with fields")) + } + + fn struct_variant>(self, _: &'static [&'static str], visitor: V) -> Result { + visitor.visit_map(self.0) + } + } +} diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs new file mode 100644 index 0000000000..65dad904ef --- /dev/null +++ b/crates/doc/src/node/live_shape.rs @@ -0,0 +1,346 @@ +use super::*; + +/// Live shape parameters (Illustrator's "Live Shapes"). The node's path is regenerated from these +/// while the shape stays live; editing anchors directly converts it to a plain path. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "shape", rename_all = "lowercase")] +pub enum LiveShape { + Rectangle { + /// Untransformed width/height. Transforms fold their scale into these (see + /// [`LiveShape::transform`]), so they are document lengths unless `xf` shears. + w: f64, + h: f64, + /// Corner radii: top-left, top-right, bottom-right, bottom-left. In the same units as + /// `w`/`h`: the corners are circular arcs in the document whenever `xf` doesn't scale. + radii: [f64; 4], + /// Corner kinds, in the same order (Live Corners' corner types). + #[serde(default, skip_serializing_if = "all_round")] + kinds: [CornerKind; 4], + /// When true, `radii` are fractions in 0..1 of each corner's largest possible radius. + #[serde(default, skip_serializing_if = "is_false")] + radii_relative: bool, + /// Maps the untransformed shape (origin at its top-left) into the document. A rotation + /// or reflection plus a move, unless a shear (or a file saved before transforms folded + /// their scale into `w`/`h`) put more in it. + xf: Affine, + }, + Ellipse { + w: f64, + h: f64, + /// Pie start/end angles in degrees (0/360 = full ellipse). + pie: (f64, f64), + xf: Affine, + }, + Polygon { + radius: f64, + /// 3–1000, as [`LiveShape::set_sides`] gives it; a file's count is clamped when read. + #[serde(deserialize_with = "de_sides")] + sides: u32, + xf: Affine, + /// Corner radii in document units, by vertex from the first one clockwise (none: sharp). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + radii: Vec, + /// Corner kinds, in the same order (none: round). + #[serde(default, skip_serializing_if = "all_round")] + kinds: Vec, + #[serde(default, skip_serializing_if = "is_false")] + radii_relative: bool, + }, + Line { + a: Point, + b: Point, + }, + /// Any other path whose corners Live Corners cut (a star, a pen path): it keeps its uncut + /// outline so the corners stay editable. Without a cut corner it is a plain path again. + Path { + /// The path with its corners uncut, in the document. + base: PathData, + /// Corner radii in document units, by anchor index of `base` (counting every subpath's + /// anchors in order; missing: sharp). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + radii: Vec, + /// Corner kinds, in the same order (missing: round). + #[serde(default, skip_serializing_if = "all_round")] + kinds: Vec, + #[serde(default, skip_serializing_if = "is_false")] + radii_relative: bool, + }, +} + +fn is_false(b: &bool) -> bool { + !*b +} + +impl LiveShape { + pub fn radii_relative(&self) -> bool { + match self { + LiveShape::Rectangle { radii_relative, .. } | LiveShape::Polygon { radii_relative, .. } | LiveShape::Path { radii_relative, .. } => { + *radii_relative + } + LiveShape::Ellipse { .. } | LiveShape::Line { .. } => false, + } + } + pub fn label(&self) -> &'static str { + match self { + LiveShape::Rectangle { radii, .. } if radii.iter().any(|r| *r > 0.0) => "Rounded Rectangle", + LiveShape::Rectangle { .. } => "Rectangle", + LiveShape::Ellipse { .. } => "Ellipse", + LiveShape::Polygon { .. } => "Polygon", + LiveShape::Line { .. } => "Line", + LiveShape::Path { .. } => "Path", + } + } + /// Regenerate the path. + pub fn to_path(&self) -> PathData { + match self { + LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } => { + let base = shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)); + let resolved = crate::corners::resolve_stored_radii(&base, radii, *radii_relative); + let radii = std::array::from_fn(|i| resolved.get(i).copied().unwrap_or(0.0)); + shapes::rectangle_with_corners(Rect::new(0.0, 0.0, *w, *h), radii, *kinds).transformed(*xf) + } + LiveShape::Ellipse { w, h, pie, xf } => shapes::ellipse_pie(Rect::new(0.0, 0.0, *w, *h), pie.0, pie.1).transformed(*xf), + LiveShape::Polygon { radii, kinds, radii_relative, .. } => { + let outline = self.polygon_outline(); + let radii = crate::corners::resolve_stored_radii(&outline, radii, *radii_relative); + cut_corners(&outline, &radii, kinds).0 + } + LiveShape::Line { a, b } => shapes::line(*a, *b), + LiveShape::Path { base, radii, kinds, radii_relative } => { + let radii = crate::corners::resolve_stored_radii(base, radii, *radii_relative); + cut_corners(base, &radii, kinds).0 + } + } + } + /// A polygon's outline with its corners uncut, in the document (empty for other shapes). + pub fn polygon_outline(&self) -> PathData { + match self { + LiveShape::Polygon { radius, sides, xf, .. } => shapes::polygon(Point::ZERO, *radius, *sides, 0.0).transformed(*xf), + _ => PathData::default(), + } + } + /// Give a polygon `n` sides (3–1000). Its corners keep the radius and kind they shared; else + /// the corners past the old last one are sharp. + pub fn set_sides(&mut self, n: u64) { + let LiveShape::Polygon { sides, radii, kinds, .. } = self else { return }; + *sides = n.clamp(3, 1000) as u32; + fn spread(v: &mut Vec, n: usize) { + match v.first().copied() { + Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n], + Some(_) => v.resize(n, T::default()), + None => {} + } + } + spread(radii, *sides as usize); + spread(kinds, *sides as usize); + } + /// A polygon's radius in the document, centre to vertex: its own radius by the mean scale of + /// `xf` (exact while its sides are equal). None for other shapes. + pub fn polygon_radius(&self) -> Option { + let LiveShape::Polygon { radius, xf, .. } = self else { return None }; + Some(radius * xf.determinant().abs().sqrt()) + } + /// A polygon's angle: the counterclockwise degrees in [0, 360) its first vertex is turned by + /// from straight up (the Rotate field's sense). None for other shapes. + pub fn polygon_angle(&self) -> Option { + let LiveShape::Polygon { .. } = self else { return None }; + // No −0° or 360° from rounding: a polygon drawn upright reads 0°. + let a = (-self.angle_deg()).rem_euclid(360.0); + Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) + } + /// Whether a polygon's sides are all as long: `xf` scales it evenly and doesn't shear it. True + /// for other shapes. + pub fn polygon_sides_equal(&self) -> bool { + let LiveShape::Polygon { xf, .. } = self else { return true }; + let [a, b, c, d, _, _] = xf.as_coeffs(); + let (sx, sy) = (a.hypot(b), c.hypot(d)); + (sx - sy).abs() <= 1e-9 * sx.max(sy) && (a * c + b * d).abs() <= 1e-9 * sx * sy + } + /// Give a polygon the document radius `r` (centre to vertex, see [`LiveShape::polygon_radius`]). + pub fn set_polygon_radius(&mut self, r: f64) { + let LiveShape::Polygon { radius, xf, .. } = self else { return }; + let k = xf.determinant().abs().sqrt(); + if k > 1e-12 && r.is_finite() { + *radius = r.max(0.0) / k; + } + } + /// The document radius that makes a polygon's sides `side` long (with its sides equal). + pub fn polygon_radius_for_side(&self, side: f64) -> Option { + let LiveShape::Polygon { sides, .. } = self else { return None }; + Some(side / (2.0 * (std::f64::consts::PI / f64::from((*sides).max(3))).sin())) + } + /// Turn a polygon about its centre to `angle` (degrees, as [`LiveShape::polygon_angle`]). + pub fn set_polygon_angle(&mut self, angle: f64) { + let Some(now) = self.polygon_angle() else { return }; + if let LiveShape::Polygon { xf, .. } = self + && angle.is_finite() + { + let centre = *xf * Point::ZERO; + *xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf; + } + } + /// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from + /// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`]. + pub fn make_sides_equal(&mut self) { + let Some(r) = self.polygon_radius() else { return }; + let LiveShape::Polygon { radius, xf, .. } = self else { return }; + let [a, b, _, _, e, f] = xf.as_coeffs(); + let flip = if xf.determinant() < 0.0 { Affine::FLIP_Y } else { Affine::IDENTITY }; + *xf = Affine::translate((e, f)) * Affine::rotate(b.atan2(a)) * flip; + *radius = r; + } + /// Apply `a` to the shape. True when the shape is no longer `a` applied to the old path, so + /// the caller must regenerate the path with [`LiveShape::to_path`]. + /// + /// A rectangle keeps round corners whatever its proportions: when `a` scales it along its own + /// sides (any rotation or reflection, no shear), the scale goes into `w`/`h` and `xf` keeps + /// only the rotation, reflection and position. The radii scale by the mean scale (the square + /// root of the determinant), which [`LiveShape::keep_corners`] undoes for Scale Corners off. + /// A shear can't keep circular corners: `xf` takes it, as do moves (so files saved with a + /// scale in `xf` keep their exact geometry until they're next transformed). A polygon's or a + /// path's corner radii are document lengths: they scale by the mean scale and the corners are + /// cut again, circular whatever `a` does. + pub fn transform(&mut self, a: Affine) -> bool { + match self { + LiveShape::Rectangle { xf, .. } => { + *xf = a * *xf; + !moves_only(a) && self.fold_scale() + } + LiveShape::Ellipse { xf, .. } => { + *xf = a * *xf; + false + } + LiveShape::Polygon { xf, radii, radii_relative, .. } => { + *xf = a * *xf; + scale_radii(radii, a, *radii_relative) + } + LiveShape::Path { base, radii, radii_relative, .. } => { + base.transform(a); + scale_radii(radii, a, *radii_relative) + } + LiveShape::Line { a: p, b } => { + *p = a * *p; + *b = a * *b; + false + } + } + } + /// Move the scale of a rectangle's `xf` into `w`/`h` (and its radii, by the mean scale), so + /// `xf` keeps only a rotation or reflection plus a move and the corners are circular in the + /// document. False (and nothing changes) when there is no scale to move, when `xf` shears or + /// isn't finite, and for other shapes. Files saved before transforms did this (#291) carry an + /// uneven scale in `xf`: their corners are elliptical until this runs. + pub fn fold_scale(&mut self) -> bool { + let LiveShape::Rectangle { w, h, radii, radii_relative, xf, .. } = self else { return false }; + let [m0, m1, m2, m3, m4, m5] = xf.as_coeffs(); + let (sx, sy) = (m0.hypot(m1), m2.hypot(m3)); + let orthogonal = sx > 1e-12 && sy > 1e-12 && (m0 * m2 + m1 * m3).abs() <= 1e-9 * sx * sy; + let finite = xf.as_coeffs().iter().all(|c| c.is_finite()) && w.is_finite() && h.is_finite(); + let unscaled = (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12; + if !orthogonal || !finite || unscaled { + return false; + } + let k = (sx * sy).sqrt(); + if !*radii_relative { + radii.iter_mut().for_each(|r| *r *= k); + } + *w *= sx; + *h *= sy; + *xf = Affine::new([m0 / sx, m1 / sx, m2 / sy, m3 / sy, m4, m5]); + true + } + /// This shape with [`LiveShape::fold_scale`] applied: a rectangle's size and radii in document + /// units (what Live Corners show and edit). + pub fn folded(&self) -> Self { + let mut s = self.clone(); + s.fold_scale(); + s + } + /// Divide live corner radii by `k`, the mean scale of a transform just applied, so the corners + /// keep their size (Scale Corners off). False when nothing changed. + pub fn keep_corners(&mut self, k: f64) -> bool { + let relative = self.radii_relative(); + let radii: &mut [f64] = match self { + LiveShape::Rectangle { radii, .. } => radii, + LiveShape::Polygon { radii, .. } | LiveShape::Path { radii, .. } => radii, + LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return false, + }; + if relative || !radii.iter().any(|r| *r > 0.0) || k <= 1e-12 { + return false; + } + radii.iter_mut().for_each(|r| *r /= k); + true + } + /// Rotation angle of the live shape in degrees, clockwise on the page (y points down). + pub fn angle_deg(&self) -> f64 { + match self { + LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } => { + let c = xf.as_coeffs(); + c[1].atan2(c[0]).to_degrees() + } + LiveShape::Line { a, b } => (b.y - a.y).atan2(b.x - a.x).to_degrees(), + LiveShape::Path { .. } => 0.0, + } + } +} + +fn all_round(kinds: &[CornerKind]) -> bool { + kinds.iter().all(|k| *k == CornerKind::Round) +} + +/// A polygon's side count read from a file, clamped as the commands clamp it: the outline and its +/// corner lists hold one entry per side, so a huge count would allocate gigabytes. +fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + u32::deserialize(d).map(|n| n.clamp(3, 1000)) +} + +/// Whether `a` only moves (no rotation, scale, shear or reflection). +pub(super) fn moves_only(a: Affine) -> bool { + let [a0, a1, a2, a3, _, _] = a.as_coeffs(); + (a0 - 1.0).abs() < 1e-12 && a1.abs() < 1e-12 && a2.abs() < 1e-12 && (a3 - 1.0).abs() < 1e-12 +} + +/// Scale corner radii in document units by the mean scale of `a`, applied to their path. True +/// when the path must be cut again: some corner is cut and `a` does more than move it (an +/// uneven scale would otherwise make the cuts elliptical). +fn scale_radii(radii: &mut [f64], a: Affine, relative: bool) -> bool { + if relative || moves_only(a) || !radii.iter().any(|r| *r > 0.0) { + return false; + } + let k = a.determinant().abs().sqrt(); + radii.iter_mut().for_each(|r| *r *= k); + true +} + +/// What a transform scales besides geometry, by its mean scale (the square root of its +/// determinant). `Scaling::default()` (and `false`) scales nothing else; `true` scales stroke +/// weights and dashes only. Transforms the user asks for take theirs from Scale Strokes & Effects +/// and Scale Corners. +#[derive(Clone, Copy, Debug, Default)] +pub struct Scaling { + /// Stroke weights, dash lengths and dash offsets scale. + pub strokes: bool, + /// With `strokes`: scales an effect's distance parameters (the effects catalogue's). + pub effects: Option, + /// Type keeps its character strokes' weight (they otherwise scale with the type). + pub keep_type_strokes: bool, + /// Live corner radii keep their size. + pub keep_corners: bool, + /// Pattern fills and strokes move with the art (Transform Patterns; General › Transform + /// Pattern Tiles is its default): their tiles transform too, instead of staying put. + pub patterns: bool, +} + +impl Scaling { + /// The mean scale of `a` when it scales (isn't 1): what strokes, effects and corners scale by. + pub fn factor(a: Affine) -> Option { + let k = a.determinant().abs().sqrt(); + ((k - 1.0).abs() > 1e-9).then_some(k) + } +} + +impl From for Scaling { + fn from(strokes: bool) -> Self { + Self { strokes, ..Self::default() } + } +} diff --git a/crates/doc/src/node/opacity.rs b/crates/doc/src/node/opacity.rs new file mode 100644 index 0000000000..0996b8c656 --- /dev/null +++ b/crates/doc/src/node/opacity.rs @@ -0,0 +1,129 @@ +use super::kind::NodeKind; +use super::*; + +/// Opacity mask: the luminance of the mask art sets the object's opacity (white = opaque). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct OpacityMask { + /// Mask art in document coordinates. + pub art: Arc, + /// Clip: outside the mask art is hidden. Off: outside the mask art stays visible. + #[serde(default = "yes")] + pub clip: bool, + /// Invert the mask's luminance. + #[serde(default)] + pub invert: bool, + /// Disabled masks are kept but not applied. + #[serde(default)] + pub disabled: bool, + /// Linked masks move with the object. + #[serde(default = "yes")] + pub linked: bool, +} + +impl OpacityMask { + pub fn new(art: Node, clip: bool) -> Self { + Self { art: Arc::new(art), clip, invert: false, disabled: false, linked: true } + } +} + +/// Every paint of `n` (and its children) white, opacities kept: an alpha mask's art as an opacity +/// mask's, whose luminance over the black outside the art is then the art's alpha. +pub fn whiten(n: &mut Node) { + let white = |p: &mut Paint| match p { + Paint::Solid { color, swatch, tint } => { + (*color, *swatch, *tint) = (Color::WHITE, None, 1.0); + } + Paint::Gradient(g) => { + for s in &mut g.gradient.stops { + (s.color, s.swatch, s.tint) = (Color::WHITE, None, 1.0); + } + } + Paint::None | Paint::Pattern { .. } => {} + }; + for item in &mut n.appearance.items { + white(item.paint_mut()); + } + match &mut n.kind { + NodeKind::Mesh(m) => m.points.iter_mut().for_each(|p| p.color = Color::WHITE), + NodeKind::Text(t) => t.runs.iter_mut().for_each(|r| { + white(&mut r.style.fill); + white(&mut r.style.stroke); + }), + _ => {} + } + if let Some(ch) = n.children_mut() { + for c in ch { + whiten(Arc::make_mut(c)); + } + } +} + +/// Knockout Group state of a container (the Transparency panel's three-state checkbox). In a +/// knockout group each child composites against the group's backdrop, so it hides the children +/// below it instead of showing them through its transparency. Neutral passes the enclosing +/// group's setting through to the children. Files from before the three states stored a bool: +/// `true` loads as On, `false` as Neutral. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Knockout { + #[default] + Neutral, + Off, + On, +} + +impl Knockout { + pub const ALL: [Knockout; 3] = [Knockout::Neutral, Knockout::Off, Knockout::On]; + + /// Name in files and command parameters. + pub fn label(self) -> &'static str { + match self { + Knockout::Neutral => "neutral", + Knockout::Off => "off", + Knockout::On => "on", + } + } + /// A name ([`Self::label`], any case) or a bool as older files and commands wrote it. + pub fn from_value(v: &serde_json::Value) -> Option { + match v { + serde_json::Value::Bool(b) => Some(Self::from(*b)), + serde_json::Value::String(s) => Self::ALL.into_iter().find(|k| k.label().eq_ignore_ascii_case(s.trim())), + _ => None, + } + } + /// The state a click on the checkbox moves to: on → neutral → off → on. + pub fn cycle(self) -> Self { + match self { + Knockout::On => Knockout::Neutral, + Knockout::Neutral => Knockout::Off, + Knockout::Off => Knockout::On, + } + } + /// Whether children of a group with this state knock each other out, inside a group (or page) + /// where that is `enclosing`. + pub fn resolve(self, enclosing: bool) -> bool { + match self { + Knockout::Neutral => enclosing, + Knockout::Off => false, + Knockout::On => true, + } + } +} + +impl From for Knockout { + fn from(b: bool) -> Self { + if b { Knockout::On } else { Knockout::Neutral } + } +} + +impl Serialize for Knockout { + fn serialize(&self, s: S) -> Result { + s.serialize_str(self.label()) + } +} + +impl<'de> Deserialize<'de> for Knockout { + fn deserialize>(d: D) -> Result { + let v = serde_json::Value::deserialize(d)?; + Self::from_value(&v).ok_or_else(|| serde::de::Error::custom(format!("invalid knockout {v}"))) + } +} diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs new file mode 100644 index 0000000000..6cc0cb3be7 --- /dev/null +++ b/crates/doc/src/node/ops.rs @@ -0,0 +1,712 @@ +use super::extras::Extras; +use super::ids::{LayerColor, NodeId}; +use super::kind::NodeKind; +use super::live_shape::{Scaling, moves_only}; +use super::opacity::Knockout; +use super::*; + +impl Node { + pub fn new(id: NodeId, kind: NodeKind) -> Self { + Self { + id, + name: None, + visible: true, + locked: false, + opacity: 1.0, + blend: BlendMode::Normal, + isolate: false, + knockout: Knockout::Neutral, + knockout_shape: false, + appearance: Appearance::default().into(), + kind, + bbox_angle: 0.0, + extras: Extras::default(), + } + } + + pub fn path(id: NodeId, path: PathData, appearance: Appearance) -> Self { + let mut n = Self::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }); + n.appearance = appearance.into(); + n + } + + pub fn group(id: NodeId, children: Vec>) -> Self { + Self::new(id, NodeKind::Group { children, clip: false }) + } + + pub fn layer(id: NodeId, name: &str, color: LayerColor) -> Self { + let mut n = Self::new( + id, + NodeKind::Layer { color, template: false, printable: true, children: vec![], clip: false, preview: true, dim_images: None }, + ); + n.name = Some(name.to_string()); + n + } + + pub fn children(&self) -> Option<&Vec>> { + match &self.kind { + NodeKind::Layer { children, .. } + | NodeKind::Group { children, .. } + | NodeKind::Compound { children, .. } + | NodeKind::Blend { children, .. } + | NodeKind::Envelope { content: children, .. } + | NodeKind::Repeat(RepeatSpec { source: children, .. }) + | NodeKind::Intertwine { children } => Some(children), + _ => None, + } + } + + pub fn children_mut(&mut self) -> Option<&mut Vec>> { + match &mut self.kind { + NodeKind::Layer { children, .. } + | NodeKind::Group { children, .. } + | NodeKind::Compound { children, .. } + | NodeKind::Blend { children, .. } + | NodeKind::Envelope { content: children, .. } + | NodeKind::Repeat(RepeatSpec { source: children, .. }) + | NodeKind::Intertwine { children } => Some(children), + _ => None, + } + } + + /// Does this object or layer move with its artboard? Locked and hidden ones only with + /// `locked_and_hidden` (Selection & Anchor Display › Move Locked and Hidden Artwork with + /// Artboard). + pub fn rides_with_artboard(&self, locked_and_hidden: bool) -> bool { + locked_and_hidden || (!self.locked && self.visible) + } + + pub fn is_layer(&self) -> bool { + matches!(self.kind, NodeKind::Layer { .. }) + } + + /// A template layer (Layer Options → Template). + pub fn is_template(&self) -> bool { + matches!(self.kind, NodeKind::Layer { template: true, .. }) + } + + /// The art objects of this container: its children, looking through sublayers, which are not + /// objects (bottom first). With `editable`, only the visible, unlocked objects in visible, + /// unlocked, non-template sublayers. + pub fn layer_art(&self, editable: bool) -> Vec { + fn visit(n: &Node, editable: bool, out: &mut Vec) { + for c in n.children().into_iter().flatten() { + if editable && (!c.visible || c.locked || c.is_template()) { + continue; + } + if c.is_layer() { + visit(c, editable, out); + } else { + out.push(c.id); + } + } + } + let mut out = vec![]; + visit(self, editable, &mut out); + out + } + + pub fn is_container(&self) -> bool { + self.children().is_some() + } + + /// Full opacity, Normal blending, no isolation, knockout or opacity mask (the Layers panel + /// fills an object's target circle otherwise). + pub fn has_default_transparency(&self) -> bool { + self.opacity >= 1.0 + && self.blend == BlendMode::Normal + && !self.isolate + && self.knockout == Knockout::Neutral + && !self.knockout_shape + && self.extras().mask.is_none() + } + + /// Kind name as the Layers panel / Properties panel shows it. + pub fn kind_label(&self) -> &'static str { + match &self.kind { + NodeKind::Layer { .. } => "Layer", + NodeKind::Group { clip: true, .. } => "Clip Group", + NodeKind::Group { .. } if self.extras().objects_on_path.is_some() => "Objects on Path", + NodeKind::Group { .. } => "Group", + NodeKind::Path { live: Some(l), .. } => l.label(), + NodeKind::Path { guide: true, .. } => "Guide", + NodeKind::Path { .. } => "Path", + NodeKind::Compound { .. } => "Compound Path", + NodeKind::Text(_) => "Type", + NodeKind::Image(_) => "Image", + NodeKind::SymbolInstance { .. } => "Symbol", + NodeKind::Blend { .. } => "Blend", + NodeKind::Envelope { .. } => "Envelope", + NodeKind::Mesh(_) => "Mesh", + NodeKind::Repeat(r) => r.kind.label(), + NodeKind::PlacedDocument(_) => "Placed Document", + NodeKind::Intertwine { .. } => "Intertwine", + } + } + + /// Name shown in the Layers panel: explicit name or ``. + pub fn display_name(&self) -> String { + if let Some(n) = &self.name { + return n.clone(); + } + match &self.kind { + NodeKind::Text(t) => { + let s: String = t.plain_text().chars().take(32).collect(); + if s.is_empty() { "".into() } else { s } + } + _ => format!("<{}>", self.kind_label()), + } + } + + /// [`Self::display_name`], or its XML id when Preferences › Units › Identify Objects By is XML ID. + pub fn identify_label(&self, xml_id: bool) -> String { + let name = self.display_name(); + if xml_id { crate::xml_id::from_object_name(&name) } else { name } + } + + /// Path data for path nodes. + pub fn path_data(&self) -> Option<&PathData> { + match &self.kind { + NodeKind::Path { path, .. } => Some(path), + _ => None, + } + } + + pub fn path_data_mut(&mut self) -> Option<&mut PathData> { + match &mut self.kind { + NodeKind::Path { path, .. } => Some(path), + _ => None, + } + } + + /// The path a path's or compound path's own strokes follow (a compound's members' together). + pub fn stroke_path(&self) -> Option { + match &self.kind { + NodeKind::Path { path, .. } => Some(path.to_bezpath()), + NodeKind::Compound { children, .. } => { + let mut bp = vectorcraft_geom::BezPath::new(); + children.iter().filter_map(|c| c.path_data()).for_each(|pd| bp.extend(pd.to_bezpath())); + Some(bp) + } + _ => None, + } + } + + /// A quick box round everything the object can paint, for culling clicks: paths and compound + /// paths grow their geometric bounds by the farthest their strokes can reach from any path + /// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in + /// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers + /// without a clipping mask and Intertwine groups take in their members' boxes, grown by their + /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. + pub fn reach_bounds(&self) -> Option { + self.reach(None) + } + + /// [`Node::reach_bounds`] with symbol instances measured by their symbol's art box from + /// `symbols`. An instance that only moves its art is measured as the art's visual box moved, + /// and any other instance is measured as its geometric box ([`Node::geometric_bounds_with`]) + /// grown by the farthest a stroke in the art can reach. + pub fn reach_bounds_with(&self, symbols: &SymbolBoxes) -> Option { + symbols.quickly(|| self.reach(Some(symbols))) + } + + /// The box of [`Node::reach_bounds`], or of [`Node::reach_bounds_with`] when `symbols` is given. + pub(crate) fn reach(&self, symbols: Option<&SymbolBoxes>) -> Option { + match &self.kind { + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + let o = self.appearance.outset(); + self.geometric(symbols).map(|b| b.inflate(o, o)) + } + // The members' reach, grown by the container's own strokes. + NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => { + let o = self.appearance.outset(); + children + .iter() + .skip(usize::from(self.extras().shaper.is_some())) + .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))) + .map(|b| b.inflate(o, o)) + } + NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))), + // The frame and each shape the image's own fills and strokes paint, a stroke's grown by + // the farthest it can reach from its shape. + NodeKind::Image(_) => crate::hit::image_paint(self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| { + let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; + vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) + }), + _ => self.visual(symbols), + } + } + + /// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path. A + /// symbol instance is measured as its transform applied to the 20 × 20 square around the origin + /// that symbols made in the app keep their art in ([`Node::geometric_bounds_with`] measures + /// its art). + pub fn geometric_bounds(&self) -> Option { + self.geometric(None) + } + + /// [`Node::geometric_bounds`] with each symbol instance measured as its transform applied to + /// its symbol's art box from `symbols`. An instance is measured as the square when its symbol + /// is missing, when its symbol or a symbol nested in its art holds an instance of itself, and + /// when symbols nest 32 deep in its art. + pub fn geometric_bounds_with(&self, symbols: &SymbolBoxes) -> Option { + self.geometric(Some(symbols)) + } + + /// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a + /// hidden bitmap for re-tracing/release; only source-image views measure that bitmap. + pub fn editing_children(&self) -> &[Arc] { + let children = self.children().map(Vec::as_slice).unwrap_or_default(); + let trace_source = self.extras().trace.is_some() + && !self.trace_view().shows_source() + && children.first().is_some_and(|n| !n.visible && matches!(n.kind, NodeKind::Image(_))); + let skip = usize::from(self.extras().shaper.is_some() || trace_source); + children.get(skip..).unwrap_or_default() + } + + /// The box of [`Node::geometric_bounds`], or of [`Node::geometric_bounds_with`] when `symbols` + /// is given. + pub(crate) fn geometric(&self, symbols: Option<&SymbolBoxes>) -> Option { + let union = |nodes: &[Arc]| nodes.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric(symbols))); + match &self.kind { + NodeKind::Path { path, .. } => path.bounds(), + NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => { + children.first().and_then(|c| c.geometric(symbols)) + } + NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. } => self + .editing_children() + .iter() + .filter(|c| c.visible || !matches!(self.kind, NodeKind::Layer { .. })) + .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric(symbols))), + NodeKind::Text(t) => self.projected(t.bounds()), + NodeKind::Image(im) => Some(im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, im.width as f64, im.height as f64))), + NodeKind::SymbolInstance { symbol, xf } => { + let art = symbols.and_then(|s| s.art(symbol)).map_or(SYMBOL_SQUARE, |a| a.geometric); + self.projected(Some(xf.transform_rect_bbox(art))) + } + NodeKind::Blend { children, spec } => vectorcraft_geom::union_opt(union(children), spec.spine.as_ref().and_then(|s| s.bounds())), + NodeKind::Envelope { content, kind, frame, .. } => crate::live::envelope_bounds(content, kind, **frame), + NodeKind::Mesh(m) => m.bounds(), + // Each copy is measured where the repeat draws it: `RepeatSpec::transforms` lays the + // copies out by the source's bounds measured without the document. + NodeKind::Repeat(r) => r.copies_bounds(union(&r.source)?, symbols.map(|s| s.document())), + NodeKind::PlacedDocument(p) => Some(p.bounds()), + // The members drawn over the others are drawn where they are. + NodeKind::Intertwine { children } => union(children), + } + } + + /// Visual bounds: what the object paints, its strokes included (paths and compound paths + /// measure theirs along their own shape, see [`Appearance::stroked_bounds`]). An image is + /// measured by its frame. A symbol instance is measured as in [`Node::geometric_bounds`], + /// grown by its own strokes' reach ([`Node::visual_bounds_with`] measures its art). + pub fn visual_bounds(&self) -> Option { + self.visual(None) + } + + /// [`Node::visual_bounds`] with symbol instances measured by their symbol's art from + /// `symbols`, the strokes in it included. An instance that only moves its art is measured as + /// the art's visual box moved. Any other instance is measured as its art transformed by it with + /// the strokes at their own weight, as the renderer draws it, and never smaller than its + /// geometric box ([`Node::geometric_bounds_with`]). Instances inside symbol art are measured as + /// in [`Node::reach_bounds_with`]. In boxes made by [`SymbolBoxes::with_brush_art`], the box of + /// an instance whose art holds brushed strokes grows by as far as their brush art can paint. In + /// boxes made by [`SymbolBoxes::without_art_strokes`], an instance is measured as its art's + /// geometric box placed by its transform, grown by its own strokes. + pub fn visual_bounds_with(&self, symbols: &SymbolBoxes) -> Option { + self.visual(Some(symbols)) + } + + /// The box of [`Node::visual_bounds`], or of [`Node::visual_bounds_with`] when `symbols` is + /// given. + pub(crate) fn visual(&self, symbols: Option<&SymbolBoxes>) -> Option { + match &self.kind { + NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => { + // A clipping path that paints (see `clip_paint`) strokes over the clip edge. + let clip = children.first()?; + if matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)) { + clip.visual(symbols) + } else { + clip.geometric(symbols) + } + } + NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))), + NodeKind::Layer { .. } | NodeKind::Group { .. } => { + // The container's own strokes paint around its members. + let o = self.appearance.outset(); + self.editing_children().iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))).map(|b| b.inflate(o, o)) + } + NodeKind::Blend { children, spec } => { + let b = children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))); + let o = crate::live::max_outset(children, symbols); + vectorcraft_geom::union_opt(b, spec.spine.as_ref().and_then(|s| s.bounds()).map(|r| r.inflate(o, o))) + } + NodeKind::Envelope { content, .. } | NodeKind::Repeat(RepeatSpec { source: content, .. }) => { + let o = crate::live::max_outset(content, symbols); + self.geometric(symbols).map(|b| b.inflate(o, o)) + } + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + let b = self.geometric(symbols)?; + Some(self.appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default())) + } + NodeKind::SymbolInstance { symbol, xf } => { + let b = match symbols.and_then(|s| Some((s, s.art(symbol)?))) { + Some((s, art)) if !s.art_strokes() => xf.transform_rect_bbox(art.geometric), + Some((_, art)) if moves_only(*xf) => xf.transform_rect_bbox(art.visual), + Some((s, art)) => { + let placed = xf.transform_rect_bbox(art.geometric); + match s.placed_visual(symbol, *xf) { + Some(v) => v.union(placed), + None => placed.inflate(art.reach, art.reach), + } + } + None => xf.transform_rect_bbox(SYMBOL_SQUARE), + }; + let o = self.appearance.outset() + symbols.map_or(0.0, |s| s.brush_pad(symbol)); + self.projected(Some(b)).map(|b| b.inflate(o, o)) + } + NodeKind::Text(t) => { + // The characters' strokes paint around the glyphs. + let o = self.appearance.outset().max(t.char_stroke_outset()); + self.geometric(symbols).map(|b| b.inflate(o, o)) + } + // An image is measured by its frame, without its own fills and strokes. + NodeKind::Image(_) => self.geometric(symbols), + _ => { + let o = self.appearance.outset(); + self.geometric(symbols).map(|b| b.inflate(o, o)) + } + } + } + + /// Apply an affine transform to the geometry (and gradients) of this node and its descendants. + /// `scaling` says what else scales by the transform's mean scale (a bool: stroke weights + /// only, see [`Scaling`]). + pub fn transform(&mut self, a: Affine, scaling: impl Into) { + self.transform_scaled(a, &scaling.into()); + } + + fn transform_scaled(&mut self, a: Affine, sc: &Scaling) { + // A dimension's measurement moves with it. + if let Some(e) = self.extras_if_any() + && let Some(dimension) = &mut e.dimension + { + dimension.transform(a); + } + // The frames of the objects attached to a path move with them. + if let Some(e) = self.extras_if_any() + && let Some(on_path) = &mut e.objects_on_path + { + on_path.transform(a); + } + if !self.is_layer() { + self.bbox_angle = crate::orient::transformed_angle(self.bbox_angle, a); + } + // Type and symbols in perspective keep looking the same, moved by `a`. + self.transform_projection(a); + // Refitting an unplaced gradient only reproduces moves and uniform scales. + if !keeps_gradient_fit(a) { + self.pin_gradients(); + } + let k = Scaling::factor(a); + if let Some(k) = k + && sc.strokes + { + self.appearance.scale_strokes(k); + if let Some(f) = sc.effects { + self.appearance.scale_effects(k, f); + } + } + // Only through `DerefMut` when there is something to change: the appearance is shared + // copy-on-write (`Shared`), and a move must not copy what it leaves as it is. + if self.appearance.gradients().next().is_some() { + self.appearance.transform_gradients(a); + } + if sc.patterns { + crate::pattern::transform_pattern_paints(self, a); + } + match &mut self.kind { + NodeKind::Path { path, live, .. } => { + path.transform(a); + if let Some(l) = live { + // A rectangle scaled unevenly keeps circular corners: its path is regenerated. + let reshaped = l.transform(a); + let kept = sc.keep_corners && k.is_some_and(|k| l.keep_corners(k)); + if reshaped || kept { + *path = l.to_path(); + } + } + } + NodeKind::Layer { children, .. } + | NodeKind::Group { children, .. } + | NodeKind::Compound { children, .. } + | NodeKind::Intertwine { children } => { + for c in children.iter_mut() { + Arc::make_mut(c).transform_scaled(a, sc); + } + } + NodeKind::Text(t) => { + t.transform(a); + // Character strokes scale with the type: undo that when strokes keep their weight. + if sc.keep_type_strokes + && let Some(k) = k.filter(|k| *k > 1e-12) + { + t.scale_char_strokes(1.0 / k); + } + } + NodeKind::Image(im) => im.xf = a * im.xf, + NodeKind::PlacedDocument(p) => p.xf = a * p.xf, + NodeKind::SymbolInstance { xf, .. } => *xf = a * *xf, + NodeKind::Blend { children, spec } => { + for c in children.iter_mut() { + Arc::make_mut(c).transform_scaled(a, sc); + } + if let Some(s) = &mut spec.spine { + s.transform(a); + } + } + NodeKind::Envelope { content, kind, frame, .. } => { + for c in content.iter_mut() { + Arc::make_mut(c).transform_scaled(a, sc); + } + **frame = crate::live::envelope_frame(a * **frame); + match &mut **kind { + EnvelopeKind::Mesh { points, handles, .. } => { + for p in points.iter_mut() { + *p = a * *p; + } + // Handles are offsets: they take the linear part. + let [m0, m1, m2, m3, _, _] = a.as_coeffs(); + let lin = Affine::new([m0, m1, m2, m3, 0.0, 0.0]); + for h in handles.iter_mut().flatten() { + *h = (lin * h.to_point()).to_vec2(); + } + } + EnvelopeKind::TopObject { path } => path.transform(a), + EnvelopeKind::Warp { .. } => {} + } + } + NodeKind::Mesh(m) => m.transform(a), + NodeKind::Repeat(r) => r.transform(a, *sc), + } + if let Some(m) = self.extras_if_any().and_then(|e| e.mask.as_mut()) + && m.linked + { + Arc::make_mut(&mut m.art).transform_scaled(a, sc); + } + // The area where an Intertwine member is drawn over the others moves with it. + if let Some(area) = self.extras_if_any().and_then(|e| e.intertwine.as_mut()) { + area.transform(a); + } + } + + /// Visit this node and all descendants depth first (paint order). + pub fn walk<'a>(&'a self, f: &mut impl FnMut(&'a Node)) { + f(self); + if let Some(ch) = self.children() { + for c in ch { + c.walk(f); + } + } + } + + /// Count of nodes in this subtree. + pub fn count(&self) -> usize { + let mut n = 0; + self.walk(&mut |_| n += 1); + n + } + + /// [`Self::count`], with the art of the opacity masks in the subtree (and theirs): what copying + /// and transforming the subtree makes, as [`Self::walk`] doesn't go into masks. + pub fn count_with_masks(&self) -> usize { + let mut n = 0; + self.walk(&mut |c| { + n += 1; + if let Some(m) = &c.extras().mask { + n += m.art.count_with_masks(); + } + }); + n + } + + /// Fix this node's unplaced gradients to their fit on its current bounds (before a transform + /// or warp that refitting wouldn't reproduce). Descendants pin their own when transformed. + pub fn pin_gradients(&mut self) { + if self.appearance.has_unplaced_gradient() + && let Some(b) = self.geometric_bounds() + { + self.appearance.pin_gradients(b); + } + } + + /// The paint behind the Fill (or Stroke) proxy, the map from its space to the document and + /// the box (in that space) an unplaced gradient fits. `item` (the Appearance panel's active + /// item) stands in for the topmost fill or stroke when it is of the proxy's kind. Otherwise + /// type objects paint their runs (the first run speaks for all) in text space, fitted to the + /// layout bounds; everything else paints its fill or stroke in the document, fitted to the + /// geometric bounds. Strokes fit the box grown by half their weight. + pub fn proxy_paint(&self, stroke: bool, item: Option) -> Option<(&vectorcraft_color::Paint, Affine, Rect)> { + let item = self.appearance.item_of_kind(item, !stroke); + if item.is_none() + && let NodeKind::Text(t) = &self.kind + { + let st = &t.runs.first()?.style; + let b = t.local_bounds(); + return Some(if stroke { (&st.stroke, t.xf, crate::appearance::stroke_paint_bounds(b, st.stroke_width)) } else { (&st.fill, t.xf, b) }); + } + // An object without bounds (an empty path) still shows its paints, fitted to an empty box. + let b = self.geometric_bounds().unwrap_or(Rect::ZERO); + if stroke { + self.appearance.stroke_at(item).map(|s| (&s.paint, Affine::IDENTITY, s.paint_bounds(b))) + } else { + self.appearance.fill_at(item).map(|f| (&f.paint, Affine::IDENTITY, b)) + } + } + + /// The gradient behind the Fill (or Stroke) proxy and its placement in document coordinates + /// (see [`Node::proxy_paint`]): what the gradient annotator shows and edits. + pub fn proxy_gradient(&self, stroke: bool, item: Option) -> Option<(&vectorcraft_color::GradientPaint, vectorcraft_color::GradientGeom)> { + let (paint, to_doc, b) = self.proxy_paint(stroke, item)?; + let vectorcraft_color::Paint::Gradient(g) = paint else { return None }; + let mut geom = g.resolve(b); + if to_doc != Affine::IDENTITY { + geom.transform(to_doc, g.gradient.kind); + } + Some((g, geom)) + } + + /// The freeform gradient behind the Fill (or Stroke) proxy, its points in document coordinates + /// (the automatic ones while unplaced), and the length its spreads are fractions of there + /// (see [`Node::proxy_paint`]): what the Gradient tool's freeform annotator shows and edits. + pub fn proxy_freeform(&self, stroke: bool, item: Option) -> Option<(vectorcraft_color::Freeform, f64)> { + let (paint, to_doc, b) = self.proxy_paint(stroke, item)?; + let vectorcraft_color::Paint::Gradient(g) = paint else { return None }; + if g.gradient.kind != vectorcraft_color::GradientKind::Freeform { + return None; + } + let mut f = g.freeform_on(b).into_owned(); + let mut scale = vectorcraft_color::freeform::spread_scale(b); + if to_doc != Affine::IDENTITY { + f.transform(to_doc); + scale *= to_doc.determinant().abs().sqrt(); + } + Some((f, scale)) + } +} + +impl Node { + /// Whether the children of this group or layer knock each other out, inside a group (or page) + /// where that is `enclosing`. + pub fn knocks_out(&self, enclosing: bool) -> bool { + matches!(self.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && self.knockout.resolve(enclosing) + } + + /// A plain group or layer that is neutral to knockout and has no transparency or appearance + /// of its own: inside a knockout group its children composite as the group's own children. + pub fn passes_knockout_through(&self) -> bool { + matches!(self.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { template: false, clip: false, .. }) + && self.has_default_transparency() + && self.appearance.items.is_empty() + && self.appearance.effects.is_empty() + } + + /// The visible elements of a knockout group made of `children` (bottom first): neutral plain + /// groups ([`Self::passes_knockout_through`]) contribute their children instead of themselves. + pub fn knockout_elements(children: &[Arc]) -> Vec<&Arc> { + fn push<'a>(children: &'a [Arc], out: &mut Vec<&'a Arc>) { + for c in children.iter().filter(|c| c.visible) { + match c.children() { + Some(ch) if c.passes_knockout_through() => push(ch, out), + _ => out.push(c), + } + } + } + let mut out = Vec::with_capacity(children.len()); + push(children, &mut out); + out + } + + /// Whether this is a clip group or a layer with a clipping mask: its first child clips the rest. + pub fn clips(&self) -> bool { + matches!(self.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }) + } + + /// Make this group or layer clip its children by its first child, or stop it. + pub fn set_clips(&mut self, on: bool) { + if let NodeKind::Group { clip, .. } | NodeKind::Layer { clip, .. } = &mut self.kind { + *clip = on; + } + } + + /// Whether blending inside this object reaches the art below it unless the object isolates + /// it: a blend mode other than Normal on a child (or, in a leaf, on a fill or stroke), + /// directly or through children that don't isolate their own blending. + pub fn blends_through(&self) -> bool { + self.blends_through_with(&mut |c| c.blends_through()) + } + + /// [`Self::blends_through`], with `inner` answering it for the children (e.g. from a cache). + pub fn blends_through_with(&self, inner: &mut dyn FnMut(&Arc) -> bool) -> bool { + match self.children() { + Some(ch) if !matches!(self.kind, NodeKind::Compound { .. }) => Self::children_blend(ch, inner), + _ => self.appearance.items.iter().any(|i| i.visible() && i.blend() != BlendMode::Normal), + } + } + + /// [`Self::blends_through`] of a group made of `children` (`inner` answers it for each child). + pub fn children_blend(children: &[Arc], inner: &mut dyn FnMut(&Arc) -> bool) -> bool { + children.iter().any(|c| c.visible && (c.blend != BlendMode::Normal || (!c.isolate && inner(c)))) + } +} + +impl Node { + /// The Appearance panel's row for what this object's own fills and strokes paint around: + /// "Contents" for a group or layer (its members) and for an image (its pixels), "Characters" + /// for type; `None` for objects whose fills and strokes paint their own geometry. + pub fn contents_label(&self) -> Option<&'static str> { + match self.kind { + NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Image(_) => Some("Contents"), + NodeKind::Text(_) => Some("Characters"), + _ => None, + } + } +} + +impl Node { + /// Whether this object shows any transparency, itself or anything inside it: object, fill or + /// stroke opacity below 100%, a blend mode, an opacity mask, effects or transparent gradient + /// stops. Hidden objects show none. + pub fn shows_transparency(&self) -> bool { + use vectorcraft_color::Paint; + let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0)); + 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) + || 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()))) + } +} + +/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)? +fn keeps_gradient_fit(a: Affine) -> bool { + let [m0, m1, m2, m3, _, _] = a.as_coeffs(); + let eps = 1e-12 * m0.abs().max(1.0); + m0 > 0.0 && m1.abs() <= eps && m2.abs() <= eps && (m0 - m3).abs() <= eps +} + +impl Node { + /// Whether a document point lies in this object's filled regions ([`Node::clip_shapes`]; true + /// everywhere for objects without them, such as type, whose boxes stand in). + pub fn contains_fn(&self) -> impl Fn(Point) -> bool + use<> { + let shapes = self.clip_shapes(None); + move |p| shapes.is_empty() || shapes.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p)) + } +} diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs new file mode 100644 index 0000000000..3e7a399f26 --- /dev/null +++ b/crates/doc/src/node/tests.rs @@ -0,0 +1,435 @@ +use super::*; + +/// A node writes its rarely set parts among the others, in the file's field order, and reads +/// them back into its extras; a node without any keeps none. +#[test] +fn extras_are_written_flat_in_order() { + let mut n = Node::path(NodeId(7), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art()); + n.name = Some("n".into()); + n.knockout_shape = true; + n.bbox_angle = 30.0; + { + let mut e = n.extras_mut(); + e.mask = Some(Box::new(OpacityMask::new(Node::group(NodeId(8), vec![]), true))); + e.trace = Some(Box::new(serde_json::json!({"preset": "p"}))); + e.series_index = Some(2); + e.type_outlines = true; + e.graphic_style = Some(3); + e.attrs = Some(Box::default()); + e.slice = Some(Box::default()); + e.perspective = Some(Box::new(crate::PerspectiveAttachment::new("left", 1.0))); + e.live_paint_gaps = Some(Box::default()); + } + /// The top-level keys of a JSON object, in the order written. + struct Keys(Vec); + impl<'de> Deserialize<'de> for Keys { + fn deserialize>(d: D) -> Result { + struct V; + impl<'de> serde::de::Visitor<'de> for V { + type Value = Keys; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("an object") + } + fn visit_map>(self, mut a: A) -> Result { + let mut out = vec![]; + while let Some(k) = a.next_key::()? { + a.next_value::()?; + out.push(k); + } + Ok(Keys(out)) + } + } + d.deserialize_map(V) + } + } + let text = serde_json::to_string(&n).unwrap(); + let keys = serde_json::from_str::(&text).unwrap().0; + let v: serde_json::Value = serde_json::from_str(&text).unwrap(); + let order = [ + "id", + "name", + "knockout_shape", + "appearance", + "mask", + "trace", + "series_index", + "type_outlines", + "kind", + "graphic_style", + "attrs", + "slice", + "bbox_angle", + "perspective", + "live_paint_gaps", + ]; + assert_eq!(keys, order); + assert_eq!(serde_json::from_value::(v).unwrap(), n); + let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art()); + let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap(); + assert!(back.extras_box().is_none()); + // Clearing the last extra lets them go; clearing one a node doesn't have allocates none. + n.extras_mut().mask = None; + assert!(n.extras_box().is_some()); + *n.extras_mut() = NodeExtras::default(); + assert!(n.extras_box().is_none()); + n.extras_mut().mask = None; + assert!(n.extras_box().is_none()); + assert_eq!(n.extras(), &NodeExtras::default()); +} + +#[test] +fn rect_live_shape_roundtrip() { + let l = LiveShape::Rectangle { + w: 10.0, + h: 20.0, + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::translate((5.0, 5.0)), + }; + assert_eq!(l.to_path().bounds(), Some(Rect::new(5.0, 5.0, 15.0, 25.0))); + assert_eq!(l.label(), "Rectangle"); +} + +#[test] +fn corner_kinds_save_only_when_some_corner_isnt_round() { + let mut l = LiveShape::Rectangle { + w: 100.0, + h: 50.0, + radii: [0.0, 10.0, 0.0, 0.0], + kinds: Default::default(), + radii_relative: false, + xf: Affine::IDENTITY, + }; + // Older files read as round. + let json = serde_json::to_value(&l).unwrap(); + assert!(json.get("kinds").is_none(), "{json}"); + assert_eq!(serde_json::from_value::(json).unwrap(), l); + if let LiveShape::Rectangle { kinds, .. } = &mut l { + kinds[1] = CornerKind::Chamfer; + } + let json = serde_json::to_value(&l).unwrap(); + assert_eq!(json["kinds"], serde_json::json!(["round", "chamfer", "round", "round"])); + assert_eq!(serde_json::from_value::(json).unwrap(), l); + // Polygons saved before Live Corners cut theirs read as sharp; a live path round-trips. + let p: LiveShape = serde_json::from_value(serde_json::json!({"shape": "polygon", "radius": 10.0, "sides": 5, "xf": [1, 0, 0, 1, 0, 0]})).unwrap(); + assert_eq!(p, LiveShape::Polygon { radius: 10.0, sides: 5, xf: Affine::IDENTITY, radii: vec![], kinds: vec![], radii_relative: false }); + let star = shapes::star(Point::new(0.0, 0.0), 20.0, 10.0, 5, 0.0); + let path = LiveShape::Path { base: star, radii: vec![2.0; 10], kinds: vec![], radii_relative: false }; + let json = serde_json::to_value(&path).unwrap(); + assert_eq!((json["shape"].as_str(), json.get("kinds")), (Some("path"), None)); + assert_eq!(serde_json::from_value::(json).unwrap(), path); + assert_eq!(path.label(), "Path"); +} + +/// A polygon read from a file has 3 to 1000 sides, as the commands give it: selecting one +/// with four billion made its outline and corner lists allocate tens of gigabytes. +#[test] +fn a_polygon_from_a_file_has_3_to_1000_sides() { + let read = |sides: u32| { + let json = serde_json::json!({"shape": "polygon", "radius": 10.0, "sides": sides, "xf": [1, 0, 0, 1, 0, 0]}); + serde_json::from_value::(json).unwrap() + }; + let sides_of = |l: &LiveShape| match l { + LiveShape::Polygon { sides, .. } => *sides, + _ => panic!("not a polygon: {l:?}"), + }; + let huge = read(4_000_000_000); + assert_eq!([0, 5, 1000].map(|n| sides_of(&read(n))), [3, 5, 1000]); + assert_eq!(sides_of(&huge), 1000); + assert_eq!(huge.polygon_outline().anchor_count(), 1000); +} + +#[test] +fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() { + let close = |a: f64, b: f64| (a - b).abs() < 1e-9; + // A hexagon of radius 10 at (50, 50), drawn 2× and turned 30° clockwise on the page. + let xf = Affine::translate((50.0, 50.0)) * Affine::rotate(30f64.to_radians()) * Affine::scale(2.0); + let mut p = LiveShape::Polygon { radius: 10.0, sides: 6, xf, radii: vec![], kinds: vec![], radii_relative: false }; + assert!(close(p.polygon_radius().unwrap(), 20.0) && close(p.polygon_angle().unwrap(), 330.0) && p.polygon_sides_equal()); + p.set_polygon_angle(45.0); + assert!(close(p.polygon_angle().unwrap(), 45.0)); + let centre = p.to_path().bounds().unwrap().center(); + assert!(close(centre.x, 50.0) && close(centre.y, 50.0), "turned about its centre: {centre:?}"); + p.set_polygon_radius(30.0); + assert!(close(p.polygon_radius().unwrap(), 30.0)); + // A hexagon's side is as long as its radius. + assert!(close(p.polygon_radius_for_side(12.0).unwrap(), 12.0)); + // Stretched, its sides differ; Make Sides Equal keeps its centre, angle and mean radius. + p.transform(Affine::scale_non_uniform(2.0, 1.0)); + assert!(!p.polygon_sides_equal()); + let (r, a) = (p.polygon_radius().unwrap(), p.polygon_angle().unwrap()); + p.make_sides_equal(); + assert!(p.polygon_sides_equal() && close(p.polygon_radius().unwrap(), r) && close(p.polygon_angle().unwrap(), a)); + let LiveShape::Polygon { xf, .. } = &p else { panic!("polygon") }; + assert_eq!(*xf * Point::ZERO, Point::new(100.0, 50.0)); + // Other shapes have none of it. + let e = LiveShape::Ellipse { w: 1.0, h: 1.0, pie: (0.0, 360.0), xf: Affine::IDENTITY }; + assert_eq!((e.polygon_radius(), e.polygon_angle()), (None, None)); +} + +/// A node holding a live rectangle (`w` × `h`, all radii `r`, placed by `xf`) and its path. +fn live_rect(w: f64, h: f64, r: f64, xf: Affine) -> Node { + let live = LiveShape::Rectangle { w, h, radii: [r; 4], kinds: Default::default(), radii_relative: false, xf }; + let mut n = Node::path(NodeId(1), live.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(live)); + } + n +} + +fn live_of(n: &Node) -> (f64, f64, [f64; 4], Affine) { + let NodeKind::Path { live: Some(l), .. } = &n.kind else { panic!("not a live shape") }; + let LiveShape::Rectangle { w, h, radii, xf, .. } = &**l else { panic!("not a live rectangle") }; + (*w, *h, *radii, *xf) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +fn near_xf(a: Affine, b: Affine) -> bool { + a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| near(*x, y)) +} + +/// Size and radius of a live rectangle, within rounding. +fn assert_live(n: &Node, w: f64, h: f64, r: f64) { + let (lw, lh, radii, _) = live_of(n); + assert!(near(lw, w) && near(lh, h) && radii.iter().all(|x| near(*x, r)), "{lw} × {lh} r {radii:?}, want {w} × {h} r {r}"); +} + +/// Each corner arc of a rounded rectangle's path, mapped by `back` (to undo a rotation), +/// spans `r` along x and y: the corner is a circular arc of radius `r`. +fn assert_round_corners(n: &Node, back: Affine, r: f64) { + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") }; + let a: Vec = path.subpaths[0].anchors.iter().map(|a| back * a.p).collect(); + assert_eq!(a.len(), 8, "a rounded rectangle"); + // Anchors 1→2, 3→4, 5→6 and 7→0 are the arcs. + for (i, j) in [(1, 2), (3, 4), (5, 6), (7, 0)] { + let (x, y) = ((a[j].x - a[i].x).abs(), (a[j].y - a[i].y).abs()); + assert!(near(x, r) && near(y, r), "corner spans {x} × {y}, want {r} × {r}"); + } +} + +const KEEP_CORNERS: Scaling = Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: true, patterns: false }; + +#[test] +fn uneven_scales_keep_live_corners_circular() { + // A 100 pt rounded square at (10, 10) stretched to 300 × 100 (#291). + let mut n = live_rect(100.0, 100.0, 20.0, Affine::translate((10.0, 10.0))); + let stretch = Affine::translate((10.0, 10.0)) * Affine::scale_non_uniform(3.0, 1.0) * Affine::translate((-10.0, -10.0)); + n.transform(stretch, KEEP_CORNERS); + assert_live(&n, 300.0, 100.0, 20.0); + assert!(near_xf(live_of(&n).3, Affine::translate((10.0, 10.0))), "the scale went into the size"); + let b = n.geometric_bounds().unwrap(); + assert!(near(b.x0, 10.0) && near(b.y0, 10.0) && near(b.x1, 310.0) && near(b.y1, 110.0), "{b:?}"); + assert_round_corners(&n, Affine::IDENTITY, 20.0); + // Scale Corners on: the radius scales by the mean scale, still circular. + let mut n = live_rect(100.0, 100.0, 20.0, Affine::IDENTITY); + n.transform(Affine::scale_non_uniform(4.0, 1.0), Scaling::default()); + assert_live(&n, 400.0, 100.0, 40.0); + assert_round_corners(&n, Affine::IDENTITY, 40.0); + // Squashed below the radius, the short sides are fully round; stretched back, it returns. + n.transform(Affine::scale_non_uniform(1.0, 0.5), KEEP_CORNERS); + assert_round_corners(&n, Affine::IDENTITY, 25.0); + n.transform(Affine::scale_non_uniform(1.0, 2.0), KEEP_CORNERS); + assert_round_corners(&n, Affine::IDENTITY, 40.0); +} + +#[test] +fn rotated_and_reflected_live_rectangles_scale_along_their_own_sides() { + let place = Affine::translate((200.0, 100.0)) * Affine::rotate(30f64.to_radians()); + let mut n = live_rect(100.0, 50.0, 10.0, place); + // Stretched along its own width, as a bounding-box drag of a rotated shape does. + n.transform(place * Affine::scale_non_uniform(2.0, 1.0) * place.inverse(), KEEP_CORNERS); + assert_live(&n, 200.0, 50.0, 10.0); + assert!(near_xf(live_of(&n).3, place)); + assert_round_corners(&n, place.inverse(), 10.0); + // A reflection stays in `xf`; the corners stay as they were. + n.transform(Affine::scale_non_uniform(-1.0, 1.0), KEEP_CORNERS); + assert_live(&n, 200.0, 50.0, 10.0); + let xf = live_of(&n).3; + assert!(near(xf.determinant(), -1.0)); + assert_round_corners(&n, xf.inverse(), 10.0); +} + +#[test] +fn shears_and_moves_keep_the_old_transform() { + // Scaling a rotated rectangle along the page axes shears it: `xf` takes it all, as before. + let rot = Affine::rotate(30f64.to_radians()); + let mut n = live_rect(100.0, 50.0, 10.0, rot); + let before = n.clone(); + let a = Affine::scale_non_uniform(2.0, 1.0); + n.transform(a, Scaling::default()); + assert_eq!(live_of(&n), (100.0, 50.0, [10.0; 4], a * rot)); + let (NodeKind::Path { path, .. }, NodeKind::Path { path: old, .. }) = (&n.kind, &before.kind) else { panic!() }; + assert_eq!(*path, old.transformed(a)); + // A file saved with an uneven scale in `xf` keeps its exact geometry when moved... + let legacy = Affine::translate((5.0, 5.0)) * Affine::scale_non_uniform(2.0, 1.0); + let mut n = live_rect(100.0, 100.0, 20.0, legacy); + n.transform(Affine::translate((10.0, 0.0)), KEEP_CORNERS); + assert_eq!(live_of(&n), (100.0, 100.0, [20.0; 4], Affine::translate((10.0, 0.0)) * legacy)); + // ...and once scaled, has document units and circular corners of its mean radius. + n.transform(Affine::scale(2.0), Scaling::default()); + assert_live(&n, 400.0, 200.0, 20.0 * 2f64.sqrt() * 2.0); + assert!(near(live_of(&n).3.determinant(), 1.0)); + assert_round_corners(&n, Affine::IDENTITY, 20.0 * 2f64.sqrt() * 2.0); +} + +/// A rectangle saved with an uneven scale in `xf` (before #291) has elliptical corners; Live +/// Corners see and edit it in document units, with circular corners (#442). +#[test] +fn a_scale_left_in_the_transform_folds_into_the_size() { + let legacy = Affine::translate((5.0, 5.0)) * Affine::scale_non_uniform(4.0, 1.0); + let n = live_rect(50.0, 80.0, 20.0, legacy); + let NodeKind::Path { live: Some(live), .. } = &n.kind else { panic!("not live") }; + let folded = live.folded(); + assert_eq!(live_of(&n).3, legacy, "folded() leaves the shape alone"); + let LiveShape::Rectangle { w, h, radii, xf, .. } = &folded else { panic!("not a rectangle") }; + // Drawn 200 × 80 with 80 × 20 corners; folded, the corners are circles of the mean radius. + assert!(near(*w, 200.0) && near(*h, 80.0) && radii.iter().all(|r| near(*r, 40.0)), "{w} × {h} r {radii:?}"); + assert!(near_xf(*xf, Affine::translate((5.0, 5.0)))); + let (a, b) = (folded.to_path().bounds().unwrap(), live.to_path().bounds().unwrap()); + assert!(near(a.x0, b.x0) && near(a.y0, b.y0) && near(a.x1, b.x1) && near(a.y1, b.y1), "same place and size: {a:?} {b:?}"); + let corners = crate::LiveCorners::of(&n).unwrap(); + assert_eq!(corners.style(&corners.all()).0, Some(40.0), "the radius in document units"); + // Nothing to fold: a moved, rotated or reflected rectangle and a sheared one stay as they are. + let place = Affine::translate((5.0, 5.0)) * Affine::rotate(0.5) * Affine::scale_non_uniform(-1.0, 1.0); + let shear = Affine::new([1.0, 0.0, 0.5, 1.0, 0.0, 0.0]); + for xf in [place, shear] { + let mut l = live_rect(100.0, 160.0, 20.0, xf); + let NodeKind::Path { live: Some(live), .. } = &mut l.kind else { panic!("not live") }; + assert!(!live.fold_scale()); + assert_eq!(live_of(&l), (100.0, 160.0, [20.0; 4], xf)); + } +} + +#[test] +fn default_transparency() { + let p = || Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + assert!(p().has_default_transparency()); + let tweaks: [fn(&mut Node); 7] = [ + |n| n.opacity = 0.5, + |n| n.blend = BlendMode::Multiply, + |n| n.isolate = true, + |n| n.knockout = Knockout::On, + |n| n.knockout = Knockout::Off, + |n| n.knockout_shape = true, + |n| n.extras_mut().mask = Some(Box::new(OpacityMask::new(n.clone(), true))), + ]; + for tweak in tweaks { + let mut n = p(); + tweak(&mut n); + assert!(!n.has_default_transparency(), "{n:?}"); + } +} + +#[test] +fn transform_group_recurses() { + let p = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + let mut g = Node::group(NodeId(1), vec![Arc::new(p)]); + g.transform(Affine::scale(2.0), true); + assert_eq!(g.geometric_bounds(), Some(Rect::new(0.0, 0.0, 20.0, 20.0))); + let child = &g.children().unwrap()[0]; + assert_eq!(child.appearance.stroke_width(), 2.0); +} + +#[test] +fn unplaced_gradients_pin_only_when_a_refit_would_differ() { + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, Paint}; + let grad = || Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); + let fresh = || Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), Appearance::basic(grad(), grad(), 2.0)); + let geoms = |n: &Node| match (n.appearance.fill_paint(), n.appearance.stroke_paint()) { + (Paint::Gradient(f), Paint::Gradient(s)) => (f.geom, s.geom), + _ => panic!("gradient fill and stroke"), + }; + let mut n = fresh(); + n.transform(Affine::translate((10.0, 5.0)) * Affine::scale(2.0), true); + assert_eq!(geoms(&n), (None, None), "moves and uniform scales keep refitting"); + let mut n = fresh(); + n.transform(Affine::rotate(std::f64::consts::FRAC_PI_2), false); + let (f, s) = geoms(&n); + // Fitted on the old bounds (strokes on the stroke-inflated box), then rotated: vertical. + let mut want = GradientGeom::fit(GradientKind::Linear, Rect::new(0.0, 0.0, 100.0, 50.0), 0.0); + want.transform(Affine::rotate(std::f64::consts::FRAC_PI_2), GradientKind::Linear); + let f = f.unwrap(); + assert!(f.start.distance(want.start) < 1e-9 && f.end.distance(want.end) < 1e-9, "{f:?}"); + assert!((s.unwrap().length() - 102.0).abs() < 1e-9); +} + +#[test] +fn display_names() { + let p = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + assert_eq!(p.display_name(), ""); + let l = Node::layer(NodeId(1), "Layer 1", LayerColor::Preset(0)); + assert_eq!(l.display_name(), "Layer 1"); +} + +#[test] +fn visual_bounds_include_stroke() { + let mut p = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + p.appearance.stroke_mut().unwrap().join = crate::appearance::LineJoin::Round; + assert_eq!(p.visual_bounds(), Some(Rect::new(-0.5, -0.5, 10.5, 10.5))); +} + +/// Type's visual bounds grow by how far its character strokes paint past the glyphs: half the +/// weight centred, the whole weight outside, nothing inside; scaled with the type. +#[test] +fn type_visual_bounds_grow_with_the_character_stroke() { + use crate::appearance::StrokeAlign; + use crate::text::{CharStyle, TextObject}; + let style = CharStyle { stroke: vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), stroke_width: 4.0, ..Default::default() }; + let mut t = TextObject::point(vectorcraft_geom::Point::new(0.0, 0.0), "Ab", style); + t.xf = Affine::scale(2.0) * t.xf; + let node = |t: &TextObject| Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))); + let g = node(&t).geometric_bounds().unwrap(); + for (align, grow) in [(StrokeAlign::Center, 4.0), (StrokeAlign::Outside, 8.0), (StrokeAlign::Inside, 0.0)] { + t.runs[0].style.stroke_align = align; + assert_eq!(node(&t).visual_bounds(), Some(g.inflate(grow, grow)), "{align:?}"); + } + t.runs[0].style.stroke = vectorcraft_color::Paint::None; + assert_eq!(node(&t).visual_bounds(), Some(g), "no stroke, no growth"); +} + +/// A group holding a path, a compound, an image and a nested group, as a file writes it. +fn nested_group() -> Node { + let path = |id| Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + let image = ImageObject { key: "k".into(), width: 2, height: 3, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let inner = Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(path(6))], clip: true }); + let compound = Node::new(NodeId(3), NodeKind::Compound { children: vec![Arc::new(path(4))], rule: FillRule::EvenOdd }); + let kids = vec![Arc::new(path(2)), Arc::new(compound), Arc::new(Node::new(NodeId(7), NodeKind::Image(Box::new(image)))), Arc::new(inner)]; + Node::new(NodeId(1), NodeKind::Group { children: kids, clip: false }) +} + +#[test] +fn kinds_read_back_with_type_first_or_anywhere() { + let n = nested_group(); + let json = serde_json::to_string(&n).unwrap(); + assert!(json.contains(r#""kind":{"type":"group","children":["#), "written with `type` first: {json}"); + assert_eq!(serde_json::from_str::(&json).unwrap(), n); + // Through a JSON value, whose keys are sorted: `type` comes after `children`. + let v = serde_json::to_value(&n).unwrap(); + assert_eq!(serde_json::from_value::(v.clone()).unwrap(), n); + assert_eq!(serde_json::from_str::(&v.to_string()).unwrap(), n); + // `type` last, in the middle, and keys a newer version added (ignored, as before). + let kind = r#"{"children":[],"x":{"deep":[1,2]},"clip":true,"type":"group"}"#; + assert_eq!(serde_json::from_str::(kind).unwrap(), NodeKind::Group { children: vec![], clip: true }); + let kind = r#"{"symbol":"S","type":"symbolinstance","later":1,"xf":[1,0,0,1,5,6]}"#; + assert_eq!(serde_json::from_str::(kind).unwrap(), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::translate((5.0, 6.0)) }); + let kind = r#"{"width":2,"type":"image","key":"k","height":3,"xf":[1,0,0,1,0,0]}"#; + assert!(matches!(serde_json::from_str::(kind).unwrap(), NodeKind::Image(i) if i.key == "k" && i.height == 3)); + // Defaults as before. + let NodeKind::Layer { printable, preview, template, .. } = + serde_json::from_str(r#"{"type":"layer","color":{"Preset":0},"children":[]}"#).unwrap() + else { + panic!("a layer") + }; + assert!(printable && preview && !template); +} + +#[test] +fn bad_kinds_are_errors() { + for bad in [r#"{"children":[]}"#, r#"{"type":"nothing"}"#, r#"{"type":"group"}"#, r#"{"type":3,"children":[]}"#, r#"[]"#, r#""group""#] { + assert!(serde_json::from_str::(bad).is_err(), "{bad}"); + } +} diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs new file mode 100644 index 0000000000..43fcfea929 --- /dev/null +++ b/crates/doc/src/node/wire.rs @@ -0,0 +1,181 @@ +use super::attributes::ObjectAttributes; +use super::extras::{Extras, NO_EXTRAS, NodeExtras}; +use super::ids::NodeId; +use super::kind::NodeKind; +use super::opacity::{Knockout, OpacityMask}; +use super::*; + +/// How a [`Node`] is written: the flat field list of the file format, in its order, borrowed from +/// the node and its extras (nothing is copied). The node reads back through `NodeWire`. +impl Serialize for Node { + fn serialize(&self, s: S) -> Result { + use crate::skip::{is_default, is_one, is_true}; + use serde::ser::SerializeStruct; + let e = self.extras(); + // As the derive did: the fields written, then each field written or skipped in order. + let skips = [ + false, + self.name.is_none(), + is_true(&self.visible), + is_default(&self.locked), + is_one(&self.opacity), + is_default(&self.blend), + is_default(&self.isolate), + is_default(&self.knockout), + is_default(&self.knockout_shape), + is_default(&self.appearance), + e.mask.is_none(), + e.trace.is_none(), + e.wrap.is_none(), + e.graph.is_none(), + e.series_index.is_none(), + is_default(&e.type_outlines), + e.shaper.is_none(), + false, + e.graphic_style.is_none(), + e.attrs.is_none(), + e.slice.is_none(), + is_default(&self.bbox_angle), + e.perspective.is_none(), + e.dimension.is_none(), + e.intertwine.is_none(), + e.live_paint_gaps.is_none(), + e.objects_on_path.is_none(), + ]; + let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?; + let mut skip = skips.into_iter(); + macro_rules! field { + ($name:literal, $v:expr) => { + if skip.next().unwrap_or(false) { + st.skip_field($name)?; + } else { + st.serialize_field($name, $v)?; + } + }; + } + field!("id", &self.id); + field!("name", &self.name); + field!("visible", &self.visible); + field!("locked", &self.locked); + field!("opacity", &self.opacity); + field!("blend", &self.blend); + field!("isolate", &self.isolate); + field!("knockout", &self.knockout); + field!("knockout_shape", &self.knockout_shape); + field!("appearance", &self.appearance); + field!("mask", &e.mask); + field!("trace", &e.trace); + field!("wrap", &e.wrap); + field!("graph", &e.graph); + field!("series_index", &e.series_index); + field!("type_outlines", &e.type_outlines); + field!("shaper", &e.shaper); + field!("kind", &self.kind); + field!("graphic_style", &e.graphic_style); + field!("attrs", &e.attrs); + field!("slice", &e.slice); + field!("bbox_angle", &self.bbox_angle); + field!("perspective", &e.perspective); + field!("dimension", &e.dimension); + field!("intertwine", &e.intertwine); + field!("live_paint_gaps", &e.live_paint_gaps); + field!("objects_on_path", &e.objects_on_path); + st.end() + } +} + +/// How a [`Node`] is read: the flat field list of the file format. Fields move into the node +/// (and its extras, allocated only when one is set) without a copy of what they own. +#[derive(Deserialize)] +#[serde(rename = "Node")] +pub(super) struct NodeWire { + id: NodeId, + #[serde(default)] + name: Option, + #[serde(default = "yes")] + visible: bool, + #[serde(default)] + locked: bool, + #[serde(default = "one")] + opacity: f32, + #[serde(default)] + blend: BlendMode, + #[serde(default)] + isolate: bool, + #[serde(default)] + knockout: Knockout, + #[serde(default)] + knockout_shape: bool, + #[serde(default)] + appearance: crate::Shared, + #[serde(default)] + mask: Option>, + #[serde(default)] + trace: Option>, + #[serde(default)] + wrap: Option, + #[serde(default)] + graph: Option>, + #[serde(default)] + series_index: Option, + #[serde(default)] + type_outlines: bool, + #[serde(default)] + shaper: Option>, + kind: NodeKind, + #[serde(default)] + graphic_style: Option, + #[serde(default)] + attrs: Option>, + #[serde(default)] + slice: Option>, + #[serde(default)] + bbox_angle: f64, + #[serde(default)] + perspective: Option>, + #[serde(default)] + dimension: Option>, + #[serde(default)] + intertwine: Option>, + #[serde(default)] + live_paint_gaps: Option>, + #[serde(default)] + objects_on_path: Option>, +} + +impl From for Node { + fn from(w: NodeWire) -> Self { + let extras = NodeExtras { + mask: w.mask, + trace: w.trace, + wrap: w.wrap, + graph: w.graph, + series_index: w.series_index, + type_outlines: w.type_outlines, + shaper: w.shaper, + graphic_style: w.graphic_style, + attrs: w.attrs, + slice: w.slice, + perspective: w.perspective, + dimension: w.dimension, + intertwine: w.intertwine, + live_paint_gaps: w.live_paint_gaps, + objects_on_path: w.objects_on_path, + }; + Node { + id: w.id, + name: w.name, + visible: w.visible, + locked: w.locked, + opacity: w.opacity, + blend: w.blend, + isolate: w.isolate, + knockout: w.knockout, + knockout_shape: w.knockout_shape, + appearance: w.appearance, + kind: w.kind, + bbox_angle: w.bbox_angle, + extras: Extras((extras != NO_EXTRAS).then(|| Box::new(extras))), + } + } +} diff --git a/crates/doc/src/objects_on_path.rs b/crates/doc/src/objects_on_path.rs index 372fae87aa..ca2ec7dd99 100644 --- a/crates/doc/src/objects_on_path.rs +++ b/crates/doc/src/objects_on_path.rs @@ -20,7 +20,7 @@ use vectorcraft_geom::{Affine, PathData, Point}; use crate::blend::Spine; use crate::symbols::SymbolBoxes; -use crate::{Node, NodeId, NodeKind}; +use crate::{Document, Node, NodeId, NodeKind}; /// The center of the nine reference points. pub const CENTER: u8 = 4; @@ -157,6 +157,47 @@ pub fn attachable_path(n: &Node) -> Option<&PathData> { } } +/// What keeps an object from going into an Objects on Path group, as its path or as one of its +/// objects ([`held`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Held { + /// It is inside a compound path, blend, envelope, repeat or Intertwine group, as part of its art. + Live, + /// It is the clipping path of a clip group or of a layer with a clipping mask, or inside one. + Clipping, +} + +/// What keeps the object `id` of `d` where it is ([`Held`]), if anything: in an Objects on Path +/// group it would no longer be a part of the compound path, blend, envelope, repeat or Intertwine +/// group it is in, or of the clipping path it is or is in. The innermost reason counts. `None` for +/// an object that is neither a clipping path nor inside one and is in a layer directly or through +/// plain groups and clip groups, and for an id not in `d`. +pub fn held(d: &Document, id: NodeId) -> Option { + let path = d.index_path(id)?; + let mut chain: Vec<&Node> = Vec::with_capacity(path.len()); + let mut nodes = &d.layers; + for &i in &path { + let n: &Node = nodes.get(i)?; + chain.push(n); + if let Some(children) = n.children() { + nodes = children; + } + } + for (depth, n) in chain.iter().enumerate().rev() { + let Some(parent) = depth.checked_sub(1).and_then(|up| chain.get(up)) else { break }; + if matches!(n.kind, NodeKind::Path { clipping: true, .. }) || (parent.clips() && path.get(depth) == Some(&0)) { + return Some(Held::Clipping); + } + if matches!( + parent.kind, + NodeKind::Compound { .. } | NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } + ) { + return Some(Held::Live); + } + } + None +} + /// The frame `n` is drawn in when it is attached: the page's axes turned by its rotation /// ([`Node::bbox_angle`]) less the nearest multiple of 90°, about the center of its bounds. Placed in /// that frame, an object stands square to the path or across it. diff --git a/crates/doc/src/orient.rs b/crates/doc/src/orient.rs index 6f61a09d8d..43c67d86f3 100644 --- a/crates/doc/src/orient.rs +++ b/crates/doc/src/orient.rs @@ -90,8 +90,8 @@ impl Node { /// ([`Node::geometric_bounds_with`]). pub fn bounds_in(&self, symbols: &SymbolBoxes, a: Affine, visual: bool) -> Option { match &self.kind { - NodeKind::Group { children, clip: false } => { - let b = children.iter().fold(None, |acc, c| union_opt(acc, c.bounds_in(symbols, a, visual))); + NodeKind::Group { clip: false, .. } => { + let b = self.editing_children().iter().fold(None, |acc, c| union_opt(acc, c.bounds_in(symbols, a, visual))); // The group's own strokes paint around its members (as in `visual_bounds`). let o = if visual { self.appearance.outset() } else { 0.0 }; b.map(|b| b.inflate(o, o)) diff --git a/crates/doc/src/overprint.rs b/crates/doc/src/overprint.rs index a822728a3a..056c8c888f 100644 --- a/crates/doc/src/overprint.rs +++ b/crates/doc/src/overprint.rs @@ -142,8 +142,10 @@ impl Document { let ids: Vec = list.as_array().into_iter().flatten().filter_map(|v| v.as_u64()).map(NodeId).collect(); // The old list marked spot-linked blacks too (so the spot names don't matter). let op = OverprintBlack { spot: true, ..Default::default() }; - for id in ids { - if let Some(n) = self.node_mut(id) { + // One walk of the tree finds them all (a missing id costs a walk each, and a list can repeat it). + let paths = self.index_paths(ids); + for path in paths.values() { + if let Some(n) = self.node_mut_at(path) { op.apply(n, &[]); } } diff --git a/crates/doc/src/pattern.rs b/crates/doc/src/pattern.rs index 1b587e70fa..a0b19b844c 100644 --- a/crates/doc/src/pattern.rs +++ b/crates/doc/src/pattern.rs @@ -11,12 +11,15 @@ //! **Repeats.** A [`RepeatSpec`] holds source art and a radial / grid / mirror arrangement; the //! instances are the source under [`repeat_transforms`] (evaluated on demand like blends). +use std::cell::RefCell; +use std::collections::HashMap; use std::sync::Arc; use serde::{Deserialize, Serialize}; use vectorcraft_color::Paint; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; +use crate::Document; use crate::appearance::AppearanceItem; use crate::node::{Node, NodeId, NodeKind}; @@ -279,7 +282,7 @@ impl PatternDef { out } /// Offsets of the pattern-editing preview copies (`copies`×`copies` around the tile, the - /// centre `(0, 0)` excluded). + /// centre `(0, 0)` excluded), in row-major order (not paint order). pub fn preview_offsets(&self) -> Vec { let k = (self.copies.clamp(1, 15) / 2) as i64; let mut out = vec![]; @@ -292,6 +295,38 @@ impl PatternDef { } out } + /// Offsets of every pattern-editing preview copy, including the centre tile, in the same paint + /// order [`offsets_covering`] uses for [`Overlap`]. + pub fn preview_offsets_in_paint_order(&self) -> Vec { + let k = (self.copies.clamp(1, 15) / 2) as i64; + let (i0, i1, j0, j1) = (-k, k, -k, k); + let mut out = vec![]; + let rows: Vec = if self.overlap.bottom_in_front { (j0..=j1).collect() } else { (j0..=j1).rev().collect() }; + for &j in &rows { + let cols: Vec = if self.overlap.right_in_front { (i0..=i1).collect() } else { (i0..=i1).rev().collect() }; + for i in cols { + out.push(self.offset(i, j)); + } + } + out + } + /// Preview copies drawn before and after the centre tile in [`Self::preview_offsets_in_paint_order`], + /// for one dimmed composite each (the centre tile is drawn at full strength between them). + pub fn preview_offsets_dimmed_sides(&self) -> (Vec, Vec) { + let mut before = vec![]; + let mut after = vec![]; + let mut past_center = false; + for o in self.preview_offsets_in_paint_order() { + if o.x == 0.0 && o.y == 0.0 { + past_center = true; + } else if past_center { + after.push(o); + } else { + before.push(o); + } + } + (before, after) + } /// Instances covering `region` (document space) as plain nodes for a pattern painted with /// `paint_xf` (pattern space → document), fresh-id-less (id 0). Used by exporters and Distort /// Pattern Fills; Expand uses [`Self::instances_in_with`]. @@ -487,17 +522,51 @@ pub struct RepeatSpec { /// many as one 500 × 500 grid, the budget [`PatternDef::offsets_covering`] also keeps. const MAX_REPEAT_INSTANCES: usize = 250_000; -/// Instances the Repeats in `nodes` make in all (0 when there are none). -fn nested_instances(nodes: &[Arc]) -> usize { - let mut sum = 0usize; - for n in nodes { - sum = sum.saturating_add(match (&n.kind, n.children()) { - (NodeKind::Repeat(r), _) => r.instances_in_all(), - (_, Some(c)) => nested_instances(c), - _ => 0, - }); +/// Counts the instances Repeats make in all, following symbol instances into their symbol's art +/// in `doc`: each symbol's art is counted once, and a missing symbol, or an instance of a symbol +/// inside its own art, counts as none. +/// +/// Limitation: symbols that show each other (A's art holds an instance of B and B's holds one of +/// A) are counted along the first path that reaches them. While A is counted, the instance of A +/// in B's art counts as none, and B keeps that count; had B been counted first, A's count would +/// include B's Repeats and B's would not. So within one count, what such symbols add can depend on +/// which of them came first. A symbol whose art reaches no such loop always counts the same. +struct NestedCount<'a> { + doc: Option<&'a Document>, + /// The counts made so far, by symbol name (`None` while that symbol's art is being counted). + symbols: RefCell>>, +} + +impl<'a> NestedCount<'a> { + fn new(doc: Option<&'a Document>) -> Self { + Self { doc, symbols: RefCell::default() } + } + + /// Instances the Repeats in the art of symbol `name` make in all. + fn symbol(&self, name: &str) -> usize { + if let Some(known) = self.symbols.borrow().get(name) { + return known.unwrap_or(0); + } + let Some(sym) = self.doc.and_then(|d| d.symbols.iter().find(|s| s.name == name)) else { return 0 }; + self.symbols.borrow_mut().insert(name.to_owned(), None); + let n = self.nodes(std::slice::from_ref(&sym.art)); + self.symbols.borrow_mut().insert(name.to_owned(), Some(n)); + n + } + + /// Instances the Repeats in `nodes` make in all (0 when there are none). + fn nodes(&self, nodes: &[Arc]) -> usize { + let mut sum = 0usize; + for n in nodes { + sum = sum.saturating_add(match (&n.kind, n.children()) { + (NodeKind::Repeat(r), _) => r.instances_in_all(self), + (NodeKind::SymbolInstance { symbol, .. }, _) => self.symbol(symbol), + (_, Some(c)) => self.nodes(c), + _ => 0, + }); + } + sum } - sum } /// Reflection across the line through `c` with direction angle `deg`. @@ -560,11 +629,18 @@ impl RepeatSpec { pub fn source_bounds(&self) -> Option { crate::live::nodes_bounds(&self.source) } - pub fn transforms(&self) -> Vec { - let mut v = repeat_transforms(&self.kind, self.source_bounds()); + /// Where the instances go, counting toward the budget the Repeats in the art of the symbols + /// of `doc` that instances in the source show (none without a document). + pub fn transforms(&self, doc: Option<&Document>) -> Vec { + self.transforms_from(doc, self.source_bounds()) + } + /// [`Self::transforms`] with the source's bounds (as [`Self::source_bounds`] measures them) + /// already at hand: measuring them again, at every level of nested Repeats, doubles the work. + fn transforms_from(&self, doc: Option<&Document>, bounds: Option) -> Vec { + let mut v = repeat_transforms(&self.kind, bounds); // Each instance draws the Repeats in the source again, so nested ones multiply (a 500 × 500 // grid of one is 62.5 billion instances): keep the first that fit the budget. - v.truncate(self.kept(nested_instances(&self.source))); + v.truncate(self.kept(NestedCount::new(doc).nodes(&self.source))); v } /// How many of its instances this Repeat keeps when each makes `nested` instances of the @@ -572,14 +648,21 @@ impl RepeatSpec { fn kept(&self, nested: usize) -> usize { self.kind.count().min(MAX_REPEAT_INSTANCES / nested.max(1)).max(1) } + /// How many instances this Repeat draws ([`Self::transforms`] for `doc`): as many as its + /// options make, fewer when the Repeats in its source would take it past + /// [`MAX_REPEAT_INSTANCES`]. + pub fn instances(&self, doc: Option<&Document>) -> usize { + self.kept(NestedCount::new(doc).nodes(&self.source)) + } /// Instances made in all, those of the Repeats nested in the source included. - fn instances_in_all(&self) -> usize { - let nested = nested_instances(&self.source); + fn instances_in_all(&self, count: &NestedCount) -> usize { + let nested = count.nodes(&self.source); self.kept(nested).saturating_mul(nested.max(1)) } - /// Evaluated instances: one group of the (transformed) source per instance (ids 0). - pub fn expand(&self) -> Vec { - self.transforms() + /// Evaluated instances: one group of the (transformed) source per instance (ids 0), as many + /// as [`Self::transforms`] keeps for `doc`. + pub fn expand(&self, doc: Option<&Document>) -> Vec { + self.transforms(doc) .into_iter() .map(|m| { let children = self @@ -596,14 +679,16 @@ impl RepeatSpec { }) .collect() } - /// Geometric bounds of all instances. - pub fn bounds(&self) -> Option { - self.copies_bounds(self.source_bounds()?) + /// Geometric bounds of all instances ([`Self::transforms`] for `doc`). + pub fn bounds(&self, doc: Option<&Document>) -> Option { + self.copies_bounds(self.source_bounds()?, doc) } /// The bounds of all instances of a source measuring `source`, each placed by its transform - /// ([`Self::transforms`]). - pub(crate) fn copies_bounds(&self, source: Rect) -> Option { - self.transforms().into_iter().fold(None, |acc, m| vectorcraft_geom::union_opt(acc, Some(m.transform_rect_bbox(source)))) + /// ([`Self::transforms`] for `doc`). + pub(crate) fn copies_bounds(&self, source: Rect, doc: Option<&Document>) -> Option { + // Without a document the source's bounds are the ones `source` is: not measured twice. + let transforms = if doc.is_none() { self.transforms_from(None, Some(source)) } else { self.transforms(doc) }; + transforms.into_iter().fold(None, |acc, m| vectorcraft_geom::union_opt(acc, Some(m.transform_rect_bbox(source)))) } /// Apply a document transform (source + arrangement parameters). pub fn transform(&mut self, a: Affine, scaling: impl Into) { @@ -739,6 +824,20 @@ mod tests { } } + #[test] + fn preview_paint_order_respects_overlap() { + let mut def = PatternDef::new("p", vec![sq(0.0, 0.0, 10.0)]); + def.copies = 3; + assert!(close(*def.preview_offsets_in_paint_order().last().unwrap(), Vec2::new(-10.0, -10.0))); + let mut d2 = def.clone(); + d2.overlap = Overlap { right_in_front: true, bottom_in_front: true }; + assert!(close(*d2.preview_offsets_in_paint_order().last().unwrap(), Vec2::new(10.0, 10.0))); + assert_eq!(def.preview_offsets_in_paint_order().len(), 9); + let (before, after) = def.preview_offsets_dimmed_sides(); + assert_eq!(before.len() + after.len(), 8); + assert!(before.iter().all(|o| *o != Vec2::ZERO) && after.iter().all(|o| *o != Vec2::ZERO)); + } + #[test] fn covering_offsets_and_overlap_order() { let def = PatternDef::new("p", vec![sq(0.0, 0.0, 10.0)]); @@ -813,11 +912,11 @@ mod tests { let r = RepeatSpec::radial(vec![sq(-5.0, -105.0, 10.0)], 4, Some(100.0)); let RepeatKind::Radial { center, .. } = r.kind else { panic!() }; assert!((center - Point::new(0.0, -0.0)).hypot() < 1e-9, "{center:?}"); - let cs: Vec = r.transforms().iter().map(|m| *m * Point::new(0.0, -100.0)).collect(); + let cs: Vec = r.transforms(None).iter().map(|m| *m * Point::new(0.0, -100.0)).collect(); assert!((cs[0] - Point::new(0.0, -100.0)).hypot() < 1e-9); assert!((cs[1] - Point::new(100.0, 0.0)).hypot() < 1e-9, "{cs:?}"); assert!((cs[2] - Point::new(0.0, 100.0)).hypot() < 1e-9); - assert_eq!(r.expand().len(), 4); + assert_eq!(r.expand(None).len(), 4); } #[test] @@ -826,18 +925,18 @@ mod tests { if let RepeatKind::Radial { radius, .. } = &mut r.kind { *radius = 50.0; } - let m = r.transforms()[0]; + let m = r.transforms(None)[0]; assert!((m * Point::new(0.0, -100.0) - Point::new(0.0, -50.0)).hypot() < 1e-9); } #[test] fn grid_repeat_transforms() { let g = RepeatSpec::grid(vec![sq(0.0, 0.0, 10.0)], 5.0, 2.0); - let t = g.transforms(); + let t = g.transforms(None); assert_eq!(t.len(), 9); assert!((t[1] * Point::ZERO - Point::new(15.0, 0.0)).hypot() < 1e-9); assert!((t[3] * Point::ZERO - Point::new(0.0, 12.0)).hypot() < 1e-9); - assert_eq!(g.bounds(), Some(Rect::new(0.0, 0.0, 40.0, 34.0))); + assert_eq!(g.bounds(None), Some(Rect::new(0.0, 0.0, 40.0, 34.0))); } #[test] @@ -846,7 +945,7 @@ mod tests { if let RepeatKind::Grid { flip_cols, .. } = &mut g.kind { *flip_cols = true; } - let t = g.transforms(); + let t = g.transforms(None); // Column 1 is mirrored about the source centre, then moved one tile right. assert!((t[1] * Point::new(0.0, 0.0) - Point::new(20.0, 0.0)).hypot() < 1e-9); } @@ -854,10 +953,10 @@ mod tests { #[test] fn mirror_transforms() { let m = RepeatSpec::mirror(vec![sq(0.0, 0.0, 10.0)], 90.0, 5.0); - let t = m.transforms(); + let t = m.transforms(None); assert_eq!(t.len(), 2); assert!((t[1] * Point::new(0.0, 3.0) - Point::new(30.0, 3.0)).hypot() < 1e-9); - let b = m.bounds().unwrap(); + let b = m.bounds(None).unwrap(); assert!((b.x1 - 30.0).abs() < 1e-9 && b.x0.abs() < 1e-9 && (b.y1 - 10.0).abs() < 1e-9, "{b:?}"); // Horizontal axis. let h = reflect_about(Point::new(0.0, 10.0), 0.0); @@ -867,9 +966,9 @@ mod tests { #[test] fn repeat_transform_moves_arrangement() { let mut r = RepeatSpec::radial(vec![sq(-5.0, -105.0, 10.0)], 4, Some(100.0)); - let before = r.bounds().unwrap(); + let before = r.bounds(None).unwrap(); r.transform(Affine::translate((50.0, 0.0)), false); - let after = r.bounds().unwrap(); + let after = r.bounds(None).unwrap(); assert!((after.x0 - before.x0 - 50.0).abs() < 1e-9); let mut m = RepeatSpec::mirror(vec![sq(0.0, 0.0, 10.0)], 90.0, 5.0); m.transform(Affine::rotate(std::f64::consts::FRAC_PI_2), false); @@ -882,7 +981,7 @@ mod tests { // Instances made in all, counted from the transforms without drawing any. fn made(r: &RepeatSpec) -> usize { let each: usize = r.source.iter().map(|s| if let NodeKind::Repeat(n) = &s.kind { made(n) } else { 1 }).sum(); - r.transforms().len().saturating_mul(each) + r.transforms(None).len().saturating_mul(each) } let grid = |source: Arc| { let mut g = RepeatSpec::grid(vec![source], 0.0, 0.0); @@ -899,7 +998,7 @@ mod tests { // A 500 × 500 grid of it made 62.5 billion. let outer = grid(repeat(inner.clone())); assert!(made(&outer) <= 250_000, "{} instances", made(&outer)); - assert_eq!(outer.expand().len(), outer.transforms().len()); + assert_eq!(outer.expand(None).len(), outer.transforms(None).len()); assert!(made(&RepeatSpec::mirror(vec![repeat(inner)], 90.0, 5.0)) <= 250_000); // Small nests are left as they are. let small = RepeatSpec::mirror(vec![repeat(RepeatSpec::grid(vec![sq(0.0, 0.0, 10.0)], 1.0, 1.0))], 90.0, 5.0); diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index 6656e75ae8..9b00da57eb 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -1,4 +1,5 @@ -//! Placed documents: another VectorCraft file placed linked ([`PlacedDocument`]). +//! Placed documents: another VectorCraft file, or a page of a PDF or `.ai` file, placed linked +//! ([`PlacedDocument`]). //! //! The object keeps the link to the file and the file's bytes, stored like image data in //! [`Document::images`] (with a small preview a save writes instead, as for linked images), so the @@ -6,8 +7,9 @@ //! joins the object tree, so editing can't reach it: it is locked by design. Drawing and exporting //! expand it like a live object ([`crate::live::expanded`]). //! -//! The file is read by the native format's loader, which lives above this crate and registers -//! itself ([`set_loader`]); the art read is kept in a small cache by content. Before exporting, +//! The file is read by the engine's loader (native documents, PDF and `.ai` pages), which lives +//! above this crate and registers itself ([`set_loader`]); the art read is kept in a small cache +//! by content. Before exporting, //! every exporter calls [`Document::with_placed_art`], which adds the resources the art uses //! (images, symbols, patterns) under names of their own ([`RESOURCE_PREFIX`]) to a temporary copy //! of the document, so they never meet the user's or show in panels. Placed documents inside a @@ -25,16 +27,21 @@ use vectorcraft_color::Paint; use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol}; -/// A placed document: an artboard of another VectorCraft file, shown as one locked object. +/// A placed document: an artboard of another VectorCraft file, or a page of a PDF or `.ai` file, +/// shown as one locked object. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PlacedDocument { - /// The file (its `page` is the artboard shown, 1-based). + /// The file (its `page` is the artboard or page shown, 1-based). pub link: LinkInfo, /// Key into [`Document::images`]: the file's bytes (see [`key_for`]). pub key: String, /// The art's bounds rather than the artboard (File › Place's `crop: "bounding"`). #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub bounding: bool, + /// The box of a PDF or `.ai` page shown when not `bounding` (File › Place's `crop`); a + /// VectorCraft document shows its artboard whatever this says. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub page_box: PageBox, /// The artboard's size (or the art's) at 100% (pt). pub width: f64, pub height: f64, @@ -45,11 +52,43 @@ pub struct PlacedDocument { pub placement: PlacementOptions, } +/// The box of a PDF page a placed PDF or `.ai` file shows (File › Place's `crop`, other than +/// `bounding`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum PageBox { + /// The visible page area. + #[default] + Crop, + Art, + Trim, + Bleed, + Media, +} + +impl PageBox { + /// The `crop` param value. + pub fn id(self) -> &'static str { + match self { + PageBox::Crop => "crop", + PageBox::Art => "art", + PageBox::Trim => "trim", + PageBox::Bleed => "bleed", + PageBox::Media => "media", + } + } +} + /// The images key of a file's bytes (`hash`, [`crate::links::hash_bytes`]) placed showing -/// artboard `page` (`bounding`: its art's bounds): objects showing the same thing share a blob and -/// its preview. -pub fn key_for(hash: &str, page: u32, bounding: bool) -> String { - format!("{hash}-{page}{}", if bounding { "b" } else { "" }) +/// artboard or page `page` (`bounding`: its art's bounds; else the page's box `page_box`): +/// objects showing the same thing share a blob and its preview. +pub fn key_for(hash: &str, page: u32, bounding: bool, page_box: PageBox) -> String { + let shown = match (bounding, page_box) { + (true, _) => "b", + (false, PageBox::Crop) => "", + (false, b) => b.id(), + }; + format!("{hash}-{page}{shown}") } impl PlacedDocument { @@ -107,7 +146,7 @@ impl PlacedDocument { pub fn preview_image(&self, bytes: &[u8]) -> Option { let (w, h) = image_size(bytes).filter(|(w, h)| *w > 0 && *h > 0)?; let px = Affine::scale_non_uniform(self.width / w as f64, self.height / h as f64); - Some(ImageObject { key: self.key.clone(), width: w, height: h, xf: self.xf * px, link: None, placement: Default::default() }) + Some(ImageObject { key: self.key.clone(), width: w, height: h, xf: self.xf * px, link: None, placement: Default::default(), pixels: None }) } } @@ -249,11 +288,23 @@ pub fn set_file_reader(f: FileReader) { let _ = FILE_READER.set(f); } +/// Whether the caller may read the file at a path (`true`: it may). The engine registers one with +/// [`set_read_check`]: the cache below is shared by every caller, and a cached file is handed out +/// only to a caller that may read the file it came from. +pub type ReadCheck = fn(&str) -> bool; + +static READ_CHECK: OnceLock = OnceLock::new(); + +/// Register how a caller's right to read a file is checked (the first registration stays). +pub fn set_read_check(f: ReadCheck) { + let _ = READ_CHECK.set(f); +} + /// The most bytes of files read again kept. const FULL_BYTES: usize = 512 << 20; -/// Files read again, by key, the most recently read last. -type FullFiles = Vec<(String, Arc>)>; +/// Files read again, by key, with the path each was read from, the most recently read last. +type FullFiles = Vec<(String, String, Arc>)>; static FULL: Mutex = Mutex::new(Vec::new()); @@ -268,7 +319,11 @@ pub fn full_bytes_cached(p: &PlacedDocument, blob: &ImageBlob) -> Option>)> = + full().iter().rev().filter(|(k, _, _)| *k == p.key).map(|(_, path, b)| (path.clone(), b.clone())).collect(); + candidates.into_iter().find(|(path, _)| allowed(path)).map(|(_, b)| b) } /// The file's bytes: stored, read again already, or read again now ([`set_file_reader`]). `None` @@ -279,10 +334,10 @@ pub fn full_bytes(p: &PlacedDocument, blob: &ImageBlob) -> Option>> } let b = Arc::new(FILE_READER.get()?(p)?); let mut c = full(); - c.push((p.key.clone(), b.clone())); - let mut total: usize = c.iter().map(|(_, b)| b.len()).sum(); + c.push((p.key.clone(), p.link.path.clone(), b.clone())); + let mut total: usize = c.iter().map(|(_, _, b)| b.len()).sum(); while total > FULL_BYTES && c.len() > 1 { - total = total.saturating_sub(c.remove(0).1.len()); + total = total.saturating_sub(c.remove(0).2.len()); } Some(b) } @@ -405,7 +460,7 @@ fn read_preview(p: &PlacedDocument, bytes: &Arc>) -> Option> = vec![]; + // Placed documents are told apart by the names their art's resources get here, so one + // file placed in itself, or many times in a file placed many times, read again in every + // branch: past [`MAX_PLACED_READS`] reads, the rest show their previews. + let mut reads = 0usize; while let Some((p, depth)) = queue.pop() { let Some(blob) = d.images.get(&p.key).cloned() else { continue }; - let full = if depth < MAX_DEPTH { full_bytes(&p, &blob) } else { None }; + // Top-level placements are distinct already (by key): only reads nested inside placed + // documents count, so a catalogue placing many files still reads each of them. + let read_full = depth < MAX_DEPTH && (depth == 0 || reads < MAX_PLACED_READS); + reads += usize::from(read_full && depth > 0); + let full = if read_full { full_bytes(&p, &blob) } else { None }; if full.and_then(|b| read(&p, &b)).is_none() { let preview = if blob.is_proxy() { Some(blob.bytes.clone()) } else { blob.proxy.clone() }; if let Some(bytes) = preview { @@ -507,7 +573,7 @@ impl Document { .chain(e.doc.symbols.iter().map(|s| &s.art)) .chain(e.doc.graph_designs.iter().map(|g| &g.art)) .chain(e.doc.patterns.iter().flat_map(|p| &p.art)); - for root in inner { + for root in inner.filter(|_| reads < MAX_PLACED_READS) { walk_all(root, &mut |n| { if let NodeKind::PlacedDocument(q) = &n.kind { let key = format!("{prefix}{}", q.key); @@ -576,6 +642,7 @@ mod tests { link: LinkInfo::new("/art/logo.vectorcraft"), key: key.into(), bounding: false, + page_box: PageBox::Crop, width: 80.0, height: 40.0, xf: Affine::translate((10.0, 10.0)), @@ -597,6 +664,7 @@ mod tests { xf: Affine::IDENTITY, link: None, placement: Default::default(), + pixels: None, })), ); d.symbols.push(Symbol { name: "Star".into(), art: Arc::new(art) }); @@ -616,9 +684,18 @@ mod tests { let v = serde_json::to_value(&n).unwrap(); assert_eq!(v["kind"]["type"], "placeddocument"); assert_eq!(v["kind"]["link"]["path"], "/art/logo.vectorcraft"); + // The box of a PDF page is written only when it isn't the crop box. + assert!(v["kind"].get("page_box").is_none(), "{v}"); let back: Node = serde_json::from_value(v).unwrap(); assert_eq!(back, n); - assert_eq!(key_for("img00", 2, true), "img00-2b"); + assert_eq!(key_for("img00", 2, true, PageBox::Crop), "img00-2b"); + assert_eq!(key_for("img00", 2, false, PageBox::Crop), "img00-2"); + assert_eq!(key_for("img00", 2, false, PageBox::Trim), "img00-2trim"); + let mut trim = placed("doc1-1trim"); + trim.page_box = PageBox::Trim; + let v = serde_json::to_value(&trim).unwrap(); + assert_eq!(v["page_box"], "trim"); + assert_eq!(serde_json::from_value::(v).unwrap(), trim); } #[test] diff --git a/crates/doc/src/plugin_data.rs b/crates/doc/src/plugin_data.rs new file mode 100644 index 0000000000..f29ab93703 --- /dev/null +++ b/crates/doc/src/plugin_data.rs @@ -0,0 +1,86 @@ +//! What plug-ins keep with a document: settings that belong to the whole document rather than to +//! one object, such as the pens a plotter holds or a machine's profile. +//! +//! They are the document's foreign data ([`Document::unknown`], under [`PLUGIN_DATA`]), as the +//! perspective grid and the brushes are, so the native file has no section of its own for them +//! and a version from before them keeps them when it saves. The host never reads them: a filter +//! plug-in writes its own and reads only its own back, and an exporter, which is given the whole +//! document, can read them all (`vectorcraft-plugins`, which caps what one plug-in keeps). + +use serde_json::{Map, Value}; + +use crate::Document; + +/// `Document::unknown` key: `{"": }`. +pub const PLUGIN_DATA: &str = "pluginData"; + +impl Document { + /// What plug-in `id` keeps with the document, if anything. + pub fn plugin_data(&self, id: &str) -> Option<&Value> { + self.unknown.get(PLUGIN_DATA).and_then(|m| m.get(id)) + } + + /// Keeps `data` for plug-in `id` in place of what it kept; `None` forgets it, and the key goes + /// once no plug-in keeps anything. A value under the key that isn't a map of plug-in ids (a + /// damaged file) is replaced when a plug-in keeps something. + pub fn set_plugin_data(&mut self, id: &str, data: Option) { + let Some(data) = data else { + // Nothing to forget: don't copy the foreign data the undo history shares. + if self.plugin_data(id).is_none() { + return; + } + let Some(m) = self.unknown.get_mut(PLUGIN_DATA).and_then(Value::as_object_mut) else { return }; + m.remove(id); + if m.is_empty() { + self.unknown.remove(PLUGIN_DATA); + } + return; + }; + let kept = self.unknown.entry(PLUGIN_DATA.to_string()).or_insert_with(|| Value::Object(Map::new())); + if !kept.is_object() { + *kept = Value::Object(Map::new()); + } + if let Some(m) = kept.as_object_mut() { + m.insert(id.to_string(), data); + } + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + /// Each plug-in has its own entry, replaced when it keeps something else; forgetting the last + /// one removes the key, and forgetting what isn't kept copies nothing. + #[test] + fn each_plug_in_keeps_its_own_data() { + let mut d = Document::new(10.0, 10.0); + assert_eq!(d.plugin_data("a"), None); + d.set_plugin_data("a", Some(json!({"pens": 2}))); + d.set_plugin_data("b", Some(json!([1, 2]))); + d.set_plugin_data("a", Some(json!({"pens": 3}))); + assert_eq!((d.plugin_data("a"), d.plugin_data("b")), (Some(&json!({"pens": 3})), Some(&json!([1, 2])))); + d.set_plugin_data("a", None); + assert_eq!(d.unknown[PLUGIN_DATA], json!({"b": [1, 2]})); + let before = d.clone(); + d.set_plugin_data("a", None); + assert!(crate::Shared::ptr_eq(&before.unknown, &d.unknown), "still shared with the earlier version"); + d.set_plugin_data("b", None); + assert!(!d.unknown.contains_key(PLUGIN_DATA)); + } + + /// A damaged file's value under the key holds nothing for any plug-in, stays while there is + /// nothing to forget, and is replaced when a plug-in keeps something. + #[test] + fn a_damaged_value_holds_nothing() { + let mut d = Document::new(10.0, 10.0); + d.unknown.insert(PLUGIN_DATA.into(), json!(5)); + assert_eq!(d.plugin_data("a"), None); + d.set_plugin_data("a", None); + assert_eq!(d.unknown[PLUGIN_DATA], json!(5)); + d.set_plugin_data("a", Some(json!(true))); + assert_eq!(d.unknown[PLUGIN_DATA], json!({"a": true})); + } +} diff --git a/crates/doc/src/range.rs b/crates/doc/src/range.rs index 80b4d6d338..87db16f206 100644 --- a/crates/doc/src/range.rs +++ b/crates/doc/src/range.rs @@ -9,9 +9,15 @@ pub fn parse_range(s: &str, count: usize) -> Result, String> { if t.is_empty() { return Ok(open); } - t.parse().ok().filter(|n| (1..=count).contains(n)).ok_or_else(|| format!("range `{s}`: `{t}` is not a number from 1 to {count}")) + t.bytes() + .all(|b| b.is_ascii_digit()) + .then(|| t.parse().ok()) + .flatten() + .filter(|n| (1..=count).contains(n)) + .ok_or_else(|| format!("range `{s}`: `{t}` is not a number from 1 to {count}")) }; let mut out = vec![]; + let mut seen = std::collections::HashSet::new(); for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) { let (a, b) = match part.replace('\u{2013}', "-").split_once('-') { Some((a, b)) if a.trim().is_empty() && b.trim().is_empty() => return Err(format!("range `{s}`: `{part}` names no number")), @@ -25,7 +31,7 @@ pub fn parse_range(s: &str, count: usize) -> Result, String> { return Err(format!("range `{s}`: `{part}` runs backwards")); } for i in a - 1..b { - if !out.contains(&i) { + if seen.insert(i) { out.push(i); } } @@ -35,3 +41,16 @@ pub fn parse_range(s: &str, count: usize) -> Result, String> { } Ok(out) } + +#[cfg(test)] +mod tests { + use super::parse_range; + + #[test] + fn sign_is_not_part_of_a_page_number() { + assert!(parse_range("+2", 5).is_err()); + assert!(parse_range("1-+3", 5).is_err()); + assert!(parse_range("-+2", 5).is_err()); + assert_eq!(parse_range("1-3, 5", 5), Ok(vec![0, 1, 2, 4])); + } +} diff --git a/crates/doc/src/recolor.rs b/crates/doc/src/recolor.rs index 715c1aa9ad..a5a8787104 100644 --- a/crates/doc/src/recolor.rs +++ b/crates/doc/src/recolor.rs @@ -65,7 +65,9 @@ pub fn recolor_node(n: &mut Node, reach: Reach, v: &mut dyn ColorVisitor) -> usi } changed += ch as usize; } - NodeKind::Image(im) if reach.images && im.link.is_none() => { + // An image holding its own pixels is a glyph's (emoji in outlined type): it keeps its + // colours, as the glyph does in type. + NodeKind::Image(im) if reach.images && im.link.is_none() && im.pixels.is_none() => { if let Some(k) = v.image(&im.key) { im.key = k; changed += 1; diff --git a/crates/doc/src/records.rs b/crates/doc/src/records.rs new file mode 100644 index 0000000000..e9af0e682e --- /dev/null +++ b/crates/doc/src/records.rs @@ -0,0 +1,123 @@ +use super::*; + +/// New art on a locked artboard ([`Document::new_art`]). Setting it changes the document in +/// place, so a selection change that sets it doesn't replace the document. +#[derive(Default)] +pub struct NewArtIds(pub(crate) std::sync::RwLock>>); + +impl NewArtIds { + /// The objects. + pub fn get(&self) -> Arc> { + self.0.read().map(|g| g.clone()).unwrap_or_default() + } + /// Make `ids` the objects. + pub fn set(&self, ids: Arc>) { + if let Ok(mut g) = self.0.write() { + *g = ids; + } + } +} + +impl Clone for NewArtIds { + fn clone(&self) -> Self { + NewArtIds(std::sync::RwLock::new(self.get())) + } +} + +/// Editing state, not document content: two documents are equal whatever new art they name. +impl PartialEq for NewArtIds { + fn eq(&self, _: &Self) -> bool { + true + } +} + +impl std::fmt::Debug for NewArtIds { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("NewArtIds").field(&self.get()).finish() + } +} + +/// Opacity-mask editing mode: `object`'s mask art lives on the temporary `layer` while editing. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct MaskEdit { + pub object: NodeId, + pub layer: NodeId, +} + +/// A saved view (View → New View…): zoom, centre and rotation, listed at the bottom of the View menu. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SavedView { + pub name: String, + pub center: Point, + pub zoom: f64, + #[serde(default)] + pub rotation: f64, +} + +impl SavedView { + /// Most views a document keeps (the View menu lists every one). + pub const MAX: usize = 25; + /// Longest name, in characters. + pub const MAX_NAME: usize = 255; + + /// `name` trimmed and cut to [`Self::MAX_NAME`] characters (`None` when blank). + pub fn clean_name(name: &str) -> Option { + let name: String = name.trim().chars().take(Self::MAX_NAME).collect(); + (!name.is_empty()).then_some(name) + } + + /// The first "View N" none of `saved` is named. + pub fn default_name(saved: &[SavedView]) -> String { + (1..=saved.len() + 1).map(|i| format!("View {i}")).find(|n| !saved.iter().any(|x| &x.name == n)).unwrap_or_default() + } + + /// Can the canvas show this view: a finite centre and a finite, positive zoom. + pub fn is_usable(&self) -> bool { + self.center.x.is_finite() && self.center.y.is_finite() && self.zoom.is_finite() && self.zoom > 0.0 + } +} + +/// A saved selection (Select → Save Selection…): the objects that were selected, listed by name at +/// the bottom of the Select menu. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SavedSelection { + pub name: String, + pub objects: Vec, +} + +impl SavedSelection { + /// Most saved selections a document keeps (the Select menu lists every one). + pub const MAX: usize = 25; + /// Longest name, in characters. + pub const MAX_NAME: usize = 255; + + /// `name` trimmed and cut to [`Self::MAX_NAME`] characters (`None` when blank). + pub fn clean_name(name: &str) -> Option { + let name: String = name.trim().chars().take(Self::MAX_NAME).collect(); + (!name.is_empty()).then_some(name) + } + + /// The first "Selection N" none of `saved` is named. + pub fn default_name(saved: &[SavedSelection]) -> String { + (1..=saved.len() + 1).map(|i| format!("Selection {i}")).find(|n| !saved.iter().any(|x| &x.name == n)).unwrap_or_default() + } +} + +/// A symbol definition. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Symbol { + pub name: String, + pub art: Arc, +} + +/// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ImageBlob { + pub mime: String, + #[serde(skip)] + pub bytes: Arc>, + /// A linked image's low-resolution preview (PNG, see [`links`]): what a save writes when only + /// linked images show this blob, and what `bytes` hold while the linked file can't be read. + #[serde(skip)] + pub proxy: Option>>, +} diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 1d45f5d738..f034027917 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -1,6 +1,7 @@ //! Selection state (objects and, for direct selection, anchors and segments; ruler guides). use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::sync::Arc; use serde::{Deserialize, Serialize}; @@ -48,6 +49,11 @@ pub struct Selection { /// with `key`; [`Self::prune`] clears it when no object is selected to align to it. #[serde(default, skip_serializing_if = "Option::is_none")] pub key_guide: Option, + /// The new art on a locked artboard that this selection keeps editable + /// ([`Document::new_art`]). Undo, Redo and a failed batch restore it with the selection, and + /// the engine then sets the document's from it. Editing state, never saved. + #[serde(skip)] + pub new_art: Arc>, } impl Selection { @@ -148,7 +154,11 @@ impl Selection { if self.anchors.is_empty() { return None; } - let mut acc = doc.bounds_of(&self.whole(), visual); + vectorcraft_geom::union_opt(doc.bounds_of(&self.whole(), visual), self.anchors_box(doc)) + } + /// The box around the anchors selected with Direct Selection. `None` without any. + pub fn anchors_box(&self, doc: &Document) -> Option { + let mut acc = None; for (id, set) in &self.anchors { let Some(NodeKind::Path { path, .. }) = doc.node(*id).map(|n| &n.kind) else { continue }; for a in set.iter().filter_map(|&(si, ai)| path.subpaths.get(si)?.anchors.get(ai)) { @@ -202,16 +212,36 @@ impl Selection { /// around them (and so the key object when it is one): hidden or locked art can't stay /// selected. pub fn deselect_uneditable(&mut self, doc: &Document) { - let uneditable: HashSet = self.objects.iter().copied().filter(|o| !doc.is_editable(*o)).collect(); - if uneditable.is_empty() { + let locks = doc.locked_artboards(); + let uneditable: HashSet = self.objects.iter().copied().filter(|o| !doc.is_editable_with(&locks, *o)).collect(); + self.deselect_all(&uneditable); + } + /// Deselect the objects on a locked artboard ([`crate::LockedArtboards::holds_id`]), whatever + /// selected them or moved them there (and so the key object when it is one): they act as + /// locked art. A targeted layer stays targeted, as it does with locked objects in it. + pub fn deselect_on_locked_artboards(&mut self, doc: &Document) { + let locks = doc.locked_artboards(); + if locks.is_empty() { + return; + } + let locked: HashSet = self.objects.iter().copied().filter(|o| locks.holds_id(*o)).collect(); + let layer = self.target.filter(|t| doc.node(*t).is_some_and(crate::Node::is_layer)); + self.deselect_all(&locked); + if layer.is_some() { + self.target = layer; + } + } + /// Deselect the objects `gone` in one pass, with their anchors, segments and key. + fn deselect_all(&mut self, gone: &HashSet) { + if gone.is_empty() { return; } self.target = None; self.slices.clear(); - self.objects.retain(|o| !uneditable.contains(o)); - self.anchors.retain(|id, _| !uneditable.contains(id)); - self.segments.retain(|id, _| !uneditable.contains(id)); - if self.key.is_some_and(|k| uneditable.contains(&k)) { + self.objects.retain(|o| !gone.contains(o)); + self.anchors.retain(|id, _| !gone.contains(id)); + self.segments.retain(|id, _| !gone.contains(id)); + if self.key.is_some_and(|k| gone.contains(&k)) { self.key = None; } } @@ -225,12 +255,16 @@ impl Selection { self.target = Some(id); } /// Shift-clicking `id`'s target circle: it (a layer: its art) joins the selection, or leaves it - /// when it is all selected already. Several objects are then selected, none targeted. + /// when it is all selected already. Several objects are then selected, none targeted. Art on a + /// locked artboard is neither counted nor added, since + /// [`Selection::deselect_on_locked_artboards`] deselects it. pub fn toggle_target(&mut self, doc: &Document, id: NodeId) { - let ids = match doc.node(id) { + let mut ids = match doc.node(id) { Some(n) if n.is_layer() => n.layer_art(true), _ => vec![id], }; + let locks = doc.locked_artboards(); + ids.retain(|i| !locks.holds_id(*i)); if ids.iter().all(|i| self.contains(*i)) { ids.iter().for_each(|i| self.remove(*i)); } else { diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index 441a64dec2..b5a1ffe328 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -154,6 +154,7 @@ pub const LANGUAGES: &[(&str, Quotes)] = &[ ("Polish", Quotes { double: ['„', '”'], single: ['‚', '’'] }), ("Czech", Quotes { double: ['„', '“'], single: ['‚', '‘'] }), ("Russian", Quotes { double: ['«', '»'], single: ['„', '“'] }), + ("Turkish", Quotes { double: ['“', '”'], single: ['‘', '’'] }), ("Japanese", Quotes { double: ['「', '」'], single: ['『', '』'] }), ("Chinese", Quotes { double: ['“', '”'], single: ['‘', '’'] }), ]; @@ -211,7 +212,8 @@ pub struct DocSetup { pub bleed: [f64; 4], /// Show Images in Outline Mode. pub outline_images: bool, - /// Highlight text whose font is missing (drawn in a substitute font). + /// The Highlight Substituted Fonts value older builds kept in Document Setup. Files keep it as + /// they were saved; the screen follows Preferences › Type › Highlight Substituted Fonts. pub highlight_substituted_fonts: bool, /// Highlight glyphs the font lacks (drawn from a fallback font). pub highlight_substituted_glyphs: bool, @@ -238,6 +240,11 @@ pub struct DocSetup { pub export_text: ExportText, /// Background Contents chosen in New Document. pub background: Background, + /// Character panel menu › System Layout: every text object advances by whole points. Off by + /// default and for documents from before it, and saved only when on. + /// + #[serde(default, rename = "systemLayout", skip_serializing_if = "crate::skip::is_default")] + pub system_layout: bool, } impl Default for DocSetup { @@ -260,6 +267,7 @@ impl Default for DocSetup { small_caps_size: 70.0, export_text: ExportText::Editable, background: Background::Transparent, + system_layout: false, } } } diff --git a/crates/doc/src/skip.rs b/crates/doc/src/skip.rs new file mode 100644 index 0000000000..15f294c009 --- /dev/null +++ b/crates/doc/src/skip.rs @@ -0,0 +1,15 @@ +pub fn is_default(v: &T) -> bool { + *v == T::default() +} +pub fn is_true(v: &bool) -> bool { + *v +} +pub fn is_one(v: &f32) -> bool { + *v == 1.0 +} +pub fn is_empty_vec(v: &[T]) -> bool { + v.is_empty() +} +pub fn is_empty_map(v: &serde_json::Map) -> bool { + v.is_empty() +} diff --git a/crates/doc/src/slices.rs b/crates/doc/src/slices.rs index 8deba728fa..33299a3099 100644 --- a/crates/doc/src/slices.rs +++ b/crates/doc/src/slices.rs @@ -274,6 +274,10 @@ pub fn auto_slices(region: Rect, cut: &[Rect]) -> Vec { return vec![]; } let inside: Vec = cut.iter().map(|r| region.intersect(*r)).filter(|r| valid_rect(*r)).collect(); + // Every band scans every cut: past a bound the layout is refused, not truncated. + if inside.len() > MAX_AUTO_CUTS { + return vec![]; + } let mut ys: Vec = inside.iter().flat_map(|r| [r.y0, r.y1]).chain([region.y0, region.y1]).collect(); ys.sort_by(f64::total_cmp); ys.dedup_by(|a, b| (*a - *b).abs() <= EPS); @@ -298,6 +302,9 @@ pub fn auto_slices(region: Rect, cut: &[Rect]) -> Vec { // Spans continuing an open slice extend it; the others close. let mut next = Vec::with_capacity(free.len()); for (a, b) in free { + if done.len() + open.len() + next.len() >= MAX_AUTO_SLICES { + break; + } match open.iter().position(|r: &Rect| (r.x0 - a).abs() <= EPS && (r.x1 - b).abs() <= EPS) { Some(i) => { let mut r = open.swap_remove(i); @@ -309,7 +316,18 @@ pub fn auto_slices(region: Rect, cut: &[Rect]) -> Vec { } done.append(&mut open); open = next; + // Crossing strips make a cell of every crossing: the layout stops, short, past a bound. + if done.len() + open.len() >= MAX_AUTO_SLICES { + break; + } } done.append(&mut open); + done.truncate(MAX_AUTO_SLICES); done } + +/// The most slices automatic layout makes. +const MAX_AUTO_SLICES: usize = 10_000; + +/// The most cut rectangles automatic layout works through. +const MAX_AUTO_CUTS: usize = 2_000; diff --git a/crates/doc/src/style_libs.rs b/crates/doc/src/style_libs.rs index 649a5bc1b5..30aae49e1e 100644 --- a/crates/doc/src/style_libs.rs +++ b/crates/doc/src/style_libs.rs @@ -189,7 +189,7 @@ fn fx(id: &str, params: Value) -> Effect { /// A gradient of `(offset, colour, opacity)` stops. fn gradient(kind: GradientKind, stops: &[(f32, &str, f32)]) -> Gradient { - Gradient { kind, stops: stops.iter().map(|&(offset, c, opacity)| GradientStop { opacity, ..GradientStop::new(offset, hex(c)) }).collect() } + Gradient::new(kind, stops.iter().map(|&(offset, c, opacity)| GradientStop { opacity, ..GradientStop::new(offset, hex(c)) }).collect()) } /// A linear gradient fitted to each object's box at `angle` degrees (90: upwards). diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 19e36da805..8dbed28aed 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -297,7 +297,7 @@ fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> { /// Visit `n` and its subtree, the art of opacity masks included (mask art after the masked /// object, before its children). -fn walk_with_masks<'a>(n: &'a Node, f: &mut dyn FnMut(&'a Node)) { +pub fn walk_with_masks<'a>(n: &'a Node, f: &mut dyn FnMut(&'a Node)) { f(n); if let Some(mask) = n.extras().mask.as_deref() { walk_with_masks(&mask.art, f); diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs new file mode 100644 index 0000000000..a13fb21680 --- /dev/null +++ b/crates/doc/src/tests.rs @@ -0,0 +1,418 @@ +use super::*; +use vectorcraft_geom::shapes; + +mod lookups; +mod slices; +mod units; + +/// Zooming in on an inch ruler divided the inch into tenths (#2827). Its steps below an inch +/// are binary fractions now, and the minor ticks between them stay binary too; every other +/// unit is still read in tenths. +#[test] +fn an_inch_ruler_steps_in_binary_fractions() { + let step = |u: Unit, zoom: f64| u.ruler_step(zoom); + // Every inch step at or below an inch is 1/2^k, never a tenth or a fifth. + for zoom in [1.0, 2.0, 5.0, 7.5, 10.0, 20.0, 40.0, 100.0, 400.0] { + let s = step(Unit::Inches, zoom); + if s <= 1.0 { + let k = s.recip(); + assert_eq!(k, k.round(), "{s} at zoom {zoom} is 1/k for a whole k"); + assert!((k.round() as u64).is_power_of_two(), "{s} at zoom {zoom} is 1/2^k"); + } + // A label step always leaves at least 50 px, which is what the ladder is picked for. + assert!(s * Unit::Inches.points() * zoom >= 50.0, "zoom {zoom}"); + } + // The steps the report named: tenths became quarters, eighths and sixteenths. + assert_eq!(step(Unit::Inches, 5.0), 0.25); + assert_eq!(step(Unit::Inches, 10.0), 0.125); + assert_eq!(step(Unit::Inches, 20.0), 0.0625); + // An inch and wider is unchanged. + assert_eq!(step(Unit::Inches, 1.0), 1.0); + // Labelling stops at a sixteenth, as the report says Illustrator's does, so zooming in + // further only adds ticks. A label therefore never needs more than the six characters of + // "0.0625", which the left ruler has room for when it spells one out a character per line. + for zoom in [20.0, 50.0, 100.0, 400.0, 1600.0] { + assert_eq!(step(Unit::Inches, zoom), 0.0625, "zoom {zoom}"); + } + // The unlabelled ticks go on down to a hundred and twenty-eighth: the 32nds, 64ths and + // 128ths the report expects to appear unlabelled when zoomed in close. + assert_eq!(Unit::Inches.ruler_minor(0.0625), 1.0 / 128.0); + // The minor ticks: an eighth of the step on an inch ruler, a tenth elsewhere. + assert_eq!(Unit::Inches.ruler_minor(0.25), 0.03125); + assert_eq!(Unit::Millimeters.ruler_minor(25.0), 2.5); + assert_eq!(Unit::Points.ruler_minor(100.0), 10.0); + // Other units keep the decimal ladder, so a tenth and a fifth still appear. + assert!([0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0].contains(&step(Unit::Millimeters, 5.0)), "{}", step(Unit::Millimeters, 5.0)); +} + +fn doc_with_rects() -> (Document, NodeId, NodeId) { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let a = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art())).unwrap(); + let b = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(b, shapes::rectangle(Rect::new(20.0, 0.0, 30.0, 10.0)), Appearance::default_art())).unwrap(); + (d, a, b) +} + +#[test] +fn new_document_has_layer_and_artboard() { + let d = Document::new(612.0, 792.0); + assert_eq!(d.layers.len(), 1); + assert_eq!(d.layers[0].display_name(), "Layer 1"); + assert_eq!(d.artboards[0].rect, Rect::new(0.0, 0.0, 612.0, 792.0)); +} + +#[test] +fn art_on_artboard_takes_unlocked_objects_wholly_inside() { + let (mut d, a, b) = doc_with_rects(); + let wide = Rect::new(-1.0, -1.0, 40.0, 15.0); + assert_eq!(d.art_on_artboard(Rect::new(-1.0, -1.0, 15.0, 15.0), false), vec![a]); + assert_eq!(d.art_on_artboard(Rect::new(-1.0, -1.0, 25.0, 15.0), false), vec![a], "b only half inside"); + // Flush with the artboard's edges counts as inside: the right and bottom ones too (#890). + for board in [Rect::new(0.0, 0.0, 10.0, 10.0), Rect::new(-5.0, 0.0, 10.0, 15.0), Rect::new(0.0, -5.0, 15.0, 10.0)] { + assert_eq!(d.art_on_artboard(board, false), vec![a], "{board:?}"); + } + d.node_mut(a).unwrap().locked = true; + assert_eq!(d.art_on_artboard(wide, false), vec![b]); + // Move Locked and Hidden Artwork with Artboard (#394): hidden art stays too, unless on. + d.node_mut(b).unwrap().visible = false; + assert!(d.art_on_artboard(wide, false).is_empty()); + assert_eq!(d.art_on_artboard(wide, true), vec![a, b]); + Arc::make_mut(&mut d.layers[0]).locked = true; + assert!(d.art_on_artboard(wide, false).is_empty()); + assert_eq!(d.art_on_artboard(wide, true), vec![a, b], "a locked layer's art too"); +} + +#[test] +fn art_on_artboard_tolerates_roundoff_at_each_edge() { + let (d, a, _) = doc_with_rects(); + let roundoff = 1e-12; + for board in [ + Rect::new(roundoff, 0.0, 10.0, 10.0), + Rect::new(0.0, roundoff, 10.0, 10.0), + Rect::new(0.0, 0.0, 10.0 - roundoff, 10.0), + Rect::new(0.0, 0.0, 10.0, 10.0 - roundoff), + ] { + assert_eq!(d.art_on_artboard(board, false), vec![a], "roundoff at {board:?}"); + } + // A real overhang remains outside. + for board in + [Rect::new(0.001, 0.0, 10.0, 10.0), Rect::new(0.0, 0.001, 10.0, 10.0), Rect::new(0.0, 0.0, 9.999, 10.0), Rect::new(0.0, 0.0, 10.0, 9.999)] + { + assert!(d.art_on_artboard(board, false).is_empty(), "overhang at {board:?}"); + } +} + +/// The art on a locked artboard (each object of a layer whose bounds overlap it, a group as one +/// object) can't be edited, and Select All, a click and a marquee pass over it; art flush with +/// the artboard from outside isn't on it, a layer is on no artboard, and new art isn't on one. +/// Unlocking the artboard gives the art back. +#[test] +fn art_on_a_locked_artboard_cannot_be_selected_or_edited() { + use crate::hit::{HitOptions, hit_test, marquee, objects_at}; + let (mut d, a, b) = doc_with_rects(); + let layer = d.layers[0].id; + d.artboards.push(Artboard { + id: 2, + name: "Artboard 2".into(), + rect: Rect::new(700.0, 0.0, 900.0, 200.0), + locked: false, + show_center_mark: false, + show_cross_hairs: false, + show_video_safe_areas: false, + video_ruler_pixel_aspect_ratio: 1.0, + color: None, + }); + let rect = |d: &mut Document, r: Rect, appearance: Appearance| { + let id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(id, shapes::rectangle(r), appearance)).unwrap(); + id + }; + let c = rect(&mut d, Rect::new(710.0, 10.0, 730.0, 30.0), Appearance::default_art()); + // A group with one member on the artboard and one right of it. + let (g, m1, m2) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let members = [(m1, 750.0), (m2, 950.0)] + .map(|(id, x)| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, 50.0, x + 10.0, 60.0)), Appearance::default_art()))); + d.insert(Some(layer), usize::MAX, Node::group(g, members.to_vec())).unwrap(); + // Unstroked and flush with the artboard's left edge, from outside. + let e = rect(&mut d, Rect::new(680.0, 10.0, 700.0, 30.0), Appearance::default()); + let opt = HitOptions::default(); + let top = |d: &Document, x, y| hit_test(d, Point::new(x, y), opt).map(|h| h.top_object(None)); + let all = Rect::new(-10.0, -10.0, 1000.0, 800.0); + assert_eq!(top(&d, 720.0, 20.0), Some(c)); + d.artboards[1].locked = true; + for id in [c, g, m1, m2] { + assert!(d.on_locked_artboard(id) && !d.is_editable(id), "{id:?} is on the locked artboard"); + } + for id in [a, b, e, layer] { + assert!(!d.on_locked_artboard(id) && d.is_editable(id), "{id:?} isn't"); + } + assert_eq!(d.selectable_art(), [a, b, e]); + assert_eq!(top(&d, 720.0, 20.0), None, "a click passes over c"); + assert_eq!(top(&d, 955.0, 55.0), None, "and over the group's member off the artboard"); + let isolated = HitOptions { scope: Some(g), ..opt }; + assert!(hit_test(&d, Point::new(755.0, 55.0), isolated).is_none(), "and inside the group isolated before the lock"); + assert!(objects_at(&d, Point::new(720.0, 20.0), opt, None).is_empty()); + assert_eq!(marquee(&d, all, None, false), [a, b, e]); + assert_eq!(marquee(&d, all, None, true), [a, b, e], "the Direct Selection tool's marquee too"); + // Deselected in one pass, with the key object and the anchors. + let mut sel = Selection::default(); + sel.set([a, c]); + sel.key = Some(c); + sel.anchors.insert(c, [(0, 0)].into()); + sel.deselect_on_locked_artboards(&d); + assert_eq!((sel.objects.clone(), sel.key, sel.anchors.is_empty()), (vec![a], None, true)); + // A targeted layer stays targeted, with its art off the locked artboard selected. + sel.set_target(&d, layer); + sel.deselect_on_locked_artboards(&d); + assert_eq!((sel.objects.clone(), sel.target), (vec![a, b, e], Some(layer))); + // Shift-clicking the layer's target circle removes its art off the locked artboard, and + // a second Shift-click adds it again. + sel.toggle_target(&d, layer); + sel.deselect_on_locked_artboards(&d); + assert_eq!((sel.objects.clone(), sel.target), (vec![], None)); + sel.toggle_target(&d, layer); + sel.deselect_on_locked_artboards(&d); + assert_eq!(sel.objects, [a, b, e]); + // A sublayer with art on both artboards: its art off the locked artboard can still be clicked. + let (sub, s1, s2) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(2))).unwrap(); + for (id, x, y) in [(s1, 300.0, 300.0), (s2, 800.0, 100.0)] { + d.insert(Some(sub), usize::MAX, Node::path(id, shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)), Appearance::default_art())).unwrap(); + } + assert_eq!((top(&d, 305.0, 305.0), top(&d, 805.0, 105.0)), (Some(s1), None)); + assert!(!d.on_locked_artboard(sub)); + let mut both = Selection::default(); + both.set([s1, s2]); + both.deselect_on_locked_artboards(&d); + assert_eq!(both.objects, [s1]); + // New art on it is editable and can be clicked while it is new art. + d.new_art.set(Arc::new([c].into())); + assert!(!d.on_locked_artboard(c) && d.is_editable(c), "new art"); + assert_eq!(top(&d, 720.0, 20.0), Some(c)); + d.new_art.set(Default::default()); + d.artboards[1].locked = false; + assert_eq!(d.selectable_art(), [a, b, c, g, e, s1, s2]); + assert_eq!(top(&d, 955.0, 55.0), Some(g)); + assert_eq!(marquee(&d, all, None, false), [a, b, c, g, e, s1, s2]); +} + +#[test] +fn art_on_artboard_measures_a_symbol_instance_by_its_art() { + let mut d = Document::new(612.0, 792.0); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + d.symbols.push(Symbol { name: "Box".into(), art: Arc::new(art) }); + let (layer, id) = (d.layers[0].id, d.alloc_id()); + d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Box".into(), xf: Affine::translate((2.0, 2.0)) })).unwrap(); + // The art, (2, 2) to (12, 12), lies inside; the 20 × 20 square, (-8, -8) to (12, 12), doesn't. + assert_eq!(d.art_on_artboard(Rect::new(0.0, 0.0, 15.0, 15.0), false), vec![id]); +} + +#[test] +fn artboard_at_counts_the_right_and_bottom_edges() { + // Artboard 0 is (0, 0) to (100, 100), artboard 1 is to its right and artboard 2 below it. + let mut d = Document::new(100.0, 100.0); + for rect in [Rect::new(100.0, 0.0, 200.0, 100.0), Rect::new(0.0, 100.0, 100.0, 200.0)] { + let mut a = d.artboards[0].clone(); + a.rect = rect; + d.artboards.push(a); + } + let held = |d: &Document, x: f64, y: f64| (d.artboard_at(Point::new(x, y)), d.artboard_holding(Point::new(x, y), false)); + // Each artboard's own right and bottom edges, edges with roundoff, and points beyond them. + assert_eq!(held(&d, 200.0, 50.0), (Some(1), Some(1)), "right edge"); + assert_eq!(held(&d, 150.0, 100.0), (Some(1), Some(1)), "bottom edge"); + assert_eq!(held(&d, 200.0, 100.0), (Some(1), Some(1)), "bottom right corner"); + assert_eq!(held(&d, 100.0, 150.0), (Some(2), Some(2)), "right edge"); + assert_eq!(held(&d, 50.0, 200.0 + 1e-9), (Some(2), Some(2)), "roundoff past the bottom edge"); + assert_eq!(held(&d, -1e-9, 50.0), (Some(0), Some(0)), "roundoff past the left edge"); + assert_eq!(held(&d, 200.001, 50.0), (None, None)); + assert_eq!(held(&d, 50.0, 200.001), (None, None)); + // On an edge two artboards share, the artboard to the right of it or below it holds the + // point, in either list order, except at the end of the edge that lies on that artboard's + // bottom or right edge. + assert_eq!(held(&d, 100.0, 50.0), (Some(1), Some(1))); + assert_eq!(held(&d, 50.0, 100.0), (Some(2), Some(2))); + // The bottom edges of artboards 0 and 1 meet at (100, 100), which is also artboard 2's top + // right corner: the first holds the point, or the last when `topmost`. + assert_eq!(held(&d, 100.0, 100.0), (Some(2), Some(0)), "shared corner"); + d.artboards.swap(0, 1); + assert_eq!(held(&d, 100.0, 50.0), (Some(0), Some(0))); + // Where two artboards overlap, the topmost holds the point, or the first one when not + // `topmost`. + let mut inner = d.artboards[1].clone(); + inner.rect = Rect::new(10.0, 10.0, 90.0, 90.0); + d.artboards.push(inner); + assert_eq!(held(&d, 50.0, 50.0), (Some(3), Some(1))); + assert_eq!(held(&d, 90.0, 50.0), (Some(1), Some(1)), "inside artboard 1, on the right edge of artboard 3"); +} + +#[test] +fn find_and_paths() { + let (d, a, b) = doc_with_rects(); + assert_eq!(d.index_path(b), Some(vec![0, 1])); + assert_eq!(d.parent_of(a), Some(d.layers[0].id)); + assert_eq!(d.layer_of(b), Some(d.layers[0].id)); + assert!(d.node(NodeId(999)).is_none()); + assert_eq!(d.node_count(), 3); +} + +#[test] +fn copy_on_write_shares_untouched() { + let (d, a, b) = doc_with_rects(); + let mut e = d.clone(); + e.node_mut(a).unwrap().name = Some("A".into()); + // b's Arc is shared between both versions; a's is not. + let lb = &d.layers[0].children().unwrap()[1]; + let eb = &e.layers[0].children().unwrap()[1]; + assert!(Arc::ptr_eq(lb, eb)); + assert_eq!(d.node(a).unwrap().name, None); + assert_eq!(e.node(a).unwrap().name.as_deref(), Some("A")); + let _ = b; +} + +#[test] +fn move_and_remove() { + let (mut d, a, b) = doc_with_rects(); + let layer = d.layers[0].id; + d.move_node(a, Some(layer), usize::MAX).unwrap(); + assert_eq!(d.index_path(a), Some(vec![0, 1])); + assert_eq!(d.index_path(b), Some(vec![0, 0])); + let r = d.remove(a).unwrap(); + assert_eq!(r.id, a); + assert!(d.node(a).is_none()); + assert!(d.move_node(layer, Some(layer), 0).is_err()); +} + +#[test] +fn layers_and_names() { + let mut d = Document::new(100.0, 100.0); + let l2 = d.add_layer(None); + assert_eq!(d.node(l2).unwrap().display_name(), "Layer 2"); + assert_eq!(d.default_layer(), Some(l2)); + assert_eq!(d.layer_color(l2), LAYER_COLORS[1].1); +} + +/// #1718: a file whose ids or counters are at their type's largest value still hands out ids +/// nothing in it uses (and never 0), instead of overflowing. +#[test] +fn exhausted_ids_in_a_file_dont_run_out() { + let (d, a, b) = doc_with_rects(); + let mut v = serde_json::to_value(&d).unwrap(); + v["next_id"] = serde_json::json!(u64::MAX); + // Object `a` gets the largest id there is. + fn renumber(v: &mut serde_json::Value, from: u64) { + match v { + serde_json::Value::Object(o) => { + if o.get("id").and_then(serde_json::Value::as_u64) == Some(from) { + o.insert("id".into(), serde_json::json!(u64::MAX)); + } + o.values_mut().for_each(|c| renumber(c, from)); + } + serde_json::Value::Array(a) => a.iter_mut().for_each(|c| renumber(c, from)), + _ => {} + } + } + renumber(&mut v["layers"], a.0); + let mut d: Document = serde_json::from_value(v).unwrap(); + assert!(d.node(NodeId(u64::MAX)).is_some(), "the file's largest id is kept"); + d.fix_next_id(); + let fresh: Vec = (0..3).map(|_| d.alloc_id()).collect(); + assert!(fresh.iter().all(|id| d.node(*id).is_none() && id.0 > b.0 && id.0 < MAX_NEXT_ID), "{fresh:?}"); + assert!(fresh[0] != fresh[1] && fresh[1] != fresh[2]); + // A counter left at the end by other means stays there rather than wrapping to 0. + d.next_id = u64::MAX; + assert_eq!((d.alloc_id(), d.peek_next_id()), (NodeId(u64::MAX), u64::MAX)); + d.reserve_ids(u64::MAX); + // Artboards and graphic styles: one past the largest, else the smallest id free. + assert_eq!(free_id([1, 2, 7].into_iter()), 8); + assert_eq!(free_id([u32::MAX, 0, 1, 2, 4].into_iter()), 3); + assert_eq!(free_id([u32::MAX].into_iter()), 1); + d.artboards[0].id = u32::MAX; + assert_eq!(d.next_artboard_id(), 1); +} + +#[test] +fn serde_roundtrip() { + let (d, _, _) = doc_with_rects(); + let s = serde_json::to_string(&d).unwrap(); + let back: Document = serde_json::from_str(&s).unwrap(); + assert_eq!(back.node_count(), d.node_count()); + assert_eq!(back.peek_next_id(), d.peek_next_id()); +} + +#[test] +fn reid_gives_fresh_ids() { + let (mut d, a, b) = doc_with_rects(); + let g = d.alloc_id(); + let na = (*d.remove(a).unwrap()).clone(); + let nb = (*d.remove(b).unwrap()).clone(); + let group = Node::group(g, vec![Arc::new(na), Arc::new(nb)]); + let copy = d.reid(&group); + assert_ne!(copy.id, g); + let ids: Vec = copy.children().unwrap().iter().map(|c| c.id).collect(); + assert!(!ids.contains(&a) && !ids.contains(&b)); +} + +#[test] +fn setup_round_trips_and_old_files_load() { + let (mut d, _, _) = doc_with_rects(); + // A document without a setup writes no `setup` key (old readers and files stay unchanged). + assert!(!serde_json::to_string(&d).unwrap().contains("\"setup\"")); + d.setup.bleed = [9.0, 9.0, 0.0, 18.0]; + d.setup.grid_size = GridSize::Large; + d.setup.typographers_quotes = false; + d.setup.quotes = setup::language_quotes("German").unwrap(); + d.setup.flattener_preset = Some("High Resolution".into()); + d.setup.background = Background::White; + d.setup.export_text = ExportText::Appearance; + let back: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap(); + assert_eq!(back.setup, d.setup); + // Files written before Document Setup existed load with the defaults. + let mut v = serde_json::to_value(&d).unwrap(); + v.as_object_mut().unwrap().remove("setup"); + let old: Document = serde_json::from_value(v).unwrap(); + assert_eq!(old.setup, DocSetup::default()); +} + +#[test] +fn char_position_round_trips() { + let st = + CharStyle { position: CharPosition::Subscript(ScriptMetrics { size: 50.0, position: 20.0 }), small_caps: Some(75.0), ..CharStyle::default() }; + let v = serde_json::to_value(&st).unwrap(); + assert_eq!(v["position"], serde_json::json!({"kind": "subscript", "size": 50.0, "position": 20.0})); + assert_eq!(serde_json::from_value::(v).unwrap(), st); + let plain = serde_json::to_value(CharStyle::default()).unwrap(); + assert!(plain.get("position").is_none() && plain.get("small_caps").is_none()); + let (scale, shift) = CharPosition::Subscript(ScriptMetrics::DEFAULT).scale_shift(10.0); + assert!((scale - 0.583).abs() < 1e-9 && (shift + 3.33).abs() < 1e-9); +} + +#[test] +fn units() { + assert_eq!(Unit::Inches.parse("1"), Some(72.0)); + assert_eq!(Unit::Points.parse("1in"), Some(72.0)); + assert_eq!(Unit::Points.parse("10 mm").map(|v| (v * 1000.0).round()), Some(28346.0)); + assert_eq!(Unit::Points.parse("2p6"), Some(30.0)); + assert_eq!(Unit::Points.parse("10+5"), Some(15.0)); + assert_eq!(Unit::Points.parse("100/4"), Some(25.0)); + assert_eq!(Unit::Points.parse("-5"), Some(-5.0)); + assert_eq!(Unit::Points.parse("abc"), None); + assert_eq!(Unit::Points.format(12.5), "12.5 pt"); + assert_eq!(Unit::Inches.format(144.0), "2 in"); +} + +#[test] +fn negative_picas_and_points_sign_applies_to_whole_value() { + assert_eq!(Unit::Points.parse("-2p6"), Some(-30.0)); + assert_eq!(Unit::Points.parse("-0p6"), Some(-6.0)); + assert_eq!(Unit::Points.parse("-2p"), Some(-24.0)); + assert_eq!(Unit::Points.parse("2p6"), Some(30.0)); +} + +#[test] +fn pica_form_rejects_exponent_notation() { + for s in ["1e5p", "infp", "nanp", "infp3", "1p1e2"] { + assert_eq!(Unit::Points.parse(s), None, "{s}"); + } +} diff --git a/crates/doc/src/tests_lookups.rs b/crates/doc/src/tests/lookups.rs similarity index 99% rename from crates/doc/src/tests_lookups.rs rename to crates/doc/src/tests/lookups.rs index 0fda214ee0..2f83b65c5e 100644 --- a/crates/doc/src/tests_lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -2,7 +2,7 @@ //! with the one-id ones on nested trees with missing and duplicated ids, and the edits of many nodes //! ([`Document::remove_many`], `wrap`, `insert_beside`) leave the tree that `remove`, `insert` and //! `move_node` leave one node at a time. -use super::*; +use crate::*; use vectorcraft_geom::shapes; /// Layers with paths and groups nested `depth` deep; every 7th id is reused (a damaged file), so diff --git a/crates/doc/src/tests_slices.rs b/crates/doc/src/tests/slices.rs similarity index 100% rename from crates/doc/src/tests_slices.rs rename to crates/doc/src/tests/slices.rs diff --git a/crates/doc/src/tests_units.rs b/crates/doc/src/tests/units.rs similarity index 93% rename from crates/doc/src/tests_units.rs rename to crates/doc/src/tests/units.rs index a5dbe9fb33..909a0adf3b 100644 --- a/crates/doc/src/tests_units.rs +++ b/crates/doc/src/tests/units.rs @@ -3,7 +3,7 @@ use proptest::prelude::*; -use super::Unit; +use crate::Unit; #[test] fn every_unit_round_trips_through_its_field_text() { @@ -23,6 +23,14 @@ fn every_unit_round_trips_through_its_field_text() { } } +#[test] +fn an_explicit_leading_plus_is_accepted() { + assert_eq!(Unit::Points.parse("+5"), Some(5.0)); + assert_eq!(Unit::Millimeters.parse("+5mm"), Some(Unit::Millimeters.to_pt(5.0))); + assert_eq!(Unit::Points.parse("+5+3"), Some(8.0)); + assert_eq!(Unit::Points.parse("5+-3"), Some(2.0)); +} + #[test] fn typed_units_win_over_the_fields_unit() { let mm = 72.0 / 25.4; @@ -125,7 +133,7 @@ fn a_negative_operand_after_an_operator_is_a_sign() { assert_eq!(Unit::Points.parse("5 - -3"), Some(8.0)); assert_eq!(Unit::Points.parse("5+-3"), Some(2.0)); assert_eq!(Unit::Points.parse("10-2"), Some(8.0)); - assert_eq!(super::parse_number("90*-1"), Some(-90.0)); + assert_eq!(crate::parse_number("90*-1"), Some(-90.0)); } #[test] diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index d98e8d4c7e..a3ab2ccc56 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -6,1251 +6,22 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Vec2}; use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer}; -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum Justify { - /// Align to the start of each paragraph's direction ([`ParaStyle::direction`]): left for - /// left-to-right paragraphs, right for right-to-left ones. New type's alignment. - Auto, - #[default] - Left, - Center, - Right, - JustifyLeft, - JustifyCenter, - JustifyRight, - JustifyAll, -} - -/// Character attributes (the Character panel). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct CharStyle { - pub font_family: String, - #[serde(default = "regular")] - pub font_style: String, - /// Which installed version of the font (its version string) when several versions of the - /// family and style are installed and the text was set in one the family and style alone - /// wouldn't pick (an imported file's type matched to it); None = the one they pick. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub font_version: Option, - /// Variation axis settings of a variable font (Character panel › Variable Font), by axis tag - /// (`wght`, `wdth`), in the axis's own units. They replace the named instance's setting of - /// each axis they name; the other axes keep the style's settings. Empty: the style as it is. - #[serde(default, rename = "fontAxes", skip_serializing_if = "std::collections::BTreeMap::is_empty")] - pub font_axes: std::collections::BTreeMap, - /// Size in points. - pub size: f64, - /// Leading in points; None = Auto (120% of size). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub leading: Option, - /// Tracking in 1/1000 em. - #[serde(default)] - pub tracking: f64, - /// Kerning: None = Auto (metrics), Some(v) = manual in 1/1000 em. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub kerning: Option, - #[serde(default)] - pub baseline_shift: f64, - #[serde(default = "hundred")] - pub h_scale: f64, - #[serde(default = "hundred")] - pub v_scale: f64, - #[serde(default)] - pub rotation: f64, - pub fill: Paint, - #[serde(default)] - pub stroke: Paint, - #[serde(default)] - pub stroke_width: f64, - #[serde(default)] - pub underline: bool, - #[serde(default)] - pub strikethrough: bool, - #[serde(default)] - pub all_caps: bool, - /// OpenType features that differ from the defaults (OpenType panel), as tags: `"dlig"` turns - /// a feature on, `"-liga"` off. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub features: Vec, - /// Character style (Character Styles panel) these attributes come from; None = Normal. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub style_name: Option, - /// Overprint Fill / Overprint Stroke of these characters (see [`crate::FillLayer::overprint`]). - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub overprint_fill: bool, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub overprint_stroke: bool, - /// Cap, join, miter limit and dashes of the character stroke (Stroke panel, with type - /// selected); defaults as for object strokes. - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub stroke_cap: LineCap, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub stroke_join: LineJoin, - #[serde(default = "ten", skip_serializing_if = "is_ten")] - pub stroke_miter_limit: f64, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub stroke_dash: Option, - /// Align Stroke of the character stroke (Stroke panel, with type selected): centred on the - /// glyph outlines, inside or outside them, as for object strokes; the type stays live. - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub stroke_align: StrokeAlign, - /// Superscript or subscript (Character panel). - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub position: CharPosition, - /// Small Caps (Character panel): lowercase letters drawn as capitals at this percentage of the - /// size (Document Setup → Type → Small Caps); None = off. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub small_caps: Option, - /// Character Alignment (Character panel menu): where characters smaller than the largest on - /// their line line up with it. - #[serde(default, rename = "charAlign", skip_serializing_if = "crate::skip::is_default")] - pub char_align: CharAlign, - /// Proportional Metrics (Character panel menu, East Asian options): full-width glyphs take the - /// font's own proportional widths, OpenType `palt` (#966); in vertical type upright glyphs take - /// its proportional heights, `vpal`. - #[serde(default, rename = "proportionalMetrics", skip_serializing_if = "crate::skip::is_default")] - pub proportional_metrics: bool, - /// Digits (Character panel menu, Middle Eastern options): the numeral system the digits of - /// these characters are drawn in, whatever digits were typed. - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - pub digits: Digits, -} - -/// The numeral system digits are drawn in ([`CharStyle::digits`]): as typed, or every digit of -/// the Western, Arabic-Indic and Eastern Arabic-Indic sets drawn in one of them. The text keeps -/// the digits that were typed; only the glyphs change (like All Caps). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum Digits { - /// Each digit as typed. - #[default] - Default, - /// Western digits 0–9 (the digits Arabic typography calls Arabic). - Arabic, - /// Arabic-Indic digits ٠–٩ (U+0660–U+0669), used in Arabic. - Hindi, - /// Eastern Arabic-Indic digits ۰–۹ (U+06F0–U+06F9), used in Persian and Urdu. - Farsi, -} - -impl Digits { - /// The digit `c` is drawn as in this numeral system: the same digit in the chosen set, or `c` - /// itself when `c` isn't a digit of the Western, Arabic-Indic or Eastern Arabic-Indic set. - pub fn map(self, c: char) -> char { - let value = match c { - '0'..='9' => c as u32 - '0' as u32, - '\u{660}'..='\u{669}' => c as u32 - 0x660, - '\u{6F0}'..='\u{6F9}' => c as u32 - 0x6F0, - _ => return c, - }; - let base = match self { - Digits::Default => return c, - Digits::Arabic => '0' as u32, - Digits::Hindi => 0x660, - Digits::Farsi => 0x6F0, - }; - char::from_u32(base + value).unwrap_or(c) - } -} - -/// Where a character smaller than the largest on its line lines up with it: on the Roman -/// baseline, at the top (right, in vertical type), centre or bottom (left) of the ideographic -/// em boxes, or at the top (right) or bottom (left) of the ideographic character faces (ICF, the -/// average box of the ideographs inside the em box: OpenType's `icft` and `icfb` baselines). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum CharAlign { - #[default] - RomanBaseline, - EmBoxTop, - EmBoxCenter, - EmBoxBottom, - IcfTop, - IcfBottom, -} - -/// Superscript or subscript proportions in percent of the font size (Document Setup → Type). -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct ScriptMetrics { - /// Glyph size. - pub size: f64, - /// Baseline offset: up for superscript, down for subscript. - pub position: f64, -} - -impl ScriptMetrics { - pub const DEFAULT: Self = Self { size: 58.3, position: 33.3 }; - /// Returns these proportions with the size kept to 1 to 500% and the position kept to -500 to - /// 500%, the ranges `document.setup` takes for `superscript` and `subscript`. A value outside - /// its range becomes the nearer end. - pub fn in_range(self) -> Self { - Self { size: self.size.clamp(1.0, 500.0), position: self.position.clamp(-500.0, 500.0) } - } -} - -/// Returns a small caps size kept to 1 to 200%, the range `document.setup` takes for -/// `smallCapsSize`. A size outside it becomes the nearer end. -fn small_caps_in_range(size: f64) -> f64 { - size.clamp(1.0, 200.0) -} - -impl Default for ScriptMetrics { - fn default() -> Self { - Self::DEFAULT - } -} - -/// Character position (Character panel Superscript / Subscript). The proportions are the -/// document's when the position is applied, and follow later Document Setup changes. -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "camelCase")] -pub enum CharPosition { - #[default] - Normal, - Superscript(ScriptMetrics), - Subscript(ScriptMetrics), -} - -impl CharPosition { - /// Glyph scale and baseline shift (points, positive = up) for text of `size` points. - pub fn scale_shift(self, size: f64) -> (f64, f64) { - match self { - CharPosition::Normal => (1.0, 0.0), - CharPosition::Superscript(m) => (m.size / 100.0, m.position / 100.0 * size), - CharPosition::Subscript(m) => (m.size / 100.0, -m.position / 100.0 * size), - } - } - /// `normal`, `superscript` or `subscript`. - pub fn id(self) -> &'static str { - match self { - CharPosition::Normal => "normal", - CharPosition::Superscript(_) => "superscript", - CharPosition::Subscript(_) => "subscript", - } - } - /// Returns this position with its proportions kept by [`ScriptMetrics::in_range`]. - pub fn in_range(self) -> Self { - match self { - CharPosition::Normal => CharPosition::Normal, - CharPosition::Superscript(m) => CharPosition::Superscript(m.in_range()), - CharPosition::Subscript(m) => CharPosition::Subscript(m.in_range()), - } - } -} - -fn ten() -> f64 { - 10.0 -} -fn is_ten(v: &f64) -> bool { - *v == 10.0 -} -fn regular() -> String { - "Regular".into() -} -fn hundred() -> f64 { - 100.0 -} - -impl Default for CharStyle { - fn default() -> Self { - Self { - font_family: "Source Sans 3".into(), - font_style: "Regular".into(), - font_version: None, - font_axes: std::collections::BTreeMap::new(), - size: 12.0, - leading: None, - tracking: 0.0, - kerning: None, - baseline_shift: 0.0, - h_scale: 100.0, - v_scale: 100.0, - rotation: 0.0, - fill: Paint::solid(Color::BLACK), - stroke: Paint::None, - stroke_width: 0.0, - underline: false, - strikethrough: false, - all_caps: false, - features: vec![], - style_name: None, - overprint_fill: false, - overprint_stroke: false, - stroke_cap: LineCap::Butt, - stroke_join: LineJoin::Miter, - stroke_miter_limit: 10.0, - stroke_dash: None, - stroke_align: StrokeAlign::Center, - position: CharPosition::Normal, - char_align: CharAlign::RomanBaseline, - proportional_metrics: false, - small_caps: None, - digits: Digits::Default, - } - } -} - -impl CharStyle { - pub fn effective_leading(&self) -> f64 { - self.leading.unwrap_or(self.size * 1.2) - } - /// Keeps the size, leading, baseline shift and horizontal and vertical scales in range: a size - /// or scale of 0 or less becomes the default new type takes (12 pt, 100%), a negative leading - /// 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. - 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 }; - self.size = within(self.size, default.size); - self.h_scale = within(self.h_scale, default.h_scale); - self.v_scale = within(self.v_scale, default.v_scale); - self.leading = self.leading.filter(|l| *l >= 0.0).map(|l| l.min(crate::MAX_COORD)); - self.baseline_shift = if self.baseline_shift.is_nan() { 0.0 } else { self.baseline_shift.clamp(-crate::MAX_COORD, crate::MAX_COORD) }; - } - /// Do the characters draw a stroke (a paint and a positive weight)? - pub fn has_stroke(&self) -> bool { - !self.stroke.is_none() && self.stroke_width > 0.0 - } - /// The character stroke as a stroke layer (paint, weight, cap, join, miter limit, dashes, - /// alignment and overprint), so type strokes share the object strokes' geometry, rendering - /// and export. - pub fn stroke_layer(&self) -> StrokeLayer { - StrokeLayer { - overprint: self.overprint_stroke, - cap: self.stroke_cap, - join: self.stroke_join, - miter_limit: self.stroke_miter_limit, - dash: self.stroke_dash.clone(), - align: self.stroke_align, - ..StrokeLayer::new(self.stroke.clone(), self.stroke_width) - } - } - /// Take the paint, weight, cap, join, miter limit, dashes and alignment of `st` as the - /// character stroke (the options characters have no use for, such as arrowheads and width - /// profiles, are dropped). - pub fn set_stroke_layer(&mut self, st: &StrokeLayer) { - self.stroke = st.paint.clone(); - self.stroke_width = st.width; - self.stroke_cap = st.cap; - self.stroke_join = st.join; - self.stroke_miter_limit = st.miter_limit; - self.stroke_dash = st.dash.clone(); - self.stroke_align = st.align; - } - /// How far the character stroke paints past the glyph outlines (text space): half the weight - /// centred, the whole weight outside, nothing inside (miter spikes aside). - pub fn stroke_outset(&self) -> f64 { - if !self.has_stroke() { - return 0.0; - } - match self.stroke_align { - StrokeAlign::Center => self.stroke_width / 2.0, - StrokeAlign::Outside => self.stroke_width, - StrokeAlign::Inside => 0.0, - } - } - /// The character fill as a fill layer, overprinting as the characters do. - fn fill_layer(&self) -> FillLayer { - FillLayer { overprint: self.overprint_fill, ..FillLayer::new(self.fill.clone()) } - } - /// The characters' paint as an object appearance (their outlines'): the fill, plus the - /// stroke when it draws one, overprinting as the characters do. - pub fn appearance(&self) -> Appearance { - let mut a = Appearance { items: vec![AppearanceItem::Fill(self.fill_layer())], ..Default::default() }; - if self.has_stroke() { - a.items.push(AppearanceItem::Stroke(self.stroke_layer())); - } - a - } - /// The characters' paint as the basic fill and stroke rows (the stroke row even when it has - /// no paint): the appearance the Eyedropper and graphic styles take from type. - pub fn basic_appearance(&self) -> Appearance { - Appearance { items: vec![AppearanceItem::Fill(self.fill_layer()), AppearanceItem::Stroke(self.stroke_layer())], ..Default::default() } - } - /// Keeps the superscript or subscript proportions in range with [`CharPosition::in_range`] and - /// keeps the small caps size to 1 to 200%, the range `document.setup` takes for `smallCapsSize`. - pub fn keep_scripts_in_range(&mut self) { - self.position = self.position.in_range(); - self.small_caps = self.small_caps.map(small_caps_in_range); - } -} - -impl crate::Document { - /// Keeps the superscript, subscript and small caps proportions to the ranges `document.setup` - /// takes ([`CharStyle::keep_scripts_in_range`]) in the type of the layers, symbols, graph - /// designs, pattern swatches and the pattern definition that pattern editing's Cancel puts - /// back (opacity-mask art included), in graphs' label styles and in the character styles. It - /// recurses through the art: call it on a document no deeper than [`crate::depth::MAX_DEPTH`]. - pub fn keep_scripts_in_range(&mut self) { - let mut fix = |n: &mut crate::Node| { - if let crate::NodeKind::Text(t) = &mut n.kind { - for r in &mut t.runs { - r.style.keep_scripts_in_range(); - } - } - if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) { - let l = &mut g.label_styles; - for st in [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten() { - st.keep_scripts_in_range(); - } - } - }; - let roots = self - .layers - .iter_mut() - .chain(self.symbols.iter_mut().map(|s| &mut s.art)) - .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) - .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) - .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); - for root in roots { - crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix); - } - // Character styles store the attributes they set by their serialized names. - for def in self.char_styles.iter_mut() { - if let Some(v) = def.attrs.get_mut("position") - && let Ok(p) = serde_json::from_value::(v.clone()) - && p.in_range() != p - { - *v = serde_json::to_value(p.in_range()).unwrap_or(serde_json::Value::Null); - } - if let Some(v) = def.attrs.get_mut("small_caps") - && let Some(size) = v.as_f64() - && small_caps_in_range(size) != size - { - *v = small_caps_in_range(size).into(); - } - } - } -} - -/// Tab stop alignment (Tabs panel). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum TabAlign { - #[default] - Left, - Center, - Right, - /// Aligns on the first `align_on` character (a decimal point by default). - Decimal, -} - -/// A tab stop, measured from the left edge of the text (area type: the frame's left edge). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct TabStop { - pub position: f64, - #[serde(default)] - pub align: TabAlign, - /// Leader characters repeated across the tab's gap (e.g. ". "). - #[serde(default, skip_serializing_if = "String::is_empty")] - pub leader: String, - /// Decimal tabs align on this character. - #[serde(default = "default_align_on")] - pub align_on: char, -} - -fn default_align_on() -> char { - '.' -} - -/// Distance between default tab stops when no explicit stop applies (½ inch). -pub const DEFAULT_TAB_INTERVAL: f64 = 36.0; - -/// Paragraph composer (Paragraph panel menu): how lines are broken. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum Composer { - /// Break each line as soon as it is full. - SingleLine, - /// Total fit over the whole paragraph (Illustrator's default): justified lines get even word - /// spacing, ragged lines an even rag. - #[default] - EveryLine, -} - -impl Composer { - fn is_default(&self) -> bool { - *self == Self::default() - } -} - -/// A paragraph's hyphenation options (Paragraph panel menu › Hyphenation…): which words automatic -/// hyphenation may break, where, and on how many lines in a row. Saved only when they differ from -/// the defaults: words longer than 5 letters, 3 letters on each side of the hyphen, no hyphen -/// limit, no hyphenation zone, and capitalized words hyphenated. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct HyphenationOptions { - /// Words Longer Than: only words with more letters than this are hyphenated. - pub words_longer_than: u32, - /// After First: the fewest letters a word keeps before the hyphen. - pub after_first: u32, - /// Before Last: the fewest letters a word keeps after the hyphen. - pub before_last: u32, - /// Hyphen Limit: the most consecutive lines that automatic hyphenation may end with a hyphen; - /// 0 sets no limit. - pub hyphen_limit: u32, - /// Hyphenation Zone (pt): with the Single-line Composer, a line whose text before the next - /// word already ends within this distance of its right edge breaks before that word instead - /// of hyphenating it. 0 allows every hyphenation. - pub zone: f64, - /// Hyphenate Capitalized Words: when it is off, words that start with a capital letter are not - /// hyphenated. Words in capitals only are never hyphenated. - pub capitalized: bool, -} - -impl Default for HyphenationOptions { - fn default() -> Self { - Self { words_longer_than: 5, after_first: 3, before_last: 3, hyphen_limit: 0, zone: 0.0, capitalized: true } - } -} - -/// How a justified line holding a single word is set ([`JustificationOptions::single_word`]). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum SingleWordJustify { - /// Spread across the line, between its letters. - #[default] - FullJustify, - AlignLeft, - AlignCenter, - AlignRight, -} - -/// A paragraph's justification options (Paragraph panel menu › Justification…), in percent. -/// -/// Each spacing has a Minimum, a Desired and a Maximum value (`[min, desired, max]`). Desired -/// applies to every line of the paragraph, justified or not: word spaces are that share of the -/// font's word space, each letter is followed by that share of a word space, and glyphs are that -/// wide. Justified lines may vary them between Minimum and Maximum to fill the measure. Saved only -/// when they differ from the defaults: word spacing 80/100/133, letter spacing 0/0/0, glyph -/// scaling 100/100/100, Auto Leading 120 and Full Justify. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct JustificationOptions { - /// Word Spacing, percent of the font's word space (0..1000). - pub word_spacing: [f64; 3], - /// Letter Spacing, percent of the font's word space added after each letter (-100..500). - pub letter_spacing: [f64; 3], - /// Glyph Scaling, percent of the glyphs' width (50..200). - pub glyph_scaling: [f64; 3], - /// Auto Leading: the leading of characters whose leading is Auto, in percent of their size - /// (0..500). - pub auto_leading: f64, - /// Single Word Justification: how a justified line holding one word is set. - pub single_word: SingleWordJustify, -} - -impl JustificationOptions { - /// Word Spacing's range (percent). - pub const WORD_SPACING: (f64, f64) = (0.0, 1000.0); - /// Letter Spacing's range (percent). - pub const LETTER_SPACING: (f64, f64) = (-100.0, 500.0); - /// Glyph Scaling's range (percent). - pub const GLYPH_SCALING: (f64, f64) = (50.0, 200.0); - /// Auto Leading's range (percent). - pub const AUTO_LEADING: (f64, f64) = (0.0, 500.0); - - /// Are Desired word spacing, letter spacing and glyph scaling the defaults (nothing to change - /// in a line's natural widths)? - pub fn desired_is_default(&self) -> bool { - let d = Self::default(); - self.word_spacing[1] == d.word_spacing[1] && self.letter_spacing[1] == d.letter_spacing[1] && self.glyph_scaling[1] == d.glyph_scaling[1] - } - - /// Keeps options read from a file to what `text.setFormat` can set: a value that is not a - /// finite number becomes its default, every value is clamped to its range, and a Minimum, - /// Desired and Maximum out of order go back to their defaults together. - pub fn keep_in_range(&mut self) { - let d = Self::default(); - for (v, dv, (lo, hi)) in [ - (&mut self.word_spacing, d.word_spacing, Self::WORD_SPACING), - (&mut self.letter_spacing, d.letter_spacing, Self::LETTER_SPACING), - (&mut self.glyph_scaling, d.glyph_scaling, Self::GLYPH_SCALING), - ] { - for (x, dx) in v.iter_mut().zip(dv) { - *x = if x.is_finite() { x.clamp(lo, hi) } else { dx }; - } - if !(v[0] <= v[1] && v[1] <= v[2]) { - *v = dv; - } - } - let (lo, hi) = Self::AUTO_LEADING; - self.auto_leading = if self.auto_leading.is_finite() { self.auto_leading.clamp(lo, hi) } else { d.auto_leading }; - } - - /// A paragraph's leading for characters of `size` whose leading is Auto. - pub fn auto_leading_for(&self, size: f64) -> f64 { - size * self.auto_leading / 100.0 - } -} - -impl Default for JustificationOptions { - fn default() -> Self { - Self { - word_spacing: [80.0, 100.0, 133.0], - letter_spacing: [0.0, 0.0, 0.0], - glyph_scaling: [100.0, 100.0, 100.0], - auto_leading: 120.0, - single_word: SingleWordJustify::FullJustify, - } - } -} - -/// Paragraph attributes (the Paragraph panel). -/// -/// Saved through [`ParaStyleFile`], which keeps files with text openable by builds from before -/// [`Justify::Auto`]. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(from = "ParaStyleFile", into = "ParaStyleFile")] -pub struct ParaStyle { - pub justify: Justify, - pub left_indent: f64, - pub right_indent: f64, - pub first_line_indent: f64, - pub space_before: f64, - pub space_after: f64, - pub hyphenate: bool, - /// The limits automatic hyphenation keeps to (Paragraph panel menu › Hyphenation…). - pub hyphenation: HyphenationOptions, - /// Word and letter spacing, glyph scaling, Auto Leading and Single Word Justification - /// (Paragraph panel menu › Justification…). - pub justification: JustificationOptions, - /// Line breaking: Single-line or Every-line Composer. - pub composer: Composer, - /// Tab stops (Tabs panel), sorted by position. - pub tabs: Vec, - /// Paragraph style (Paragraph Styles panel) these attributes come from; None = Normal. - pub style_name: Option, - /// Japanese composition: the spacing of punctuation (Paragraph panel › Mojikumi). Type made - /// with the Type tools and `text.create` takes [`Mojikumi::LineEndHalf`]; documents from before - /// it and imported text (already set) keep [`Mojikumi::None`]. - pub mojikumi: Mojikumi, - /// Paragraph direction (Paragraph panel): the base direction of each paragraph for - /// bidirectional text (UAX #9). None: from each paragraph's first strong character (Hebrew or - /// Arabic: right to left). - pub direction: Option, - /// How leading is measured (Paragraph panel menu): from baseline to baseline, or from the top - /// of one line's ideographic em box to the next. - pub leading_model: LeadingModel, - /// Hanging punctuation (Paragraph panel menu › Burasagari): a comma or full stop ending a line - /// may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before - /// it and imported text keep [`Burasagari::None`]. - pub burasagari: Burasagari, - /// Kinsoku (Paragraph panel › Kinsoku Set): which Japanese characters may not start or end a - /// line. - pub kinsoku: Kinsoku, - /// 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. - pub roman_hanging: bool, -} - -impl ParaStyle { - /// 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 - /// not a number becomes 0. - pub fn keep_spacing_in_range(&mut self) { - let within = |v: f64, lo: f64, hi: f64| if v.is_nan() { 0.0 } else { v.clamp(lo, hi) }; - for v in [&mut self.left_indent, &mut self.right_indent, &mut self.first_line_indent, &mut self.space_before, &mut self.space_after] { - *v = within(*v, -crate::MAX_COORD, crate::MAX_COORD); - } - for t in &mut self.tabs { - t.position = within(t.position, 0.0, 100_000.0); - } - } -} - -/// [`ParaStyle`] as saved. [`Justify::Auto`] is written as the alignment it has in the paragraph -/// direction (`Right` for right to left, else `Left`) with `justify_auto` set: builds without Auto -/// read the alignment and ignore the flag, and builds with it read Auto back. -#[derive(Serialize, Deserialize)] -struct ParaStyleFile { - #[serde(default)] - justify: Justify, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - justify_auto: bool, - #[serde(default)] - left_indent: f64, - #[serde(default)] - right_indent: f64, - #[serde(default)] - first_line_indent: f64, - #[serde(default)] - space_before: f64, - #[serde(default)] - space_after: f64, - #[serde(default)] - hyphenate: bool, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - hyphenation: HyphenationOptions, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - justification: JustificationOptions, - #[serde(default, skip_serializing_if = "Composer::is_default")] - composer: Composer, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - tabs: Vec, - #[serde(default, skip_serializing_if = "Option::is_none")] - style_name: Option, - #[serde(default, skip_serializing_if = "Mojikumi::is_none")] - mojikumi: Mojikumi, - #[serde(default, skip_serializing_if = "Option::is_none")] - direction: Option, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - leading_model: LeadingModel, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - burasagari: Burasagari, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - kinsoku: Kinsoku, - #[serde(default, skip_serializing_if = "crate::skip::is_default")] - roman_hanging: bool, -} - -impl From for ParaStyleFile { - fn from(p: ParaStyle) -> Self { - let justify_auto = p.justify == Justify::Auto; - let justify = match p.justify { - Justify::Auto if p.direction == Some(ParaDirection::RightToLeft) => Justify::Right, - Justify::Auto => Justify::Left, - j => j, - }; - let ParaStyle { - left_indent, - right_indent, - first_line_indent, - space_before, - space_after, - hyphenate, - hyphenation, - justification, - composer, - tabs, - style_name, - mojikumi, - direction, - leading_model, - burasagari, - kinsoku, - roman_hanging, - .. - } = p; - Self { - justify, - justify_auto, - left_indent, - right_indent, - first_line_indent, - space_before, - space_after, - hyphenate, - hyphenation, - justification, - composer, - tabs, - style_name, - mojikumi, - direction, - leading_model, - burasagari, - kinsoku, - roman_hanging, - } - } -} - -impl From for ParaStyle { - fn from(f: ParaStyleFile) -> Self { - let justify = if f.justify_auto { Justify::Auto } else { f.justify }; - let mut justification = f.justification; - justification.keep_in_range(); - let ParaStyleFile { - left_indent, - right_indent, - first_line_indent, - space_before, - space_after, - hyphenate, - hyphenation, - composer, - tabs, - style_name, - mojikumi, - direction, - leading_model, - burasagari, - kinsoku, - roman_hanging, - .. - } = f; - Self { - justify, - left_indent, - right_indent, - first_line_indent, - space_before, - space_after, - hyphenate, - hyphenation, - justification, - composer, - tabs, - style_name, - mojikumi, - direction, - leading_model, - burasagari, - kinsoku, - roman_hanging, - } - } -} - -/// A paragraph's base direction ([`ParaStyle::direction`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum ParaDirection { - LeftToRight, - RightToLeft, -} - -/// How a paragraph's leading is measured. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum LeadingModel { - /// From one line's baseline to the next's: a line's leading is the space above it, and area - /// type's first baseline follows Area Type Options › First Baseline. - #[default] - RomanBaseline, - /// From the top of one line's ideographic em box (the right side, in vertical type) to the - /// next's: a line's leading is the space below it, and area type's first line touches the top - /// of the frame. Japanese layout's usual model. - EmBoxTop, -} - -/// How Japanese punctuation is spaced (JLREQ 3.1). Full-width punctuation is half a glyph and half -/// a space: an opening bracket's space before it, a closing bracket's, a comma's or a full stop's -/// after it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum Mojikumi { - /// Every character takes its full advance. - #[default] - None, - /// 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, -} - -impl Mojikumi { - pub fn is_none(&self) -> bool { - *self == Mojikumi::None - } -} - -/// Which Japanese characters may not start or end a line (kinsoku shori). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum Kinsoku { - /// No kinsoku: a line may break between any two characters that allow a break. - None, - /// Closing brackets, commas, full stops, iteration marks, the prolonged sound mark, small - /// kana and the like don't start a line; opening brackets don't end one. - #[default] - Hard, - /// As Hard, except that 々, the prolonged sound mark ー and small kana may start a line - /// (JLREQ's level 3 line-breaking rules, Appendix C.3). - Soft, -} - -/// Hanging punctuation (burasagari): an East Asian comma or full stop ending a line (、。,.、。) -/// stands outside the line's measure, in the space its punctuation spacing gives it (half width -/// with Line-end Punctuation Half Width). Closing brackets and Latin punctuation don't hang. Shown -/// as None / Regular / Force. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum Burasagari { - /// A comma or full stop that doesn't fit goes to the next line with the character before it. - #[default] - None, - /// A comma or full stop that doesn't fit hangs outside the line; one that fits stays inside. - Standard, - /// A comma or full stop ending a line always hangs, and the rest of the line fills the measure. - Forced, -} - -/// Area Type Options "First Baseline" offset. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum FirstBaseline { - /// The tallest glyph ascent touches the frame top (Illustrator's default). - #[default] - Ascent, - CapHeight, - XHeight, - /// The first line's leading. - Leading, - /// Exactly `first_baseline_min` below the top. - Fixed, -} - -/// Area Type Options "Align" (vertical): where the lines of each row/column sit in it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum VerticalAlign { - /// Lines start at the top of the cell (the default). - #[default] - Top, - /// The block of lines is centred in the cell. - Center, - /// The last line's descent touches the cell bottom. - Bottom, - /// The first line stays at the top, the last one moves to the bottom and the space left over - /// is shared equally between the lines (no paragraph spacing limit). - Justify, -} - -impl VerticalAlign { - pub const ALL: [VerticalAlign; 4] = [VerticalAlign::Top, VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify]; - pub fn id(self) -> &'static str { - match self { - VerticalAlign::Top => "top", - VerticalAlign::Center => "center", - VerticalAlign::Bottom => "bottom", - VerticalAlign::Justify => "justify", - } - } -} - -/// Text Wrap Options of a wrap object (Object → Text Wrap). -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct TextWrap { - /// Distance kept between the text and the object, in points (Illustrator's default 6 pt). - pub offset: f64, - /// Invert Wrap: text flows inside the object instead of around it. - pub invert: bool, -} - -impl Default for TextWrap { - fn default() -> Self { - Self { offset: 6.0, invert: false } - } -} - -/// A resolved wrap shape on an area text object: the outline of a wrap object in text space. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct WrapShape { - pub path: PathData, - #[serde(flatten)] - pub wrap: TextWrap, -} - -/// Type on a Path effect: how each glyph is oriented on the path (Type → Type on a Path). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum PathEffect { - /// Glyphs rotate with the path (the default). - #[default] - Rainbow, - /// Vertical edges stay vertical; the baseline follows the path. - Skew, - /// Horizontal edges stay horizontal; vertical edges are perpendicular to the path. - #[serde(rename = "3dRibbon")] - Ribbon3d, - /// No rotation: the left end of each glyph's baseline sits on the path. - StairStep, - /// The baseline centre sits on the path and glyphs point away from the path's centre. - Gravity, -} - -impl PathEffect { - pub const ALL: [PathEffect; 5] = [PathEffect::Rainbow, PathEffect::Skew, PathEffect::Ribbon3d, PathEffect::StairStep, PathEffect::Gravity]; - pub fn id(self) -> &'static str { - match self { - PathEffect::Rainbow => "rainbow", - PathEffect::Skew => "skew", - PathEffect::Ribbon3d => "3dRibbon", - PathEffect::StairStep => "stairStep", - PathEffect::Gravity => "gravity", - } - } - pub fn parse(s: &str) -> Option { - let k = s.to_ascii_lowercase().replace([' ', '-', '_'], ""); - Self::ALL.into_iter().find(|e| e.id().to_ascii_lowercase() == k || (k == "ribbon3d" && *e == PathEffect::Ribbon3d)) - } -} - -/// Type on a Path Options › Align to Path: which height of the type runs along the path. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum PathAlign { - /// The font's top edge: the type hangs below the path. - Ascender, - /// The font's bottom edge: the type stands above the path. - Descender, - /// Halfway between the ascender and the descender. - Center, - /// The baseline (the default). - #[default] - Baseline, -} - -impl PathAlign { - pub const ALL: [PathAlign; 4] = [PathAlign::Ascender, PathAlign::Descender, PathAlign::Center, PathAlign::Baseline]; - pub fn id(self) -> &'static str { - match self { - PathAlign::Ascender => "ascender", - PathAlign::Descender => "descender", - PathAlign::Center => "center", - PathAlign::Baseline => "baseline", - } - } - pub fn parse(s: &str) -> Option { - Self::ALL.into_iter().find(|a| a.id().eq_ignore_ascii_case(s.trim())) - } -} - -/// Area Type Options: rows and columns, gutters, inset and first baseline of area type. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct AreaOptions { - #[serde(deserialize_with = "de_rows_or_columns")] - pub rows: usize, - #[serde(deserialize_with = "de_rows_or_columns")] - pub columns: usize, - /// Gutter between rows/columns in points. - pub gutter: f64, - /// Inset from the frame edges in points. - pub inset: f64, - pub first_baseline: FirstBaseline, - /// Minimum first-baseline offset in points. - pub first_baseline_min: f64, - /// Vertical alignment of the lines in each row/column. - pub vertical_align: VerticalAlign, - /// How the frame and its text fit each other (Auto Size, Shrink Text to Fit). - #[serde(skip_serializing_if = "crate::skip::is_default")] - pub fit: AreaFit, -} - -impl Default for AreaOptions { - fn default() -> Self { - Self { - rows: 1, - columns: 1, - gutter: 18.0, - inset: 0.0, - first_baseline: FirstBaseline::Ascent, - first_baseline_min: 0.0, - vertical_align: VerticalAlign::Top, - fit: AreaFit::None, - } - } -} - -impl AreaOptions { - /// The most rows, and the most columns, area type can have. - pub const MAX_ROWS_COLUMNS: usize = 100; -} - -/// [`AreaOptions::rows`] or [`AreaOptions::columns`], read as a `u64` and clamped to -/// 1..=[`AreaOptions::MAX_ROWS_COLUMNS`]. -fn de_rows_or_columns<'de, D: serde::Deserializer<'de>>(d: D) -> Result { - let n = usize::try_from(u64::deserialize(d)?).unwrap_or(usize::MAX); - Ok(n.clamp(1, AreaOptions::MAX_ROWS_COLUMNS)) -} - -/// How area type and its frame fit each other. Serialized as `"none"`, `"autoHeight"` or -/// `{"shrinkText": {"minPercent": 50}}`. -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum AreaFit { - /// The frame keeps its size; text that doesn't fit overflows. - #[default] - None, - /// The frame's height follows the text (Illustrator's Auto Size): resolved by the engine after - /// each edit, for rectangular frames of horizontal type in one row. - AutoHeight, - /// Text that overflows is scaled down (size, leading and baseline shift; not paragraph - /// spacing) by the largest factor down to `min_percent` % that makes it fit, at layout time. - ShrinkText { - #[serde(rename = "minPercent", default = "AreaFit::default_min_percent")] - min_percent: f64, - }, -} - -impl AreaFit { - /// The smallest Shrink Text to Fit percentage allowed. - pub const MIN_PERCENT: f64 = 10.0; - /// The Shrink Text to Fit percentage new settings start with. - pub const DEFAULT_MIN_PERCENT: f64 = 50.0; - fn default_min_percent() -> f64 { - Self::DEFAULT_MIN_PERCENT - } - /// Its id: `none`, `autoHeight` or `shrinkText`. - pub fn id(self) -> &'static str { - match self { - AreaFit::None => "none", - AreaFit::AutoHeight => "autoHeight", - AreaFit::ShrinkText { .. } => "shrinkText", - } - } - /// The fit an id names (case, spaces, dashes and underscores ignored), with `min_percent` - /// for Shrink Text (clamped to 10..100; a non-finite value gives the default). - pub fn parse(id: &str, min_percent: Option) -> Option { - match id.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str() { - "none" | "off" => Some(AreaFit::None), - "autoheight" | "autosize" => Some(AreaFit::AutoHeight), - "shrinktext" | "shrinktexttofit" | "shrink" => { - Some(AreaFit::ShrinkText { min_percent: Self::clamp_percent(min_percent.unwrap_or(Self::DEFAULT_MIN_PERCENT)) }) - } - _ => None, - } - } - /// A Shrink Text minimum percentage within 10..100 (the default when not finite). - pub fn clamp_percent(p: f64) -> f64 { - if p.is_finite() { p.clamp(Self::MIN_PERCENT, 100.0) } else { Self::DEFAULT_MIN_PERCENT } - } - /// Shrink Text's minimum scale factor (0.1..1), if this is Shrink Text. - pub fn min_scale(self) -> Option { - match self { - AreaFit::ShrinkText { min_percent } => Some(Self::clamp_percent(min_percent) / 100.0), - _ => None, - } - } -} - -/// A named character or paragraph style: the attributes it sets (a subset of [`CharStyle`] or -/// [`ParaStyle`] fields, by their serialized names). Text using it records the name. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct TextStyleDef { - pub name: String, - #[serde(default)] - pub attrs: serde_json::Map, -} - -/// A run of text sharing one character style. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct TextRun { - pub text: String, - pub style: CharStyle, - /// An inline graphic: the run is one [`INLINE_CHAR`] drawn as a document symbol that flows - /// with the text like a glyph (InDesign-style inline anchored object). Its `style` still sets - /// the size and tracking; fills and strokes don't apply to the art. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub inline: Option, -} - -impl TextRun { - /// A plain text run. - pub fn new(text: impl Into, style: CharStyle) -> Self { - Self { text: text.into(), style, inline: None } - } - /// An inline graphic run showing `art`. - pub fn inline(art: InlineArt, style: CharStyle) -> Self { - Self { text: INLINE_CHAR.to_string(), style, inline: Some(art) } - } -} - -/// The object replacement character: the plain text of an inline graphic run. -pub const INLINE_CHAR: char = '\u{FFFC}'; - -/// Largest inline graphic scale (× the run's size) accepted from input. -pub const INLINE_MAX_SCALE: f64 = 100.0; - -/// A document symbol placed inline in text ([`TextRun::inline`]). -/// -/// Placement: the art is scaled uniformly so its height (visual bounds) is `scale` × the run's -/// font size, its left edge at the pen position, and its vertical centre on the middle of the -/// run's cap height, raised by `baseline_shift` (points, positive = up). Centred on the cap -/// height the art lines up with capitals and figures (like a mana symbol in rules text) and, at -/// the default scale, stays inside the font's ascent and descent so the leading doesn't change. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct InlineArt { - /// Name of the document symbol ([`crate::Symbol::name`]). - pub symbol: String, - /// Art height as a multiple of the run's font size. - #[serde(default = "one")] - pub scale: f64, - /// Extra raise in points (positive = up). - #[serde(default)] - pub baseline_shift: f64, - /// The symbol art's visual bounds at its natural size, resolved from the document's symbols by - /// [`crate::Document::resolve_inline_art`] (not saved). `None`: not resolved or missing; the - /// layout then reserves a one-em square and nothing is drawn. - #[serde(skip)] - pub bounds: Option, -} - -fn one() -> f64 { - 1.0 -} - -impl InlineArt { - pub fn new(symbol: impl Into) -> Self { - Self { symbol: symbol.into(), scale: 1.0, baseline_shift: 0.0, bounds: None } - } - /// `scale`, made finite and positive (untrusted input). - pub fn safe_scale(&self) -> f64 { - if self.scale.is_finite() && self.scale > 0.0 { self.scale.min(INLINE_MAX_SCALE) } else { 1.0 } - } - /// `baseline_shift`, made finite (untrusted input). - pub fn safe_shift(&self) -> f64 { - if self.baseline_shift.is_finite() { self.baseline_shift.clamp(-1e5, 1e5) } else { 0.0 } - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "lowercase")] -pub enum TextKind { - /// Point type: anchored at the baseline origin of the first line. - Point, - /// Area type flowed inside `frame` (document coordinates, untransformed by `xf`). - Area { frame: PathData }, - /// Type on a path, flowing from its start bracket `start` to its end bracket `end` (0..1 of the - /// path length; no `end`: the end of the path, or once round a closed path). See - /// [`TextKind::path_span`]. - OnPath { - path: PathData, - start: f64, - #[serde(default, skip_serializing_if = "Option::is_none")] - end: Option, - }, -} - -impl TextKind { - /// Type on a path's span: from its start to its end bracket, as fractions of its path's length. - /// Round a closed path the end may be past 1 (the span runs on past the path's start), a full - /// turn without an end or with the end at the start. None for other type. - pub fn path_span(&self) -> Option<(f64, f64)> { - let TextKind::OnPath { path, start, end } = self else { return None }; - let s = fraction(*start); - Some(if path.is_closed() { - let run = end.map_or(0.0, |e| (fraction(e) - s).rem_euclid(1.0)); - (s, s + if run < 1e-9 { 1.0 } else { run }) - } else { - (s, end.map_or(1.0, |e| fraction(e).max(s))) - }) - } -} - -/// `x` as a fraction of a path's length (0..1; 0 when not finite). -fn fraction(x: f64) -> f64 { - if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 } -} - -/// `path` run the other way, each point as far from its new start as it was from its old end -/// (the subpaths in reverse order, a closed one keeping its first anchor first). -fn reverse_from_end(path: &mut PathData) { - path.subpaths.reverse(); - for sp in &mut path.subpaths { - sp.reverse(); - if sp.closed && !sp.anchors.is_empty() { - sp.anchors.rotate_right(1); - } - } -} +mod area; +mod char_style; +mod object; +mod para_style; +mod runs; +mod tabs_lists; + +pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextWrap, VerticalAlign, WrapShape}; +use char_style::yes; +pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, ScriptMetrics}; +pub use para_style::{ + Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, LeadingModel, Mojikumi, ParaDirection, + ParaStyle, SingleWordJustify, +}; +pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef}; +pub use tabs_lists::{Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, NumberStyle, ParaList, TabAlign, TabStop}; /// A text object. `runs` split into paragraphs at `\n`. /// @@ -1267,11 +38,21 @@ pub struct TextObject { /// Maps text space (origin = first baseline start for point type) to the document. pub xf: Affine, pub runs: Vec, + /// Ruby (furigana / phonetic guide) over byte ranges of the plain text; empty = none. Kept on + /// the object, so the runs (and their styles) stay the text itself. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub ruby: Vec, #[serde(default)] pub para: ParaStyle, /// Per-paragraph attributes (see the type's docs); empty = every paragraph uses `para`. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub paras: Vec, + /// Threaded text: the first paragraph continues from the frame before this one in its thread, + /// so its first line here has no first-line indent and no list marker. The engine sets it for + /// every frame of a thread when the story flows through them and when a file opens, and clears + /// it on a frame that leaves its thread and on a copy. Not saved. + #[serde(skip)] + pub first_para_continues: bool, /// Area Type Options (area type only). #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub area: AreaOptions, @@ -1291,10 +72,28 @@ pub struct TextObject { pub wrap: Vec, /// Type › Optical Margin Alignment: in every paragraph, Latin punctuation and the slanted /// sides of letters such as A and W at a line's start or end hang outside the margin there - /// (point and area type of left-to-right paragraphs; see the layout's `optical_hangs`). Off - /// for new type and for documents from before it, and saved only when on. + /// (point and area type, and type on a path at its brackets; see the layout's `optical_hangs`). + /// Off for new type and for documents from before it, and saved only when on. #[serde(default, rename = "opticalMarginAlignment", skip_serializing_if = "crate::skip::is_default")] pub optical_margin: bool, + /// Character panel menu › System Layout, copied from the document: when on, each character + /// that takes space advances by a whole number of points. Off by default, and saved only when + /// on. The document setting is [`crate::DocSetup::system_layout`]. + #[serde(default, rename = "systemLayout", skip_serializing_if = "crate::skip::is_default")] + pub system_layout: bool, + /// Character panel menu › Fractional Widths: spacing between characters uses fractions of a + /// point. On for new type and for documents from before it, and saved only when off. Off, each + /// character that takes any space advances by a whole number of points, at least one, so small + /// type does not run together. The setting is the whole type object, not a range of characters. + /// + #[serde(default = "yes", rename = "fractionalWidths", skip_serializing_if = "crate::skip::is_true")] + pub fractional_widths: bool, + /// Threaded text: the numbered list paragraphs the story's earlier frames count before this + /// frame's first paragraph ([`ParaList::next_marker`]), so one count runs through the story. + /// The engine sets it whenever it re-flows a thread. Type that is not threaded has 0, and the + /// file saves the count only when it is not 0. + #[serde(default, rename = "listCount", skip_serializing_if = "crate::skip::is_default")] + pub list_count: u32, /// Cached layout bounds in text space, filled in by the layout engine (not serialized). #[serde(skip)] pub cached_bounds: Option, @@ -1313,566 +112,5 @@ pub struct TextStyleScale { pub horizontal: f64, } -impl TextObject { - /// None for collapsed or unrepresentable transforms, whose type dimensions cannot - /// be edited by compensating the stored attributes. - pub fn style_scale(&self) -> Option { - let [a, b, c, d, e, f] = self.xf.as_coeffs(); - if ![a, b, c, d, e, f].iter().all(|v| v.is_finite()) { - return None; - } - let (sx, sy) = (a.hypot(b), c.hypot(d)); - let determinant = (a / sx) * (d / sy) - (b / sx) * (c / sy); - let horizontal = sx / sy; - if !sy.is_finite() || sy <= 0.0 || !horizontal.is_finite() || horizontal <= 0.0 || !determinant.is_finite() || determinant.abs() <= 1e-12 { - return None; - } - // Avoid a pure rotation turning otherwise identical fields into mixed values. - let unit = |v: f64| if (v - 1.0).abs() <= 1e-12 { 1.0 } else { v }; - Some(TextStyleScale { points: unit(sy), horizontal: unit(horizontal) }) - } - - /// Character attributes as presented by controls (stored runs stay local for layout - /// and rich-text clipboard operations). Explicit vertical character scale stays separate. - pub fn effective_char_style(&self, style: &CharStyle) -> Option { - let scale = self.style_scale()?; - let mut style = style.clone(); - style.size *= scale.points; - style.leading = style.leading.map(|v| v * scale.points); - style.baseline_shift *= scale.points; - style.h_scale *= scale.horizontal; - if ![style.size, style.leading.unwrap_or(0.0), style.baseline_shift, style.h_scale].iter().all(|v| v.is_finite()) { - return None; - } - Some(style) - } - - pub fn point(origin: Point, text: &str, style: CharStyle) -> Self { - Self { - vertical: false, - kind: TextKind::Point, - xf: Affine::translate(origin.to_vec2()), - runs: vec![TextRun::new(text, style)], - para: ParaStyle::default(), - paras: Vec::new(), - area: AreaOptions::default(), - path_effect: PathEffect::default(), - path_align: PathAlign::default(), - path_spacing: 0.0, - wrap: Vec::new(), - optical_margin: false, - cached_bounds: None, - cached_baselines: Vec::new(), - } - } - pub fn plain_text(&self) -> String { - self.runs.iter().map(|r| r.text.as_str()).collect() - } - /// Number of paragraphs (`\n`-separated; empty text has one). - pub fn paragraph_count(&self) -> usize { - 1 + self.runs.iter().map(|r| r.text.bytes().filter(|&b| b == b'\n').count()).sum::() - } - /// Attributes of paragraph `i` (the last paragraph's past the end). - pub fn para_at(&self, i: usize) -> &ParaStyle { - self.paras.get(i).or(self.paras.last()).unwrap_or(&self.para) - } - /// Every paragraph's attributes, one per paragraph. - pub fn paragraph_styles(&self) -> Vec { - (0..self.paragraph_count()).map(|i| self.para_at(i).clone()).collect() - } - /// Set every paragraph's attributes from `styles` (one per paragraph; a short list repeats its - /// last entry, a long one is cut). - pub fn set_paragraph_styles(&mut self, styles: Vec) { - if let Some(first) = styles.first() { - self.para = first.clone(); - } - self.paras = styles; - self.normalize_paras(); - } - /// The same attributes for every paragraph. - pub fn set_all_paras(&mut self, style: ParaStyle) { - self.para = style; - self.paras.clear(); - } - /// Re-establish the `paras` invariant: one entry per paragraph (cut, or extended with the - /// last), `paras[0] == para`, and empty when every paragraph is alike. - pub fn normalize_paras(&mut self) { - if self.paras.is_empty() { - return; - } - let n = self.paragraph_count(); - let last = self.paras.last().cloned().unwrap_or_default(); - self.paras.resize(n, last); - if let Some(first) = self.paras.first_mut() { - first.clone_from(&self.para); - } - if self.paras.iter().all(|p| *p == self.para) { - self.paras.clear(); - } - } - /// Indices of the paragraphs that byte range `start..end` of the plain text touches (a caret - /// touches its paragraph). - pub fn paragraphs_in(&self, start: usize, end: usize) -> std::ops::Range { - let text = self.plain_text(); - let (a, b) = (start.min(end).min(text.len()), start.max(end).min(text.len())); - let index = |byte: usize| text.as_bytes().get(..byte).map_or(0, |s| s.iter().filter(|&&c| c == b'\n').count()); - index(a)..index(b) + 1 - } - /// Apply `f` to the attributes of paragraphs `range` (indices; None = every paragraph). - pub fn edit_paras(&mut self, range: Option>, mut f: impl FnMut(&mut ParaStyle)) { - match range { - None => { - f(&mut self.para); - for p in &mut self.paras { - f(p); - } - } - Some(r) => { - let mut v = self.paragraph_styles(); - for p in v.iter_mut().take(r.end).skip(r.start) { - f(p); - } - self.set_paragraph_styles(v); - } - } - self.normalize_paras(); - } - /// Every stored paragraph style (`para` and the per-paragraph ones), for scans and renames. - pub fn para_styles_mut(&mut self) -> impl Iterator { - std::iter::once(&mut self.para).chain(self.paras.iter_mut()) - } - /// Every stored paragraph style (`para` and the per-paragraph ones). - pub fn para_styles(&self) -> impl Iterator { - std::iter::once(&self.para).chain(self.paras.iter()) - } - /// Update the paragraph styles for replacing bytes `start..end` of the current plain text by - /// `insert` (call before changing the runs). The paragraph the range starts in keeps its - /// style (merging paragraphs: the first one's wins); paragraphs the insertion starts take that - /// style too (Return continues the paragraph it splits); later paragraphs keep theirs. - pub fn splice_paras(&mut self, start: usize, end: usize, insert: &str) { - if self.paras.is_empty() { - return; - } - let r = self.paragraphs_in(start, end); - let v = self.paragraph_styles(); - let Some(keep) = v.get(r.start).cloned() else { return }; - let added = insert.bytes().filter(|&b| b == b'\n').count(); - let mut out: Vec = v.iter().take(r.start + 1).cloned().collect(); - out.extend(std::iter::repeat_n(keep, added)); - out.extend(v.iter().skip(r.end).cloned()); - self.paras = out; - if let Some(first) = self.paras.first() { - self.para = first.clone(); - } - } - pub fn first_style(&self) -> CharStyle { - self.runs.first().map(|r| r.style.clone()).unwrap_or_default() - } - /// Approximate bounds when no layout cache is available (0.55 em average advance). - pub fn estimate_bounds(&self) -> Rect { - let st = self.first_style(); - let text = self.plain_text(); - let lines: Vec<&str> = text.split('\n').collect(); - let w = lines.iter().map(|l| l.chars().count()).max().unwrap_or(0) as f64 * st.size * 0.55; - let lead = st.effective_leading(); - Rect::new(0.0, -st.size * 0.8, w.max(1.0), -st.size * 0.8 + lead * lines.len().max(1) as f64) - } - pub fn bounds(&self) -> Option { - match &self.kind { - TextKind::Area { frame } => frame.bounds().map(|b| self.xf.transform_rect_bbox(b)), - TextKind::OnPath { path, .. } => path.bounds().map(|b| self.xf.transform_rect_bbox(b)), - TextKind::Point => Some(self.xf.transform_rect_bbox(self.cached_bounds.unwrap_or_else(|| self.estimate_bounds()))), - } - } - pub fn transform(&mut self, a: Affine) { - self.xf = a * self.xf; - } - /// Type on a path's path in document space; None for other type. - pub fn type_path(&self) -> Option { - match &self.kind { - TextKind::OnPath { path, .. } => Some(path.transformed(self.xf)), - _ => None, - } - } - /// Flip type on a path to the other side of its path (Type on a Path Options › Flip, or its - /// centre bracket dragged across the path): the path runs the other way and the brackets swap - /// ends, so the type keeps its stretch of the path. False, changing nothing, for other type. - pub fn flip_on_path(&mut self) -> bool { - let Some((s, e)) = self.kind.path_span() else { return false }; - let TextKind::OnPath { path, start, end } = &mut self.kind else { return false }; - reverse_from_end(path); - if path.is_closed() { - *start = (1.0 - e).rem_euclid(1.0); - *end = (e - s < 1.0 - 1e-9).then(|| (1.0 - s).rem_euclid(1.0)); - } else { - *start = 1.0 - e; - *end = (s > 1e-9).then_some(1.0 - s); - } - true - } - /// Area type's frame (the type area) in document space; None for other type. - pub fn area_frame(&self) -> Option { - match &self.kind { - TextKind::Area { frame } => Some(frame.transformed(self.xf)), - _ => None, - } - } - /// Reshape area type's frame by `a`, a document-space transform, keeping the type at its size - /// (a bounding-box resize: the text reflows, it isn't scaled). False, changing nothing, for - /// other type, a degenerate `xf` or a frame that would not be finite. - pub fn transform_area(&mut self, a: Affine) -> bool { - let xf = self.xf; - self.reshape_area(|frame, to_text| { - frame.transform(to_text * a * xf); - true - }) - } - /// Move anchors `refs` (subpath, anchor) of area type's frame by `d` in document space, with - /// their handles (a Direct Selection drag of a frame corner or edge). False, changing - /// nothing, when an anchor doesn't exist, or as [`Self::transform_area`]. - pub fn move_area_anchors(&mut self, refs: &[(usize, usize)], d: Vec2) -> bool { - self.reshape_area(|frame, to_text| { - // A distance: only the linear part of the document → text map applies. - let local = to_text * d.to_point() - to_text * Point::ZERO; - refs.iter().all(|&(si, ai)| frame.anchor_mut(si, ai).map(|a| a.translate(local)).is_some()) - }) - } - /// Edit a copy of the area frame with `f` (given the document → text space map) and keep it - /// when `f` succeeds and the result is finite. - fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool { - let det = self.xf.determinant(); - if !det.is_finite() || det.abs() < 1e-12 { - return false; - } - let to_text = self.xf.inverse(); - let TextKind::Area { frame } = &mut self.kind else { return false }; - let mut next = frame.clone(); - if !f(&mut next, to_text) || !next.anchors().all(|(_, _, a)| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) { - return false; - } - *frame = next; - true - } - /// Scale the character strokes' weights and dashes by `s` (they are drawn in text space, so - /// `1 / scale` keeps their weight through a transform that scales the type). - pub fn scale_char_strokes(&mut self, s: f64) { - for r in &mut self.runs { - r.style.stroke_width *= s; - if let Some(d) = &mut r.style.stroke_dash { - d.scale(s); - } - } - } - /// Layout bounds in text space (the layout cache, else the estimate): the box an unplaced run - /// gradient fits, as the renderers lay it out. - pub fn local_bounds(&self) -> Rect { - self.cached_bounds.unwrap_or_else(|| self.estimate_bounds()) - } - /// The baselines in text space (the layout cache): for point type with none cached, the first - /// one across [`Self::local_bounds`] (down the first column's centre line for vertical type). - pub fn baselines(&self) -> impl Iterator + '_ { - let first = (self.cached_baselines.is_empty() && matches!(self.kind, TextKind::Point)).then(|| { - let b = self.local_bounds(); - if self.vertical { (Point::new(0.0, b.y0), Point::new(0.0, b.y1)) } else { (Point::new(b.x0, 0.0), Point::new(b.x1, 0.0)) } - }); - self.cached_baselines.iter().copied().chain(first) - } - /// Keeps every run's size, leading, baseline shift and scales in range - /// ([`CharStyle::keep_dimensions_in_range`]) and every paragraph's indents, spacing and tab - /// stops ([`ParaStyle::keep_spacing_in_range`]). - pub fn keep_type_values_in_range(&mut self) { - for r in &mut self.runs { - r.style.keep_dimensions_in_range(); - } - for p in self.para_styles_mut() { - p.keep_spacing_in_range(); - } - } -} - -impl crate::Document { - /// Keeps the character dimensions, indents, paragraph spacing and tab stops in range - /// ([`TextObject::keep_type_values_in_range`]) in the type of the layers, symbols, graph - /// designs, pattern swatches and the pattern definition that pattern editing's Cancel puts - /// back (opacity-mask art included), and the same attributes of the character and paragraph - /// styles. It recurses through the art: call it on a document no deeper than - /// [`crate::depth::MAX_DEPTH`]. - pub fn keep_type_values_in_range(&mut self) { - let mut fix = |n: &mut crate::Node| { - if let crate::NodeKind::Text(t) = &mut n.kind { - t.keep_type_values_in_range(); - } - }; - let roots = self - .layers - .iter_mut() - .chain(self.symbols.iter_mut().map(|s| &mut s.art)) - .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) - .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) - .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); - for root in roots { - crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix); - } - // Styles store the attributes they set by their serialized names (a number, or null for - // Auto leading); a number is rewritten only when it changes. - for def in self.char_styles.iter_mut() { - let num = |k: &str| def.attrs.get(k).and_then(serde_json::Value::as_f64); - let mut st = CharStyle { leading: num("leading"), ..CharStyle::default() }; - st.size = num("size").unwrap_or(st.size); - st.h_scale = num("h_scale").unwrap_or(st.h_scale); - st.v_scale = num("v_scale").unwrap_or(st.v_scale); - st.baseline_shift = num("baseline_shift").unwrap_or(st.baseline_shift); - st.keep_dimensions_in_range(); - let kept = [ - ("size", Some(st.size)), - ("h_scale", Some(st.h_scale)), - ("v_scale", Some(st.v_scale)), - ("baseline_shift", Some(st.baseline_shift)), - ("leading", st.leading), - ]; - for (k, v) in kept { - if let Some(old) = def.attrs.get_mut(k) - && old.is_number() - && old.as_f64() != v - { - *old = v.into(); - } - } - } - for def in self.para_styles.iter_mut() { - for k in ["left_indent", "right_indent", "first_line_indent", "space_before", "space_after"] { - if let Some(v) = def.attrs.get_mut(k) - && let Some(x) = v.as_f64() - && x.abs() > crate::MAX_COORD - { - *v = x.clamp(-crate::MAX_COORD, crate::MAX_COORD).into(); - } - } - for t in def.attrs.get_mut("tabs").and_then(serde_json::Value::as_array_mut).into_iter().flatten() { - if let Some(v) = t.get_mut("position") - && let Some(x) = v.as_f64() - && !(0.0..=100_000.0).contains(&x) - { - *v = x.clamp(0.0, 100_000.0).into(); - } - } - } - } -} - #[cfg(test)] -mod tests { - use super::*; - - /// Digits map every digit of the three sets into the chosen one, leave the rest alone, and - /// are saved only when set. - #[test] - fn digits_map_between_the_numeral_systems() { - let map = |d: Digits, s: &str| -> String { s.chars().map(|c| d.map(c)).collect() }; - for s in ["0123456789", "٠١٢٣٤٥٦٧٨٩", "۰۱۲۳۴۵۶۷۸۹"] { - assert_eq!(map(Digits::Default, s), s); - assert_eq!(map(Digits::Arabic, s), "0123456789"); - assert_eq!(map(Digits::Hindi, s), "٠١٢٣٤٥٦٧٨٩"); - assert_eq!(map(Digits::Farsi, s), "۰۱۲۳۴۵۶۷۸۹"); - } - // Letters, punctuation and other scripts' digits (Devanagari ३) are not digits of these sets. - assert_eq!(map(Digits::Hindi, "a-Z ३ ٪ ۔"), "a-Z ३ ٪ ۔"); - let st = CharStyle::default(); - assert!(serde_json::to_value(&st).unwrap().get("digits").is_none()); - let farsi = CharStyle { digits: Digits::Farsi, ..CharStyle::default() }; - assert_eq!(serde_json::to_value(&farsi).unwrap()["digits"], "farsi"); - // Styles written before the attribute existed (no `digits` key) read as Default. - let old = serde_json::to_value(&st).unwrap(); - assert_eq!(serde_json::from_value::(old).unwrap().digits, Digits::Default); - assert_eq!(serde_json::from_value::(serde_json::to_value(&farsi).unwrap()).unwrap(), farsi); - } - - /// A file can't feed layout justification values `text.setFormat` would refuse: each is - /// clamped to its range, one that isn't finite takes its default, and a Minimum, Desired and - /// Maximum out of order go back to their defaults. - #[test] - fn justification_options_read_from_a_file_stay_in_range() { - let d = JustificationOptions::default(); - let read: ParaStyle = serde_json::from_value(serde_json::json!({ - "justification": { - "word_spacing": [-5.0, 1e300, 1e308], "letter_spacing": [10.0, 5.0, 20.0], - "glyph_scaling": [1.0, 100.0, 9e9], "auto_leading": -1e12 - } - })) - .unwrap(); - let j = read.justification; - assert_eq!(j.word_spacing, [0.0, 1000.0, 1000.0]); - assert_eq!(j.letter_spacing, d.letter_spacing, "out of order"); - assert_eq!(j.glyph_scaling, [50.0, 100.0, 200.0]); - assert_eq!(j.auto_leading, 0.0); - let mut j = JustificationOptions { - word_spacing: [f64::NAN, 100.0, f64::INFINITY], - letter_spacing: [-1.0, 0.0, f64::NEG_INFINITY], - auto_leading: f64::NAN, - ..d.clone() - }; - j.keep_in_range(); - assert_eq!((j.word_spacing, j.letter_spacing, j.auto_leading), (d.word_spacing, [-1.0, 0.0, 0.0], d.auto_leading)); - let mut same = d.clone(); - same.keep_in_range(); - assert_eq!(same, d); - } - - #[test] - fn character_controls_reject_collapsed_and_nonfinite_transforms() { - let mut t = TextObject::point(Point::ZERO, "Text", CharStyle::default()); - for matrix in [[0.0; 6], [1.0, 1.0, 2.0, 2.0, 0.0, 0.0], [f64::INFINITY, 0.0, 0.0, 1.0, 0.0, 0.0], [1.0, 0.0, 0.0, 1.0, f64::NAN, 0.0]] { - t.xf = Affine::new(matrix); - assert!(t.effective_char_style(&t.first_style()).is_none()); - } - t.xf = Affine::rotate(0.83); - assert_eq!(t.effective_char_style(&t.first_style()).unwrap().size, 12.0); - t.xf = Affine::scale(1e308); - assert!(t.effective_char_style(&t.first_style()).is_none(), "overflowing point size"); - } - - #[test] - fn point_text_basics() { - let t = TextObject::point(Point::new(10.0, 20.0), "Hello", CharStyle::default()); - assert_eq!(t.plain_text(), "Hello"); - let b = t.bounds().unwrap(); - assert!(b.x0 >= 10.0 - 1e-9 && b.y1 > 20.0); - assert_eq!(CharStyle::default().effective_leading(), 14.399999999999999); - } - - fn justified(j: Justify) -> ParaStyle { - ParaStyle { justify: j, ..ParaStyle::default() } - } - - #[test] - fn paragraph_styles_split_merge_and_normalize() { - let mut t = TextObject::point(Point::ZERO, "one\ntwo\nthree", CharStyle::default()); - assert_eq!((t.paragraph_count(), t.paras.len()), (3, 0), "one style for all: nothing stored"); - assert_eq!(t.paragraphs_in(0, 0), 0..1); - assert_eq!(t.paragraphs_in(4, 4), 1..2); - assert_eq!(t.paragraphs_in(2, 9), 0..3); - assert_eq!(t.paragraphs_in(99, 99), 2..3, "clamped to the text"); - t.edit_paras(Some(1..2), |p| p.justify = Justify::Center); - let js = |t: &TextObject| t.paragraph_styles().iter().map(|p| p.justify).collect::>(); - assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Left]); - // Return inside "two": the new paragraph continues its style. - t.splice_paras(5, 5, "\n"); - t.runs[0].text.insert(5, '\n'); - assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Center, Justify::Left]); - // Deleting the break between "one" and "t": the first paragraph's style wins. - t.splice_paras(3, 4, ""); - t.runs[0].text.remove(3); - assert_eq!(t.plain_text(), "onet\nwo\nthree"); - assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Left]); - // An edit that skips the splice is repaired by normalizing (the last style continues). - t.runs[0].text.push_str("\nfour"); - t.normalize_paras(); - assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Left, Justify::Left]); - // `para` is paragraph 0's; all alike collapses to `para` alone. - t.edit_paras(Some(0..1), |p| p.justify = Justify::Right); - assert_eq!(t.para.justify, Justify::Right); - t.edit_paras(None, |p| p.justify = Justify::Right); - assert!(t.paras.is_empty() && t.para.justify == Justify::Right); - // A short list repeats its last entry, a long one is cut. - t.set_paragraph_styles(vec![justified(Justify::Left), justified(Justify::Center)]); - assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Center, Justify::Center]); - t.set_paragraph_styles(vec![justified(Justify::Center); 9]); - assert!(t.paras.is_empty() && t.para.justify == Justify::Center); - // Old documents (no `paras`) load; new ones keep paragraph 0 in `para`. - t.edit_paras(Some(3..4), |p| p.space_before = 4.0); - let json = serde_json::to_value(&t).unwrap(); - assert_eq!(json["para"]["justify"], json["paras"][0]["justify"]); - let mut old = json.clone(); - old.as_object_mut().unwrap().remove("paras"); - let back: TextObject = serde_json::from_value(old).unwrap(); - assert!(back.paras.is_empty() && back.para_at(3).justify == Justify::Center); - let back: TextObject = serde_json::from_value(json).unwrap(); - assert_eq!(back.para_at(3).space_before, 4.0); - } - - /// 120 × 40 area type at (40, 40), its text drawn at twice its size. - fn area_type() -> TextObject { - let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default()); - t.kind = TextKind::Area { frame: vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 20.0)) }; - t.xf = Affine::translate((40.0, 40.0)) * Affine::scale(2.0); - t - } - - #[test] - fn area_resizes_its_frame_and_keeps_its_type() { - let mut t = area_type(); - assert_eq!(t.bounds(), Some(Rect::new(40.0, 40.0, 160.0, 80.0))); - // Bottom-right handle to (200, 140), about the top-left corner. - let o = Affine::translate((40.0, 40.0)); - assert!(t.transform_area(o * Affine::scale_non_uniform(160.0 / 120.0, 100.0 / 40.0) * o.inverse())); - assert_eq!(t.xf, Affine::translate((40.0, 40.0)) * Affine::scale(2.0), "the type keeps its size"); - let b = t.bounds().unwrap(); - assert!((b.x1 - 200.0).abs() < 1e-9 && (b.y1 - 140.0).abs() < 1e-9 && b.x0 == 40.0, "{b:?}"); - assert_eq!(t.area_frame().unwrap().bounds(), Some(b)); - // Point type has no area; a degenerate transform or a non-finite frame changes nothing. - let mut p = TextObject::point(Point::ZERO, "x", CharStyle::default()); - assert!(!p.transform_area(Affine::scale(2.0)) && p.area_frame().is_none()); - let before = t.clone(); - assert!(!t.transform_area(Affine::scale(f64::INFINITY))); - t.xf = Affine::scale(0.0); - assert!(!t.transform_area(Affine::scale(2.0))); - t.xf = before.xf; - assert_eq!(t, before); - } - - #[test] - fn area_anchors_move_in_document_space() { - let mut t = area_type(); - // The bottom-right corner (anchor 2) 20 pt right: 10 pt in text space at 2×. - assert!(t.move_area_anchors(&[(0, 2)], Vec2::new(20.0, 0.0))); - let TextKind::Area { frame } = &t.kind else { panic!() }; - assert_eq!(frame.subpaths[0].anchors[2].p, Point::new(70.0, 20.0)); - assert_eq!(frame.subpaths[0].anchors[1].p, Point::new(60.0, 0.0), "the others stay"); - // A missing anchor changes nothing. - let before = t.clone(); - assert!(!t.move_area_anchors(&[(0, 1), (0, 9)], Vec2::new(5.0, 5.0))); - assert!(!t.move_area_anchors(&[(3, 0)], Vec2::new(5.0, 5.0))); - assert_eq!(t, before); - } - - /// Builds from before [`Justify::Auto`] read new type's alignment as Left or Right (and ignore - /// `justify_auto`); this build reads Auto back. - #[test] - fn auto_alignment_saves_readable_by_older_builds() { - #[derive(Deserialize, Debug, PartialEq)] - enum OldJustify { - Left, - Center, - Right, - JustifyLeft, - JustifyCenter, - JustifyRight, - JustifyAll, - } - #[derive(Deserialize)] - struct OldPara { - justify: OldJustify, - } - #[derive(Deserialize)] - struct OldText { - para: OldPara, - } - for (direction, physical) in - [(Some(ParaDirection::RightToLeft), OldJustify::Right), (Some(ParaDirection::LeftToRight), OldJustify::Left), (None, OldJustify::Left)] - { - let mut t = TextObject::point(Point::ZERO, "שלום", CharStyle::default()); - t.para = ParaStyle { justify: Justify::Auto, direction, ..Default::default() }; - let json = serde_json::to_string(&t).unwrap(); - let old: OldText = serde_json::from_str(&json).unwrap(); - assert_eq!(old.para.justify, physical, "{json}"); - assert_eq!(serde_json::from_str::(&json).unwrap(), t); - } - // Other alignments save as before, without the flag. - let p = ParaStyle { justify: Justify::Right, ..Default::default() }; - let json = serde_json::to_string(&p).unwrap(); - assert!(!json.contains("justify_auto"), "{json}"); - assert_eq!(serde_json::from_str::(&json).unwrap(), p); - // Files from before the flag keep their alignment. - assert_eq!(serde_json::from_str::(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center); - } -} +mod tests; diff --git a/crates/doc/src/text/area.rs b/crates/doc/src/text/area.rs new file mode 100644 index 0000000000..5897d957a4 --- /dev/null +++ b/crates/doc/src/text/area.rs @@ -0,0 +1,228 @@ +use super::para_style::FirstBaseline; +use super::*; + +/// Area Type Options "Align" (vertical): where the lines of each row/column sit in it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum VerticalAlign { + /// Lines start at the top of the cell (the default). + #[default] + Top, + /// The block of lines is centred in the cell. + Center, + /// The last line's descent touches the cell bottom. + Bottom, + /// The first line stays at the top, the last one moves to the bottom and the space left over + /// is shared equally between the lines (no paragraph spacing limit). + Justify, +} + +impl VerticalAlign { + pub const ALL: [VerticalAlign; 4] = [VerticalAlign::Top, VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify]; + pub fn id(self) -> &'static str { + match self { + VerticalAlign::Top => "top", + VerticalAlign::Center => "center", + VerticalAlign::Bottom => "bottom", + VerticalAlign::Justify => "justify", + } + } +} + +/// Text Wrap Options of a wrap object (Object → Text Wrap). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct TextWrap { + /// Distance kept between the text and the object, in points (Illustrator's default 6 pt). + pub offset: f64, + /// Invert Wrap: text flows inside the object instead of around it. + pub invert: bool, +} + +impl Default for TextWrap { + fn default() -> Self { + Self { offset: 6.0, invert: false } + } +} + +/// A resolved wrap shape on an area text object: the outline of a wrap object in text space. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct WrapShape { + pub path: PathData, + #[serde(flatten)] + pub wrap: TextWrap, +} + +/// Type on a Path effect: how each glyph is oriented on the path (Type → Type on a Path). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum PathEffect { + /// Glyphs rotate with the path (the default). + #[default] + Rainbow, + /// Vertical edges stay vertical; the baseline follows the path. + Skew, + /// Horizontal edges stay horizontal; vertical edges are perpendicular to the path. + #[serde(rename = "3dRibbon")] + Ribbon3d, + /// No rotation: the left end of each glyph's baseline sits on the path. + StairStep, + /// The baseline centre sits on the path and glyphs point away from the path's centre. + Gravity, +} + +impl PathEffect { + pub const ALL: [PathEffect; 5] = [PathEffect::Rainbow, PathEffect::Skew, PathEffect::Ribbon3d, PathEffect::StairStep, PathEffect::Gravity]; + pub fn id(self) -> &'static str { + match self { + PathEffect::Rainbow => "rainbow", + PathEffect::Skew => "skew", + PathEffect::Ribbon3d => "3dRibbon", + PathEffect::StairStep => "stairStep", + PathEffect::Gravity => "gravity", + } + } + pub fn parse(s: &str) -> Option { + let k = s.to_ascii_lowercase().replace([' ', '-', '_'], ""); + Self::ALL.into_iter().find(|e| e.id().to_ascii_lowercase() == k || (k == "ribbon3d" && *e == PathEffect::Ribbon3d)) + } +} + +/// Type on a Path Options › Align to Path: which height of the type runs along the path. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum PathAlign { + /// The font's top edge: the type hangs below the path. + Ascender, + /// The font's bottom edge: the type stands above the path. + Descender, + /// Halfway between the ascender and the descender. + Center, + /// The baseline (the default). + #[default] + Baseline, +} + +impl PathAlign { + pub const ALL: [PathAlign; 4] = [PathAlign::Ascender, PathAlign::Descender, PathAlign::Center, PathAlign::Baseline]; + pub fn id(self) -> &'static str { + match self { + PathAlign::Ascender => "ascender", + PathAlign::Descender => "descender", + PathAlign::Center => "center", + PathAlign::Baseline => "baseline", + } + } + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|a| a.id().eq_ignore_ascii_case(s.trim())) + } +} + +/// Area Type Options: rows and columns, gutters, inset and first baseline of area type. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct AreaOptions { + #[serde(deserialize_with = "de_rows_or_columns")] + pub rows: usize, + #[serde(deserialize_with = "de_rows_or_columns")] + pub columns: usize, + /// Gutter between rows/columns in points. + pub gutter: f64, + /// Inset from the frame edges in points. + pub inset: f64, + pub first_baseline: FirstBaseline, + /// Minimum first-baseline offset in points. + pub first_baseline_min: f64, + /// Vertical alignment of the lines in each row/column. + pub vertical_align: VerticalAlign, + /// How the frame and its text fit each other (Auto Size, Shrink Text to Fit). + #[serde(skip_serializing_if = "crate::skip::is_default")] + pub fit: AreaFit, +} + +impl Default for AreaOptions { + fn default() -> Self { + Self { + rows: 1, + columns: 1, + gutter: 18.0, + inset: 0.0, + first_baseline: FirstBaseline::Ascent, + first_baseline_min: 0.0, + vertical_align: VerticalAlign::Top, + fit: AreaFit::None, + } + } +} + +impl AreaOptions { + /// The most rows, and the most columns, area type can have. + pub const MAX_ROWS_COLUMNS: usize = 100; +} + +/// [`AreaOptions::rows`] or [`AreaOptions::columns`], read as a `u64` and clamped to +/// 1..=[`AreaOptions::MAX_ROWS_COLUMNS`]. +fn de_rows_or_columns<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let n = usize::try_from(u64::deserialize(d)?).unwrap_or(usize::MAX); + Ok(n.clamp(1, AreaOptions::MAX_ROWS_COLUMNS)) +} + +/// How area type and its frame fit each other. Serialized as `"none"`, `"autoHeight"` or +/// `{"shrinkText": {"minPercent": 50}}`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum AreaFit { + /// The frame keeps its size; text that doesn't fit overflows. + #[default] + None, + /// The frame's height follows the text (Illustrator's Auto Size): resolved by the engine after + /// each edit, for rectangular frames of horizontal type in one row. + AutoHeight, + /// Text that overflows is scaled down (size, leading and baseline shift; not paragraph + /// spacing) by the largest factor down to `min_percent` % that makes it fit, at layout time. + ShrinkText { + #[serde(rename = "minPercent", default = "AreaFit::default_min_percent")] + min_percent: f64, + }, +} + +impl AreaFit { + /// The smallest Shrink Text to Fit percentage allowed. + pub const MIN_PERCENT: f64 = 10.0; + /// The Shrink Text to Fit percentage new settings start with. + pub const DEFAULT_MIN_PERCENT: f64 = 50.0; + fn default_min_percent() -> f64 { + Self::DEFAULT_MIN_PERCENT + } + /// Its id: `none`, `autoHeight` or `shrinkText`. + pub fn id(self) -> &'static str { + match self { + AreaFit::None => "none", + AreaFit::AutoHeight => "autoHeight", + AreaFit::ShrinkText { .. } => "shrinkText", + } + } + /// The fit an id names (case, spaces, dashes and underscores ignored), with `min_percent` + /// for Shrink Text (clamped to 10..100; a non-finite value gives the default). + pub fn parse(id: &str, min_percent: Option) -> Option { + match id.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str() { + "none" | "off" => Some(AreaFit::None), + "autoheight" | "autosize" => Some(AreaFit::AutoHeight), + "shrinktext" | "shrinktexttofit" | "shrink" => { + Some(AreaFit::ShrinkText { min_percent: Self::clamp_percent(min_percent.unwrap_or(Self::DEFAULT_MIN_PERCENT)) }) + } + _ => None, + } + } + /// A Shrink Text minimum percentage within 10..100 (the default when not finite). + pub fn clamp_percent(p: f64) -> f64 { + if p.is_finite() { p.clamp(Self::MIN_PERCENT, 100.0) } else { Self::DEFAULT_MIN_PERCENT } + } + /// Shrink Text's minimum scale factor (0.1..1), if this is Shrink Text. + pub fn min_scale(self) -> Option { + match self { + AreaFit::ShrinkText { min_percent } => Some(Self::clamp_percent(min_percent) / 100.0), + _ => None, + } + } +} diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs new file mode 100644 index 0000000000..a19b5f71c3 --- /dev/null +++ b/crates/doc/src/text/char_style.rs @@ -0,0 +1,432 @@ +use super::para_style::ParaDirection; +use super::*; + +/// Character attributes (the Character panel). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CharStyle { + pub font_family: String, + #[serde(default = "regular")] + pub font_style: String, + /// Which installed version of the font (its version string) when several versions of the + /// family and style are installed and the text was set in one the family and style alone + /// wouldn't pick (an imported file's type matched to it); None = the one they pick. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub font_version: Option, + /// Variation axis settings of a variable font (Character panel › Variable Font), by axis tag + /// (`wght`, `wdth`), in the axis's own units. They replace the named instance's setting of + /// each axis they name; the other axes keep the style's settings. Empty: the style as it is. + #[serde(default, rename = "fontAxes", skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub font_axes: std::collections::BTreeMap, + /// Size in points. + pub size: f64, + /// Leading in points; None = Auto (120% of size). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub leading: Option, + /// Tracking in 1/1000 em. + #[serde(default)] + pub tracking: f64, + /// Kerning: None = Auto (metrics), Some(v) = manual in 1/1000 em. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub kerning: Option, + #[serde(default)] + pub baseline_shift: f64, + #[serde(default = "hundred")] + pub h_scale: f64, + #[serde(default = "hundred")] + pub v_scale: f64, + #[serde(default)] + pub rotation: f64, + pub fill: Paint, + #[serde(default)] + pub stroke: Paint, + #[serde(default)] + pub stroke_width: f64, + #[serde(default)] + pub underline: bool, + #[serde(default)] + pub strikethrough: bool, + #[serde(default)] + pub all_caps: bool, + /// OpenType features that differ from the defaults (OpenType panel), as tags: `"dlig"` turns + /// a feature on, `"-liga"` off. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub features: Vec, + /// Character style (Character Styles panel) these attributes come from; None = Normal. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub style_name: Option, + /// Overprint Fill / Overprint Stroke of these characters (see [`crate::FillLayer::overprint`]). + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub overprint_fill: bool, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub overprint_stroke: bool, + /// Cap, join, miter limit and dashes of the character stroke (Stroke panel, with type + /// selected); defaults as for object strokes. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub stroke_cap: LineCap, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub stroke_join: LineJoin, + #[serde(default = "ten", skip_serializing_if = "is_ten")] + pub stroke_miter_limit: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stroke_dash: Option, + /// Align Stroke of the character stroke (Stroke panel, with type selected): centred on the + /// glyph outlines, inside or outside them, as for object strokes; the type stays live. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub stroke_align: StrokeAlign, + /// Superscript or subscript (Character panel). + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub position: CharPosition, + /// Small Caps (Character panel): lowercase letters drawn as capitals at this percentage of the + /// size (Document Setup → Type → Small Caps); None = off. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub small_caps: Option, + /// Character Alignment (Character panel menu): where characters smaller than the largest on + /// their line line up with it. + #[serde(default, rename = "charAlign", skip_serializing_if = "crate::skip::is_default")] + pub char_align: CharAlign, + /// Character Direction (Character panel menu, Middle Eastern options): these characters are + /// set left to right or right to left inside their paragraph, each stretch of them a Unicode + /// bidi embedding (UAX #9 LRE or RLE); None = Default, the direction the bidi algorithm gives + /// them. + #[serde(default, rename = "charDirection", skip_serializing_if = "Option::is_none")] + pub char_direction: Option, + /// Proportional Metrics (Character panel menu, East Asian options): full-width glyphs take the + /// font's own proportional widths, OpenType `palt` (#966); in vertical type upright glyphs take + /// its proportional heights, `vpal`. + #[serde(default, rename = "proportionalMetrics", skip_serializing_if = "crate::skip::is_default")] + pub proportional_metrics: bool, + /// Tate-chu-yoko (Character panel menu, East Asian options): in vertical type these characters + /// stand side by side across one em of the column. Horizontal type keeps the mark and does not + /// move them. Two or three half-width digits do this without the mark. + /// + #[serde(default, rename = "tateChuYoko", skip_serializing_if = "crate::skip::is_default")] + pub tate_chu_yoko: bool, + /// Digits (Character panel menu, Middle Eastern options): the numeral system the digits of + /// these characters are drawn in, whatever digits were typed. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub digits: Digits, + /// No Break (Character panel menu): these characters are not broken across lines, including + /// at a space or a hyphenation point inside the run. A run longer than the line stays together + /// and can overflow it. + /// + #[serde(default, rename = "noBreak", skip_serializing_if = "crate::skip::is_default")] + pub no_break: bool, +} + +/// The numeral system digits are drawn in ([`CharStyle::digits`]): as typed, or every digit of +/// the Western, Arabic-Indic and Eastern Arabic-Indic sets drawn in one of them. The text keeps +/// the digits that were typed; only the glyphs change (like All Caps). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Digits { + /// Each digit as typed. + #[default] + Default, + /// Western digits 0–9 (the digits Arabic typography calls Arabic). + Arabic, + /// Arabic-Indic digits ٠–٩ (U+0660–U+0669), used in Arabic. + Hindi, + /// Eastern Arabic-Indic digits ۰–۹ (U+06F0–U+06F9), used in Persian and Urdu. + Farsi, +} + +impl Digits { + /// The digit `c` is drawn as in this numeral system: the same digit in the chosen set, or `c` + /// itself when `c` isn't a digit of the Western, Arabic-Indic or Eastern Arabic-Indic set. + pub fn map(self, c: char) -> char { + let value = match c { + '0'..='9' => c as u32 - '0' as u32, + '\u{660}'..='\u{669}' => c as u32 - 0x660, + '\u{6F0}'..='\u{6F9}' => c as u32 - 0x6F0, + _ => return c, + }; + let base = match self { + Digits::Default => return c, + Digits::Arabic => '0' as u32, + Digits::Hindi => 0x660, + Digits::Farsi => 0x6F0, + }; + char::from_u32(base + value).unwrap_or(c) + } +} + +/// Where a character smaller than the largest on its line lines up with it: on the Roman +/// baseline, at the top (right, in vertical type), centre or bottom (left) of the ideographic +/// em boxes, or at the top (right) or bottom (left) of the ideographic character faces (ICF, the +/// average box of the ideographs inside the em box: OpenType's `icft` and `icfb` baselines). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum CharAlign { + #[default] + RomanBaseline, + EmBoxTop, + EmBoxCenter, + EmBoxBottom, + IcfTop, + IcfBottom, +} + +/// Superscript or subscript proportions in percent of the font size (Document Setup → Type). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct ScriptMetrics { + /// Glyph size. + pub size: f64, + /// Baseline offset: up for superscript, down for subscript. + pub position: f64, +} + +impl ScriptMetrics { + pub const DEFAULT: Self = Self { size: 58.3, position: 33.3 }; + /// Returns these proportions with the size kept to 1 to 500% and the position kept to -500 to + /// 500%, the ranges `document.setup` takes for `superscript` and `subscript`. A value outside + /// its range becomes the nearer end. + pub fn in_range(self) -> Self { + Self { size: self.size.clamp(1.0, 500.0), position: self.position.clamp(-500.0, 500.0) } + } +} + +/// Returns a small caps size kept to 1 to 200%, the range `document.setup` takes for +/// `smallCapsSize`. A size outside it becomes the nearer end. +fn small_caps_in_range(size: f64) -> f64 { + size.clamp(1.0, 200.0) +} + +impl Default for ScriptMetrics { + fn default() -> Self { + Self::DEFAULT + } +} + +/// Character position (Character panel Superscript / Subscript). The proportions are the +/// document's when the position is applied, and follow later Document Setup changes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum CharPosition { + #[default] + Normal, + Superscript(ScriptMetrics), + Subscript(ScriptMetrics), +} + +impl CharPosition { + /// Glyph scale and baseline shift (points, positive = up) for text of `size` points. + pub fn scale_shift(self, size: f64) -> (f64, f64) { + match self { + CharPosition::Normal => (1.0, 0.0), + CharPosition::Superscript(m) => (m.size / 100.0, m.position / 100.0 * size), + CharPosition::Subscript(m) => (m.size / 100.0, -m.position / 100.0 * size), + } + } + /// `normal`, `superscript` or `subscript`. + pub fn id(self) -> &'static str { + match self { + CharPosition::Normal => "normal", + CharPosition::Superscript(_) => "superscript", + CharPosition::Subscript(_) => "subscript", + } + } + /// Returns this position with its proportions kept by [`ScriptMetrics::in_range`]. + pub fn in_range(self) -> Self { + match self { + CharPosition::Normal => CharPosition::Normal, + CharPosition::Superscript(m) => CharPosition::Superscript(m.in_range()), + CharPosition::Subscript(m) => CharPosition::Subscript(m.in_range()), + } + } +} + +fn ten() -> f64 { + 10.0 +} + +fn is_ten(v: &f64) -> bool { + *v == 10.0 +} + +fn regular() -> String { + "Regular".into() +} + +fn hundred() -> f64 { + 100.0 +} + +pub(super) fn yes() -> bool { + true +} + +impl Default for CharStyle { + fn default() -> Self { + Self { + font_family: "Source Sans 3".into(), + font_style: "Regular".into(), + font_version: None, + font_axes: std::collections::BTreeMap::new(), + size: 12.0, + leading: None, + tracking: 0.0, + kerning: None, + baseline_shift: 0.0, + h_scale: 100.0, + v_scale: 100.0, + rotation: 0.0, + fill: Paint::solid(Color::BLACK), + stroke: Paint::None, + stroke_width: 0.0, + underline: false, + strikethrough: false, + all_caps: false, + features: vec![], + style_name: None, + overprint_fill: false, + overprint_stroke: false, + stroke_cap: LineCap::Butt, + stroke_join: LineJoin::Miter, + stroke_miter_limit: 10.0, + stroke_dash: None, + stroke_align: StrokeAlign::Center, + position: CharPosition::Normal, + char_align: CharAlign::RomanBaseline, + char_direction: None, + proportional_metrics: false, + tate_chu_yoko: false, + small_caps: None, + digits: Digits::Default, + no_break: false, + } + } +} + +impl CharStyle { + pub fn effective_leading(&self) -> f64 { + self.leading.unwrap_or(self.size * 1.2) + } + /// Keeps the size, leading, baseline shift and horizontal and vertical scales in range: a size + /// or scale of 0 or less becomes the default new type takes (12 pt, 100%), a negative leading + /// 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. + 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 }; + self.size = within(self.size, default.size); + self.h_scale = within(self.h_scale, default.h_scale); + self.v_scale = within(self.v_scale, default.v_scale); + self.leading = self.leading.filter(|l| *l >= 0.0).map(|l| l.min(crate::MAX_COORD)); + self.baseline_shift = if self.baseline_shift.is_nan() { 0.0 } else { self.baseline_shift.clamp(-crate::MAX_COORD, crate::MAX_COORD) }; + } + /// Do the characters draw a stroke (a paint and a positive weight)? + pub fn has_stroke(&self) -> bool { + !self.stroke.is_none() && self.stroke_width > 0.0 + } + /// The character stroke as a stroke layer (paint, weight, cap, join, miter limit, dashes, + /// alignment and overprint), so type strokes share the object strokes' geometry, rendering + /// and export. + pub fn stroke_layer(&self) -> StrokeLayer { + StrokeLayer { + overprint: self.overprint_stroke, + cap: self.stroke_cap, + join: self.stroke_join, + miter_limit: self.stroke_miter_limit, + dash: self.stroke_dash.clone(), + align: self.stroke_align, + ..StrokeLayer::new(self.stroke.clone(), self.stroke_width) + } + } + /// Take the paint, weight, cap, join, miter limit, dashes and alignment of `st` as the + /// character stroke (the options characters have no use for, such as arrowheads and width + /// profiles, are dropped). + pub fn set_stroke_layer(&mut self, st: &StrokeLayer) { + self.stroke = st.paint.clone(); + self.stroke_width = st.width; + self.stroke_cap = st.cap; + self.stroke_join = st.join; + self.stroke_miter_limit = st.miter_limit; + self.stroke_dash = st.dash.clone(); + self.stroke_align = st.align; + } + /// How far the character stroke paints past the glyph outlines (text space): half the weight + /// centred, the whole weight outside, nothing inside (miter spikes aside). + pub fn stroke_outset(&self) -> f64 { + if !self.has_stroke() { + return 0.0; + } + match self.stroke_align { + StrokeAlign::Center => self.stroke_width / 2.0, + StrokeAlign::Outside => self.stroke_width, + StrokeAlign::Inside => 0.0, + } + } + /// The character fill as a fill layer, overprinting as the characters do. + fn fill_layer(&self) -> FillLayer { + FillLayer { overprint: self.overprint_fill, ..FillLayer::new(self.fill.clone()) } + } + /// The characters' paint as an object appearance (their outlines'): the fill, plus the + /// stroke when it draws one, overprinting as the characters do. + pub fn appearance(&self) -> Appearance { + let mut a = Appearance { items: vec![AppearanceItem::Fill(self.fill_layer())], ..Default::default() }; + if self.has_stroke() { + a.items.push(AppearanceItem::Stroke(self.stroke_layer())); + } + a + } + /// The characters' paint as the basic fill and stroke rows (the stroke row even when it has + /// no paint): the appearance the Eyedropper and graphic styles take from type. + pub fn basic_appearance(&self) -> Appearance { + Appearance { items: vec![AppearanceItem::Fill(self.fill_layer()), AppearanceItem::Stroke(self.stroke_layer())], ..Default::default() } + } + /// Keeps the superscript or subscript proportions in range with [`CharPosition::in_range`] and + /// keeps the small caps size to 1 to 200%, the range `document.setup` takes for `smallCapsSize`. + pub fn keep_scripts_in_range(&mut self) { + self.position = self.position.in_range(); + self.small_caps = self.small_caps.map(small_caps_in_range); + } +} + +impl crate::Document { + /// Keeps the superscript, subscript and small caps proportions to the ranges `document.setup` + /// takes ([`CharStyle::keep_scripts_in_range`]) in the type of the layers, symbols, graph + /// designs, pattern swatches and the pattern definition that pattern editing's Cancel puts + /// back (opacity-mask art included), in graphs' label styles and in the character styles. It + /// recurses through the art: call it on a document no deeper than [`crate::depth::MAX_DEPTH`]. + pub fn keep_scripts_in_range(&mut self) { + let mut fix = |n: &mut crate::Node| { + if let crate::NodeKind::Text(t) = &mut n.kind { + for r in &mut t.runs { + r.style.keep_scripts_in_range(); + } + } + if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) { + let l = &mut g.label_styles; + for st in [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten() { + st.keep_scripts_in_range(); + } + } + }; + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix); + } + // Character styles store the attributes they set by their serialized names. + for def in self.char_styles.iter_mut() { + if let Some(v) = def.attrs.get_mut("position") + && let Ok(p) = serde_json::from_value::(v.clone()) + && p.in_range() != p + { + *v = serde_json::to_value(p.in_range()).unwrap_or(serde_json::Value::Null); + } + if let Some(v) = def.attrs.get_mut("small_caps") + && let Some(size) = v.as_f64() + && small_caps_in_range(size) != size + { + *v = small_caps_in_range(size).into(); + } + } + } +} diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs new file mode 100644 index 0000000000..58caa1602c --- /dev/null +++ b/crates/doc/src/text/object.rs @@ -0,0 +1,493 @@ +use super::area::{AreaOptions, PathAlign, PathEffect}; +use super::char_style::CharStyle; +use super::para_style::ParaStyle; +use super::runs::{RubySpan, TextKind, TextRun, move_anchors, reverse_from_end}; +use super::tabs_lists::ParaList; +use super::*; + +impl TextObject { + /// None for collapsed or unrepresentable transforms, whose type dimensions cannot + /// be edited by compensating the stored attributes. + pub fn style_scale(&self) -> Option { + let [a, b, c, d, e, f] = self.xf.as_coeffs(); + if ![a, b, c, d, e, f].iter().all(|v| v.is_finite()) { + return None; + } + let (sx, sy) = (a.hypot(b), c.hypot(d)); + let determinant = (a / sx) * (d / sy) - (b / sx) * (c / sy); + let horizontal = sx / sy; + if !sy.is_finite() || sy <= 0.0 || !horizontal.is_finite() || horizontal <= 0.0 || !determinant.is_finite() || determinant.abs() <= 1e-12 { + return None; + } + // Avoid a pure rotation turning otherwise identical fields into mixed values. + let unit = |v: f64| if (v - 1.0).abs() <= 1e-12 { 1.0 } else { v }; + Some(TextStyleScale { points: unit(sy), horizontal: unit(horizontal) }) + } + + /// Character attributes as presented by controls (stored runs stay local for layout + /// and rich-text clipboard operations). Explicit vertical character scale stays separate. + pub fn effective_char_style(&self, style: &CharStyle) -> Option { + let scale = self.style_scale()?; + let mut style = style.clone(); + style.size *= scale.points; + style.leading = style.leading.map(|v| v * scale.points); + style.baseline_shift *= scale.points; + style.h_scale *= scale.horizontal; + if ![style.size, style.leading.unwrap_or(0.0), style.baseline_shift, style.h_scale].iter().all(|v| v.is_finite()) { + return None; + } + Some(style) + } + + /// Bakes the object's scale ([`style_scale`]) into character attributes and removes that + /// scale from `xf`, so panels show document-point sizes without a separate transform factor. + /// Returns `false` when there is nothing to bake (identity scale or an unrepresentable + /// transform). + pub fn scale_text_attributes(&mut self) -> bool { + let Some(scale) = self.style_scale() else { return false }; + if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 { + return false; + } + let [a, b, c, d, _, _] = self.xf.as_coeffs(); + let (sx, sy) = (a.hypot(b), c.hypot(d)); + if sx <= 1e-12 || sy <= 1e-12 { + return false; + } + let mut baked = Vec::with_capacity(self.runs.len()); + for run in &self.runs { + let Some(eff) = self.effective_char_style(&run.style) else { return false }; + baked.push(eff); + } + for (run, style) in self.runs.iter_mut().zip(baked) { + run.style = style; + } + // Character strokes are drawn in text space: widen them by the vertical scale we remove. + self.scale_char_strokes(1.0 / sy); + self.xf *= Affine::scale_non_uniform(1.0 / sx, 1.0 / sy); + self.cached_bounds = None; + self.cached_baselines.clear(); + true + } + + pub fn point(origin: Point, text: &str, style: CharStyle) -> Self { + Self { + vertical: false, + kind: TextKind::Point, + xf: Affine::translate(origin.to_vec2()), + runs: vec![TextRun::new(text, style)], + ruby: Vec::new(), + para: ParaStyle::default(), + paras: Vec::new(), + first_para_continues: false, + area: AreaOptions::default(), + path_effect: PathEffect::default(), + path_align: PathAlign::default(), + path_spacing: 0.0, + wrap: Vec::new(), + optical_margin: false, + system_layout: false, + fractional_widths: true, + list_count: 0, + cached_bounds: None, + cached_baselines: Vec::new(), + } + } + pub fn plain_text(&self) -> String { + self.runs.iter().map(|r| r.text.as_str()).collect() + } + /// Clamp the ruby spans to the plain text, drop empty/empty-reading ones and sort them. + /// + /// Called after loading and editing text: ranges from a file or an edit are untrusted, and a + /// range past the text or an inverted one would lay out nothing (or panic in a silly place). + pub fn normalize_ruby(&mut self) { + let len: usize = self.runs.iter().map(|r| r.text.len()).sum(); + for r in &mut self.ruby { + r.start = r.start.min(len); + r.end = r.end.min(len); + if r.start > r.end { + std::mem::swap(&mut r.start, &mut r.end); + } + r.text = r.text.trim().to_string(); + } + self.ruby.retain(|r| r.start < r.end && !r.text.is_empty()); + self.ruby.sort_by_key(|r| (r.start, r.end)); + } + /// The ruby span covering byte `byte` of the plain text, if any. + pub fn ruby_at(&self, byte: usize) -> Option<&RubySpan> { + self.ruby.iter().find(|r| r.start <= byte && byte < r.end) + } + /// Ruby spans touching the plain-text byte range `start..end`, with their ranges ordered. + pub fn ruby_in(&self, start: usize, end: usize) -> impl Iterator { + let (a, b) = (start.min(end), start.max(end)); + self.ruby.iter().filter(move |r| r.start < b && a < r.end) + } + /// Keep the ruby spans over the text after replacing plain-text bytes `start..end` with + /// `inserted` bytes of text: spans after the edit move with the text, ones the edit runs into + /// keep their start and end up where the replaced part ended. Call it after every edit of the + /// runs (`vectorcraft_text::edit`), then [`Self::normalize_ruby`] has the last word. + pub fn ruby_after_replace(&mut self, start: usize, end: usize, inserted: usize) { + let (start, end) = (start.min(end), start.max(end)); + let delta = inserted as i64 - (end.saturating_sub(start)) as i64; + let shift = |v: usize| -> usize { (v as i64 + delta).max(0) as usize }; + for r in &mut self.ruby { + if r.end <= start { + continue; + } + if r.start >= end { + r.start = shift(r.start); + r.end = shift(r.end); + } else { + r.start = r.start.min(start); + r.end = shift(r.end).max(r.start); + } + } + self.normalize_ruby(); + } + /// Number of paragraphs (`\n`-separated; empty text has one). + pub fn paragraph_count(&self) -> usize { + 1 + self.runs.iter().map(|r| r.text.bytes().filter(|&b| b == b'\n').count()).sum::() + } + /// Attributes of paragraph `i` (the last paragraph's past the end). + pub fn para_at(&self, i: usize) -> &ParaStyle { + self.paras.get(i).or(self.paras.last()).unwrap_or(&self.para) + } + /// Every paragraph's attributes, one per paragraph. + pub fn paragraph_styles(&self) -> Vec { + (0..self.paragraph_count()).map(|i| self.para_at(i).clone()).collect() + } + /// Set every paragraph's attributes from `styles` (one per paragraph; a short list repeats its + /// last entry, a long one is cut). + pub fn set_paragraph_styles(&mut self, styles: Vec) { + if let Some(first) = styles.first() { + self.para = first.clone(); + } + self.paras = styles; + self.normalize_paras(); + } + /// The same attributes for every paragraph. + pub fn set_all_paras(&mut self, style: ParaStyle) { + self.para = style; + self.paras.clear(); + } + /// Re-establish the `paras` invariant: one entry per paragraph (cut, or extended with the + /// last), `paras[0] == para`, and empty when every paragraph is alike. + pub fn normalize_paras(&mut self) { + if self.paras.is_empty() { + return; + } + let n = self.paragraph_count(); + let last = self.paras.last().cloned().unwrap_or_default(); + self.paras.resize(n, last); + if let Some(first) = self.paras.first_mut() { + first.clone_from(&self.para); + } + if self.paras.iter().all(|p| *p == self.para) { + self.paras.clear(); + } + } + /// Indices of the paragraphs that byte range `start..end` of the plain text touches (a caret + /// touches its paragraph). + pub fn paragraphs_in(&self, start: usize, end: usize) -> std::ops::Range { + let text = self.plain_text(); + let (a, b) = (start.min(end).min(text.len()), start.max(end).min(text.len())); + let index = |byte: usize| text.as_bytes().get(..byte).map_or(0, |s| s.iter().filter(|&&c| c == b'\n').count()); + index(a)..index(b) + 1 + } + /// The list that the characters before byte `at` start ([`ParaList::typed`]) with the byte + /// where their paragraph starts: when the plain text from the start of the paragraph up to + /// `at` is a list's start followed by a space, and the paragraph is in no list. None otherwise. + pub fn typed_list_at(&self, at: usize) -> Option<(usize, ParaList)> { + let text = self.plain_text(); + let before = text.get(..at)?; + let start = before.rfind('\n').map_or(0, |i| i + 1); + let list = ParaList::typed(before[start..].strip_suffix(' ')?)?; + let index = before.bytes().filter(|&b| b == b'\n').count(); + self.para_at(index).list.is_none().then_some((start, list)) + } + /// Apply `f` to the attributes of paragraphs `range` (indices; None = every paragraph). + pub fn edit_paras(&mut self, range: Option>, mut f: impl FnMut(&mut ParaStyle)) { + match range { + None => { + f(&mut self.para); + for p in &mut self.paras { + f(p); + } + } + Some(r) => { + let mut v = self.paragraph_styles(); + for p in v.iter_mut().take(r.end).skip(r.start) { + f(p); + } + self.set_paragraph_styles(v); + } + } + self.normalize_paras(); + } + /// Every stored paragraph style (`para` and the per-paragraph ones), for scans and renames. + pub fn para_styles_mut(&mut self) -> impl Iterator { + std::iter::once(&mut self.para).chain(self.paras.iter_mut()) + } + /// Every stored paragraph style (`para` and the per-paragraph ones). + pub fn para_styles(&self) -> impl Iterator { + std::iter::once(&self.para).chain(self.paras.iter()) + } + /// Update the paragraph styles for replacing bytes `start..end` of the current plain text by + /// `insert` (call before changing the runs). The paragraph the range starts in keeps its + /// style (merging paragraphs: the first one's wins); paragraphs the insertion starts take that + /// style too (Return continues the paragraph it splits); later paragraphs keep theirs. + pub fn splice_paras(&mut self, start: usize, end: usize, insert: &str) { + if self.paras.is_empty() { + return; + } + let r = self.paragraphs_in(start, end); + let v = self.paragraph_styles(); + let Some(keep) = v.get(r.start).cloned() else { return }; + let added = insert.bytes().filter(|&b| b == b'\n').count(); + let mut out: Vec = v.iter().take(r.start + 1).cloned().collect(); + out.extend(std::iter::repeat_n(keep, added)); + out.extend(v.iter().skip(r.end).cloned()); + self.paras = out; + if let Some(first) = self.paras.first() { + self.para = first.clone(); + } + } + pub fn first_style(&self) -> CharStyle { + self.runs.first().map(|r| r.style.clone()).unwrap_or_default() + } + /// Approximate bounds when no layout cache is available (0.55 em average advance). + pub fn estimate_bounds(&self) -> Rect { + let st = self.first_style(); + let text = self.plain_text(); + let lines: Vec<&str> = text.split('\n').collect(); + let w = lines.iter().map(|l| l.chars().count()).max().unwrap_or(0) as f64 * st.size * 0.55; + let lead = st.effective_leading(); + Rect::new(0.0, -st.size * 0.8, w.max(1.0), -st.size * 0.8 + lead * lines.len().max(1) as f64) + } + pub fn bounds(&self) -> Option { + match &self.kind { + TextKind::Area { frame } => frame.bounds().map(|b| self.xf.transform_rect_bbox(b)), + TextKind::OnPath { path, .. } => path.bounds().map(|b| self.xf.transform_rect_bbox(b)), + TextKind::Point => Some(self.xf.transform_rect_bbox(self.cached_bounds.unwrap_or_else(|| self.estimate_bounds()))), + } + } + /// How far the characters' strokes paint past their glyphs, in document space: they scale + /// with the type. + pub fn char_stroke_outset(&self) -> f64 { + let k = crate::node::Scaling::factor(self.xf).unwrap_or(1.0); + self.runs.iter().map(|r| r.style.stroke_outset()).fold(0.0, f64::max) * k + } + /// How far the characters' strokes can paint past their glyphs, their miter spikes and square + /// caps included ([`StrokeLayer::reach`]), in document space: what a change of the type must + /// redraw. They stretch with the type, so this is as far as its transform takes them on either + /// axis. The visual bounds take [`Self::char_stroke_outset`]. + pub fn char_stroke_reach(&self) -> f64 { + let reach = self.runs.iter().filter(|r| r.style.has_stroke()).map(|r| r.style.stroke_layer().reach()).fold(0.0, f64::max); + let [a, b, c, d, ..] = self.xf.as_coeffs(); + reach * (a.abs() + c.abs()).max(b.abs() + d.abs()) + } + pub fn transform(&mut self, a: Affine) { + self.xf = a * self.xf; + } + /// Type on a path's path in document space; None for other type. + pub fn type_path(&self) -> Option { + match &self.kind { + TextKind::OnPath { path, .. } => Some(path.transformed(self.xf)), + _ => None, + } + } + /// Flip type on a path to the other side of its path (Type on a Path Options › Flip, or its + /// centre bracket dragged across the path): the path runs the other way and the brackets swap + /// ends, so the type keeps its stretch of the path. False, changing nothing, for other type. + pub fn flip_on_path(&mut self) -> bool { + let Some((s, e)) = self.kind.path_span() else { return false }; + let TextKind::OnPath { path, start, end } = &mut self.kind else { return false }; + reverse_from_end(path); + if path.is_closed() { + *start = (1.0 - e).rem_euclid(1.0); + *end = (e - s < 1.0 - 1e-9).then(|| (1.0 - s).rem_euclid(1.0)); + } else { + *start = 1.0 - e; + *end = (s > 1e-9).then_some(1.0 - s); + } + true + } + /// Area type's frame (the type area) in document space; None for other type. + pub fn area_frame(&self) -> Option { + match &self.kind { + TextKind::Area { frame } => Some(frame.transformed(self.xf)), + _ => None, + } + } + /// Reshape area type's frame by `a`, a document-space transform, keeping the type at its size + /// (a bounding-box resize: the text reflows, it isn't scaled). False, changing nothing, for + /// other type, a degenerate `xf` or a frame that would not be finite. + pub fn transform_area(&mut self, a: Affine) -> bool { + let xf = self.xf; + self.reshape_area(|frame, to_text| { + frame.transform(to_text * a * xf); + true + }) + } + /// Move anchors `refs` (subpath, anchor) of area type's frame by `d` in document space, with + /// their handles (a Direct Selection drag of a frame corner or edge). False, changing + /// nothing, when an anchor doesn't exist, or as [`Self::transform_area`]. + pub fn move_area_anchors(&mut self, refs: &[(usize, usize)], d: Vec2) -> bool { + self.reshape_area(|frame, to_text| move_anchors(frame, to_text, refs, d)) + } + /// Move anchors `refs` (subpath, anchor) of type on a path's path by `d` in document space, + /// with their handles (a Direct Selection drag of an anchor); the brackets keep their + /// fractions of the path. False, changing nothing, for other type, when an anchor doesn't + /// exist, a degenerate `xf` or a path that would not be finite. + pub fn move_path_anchors(&mut self, refs: &[(usize, usize)], d: Vec2) -> bool { + matches!(self.kind, TextKind::OnPath { .. }) && self.reshape_local(|path, to_text| move_anchors(path, to_text, refs, d)) + } + /// Edit a copy of the area frame with `f` (given the document → text space map) and keep it + /// when `f` succeeds and the result is finite. + fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool { + matches!(self.kind, TextKind::Area { .. }) && self.reshape_local(f) + } + /// [`Self::reshape_area`] for the area frame or type on a path's path. + fn reshape_local(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool { + let det = self.xf.determinant(); + if !det.is_finite() || det.abs() < 1e-12 { + return false; + } + let to_text = self.xf.inverse(); + let (TextKind::Area { frame } | TextKind::OnPath { path: frame, .. }) = &mut self.kind else { return false }; + let mut next = frame.clone(); + if !f(&mut next, to_text) || !next.anchors().all(|(_, _, a)| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) { + return false; + } + *frame = next; + true + } + /// Scale the character strokes' weights and dashes by `s` (they are drawn in text space, so + /// `1 / scale` keeps their weight through a transform that scales the type). + pub fn scale_char_strokes(&mut self, s: f64) { + for r in &mut self.runs { + r.style.stroke_width *= s; + if let Some(d) = &mut r.style.stroke_dash { + d.scale(s); + } + } + } + /// Layout bounds in text space (the layout cache, else the estimate): the box an unplaced run + /// gradient fits, as the renderers lay it out. + pub fn local_bounds(&self) -> Rect { + self.cached_bounds.unwrap_or_else(|| self.estimate_bounds()) + } + /// The baselines in text space (the layout cache): for point type with none cached, the first + /// one across [`Self::local_bounds`] (down the first column's centre line for vertical type). + pub fn baselines(&self) -> impl Iterator + '_ { + let first = (self.cached_baselines.is_empty() && matches!(self.kind, TextKind::Point)).then(|| { + let b = self.local_bounds(); + if self.vertical { (Point::new(0.0, b.y0), Point::new(0.0, b.y1)) } else { (Point::new(b.x0, 0.0), Point::new(b.x1, 0.0)) } + }); + self.cached_baselines.iter().copied().chain(first) + } + /// Keeps every run's size, leading, baseline shift and scales in range + /// ([`CharStyle::keep_dimensions_in_range`]) and every paragraph's indents, spacing and tab + /// stops ([`ParaStyle::keep_spacing_in_range`]). + pub fn keep_type_values_in_range(&mut self) { + for r in &mut self.runs { + r.style.keep_dimensions_in_range(); + } + for p in self.para_styles_mut() { + p.keep_spacing_in_range(); + } + } +} + +impl crate::Document { + /// Keeps the character dimensions, indents, paragraph spacing and tab stops in range + /// ([`TextObject::keep_type_values_in_range`]) in the type of the layers, symbols, graph + /// designs, pattern swatches and the pattern definition that pattern editing's Cancel puts + /// back (opacity-mask art included), and the same attributes of the character and paragraph + /// styles. It recurses through the art: call it on a document no deeper than + /// [`crate::depth::MAX_DEPTH`]. + pub fn keep_type_values_in_range(&mut self) { + let mut fix = |n: &mut crate::Node| { + if let crate::NodeKind::Text(t) = &mut n.kind { + t.keep_type_values_in_range(); + } + }; + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix); + } + // Styles store the attributes they set by their serialized names (a number, or null for + // Auto leading); a number is rewritten only when it changes. + for def in self.char_styles.iter_mut() { + let num = |k: &str| def.attrs.get(k).and_then(serde_json::Value::as_f64); + let mut st = CharStyle { leading: num("leading"), ..CharStyle::default() }; + st.size = num("size").unwrap_or(st.size); + st.h_scale = num("h_scale").unwrap_or(st.h_scale); + st.v_scale = num("v_scale").unwrap_or(st.v_scale); + st.baseline_shift = num("baseline_shift").unwrap_or(st.baseline_shift); + st.keep_dimensions_in_range(); + let kept = [ + ("size", Some(st.size)), + ("h_scale", Some(st.h_scale)), + ("v_scale", Some(st.v_scale)), + ("baseline_shift", Some(st.baseline_shift)), + ("leading", st.leading), + ]; + for (k, v) in kept { + if let Some(old) = def.attrs.get_mut(k) + && old.is_number() + && old.as_f64() != v + { + *old = v.into(); + } + } + } + for def in self.para_styles.iter_mut() { + for k in ["left_indent", "right_indent", "first_line_indent", "space_before", "space_after"] { + if let Some(v) = def.attrs.get_mut(k) + && let Some(x) = v.as_f64() + && x.abs() > crate::MAX_COORD + { + *v = x.clamp(-crate::MAX_COORD, crate::MAX_COORD).into(); + } + } + for t in def.attrs.get_mut("tabs").and_then(serde_json::Value::as_array_mut).into_iter().flatten() { + if let Some(v) = t.get_mut("position") + && let Some(x) = v.as_f64() + && !(0.0..=100_000.0).contains(&x) + { + *v = x.clamp(0.0, 100_000.0).into(); + } + } + } + } + + /// Clamps the ruby spans of the type in the layers, symbols, graph designs, pattern swatches + /// and the pattern definition that pattern editing's Cancel puts back (opacity-mask art + /// included) to their text ([`TextObject::normalize_ruby`]). Loaded files and edits carry + /// ranges from outside: a range past the text, an inverted one or an empty reading would lay + /// out nothing. It recurses through the art: call it on a document no deeper than + /// [`crate::depth::MAX_DEPTH`]. + pub fn fix_ruby(&mut self) { + let mut fix = |n: &mut crate::Node| { + if let crate::NodeKind::Text(t) = &mut n.kind { + t.normalize_ruby(); + } + }; + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix); + } + } +} diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs new file mode 100644 index 0000000000..6a01a18156 --- /dev/null +++ b/crates/doc/src/text/para_style.rs @@ -0,0 +1,517 @@ +use super::char_style::CharStyle; +use super::tabs_lists::{ParaList, TabStop}; +use super::*; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum Justify { + /// Align to the start of each paragraph's direction ([`ParaStyle::direction`]): left for + /// left-to-right paragraphs, right for right-to-left ones. New type's alignment. + Auto, + #[default] + Left, + Center, + Right, + JustifyLeft, + JustifyCenter, + JustifyRight, + JustifyAll, +} + +/// Paragraph composer (Paragraph panel menu): how lines are broken. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Composer { + /// Break each line as soon as it is full. + SingleLine, + /// Total fit over the whole paragraph (Illustrator's default): justified lines get even word + /// spacing, ragged lines an even rag. + #[default] + EveryLine, +} + +impl Composer { + fn is_default(&self) -> bool { + *self == Self::default() + } +} + +/// A paragraph's hyphenation options (Paragraph panel menu › Hyphenation…): which words automatic +/// hyphenation may break, where, and on how many lines in a row. Saved only when they differ from +/// the defaults: words longer than 5 letters, 3 letters on each side of the hyphen, no hyphen +/// limit, no hyphenation zone, and capitalized words hyphenated. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct HyphenationOptions { + /// Words Longer Than: only words with more letters than this are hyphenated. + pub words_longer_than: u32, + /// After First: the fewest letters a word keeps before the hyphen. + pub after_first: u32, + /// Before Last: the fewest letters a word keeps after the hyphen. + pub before_last: u32, + /// Hyphen Limit: the most consecutive lines that automatic hyphenation may end with a hyphen; + /// 0 sets no limit. + pub hyphen_limit: u32, + /// Hyphenation Zone (pt): with the Single-line Composer, a line whose text before the next + /// word already ends within this distance of its right edge breaks before that word instead + /// of hyphenating it. 0 allows every hyphenation. + pub zone: f64, + /// Hyphenate Capitalized Words: when it is off, words that start with a capital letter are not + /// hyphenated. Words in capitals only are never hyphenated. + pub capitalized: bool, +} + +impl Default for HyphenationOptions { + fn default() -> Self { + Self { words_longer_than: 5, after_first: 3, before_last: 3, hyphen_limit: 0, zone: 0.0, capitalized: true } + } +} + +/// How a justified line holding a single word is set ([`JustificationOptions::single_word`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SingleWordJustify { + /// Spread across the line, between its letters. + #[default] + FullJustify, + AlignLeft, + AlignCenter, + AlignRight, +} + +/// A paragraph's justification options (Paragraph panel menu › Justification…), in percent. +/// +/// Each spacing has a Minimum, a Desired and a Maximum value (`[min, desired, max]`). Desired +/// applies to every line of the paragraph, justified or not: word spaces are that share of the +/// font's word space, each letter is followed by that share of a word space, and glyphs are that +/// wide. Justified lines may vary them between Minimum and Maximum to fill the measure. Saved only +/// when they differ from the defaults: word spacing 80/100/133, letter spacing 0/0/0, glyph +/// scaling 100/100/100, Auto Leading 120 and Full Justify. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct JustificationOptions { + /// Word Spacing, percent of the font's word space (0..1000). + pub word_spacing: [f64; 3], + /// Letter Spacing, percent of the font's word space added after each letter (-100..500). + pub letter_spacing: [f64; 3], + /// Glyph Scaling, percent of the glyphs' width (50..200). + pub glyph_scaling: [f64; 3], + /// Auto Leading: the leading of characters whose leading is Auto, in percent of their size + /// (0..500). + pub auto_leading: f64, + /// Single Word Justification: how a justified line holding one word is set. + pub single_word: SingleWordJustify, +} + +impl JustificationOptions { + /// Word Spacing's range (percent). + pub const WORD_SPACING: (f64, f64) = (0.0, 1000.0); + /// Letter Spacing's range (percent). + pub const LETTER_SPACING: (f64, f64) = (-100.0, 500.0); + /// Glyph Scaling's range (percent). + pub const GLYPH_SCALING: (f64, f64) = (50.0, 200.0); + /// Auto Leading's range (percent). + pub const AUTO_LEADING: (f64, f64) = (0.0, 500.0); + + /// Are Desired word spacing, letter spacing and glyph scaling the defaults (nothing to change + /// in a line's natural widths)? + pub fn desired_is_default(&self) -> bool { + let d = Self::default(); + self.word_spacing[1] == d.word_spacing[1] && self.letter_spacing[1] == d.letter_spacing[1] && self.glyph_scaling[1] == d.glyph_scaling[1] + } + + /// Keeps options read from a file to what `text.setFormat` can set: a value that is not a + /// finite number becomes its default, every value is clamped to its range, and a Minimum, + /// Desired and Maximum out of order go back to their defaults together. + pub fn keep_in_range(&mut self) { + let d = Self::default(); + for (v, dv, (lo, hi)) in [ + (&mut self.word_spacing, d.word_spacing, Self::WORD_SPACING), + (&mut self.letter_spacing, d.letter_spacing, Self::LETTER_SPACING), + (&mut self.glyph_scaling, d.glyph_scaling, Self::GLYPH_SCALING), + ] { + for (x, dx) in v.iter_mut().zip(dv) { + *x = if x.is_finite() { x.clamp(lo, hi) } else { dx }; + } + if !(v[0] <= v[1] && v[1] <= v[2]) { + *v = dv; + } + } + let (lo, hi) = Self::AUTO_LEADING; + self.auto_leading = if self.auto_leading.is_finite() { self.auto_leading.clamp(lo, hi) } else { d.auto_leading }; + } + + /// A paragraph's leading for characters of `size` whose leading is Auto. + pub fn auto_leading_for(&self, size: f64) -> f64 { + size * self.auto_leading / 100.0 + } +} + +impl Default for JustificationOptions { + fn default() -> Self { + Self { + word_spacing: [80.0, 100.0, 133.0], + letter_spacing: [0.0, 0.0, 0.0], + glyph_scaling: [100.0, 100.0, 100.0], + auto_leading: 120.0, + single_word: SingleWordJustify::FullJustify, + } + } +} + +/// Insert Kashidas (Paragraph panel): how long the kashidas are that lengthen the Arabic words of +/// a justified paragraph's lines. A kashida is a tatweel (U+0640) drawn between a word's last pair +/// of joined letters, at most one in each word. Short, Medium and Long kashidas are at most a quarter +/// of an em, half an em and an em long; a Stylistic kashida is a row of whole tatweels as the font +/// draws them, at most an em long. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Kashida { + /// No kashidas: justified lines widen their word spaces. + #[default] + None, + Short, + Medium, + Long, + Stylistic, +} + +impl Kashida { + /// The longest kashida, in ems of the letter that follows it in the text; 0 for None. + pub fn max_em(self) -> f64 { + match self { + Kashida::None => 0.0, + Kashida::Short => 0.25, + Kashida::Medium => 0.5, + Kashida::Long | Kashida::Stylistic => 1.0, + } + } +} + +/// Paragraph attributes (the Paragraph panel). +/// +/// Saved through [`ParaStyleFile`], which keeps files with text openable by builds from before +/// [`Justify::Auto`]. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(from = "ParaStyleFile", into = "ParaStyleFile")] +pub struct ParaStyle { + pub justify: Justify, + pub left_indent: f64, + pub right_indent: f64, + pub first_line_indent: f64, + pub space_before: f64, + pub space_after: f64, + pub hyphenate: bool, + /// The limits automatic hyphenation keeps to (Paragraph panel menu › Hyphenation…). + pub hyphenation: HyphenationOptions, + /// Word and letter spacing, glyph scaling, Auto Leading and Single Word Justification + /// (Paragraph panel menu › Justification…). + pub justification: JustificationOptions, + /// Line breaking: Single-line or Every-line Composer. + pub composer: Composer, + /// Tab stops (Tabs panel), sorted by position. + pub tabs: Vec, + /// Bullets (Paragraph panel): the list the paragraph is in; None for a paragraph that is not + /// in a list. + pub list: Option, + /// Paragraph style (Paragraph Styles panel) these attributes come from; None = Normal. + pub style_name: Option, + /// Japanese composition: the spacing of punctuation (Paragraph panel › Mojikumi). Type made + /// with the Type tools and `text.create` takes [`Mojikumi::LineEndHalf`]; documents from before + /// it and imported text (already set) keep [`Mojikumi::None`]. + pub mojikumi: Mojikumi, + /// Paragraph direction (Paragraph panel): the base direction of each paragraph for + /// bidirectional text (UAX #9). None: from each paragraph's first strong character (Hebrew or + /// Arabic: right to left). + pub direction: Option, + /// How leading is measured (Paragraph panel menu): from baseline to baseline, or from the top + /// of one line's ideographic em box to the next. + pub leading_model: LeadingModel, + /// Hanging punctuation (Paragraph panel menu › Burasagari): a comma or full stop ending a line + /// may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before + /// it and imported text keep [`Burasagari::None`]. + pub burasagari: Burasagari, + /// Kinsoku (Paragraph panel › Kinsoku Set): which Japanese characters may not start or end a + /// line. + pub kinsoku: Kinsoku, + /// 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. + pub roman_hanging: bool, + /// Insert Kashidas (Paragraph panel): justified lines lengthen their Arabic words with + /// kashidas before they widen their word spaces. + pub kashida: Kashida, +} + +impl ParaStyle { + /// 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 + /// not a number becomes 0. + pub fn keep_spacing_in_range(&mut self) { + let within = |v: f64, lo: f64, hi: f64| if v.is_nan() { 0.0 } else { v.clamp(lo, hi) }; + for v in [&mut self.left_indent, &mut self.right_indent, &mut self.first_line_indent, &mut self.space_before, &mut self.space_after] { + *v = within(*v, -crate::MAX_COORD, crate::MAX_COORD); + } + for t in &mut self.tabs { + t.position = within(t.position, 0.0, 100_000.0); + } + } + + /// The leading of characters styled `st` in this paragraph, as the layout sets it: their own + /// leading, or for Auto leading the paragraph's Justification › Auto Leading share of their + /// size (exactly [`CharStyle::effective_leading`] at the default 120%, or when the share is + /// not a finite number). + pub fn effective_leading(&self, st: &CharStyle) -> f64 { + let auto = self.justification.auto_leading; + if st.leading.is_some() || auto == JustificationOptions::default().auto_leading { + return st.effective_leading(); + } + let l = self.justification.auto_leading_for(st.size); + if l.is_finite() { l } else { st.effective_leading() } + } +} + +/// [`ParaStyle`] as saved. [`Justify::Auto`] is written as the alignment it has in the paragraph +/// direction (`Right` for right to left, else `Left`) with `justify_auto` set: builds without Auto +/// read the alignment and ignore the flag, and builds with it read Auto back. +#[derive(Serialize, Deserialize)] +struct ParaStyleFile { + #[serde(default)] + justify: Justify, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + justify_auto: bool, + #[serde(default)] + left_indent: f64, + #[serde(default)] + right_indent: f64, + #[serde(default)] + first_line_indent: f64, + #[serde(default)] + space_before: f64, + #[serde(default)] + space_after: f64, + #[serde(default)] + hyphenate: bool, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + hyphenation: HyphenationOptions, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + justification: JustificationOptions, + #[serde(default, skip_serializing_if = "Composer::is_default")] + composer: Composer, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + tabs: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + list: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + style_name: Option, + #[serde(default, skip_serializing_if = "Mojikumi::is_none")] + mojikumi: Mojikumi, + #[serde(default, skip_serializing_if = "Option::is_none")] + direction: Option, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + leading_model: LeadingModel, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + burasagari: Burasagari, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + kinsoku: Kinsoku, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + roman_hanging: bool, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + kashida: Kashida, +} + +impl From for ParaStyleFile { + fn from(p: ParaStyle) -> Self { + let justify_auto = p.justify == Justify::Auto; + let justify = match p.justify { + Justify::Auto if p.direction == Some(ParaDirection::RightToLeft) => Justify::Right, + Justify::Auto => Justify::Left, + j => j, + }; + let ParaStyle { + left_indent, + right_indent, + first_line_indent, + space_before, + space_after, + hyphenate, + hyphenation, + justification, + composer, + tabs, + list, + style_name, + mojikumi, + direction, + leading_model, + burasagari, + kinsoku, + roman_hanging, + kashida, + .. + } = p; + Self { + justify, + justify_auto, + left_indent, + right_indent, + first_line_indent, + space_before, + space_after, + hyphenate, + hyphenation, + justification, + composer, + tabs, + list, + style_name, + mojikumi, + direction, + leading_model, + burasagari, + kinsoku, + roman_hanging, + kashida, + } + } +} + +impl From for ParaStyle { + fn from(f: ParaStyleFile) -> Self { + let justify = if f.justify_auto { Justify::Auto } else { f.justify }; + let mut justification = f.justification; + justification.keep_in_range(); + let ParaStyleFile { + left_indent, + right_indent, + first_line_indent, + space_before, + space_after, + hyphenate, + hyphenation, + composer, + tabs, + list, + style_name, + mojikumi, + direction, + leading_model, + burasagari, + kinsoku, + roman_hanging, + kashida, + .. + } = f; + Self { + justify, + left_indent, + right_indent, + first_line_indent, + space_before, + space_after, + hyphenate, + hyphenation, + justification, + composer, + tabs, + list, + style_name, + mojikumi, + direction, + leading_model, + burasagari, + kinsoku, + roman_hanging, + kashida, + } + } +} + +/// A paragraph's base direction ([`ParaStyle::direction`]), or the direction characters are set +/// in ([`CharStyle::char_direction`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ParaDirection { + LeftToRight, + RightToLeft, +} + +/// How a paragraph's leading is measured. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum LeadingModel { + /// From one line's baseline to the next's: a line's leading is the space above it, and area + /// type's first baseline follows Area Type Options › First Baseline. + #[default] + RomanBaseline, + /// From the top of one line's ideographic em box (the right side, in vertical type) to the + /// next's: a line's leading is the space below it, and area type's first line touches the top + /// of the frame. Japanese layout's usual model. + EmBoxTop, +} + +/// How Japanese punctuation is spaced (JLREQ 3.1). Full-width punctuation is half a glyph and half +/// a space: an opening bracket's space before it, a closing bracket's, a comma's or a full stop's +/// after it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Mojikumi { + /// Every character takes its full advance. + #[default] + None, + /// 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, +} + +impl Mojikumi { + pub fn is_none(&self) -> bool { + *self == Mojikumi::None + } +} + +/// Which Japanese characters may not start or end a line (kinsoku shori). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Kinsoku { + /// No kinsoku: a line may break between any two characters that allow a break. + None, + /// Closing brackets, commas, full stops, iteration marks, the prolonged sound mark, small + /// kana and the like don't start a line; opening brackets don't end one. + #[default] + Hard, + /// As Hard, except that 々, the prolonged sound mark ー and small kana may start a line + /// (JLREQ's level 3 line-breaking rules, Appendix C.3). + Soft, +} + +/// Hanging punctuation (burasagari): an East Asian comma or full stop ending a line (、。,.、。) +/// stands outside the line's measure, in the space its punctuation spacing gives it (half width +/// with Line-end Punctuation Half Width). Closing brackets and Latin punctuation don't hang. Shown +/// as None / Regular / Force. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Burasagari { + /// A comma or full stop that doesn't fit goes to the next line with the character before it. + #[default] + None, + /// A comma or full stop that doesn't fit hangs outside the line; one that fits stays inside. + Standard, + /// A comma or full stop ending a line always hangs, and the rest of the line fills the measure. + Forced, +} + +/// Area Type Options "First Baseline" offset. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum FirstBaseline { + /// The tallest glyph ascent touches the frame top (Illustrator's default). + #[default] + Ascent, + CapHeight, + XHeight, + /// The first line's leading. + Leading, + /// Exactly `first_baseline_min` below the top. + Fixed, +} diff --git a/crates/doc/src/text/runs.rs b/crates/doc/src/text/runs.rs new file mode 100644 index 0000000000..4e3de93383 --- /dev/null +++ b/crates/doc/src/text/runs.rs @@ -0,0 +1,207 @@ +use super::char_style::CharStyle; +use super::*; + +/// A named character or paragraph style: the attributes it sets (a subset of [`CharStyle`] or +/// [`ParaStyle`] fields, by their serialized names). Text using it records the name. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TextStyleDef { + pub name: String, + #[serde(default)] + pub attrs: serde_json::Map, +} + +/// A run of text sharing one character style. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TextRun { + pub text: String, + pub style: CharStyle, + /// An inline graphic: the run is one [`INLINE_CHAR`] drawn as a document symbol that flows + /// with the text like a glyph (InDesign-style inline anchored object). Its `style` still sets + /// the size and tracking; fills and strokes don't apply to the art. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub inline: Option, +} + +impl TextRun { + /// A plain text run. + pub fn new(text: impl Into, style: CharStyle) -> Self { + Self { text: text.into(), style, inline: None } + } + /// An inline graphic run showing `art`. + pub fn inline(art: InlineArt, style: CharStyle) -> Self { + Self { text: INLINE_CHAR.to_string(), style, inline: Some(art) } + } +} + +/// The object replacement character: the plain text of an inline graphic run. +pub const INLINE_CHAR: char = '\u{FFFC}'; + +/// Largest inline graphic scale (× the run's size) accepted from input. +pub const INLINE_MAX_SCALE: f64 = 100.0; + +/// A document symbol placed inline in text ([`TextRun::inline`]). +/// +/// Placement: the art is scaled uniformly so its height (visual bounds) is `scale` × the run's +/// font size, its left edge at the pen position, and its vertical centre on the middle of the +/// run's cap height, raised by `baseline_shift` (points, positive = up). Centred on the cap +/// height the art lines up with capitals and figures (like a mana symbol in rules text) and, at +/// the default scale, stays inside the font's ascent and descent so the leading doesn't change. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct InlineArt { + /// Name of the document symbol ([`crate::Symbol::name`]). + pub symbol: String, + /// Art height as a multiple of the run's font size. + #[serde(default = "one")] + pub scale: f64, + /// Extra raise in points (positive = up). + #[serde(default)] + pub baseline_shift: f64, + /// The symbol art's visual bounds at its natural size, resolved from the document's symbols by + /// [`crate::Document::resolve_inline_art`] (not saved). `None`: not resolved or missing; the + /// layout then reserves a one-em square and nothing is drawn. + #[serde(skip)] + pub bounds: Option, +} + +fn one() -> f64 { + 1.0 +} + +fn fifty() -> f64 { + 50.0 +} + +impl InlineArt { + pub fn new(symbol: impl Into) -> Self { + Self { symbol: symbol.into(), scale: 1.0, baseline_shift: 0.0, bounds: None } + } + /// `scale`, made finite and positive (untrusted input). + pub fn safe_scale(&self) -> f64 { + if self.scale.is_finite() && self.scale > 0.0 { self.scale.min(INLINE_MAX_SCALE) } else { 1.0 } + } + /// `baseline_shift`, made finite (untrusted input). + pub fn safe_shift(&self) -> f64 { + if self.baseline_shift.is_finite() { self.baseline_shift.clamp(-1e5, 1e5) } else { 0.0 } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum TextKind { + /// Point type: anchored at the baseline origin of the first line. + Point, + /// Area type flowed inside `frame` (document coordinates, untransformed by `xf`). + Area { frame: PathData }, + /// Type on a path, flowing from its start bracket `start` to its end bracket `end` (0..1 of the + /// path length; no `end`: the end of the path, or once round a closed path). See + /// [`TextKind::path_span`]. + OnPath { + path: PathData, + start: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + end: Option, + }, +} + +impl TextKind { + /// Type on a path's span: from its start to its end bracket, as fractions of its path's length. + /// Round a closed path the end may be past 1 (the span runs on past the path's start), a full + /// turn without an end or with the end at the start. None for other type. + pub fn path_span(&self) -> Option<(f64, f64)> { + let TextKind::OnPath { path, start, end } = self else { return None }; + let s = fraction(*start); + Some(if path.is_closed() { + let run = end.map_or(0.0, |e| (fraction(e) - s).rem_euclid(1.0)); + (s, s + if run < 1e-9 { 1.0 } else { run }) + } else { + (s, end.map_or(1.0, |e| fraction(e).max(s))) + }) + } +} + +/// Move anchors `refs` of `path`, in text space, by `d` in document space (`to_text`: the +/// document → text map). False when an anchor doesn't exist. +pub(super) fn move_anchors(path: &mut PathData, to_text: Affine, refs: &[(usize, usize)], d: Vec2) -> bool { + // A distance: only the linear part of the document → text map applies. + let local = to_text * d.to_point() - to_text * Point::ZERO; + refs.iter().all(|&(si, ai)| path.anchor_mut(si, ai).map(|a| a.translate(local)).is_some()) +} + +/// `x` as a fraction of a path's length (0..1; 0 when not finite). +fn fraction(x: f64) -> f64 { + if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 } +} + +/// `path` run the other way, each point as far from its new start as it was from its old end +/// (the subpaths in reverse order, a closed one keeping its first anchor first). +pub(super) fn reverse_from_end(path: &mut PathData) { + path.subpaths.reverse(); + for sp in &mut path.subpaths { + sp.reverse(); + if sp.closed && !sp.anchors.is_empty() { + sp.anchors.rotate_right(1); + } + } +} + +/// Where ruby (furigana) text sits: above its base text in horizontal type, right of it in +/// vertical type (the Japanese convention), or below (left in vertical type). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum RubyPosition { + #[default] + Above, + Below, +} + +/// How ruby text lines up over its base text when the two are different widths. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum RubyAlign { + /// Centred over the base text. + #[default] + Center, + /// Starting at the base text's start (left in horizontal type, top in vertical). + Start, + /// Ending at the base text's end (right in horizontal type, bottom in vertical). + End, +} + +/// Ruby (furigana, phonetic guide): a reading set over a range of the text. +/// +/// `start`/`end` are byte offsets into [`TextObject::plain_text`] (the same space as +/// [`crate::TextObject`] commands' `start`/`end`). The base text itself stays the text; +/// emptying the reading removes the ruby. New ruby is half the base text's size, centred, and +/// allowed to overhang neighbouring characters when the reading is longer than its base. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RubySpan { + /// Byte offset of the first base character in the plain text. + pub start: usize, + /// Byte offset just past the last base character. + pub end: usize, + /// The reading, set in the base characters' font (its size comes from `size_percent`). + pub text: String, + #[serde(default)] + pub position: RubyPosition, + #[serde(default)] + pub align: RubyAlign, + /// Ruby size as a percentage of the base text's size, 1–100 (50 = half, the usual). + #[serde(default = "fifty")] + pub size_percent: f64, + /// Let a reading wider than its base hang over the neighbouring characters instead of being + /// squeezed to the base's width. + #[serde(default = "yes")] + pub overhang: bool, +} + +impl RubySpan { + /// Ruby over `start..end` with reading `text`, at the defaults (half size, centred, overhanging). + pub fn new(start: usize, end: usize, text: impl Into) -> Self { + Self { start, end, text: text.into(), position: RubyPosition::Above, align: RubyAlign::Center, size_percent: 50.0, overhang: true } + } + /// `size_percent` made finite and usable: 1–100% (untrusted input). + pub fn safe_size_percent(&self) -> f64 { + if self.size_percent.is_finite() { self.size_percent.clamp(1.0, 100.0) } else { 50.0 } + } +} diff --git a/crates/doc/src/text/tabs_lists.rs b/crates/doc/src/text/tabs_lists.rs new file mode 100644 index 0000000000..763a82c69d --- /dev/null +++ b/crates/doc/src/text/tabs_lists.rs @@ -0,0 +1,249 @@ +use super::char_style::{CharPosition, CharStyle}; +use super::*; + +/// Tab stop alignment (Tabs panel). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TabAlign { + #[default] + Left, + Center, + Right, + /// Aligns on the first `align_on` character (a decimal point by default). + Decimal, +} + +/// A tab stop, measured from the left edge of the text (area type: the frame's left edge). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TabStop { + pub position: f64, + #[serde(default)] + pub align: TabAlign, + /// Leader characters repeated across the tab's gap (e.g. ". "). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub leader: String, + /// Decimal tabs align on this character. + #[serde(default = "default_align_on")] + pub align_on: char, +} + +fn default_align_on() -> char { + '.' +} + +/// Distance between default tab stops when no explicit stop applies (½ inch). +pub const DEFAULT_TAB_INTERVAL: f64 = 36.0; + +/// The bullet of a bulleted list ([`ParaList::bullet`]): the Paragraph panel's Bullets presets. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Bullet { + /// A filled dot (•). + #[default] + Dot, + /// A dash (–). + Dash, + /// A hollow circle (◦). + Circle, + /// A filled square (▪). + Square, +} + +impl Bullet { + /// The character the layout draws for the bullet. + pub fn character(self) -> char { + match self { + Bullet::Dot => '\u{2022}', + Bullet::Dash => '\u{2013}', + Bullet::Circle => '\u{25E6}', + Bullet::Square => '\u{25AA}', + } + } +} + +/// How a numbered list writes its numbers ([`ParaList::number`]): the Paragraph panel's Numbered +/// List presets. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum NumberStyle { + /// 1, 2, 3… + #[default] + Arabic, + /// A, B, C… Z, AA, BB… + UpperLetters, + /// a, b, c… z, aa, bb… + LowerLetters, + /// I, II, III, IV… + UpperRoman, + /// i, ii, iii, iv… + LowerRoman, + /// 01, 02… 99, 100… + TwoDigits, + /// 001, 002… 999, 1000… + ThreeDigits, +} + +/// Past this number, roman numerals and letters are written in Arabic digits. +const MAX_LETTERS_OR_ROMAN: u32 = 3999; + +impl NumberStyle { + /// Every style, in the order the Numbered List presets list them. + pub const ALL: [NumberStyle; 7] = [ + NumberStyle::Arabic, + NumberStyle::UpperLetters, + NumberStyle::LowerLetters, + NumberStyle::UpperRoman, + NumberStyle::LowerRoman, + NumberStyle::TwoDigits, + NumberStyle::ThreeDigits, + ]; + + /// Number `n` (1 or more) written in this style, without a separator. Letters run A to Z, then + /// AA to ZZ, then AAA and so on; roman numerals use the subtractive forms (IV, IX, XL, XC, CD, + /// CM); both are written in Arabic digits past 3999. Two and three digits pad with zeros and + /// keep every digit of a longer number. + pub fn format(self, n: u32) -> String { + let letters_or_roman = + matches!(self, NumberStyle::UpperLetters | NumberStyle::LowerLetters | NumberStyle::UpperRoman | NumberStyle::LowerRoman); + if n == 0 || (letters_or_roman && n > MAX_LETTERS_OR_ROMAN) { + return n.to_string(); + } + match self { + NumberStyle::Arabic => n.to_string(), + NumberStyle::TwoDigits => format!("{n:02}"), + NumberStyle::ThreeDigits => format!("{n:03}"), + NumberStyle::UpperLetters => letters(n), + NumberStyle::LowerLetters => letters(n).to_lowercase(), + NumberStyle::UpperRoman => roman(n), + NumberStyle::LowerRoman => roman(n).to_lowercase(), + } + } +} + +/// `n` (1 or more) in capital letters: A to Z, then each letter twice, three times and so on. +fn letters(n: u32) -> String { + let n = n - 1; + let letter = char::from(b'A' + (n % 26) as u8); + std::iter::repeat_n(letter, (n / 26 + 1) as usize).collect() +} + +/// `n` (1 to 3999) in capital roman numerals. +fn roman(mut n: u32) -> String { + const DIGITS: [(u32, &str); 13] = [ + (1000, "M"), + (900, "CM"), + (500, "D"), + (400, "CD"), + (100, "C"), + (90, "XC"), + (50, "L"), + (40, "XL"), + (10, "X"), + (9, "IX"), + (5, "V"), + (4, "IV"), + (1, "I"), + ]; + let mut s = String::new(); + for (value, digits) in DIGITS { + while n >= value { + s.push_str(digits); + n -= value; + } + } + s +} + +/// The list a paragraph is in (Paragraph panel › Bullets and Numbered List). The layout draws the +/// list's marker before the paragraph's first line, in the font, size and color of the paragraph's +/// first character without its baseline shift, rotation, superscript or subscript, tracking, manual +/// kerning, tate-chu-yoko, underline and strikethrough ([`Self::marker_style`]), and the text after +/// it starts at the next tab stop, the left indent counting as a stop. The marker is not a +/// character of the text, and an empty paragraph has none. A saved list reads the fields it leaves +/// out as their defaults, and a build ignores the fields it doesn't know. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(default)] +pub struct ParaList { + /// The bullet each paragraph of a bulleted list starts with. A numbered list keeps it for + /// when the list is made bulleted again. + pub bullet: Bullet, + /// A numbered list's number style. A bulleted list has none, and the file saves it only for a + /// numbered list. + #[serde(skip_serializing_if = "Option::is_none")] + pub number: Option, +} + +impl ParaList { + /// A bulleted list with `bullet`. + pub fn bulleted(bullet: Bullet) -> Self { + Self { bullet, number: None } + } + + /// A numbered list with `style`. + pub fn numbered(style: NumberStyle) -> Self { + Self { bullet: Bullet::default(), number: Some(style) } + } + + /// The characters of the marker the layout draws before the paragraph: the bullet, or for a + /// numbered list number `n` in its style followed by a period. + pub fn marker(&self, n: u32) -> String { + match self.number { + Some(style) => format!("{}.", style.format(n)), + None => self.bullet.character().to_string(), + } + } + + /// The marker of the next paragraph of a story, whose list is `list` (None: in no list) and + /// which holds no text when `empty`, with `count` the numbered paragraphs counted before it. + /// A paragraph in no list sets the count back to 0 and has no marker; an empty paragraph has + /// none and leaves the count as it is; a bulleted paragraph has its bullet and leaves the + /// count as it is; a numbered paragraph adds one to the count and is numbered with it. + pub fn next_marker(list: Option, empty: bool, count: &mut u32) -> Option { + let Some(list) = list else { + *count = 0; + return None; + }; + if empty { + return None; + } + if list.number.is_some() { + *count = count.saturating_add(1); + } + Some(list.marker(*count)) + } + + /// 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. + pub fn marker_style(first: &CharStyle) -> CharStyle { + CharStyle { + baseline_shift: 0.0, + rotation: 0.0, + position: CharPosition::Normal, + tracking: 0.0, + kerning: None, + tate_chu_yoko: false, + underline: false, + strikethrough: false, + ..first.clone() + } + } + + /// The list that the Type tool starts when `typed` and a space are typed at the start of a + /// paragraph: "1." or "1)" starts a numbered list in 1, 2, 3, "A." or "A)" starts one in A, B, + /// C, and "*", "#", ">" or "+" starts a bulleted list with the filled dot. Any other text starts + /// none. + pub fn typed(typed: &str) -> Option { + match typed { + "1." | "1)" => Some(Self::numbered(NumberStyle::Arabic)), + "A." | "A)" => Some(Self::numbered(NumberStyle::UpperLetters)), + "*" | "#" | ">" | "+" => Some(Self::bulleted(Bullet::Dot)), + _ => None, + } + } +} + +/// The left and first-line indents (pt) a list gives a paragraph whose indents are both 0: the +/// marker hangs in the first line's 18 pt before the text. +pub const LIST_HANGING_INDENT: f64 = 18.0; diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs new file mode 100644 index 0000000000..54142efd7f --- /dev/null +++ b/crates/doc/src/text/tests.rs @@ -0,0 +1,335 @@ +use super::*; + +/// Character Direction is saved only when set, and styles written before it existed read as +/// Default. +#[test] +fn character_direction_is_saved_only_when_set() { + let st = CharStyle::default(); + assert_eq!(st.char_direction, None); + assert!(serde_json::to_value(&st).unwrap().get("charDirection").is_none()); + for (d, key) in [(ParaDirection::LeftToRight, "leftToRight"), (ParaDirection::RightToLeft, "rightToLeft")] { + let set = CharStyle { char_direction: Some(d), ..CharStyle::default() }; + assert_eq!(serde_json::to_value(&set).unwrap()["charDirection"], key); + assert_eq!(serde_json::from_value::(serde_json::to_value(&set).unwrap()).unwrap(), set); + } + let old = serde_json::to_value(&st).unwrap(); + assert_eq!(serde_json::from_value::(old).unwrap().char_direction, None); +} + +/// Ruby saves with the type and a file saved before it (no `ruby` key) reads with none. +#[test] +fn ruby_is_saved_and_missing_ruby_reads_as_none() { + let mut t = TextObject::point(Point::ZERO, "漢字", CharStyle::default()); + t.ruby = vec![RubySpan { size_percent: 40.0, overhang: false, ..RubySpan::new(0, 6, "かんじ") }]; + let json = serde_json::to_string(&t).unwrap(); + assert!(json.contains("かんじ")); + let back: TextObject = serde_json::from_str(&json).unwrap(); + assert_eq!(back.ruby, t.ruby); + assert!((back.ruby[0].size_percent - 40.0).abs() < 1e-9 && !back.ruby[0].overhang); + // Old files have no `ruby` key: none. + let mut old: serde_json::Value = serde_json::from_str(&json).unwrap(); + old.as_object_mut().unwrap().remove("ruby"); + assert!(serde_json::from_value::(old).unwrap().ruby.is_empty()); + // A damaged file's range past the text and its empty reading are clamped away. + let mut damaged = t.clone(); + damaged.ruby = vec![RubySpan::new(0, 10_000, "かんじ"), RubySpan::new(3, 2, " "), RubySpan::new(0, 3, "")]; + damaged.normalize_ruby(); + assert_eq!((damaged.ruby[0].start, damaged.ruby[0].end), (0, 6)); +} + +/// Digits map every digit of the three sets into the chosen one, leave the rest alone, and +/// are saved only when set. +#[test] +fn digits_map_between_the_numeral_systems() { + let map = |d: Digits, s: &str| -> String { s.chars().map(|c| d.map(c)).collect() }; + for s in ["0123456789", "٠١٢٣٤٥٦٧٨٩", "۰۱۲۳۴۵۶۷۸۹"] { + assert_eq!(map(Digits::Default, s), s); + assert_eq!(map(Digits::Arabic, s), "0123456789"); + assert_eq!(map(Digits::Hindi, s), "٠١٢٣٤٥٦٧٨٩"); + assert_eq!(map(Digits::Farsi, s), "۰۱۲۳۴۵۶۷۸۹"); + } + // Letters, punctuation and other scripts' digits (Devanagari ३) are not digits of these sets. + assert_eq!(map(Digits::Hindi, "a-Z ३ ٪ ۔"), "a-Z ३ ٪ ۔"); + let st = CharStyle::default(); + assert!(serde_json::to_value(&st).unwrap().get("digits").is_none()); + let farsi = CharStyle { digits: Digits::Farsi, ..CharStyle::default() }; + assert_eq!(serde_json::to_value(&farsi).unwrap()["digits"], "farsi"); + // Styles written before the attribute existed (no `digits` key) read as Default. + let old = serde_json::to_value(&st).unwrap(); + assert_eq!(serde_json::from_value::(old).unwrap().digits, Digits::Default); + assert_eq!(serde_json::from_value::(serde_json::to_value(&farsi).unwrap()).unwrap(), farsi); +} + +/// Auto leading follows the paragraph's Auto Leading; a set leading doesn't. +#[test] +fn paragraph_effective_leading_follows_auto_leading() { + let st = CharStyle { size: 10.0, leading: None, ..CharStyle::default() }; + let mut para = ParaStyle::default(); + assert_eq!(para.effective_leading(&st), st.effective_leading(), "default 120%"); + para.justification.auto_leading = 200.0; + assert_eq!(para.effective_leading(&st), 20.0); + para.justification.auto_leading = 0.0; + assert_eq!(para.effective_leading(&st), 0.0); + let set = CharStyle { leading: Some(14.0), ..st.clone() }; + assert_eq!(para.effective_leading(&set), 14.0); + para.justification.auto_leading = f64::NAN; + assert_eq!(para.effective_leading(&st), st.effective_leading(), "not a number"); +} + +/// A file can't feed layout justification values `text.setFormat` would refuse: each is +/// clamped to its range, one that isn't finite takes its default, and a Minimum, Desired and +/// Maximum out of order go back to their defaults. +#[test] +fn justification_options_read_from_a_file_stay_in_range() { + let d = JustificationOptions::default(); + let read: ParaStyle = serde_json::from_value(serde_json::json!({ + "justification": { + "word_spacing": [-5.0, 1e300, 1e308], "letter_spacing": [10.0, 5.0, 20.0], + "glyph_scaling": [1.0, 100.0, 9e9], "auto_leading": -1e12 + } + })) + .unwrap(); + let j = read.justification; + assert_eq!(j.word_spacing, [0.0, 1000.0, 1000.0]); + assert_eq!(j.letter_spacing, d.letter_spacing, "out of order"); + assert_eq!(j.glyph_scaling, [50.0, 100.0, 200.0]); + assert_eq!(j.auto_leading, 0.0); + let mut j = JustificationOptions { + word_spacing: [f64::NAN, 100.0, f64::INFINITY], + letter_spacing: [-1.0, 0.0, f64::NEG_INFINITY], + auto_leading: f64::NAN, + ..d.clone() + }; + j.keep_in_range(); + assert_eq!((j.word_spacing, j.letter_spacing, j.auto_leading), (d.word_spacing, [-1.0, 0.0, 0.0], d.auto_leading)); + let mut same = d.clone(); + same.keep_in_range(); + assert_eq!(same, d); +} + +/// 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 +/// starts again after a paragraph in no list. A list from before number styles reads as +/// bulleted, and a bulleted list saves no number style. +#[test] +fn number_styles_write_their_numbers_and_roll_over() { + let numbers = |style: NumberStyle, ns: &[u32]| ns.iter().map(|&n| style.format(n)).collect::>(); + assert_eq!(numbers(NumberStyle::Arabic, &[1, 9, 10, 123]), ["1", "9", "10", "123"]); + assert_eq!( + numbers(NumberStyle::UpperLetters, &[1, 2, 26, 27, 28, 52, 53, 3999, 4000]), + ["A", "B", "Z", "AA", "BB", "ZZ", "AAA", &"U".repeat(154), "4000"] + ); + assert_eq!(numbers(NumberStyle::LowerLetters, &[1, 26, 27]), ["a", "z", "aa"]); + assert_eq!( + numbers(NumberStyle::UpperRoman, &[1, 2, 3, 4, 5, 9, 14, 40, 90, 400, 1994, 3999, 4000]), + ["I", "II", "III", "IV", "V", "IX", "XIV", "XL", "XC", "CD", "MCMXCIV", "MMMCMXCIX", "4000"] + ); + assert_eq!(numbers(NumberStyle::LowerRoman, &[1, 4, 9, 12]), ["i", "iv", "ix", "xii"]); + assert_eq!(numbers(NumberStyle::TwoDigits, &[1, 9, 10, 99, 100]), ["01", "09", "10", "99", "100"]); + assert_eq!(numbers(NumberStyle::ThreeDigits, &[1, 10, 999, 1000]), ["001", "010", "999", "1000"]); + assert_eq!(ParaList::numbered(NumberStyle::UpperRoman).marker(4), "IV."); + assert_eq!(ParaList::bulleted(Bullet::Square).marker(4), "\u{25AA}"); + let (num, dot) = (Some(ParaList::numbered(NumberStyle::Arabic)), Some(ParaList::bulleted(Bullet::Dot))); + let mut count = 0; + let markers: Vec> = [(num, false), (num, true), (dot, false), (num, false), (None, false), (num, false)] + .iter() + .map(|&(l, empty)| ParaList::next_marker(l, empty, &mut count)) + .collect(); + assert_eq!(markers, [Some("1.".into()), None, Some("\u{2022}".into()), Some("2.".into()), None, Some("1.".into())]); + assert_eq!(count, 1); + let read = |v: serde_json::Value| serde_json::from_value::(v).unwrap(); + assert_eq!(read(serde_json::json!({"bullet": "dash"})), ParaList::bulleted(Bullet::Dash)); + assert_eq!(read(serde_json::json!({"number": "threeDigits"})), ParaList::numbered(NumberStyle::ThreeDigits)); + assert_eq!(serde_json::to_value(ParaList::bulleted(Bullet::Dash)).unwrap(), serde_json::json!({"bullet": "dash"})); + assert_eq!( + serde_json::to_value(ParaList::numbered(NumberStyle::LowerRoman)).unwrap(), + serde_json::json!({"bullet": "dot", "number": "lowerRoman"}) + ); +} + +/// Typed list detection: "1.", "1)", "A." and "A)" and a space at the start of a paragraph +/// start a numbered list, and "*", "#", ">" and "+" and a space start a bulleted list with the +/// filled dot. Other text, the same characters later in a paragraph or without the space, and +/// a paragraph already in a list start nothing. +#[test] +fn typed_list_starts_are_found_at_a_paragraphs_start() { + let (arabic, letters, dot) = + (ParaList::numbered(NumberStyle::Arabic), ParaList::numbered(NumberStyle::UpperLetters), ParaList::bulleted(Bullet::Dot)); + let typed = ["1.", "1)", "A.", "A)", "*", "#", ">", "+"].map(ParaList::typed); + assert_eq!(typed, [arabic, arabic, letters, letters, dot, dot, dot, dot].map(Some)); + for other in ["", "2.", "a.", "a)", "I.", "1", "A", "1:", "-", "•", "1.)", " 1.", "*1", "1."] { + assert_eq!(ParaList::typed(other), None, "{other:?}"); + } + let mut t = TextObject::point(Point::ZERO, "Fruit\n1. Apples\nA) x * y\n+ ", CharStyle::default()); + assert_eq!(t.typed_list_at(9), Some((6, arabic))); + assert_eq!(t.typed_list_at(19), Some((16, letters))); + assert_eq!(t.typed_list_at(27), Some((25, dot))); + // Not at the paragraph's start, not right after the space, or past the end. + for at in [0, 5, 8, 10, 15, 23, 25, 26, 99] { + assert_eq!(t.typed_list_at(at), None, "{at}"); + } + let mut styles = t.paragraph_styles(); + styles[1].list = Some(ParaList::bulleted(Bullet::Square)); + t.set_paragraph_styles(styles); + assert_eq!(t.typed_list_at(9), None, "a list paragraph stays as it is"); + assert_eq!(t.typed_list_at(19), Some((16, letters))); +} + +#[test] +fn character_controls_reject_collapsed_and_nonfinite_transforms() { + let mut t = TextObject::point(Point::ZERO, "Text", CharStyle::default()); + for matrix in [[0.0; 6], [1.0, 1.0, 2.0, 2.0, 0.0, 0.0], [f64::INFINITY, 0.0, 0.0, 1.0, 0.0, 0.0], [1.0, 0.0, 0.0, 1.0, f64::NAN, 0.0]] { + t.xf = Affine::new(matrix); + assert!(t.effective_char_style(&t.first_style()).is_none()); + } + t.xf = Affine::rotate(0.83); + assert_eq!(t.effective_char_style(&t.first_style()).unwrap().size, 12.0); + t.xf = Affine::scale(1e308); + assert!(t.effective_char_style(&t.first_style()).is_none(), "overflowing point size"); +} + +#[test] +fn point_text_basics() { + let t = TextObject::point(Point::new(10.0, 20.0), "Hello", CharStyle::default()); + assert_eq!(t.plain_text(), "Hello"); + let b = t.bounds().unwrap(); + assert!(b.x0 >= 10.0 - 1e-9 && b.y1 > 20.0); + assert_eq!(CharStyle::default().effective_leading(), 14.399999999999999); +} + +fn justified(j: Justify) -> ParaStyle { + ParaStyle { justify: j, ..ParaStyle::default() } +} + +#[test] +fn paragraph_styles_split_merge_and_normalize() { + let mut t = TextObject::point(Point::ZERO, "one\ntwo\nthree", CharStyle::default()); + assert_eq!((t.paragraph_count(), t.paras.len()), (3, 0), "one style for all: nothing stored"); + assert_eq!(t.paragraphs_in(0, 0), 0..1); + assert_eq!(t.paragraphs_in(4, 4), 1..2); + assert_eq!(t.paragraphs_in(2, 9), 0..3); + assert_eq!(t.paragraphs_in(99, 99), 2..3, "clamped to the text"); + t.edit_paras(Some(1..2), |p| p.justify = Justify::Center); + let js = |t: &TextObject| t.paragraph_styles().iter().map(|p| p.justify).collect::>(); + assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Left]); + // Return inside "two": the new paragraph continues its style. + t.splice_paras(5, 5, "\n"); + t.runs[0].text.insert(5, '\n'); + assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Center, Justify::Left]); + // Deleting the break between "one" and "t": the first paragraph's style wins. + t.splice_paras(3, 4, ""); + t.runs[0].text.remove(3); + assert_eq!(t.plain_text(), "onet\nwo\nthree"); + assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Left]); + // An edit that skips the splice is repaired by normalizing (the last style continues). + t.runs[0].text.push_str("\nfour"); + t.normalize_paras(); + assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Left, Justify::Left]); + // `para` is paragraph 0's; all alike collapses to `para` alone. + t.edit_paras(Some(0..1), |p| p.justify = Justify::Right); + assert_eq!(t.para.justify, Justify::Right); + t.edit_paras(None, |p| p.justify = Justify::Right); + assert!(t.paras.is_empty() && t.para.justify == Justify::Right); + // A short list repeats its last entry, a long one is cut. + t.set_paragraph_styles(vec![justified(Justify::Left), justified(Justify::Center)]); + assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Center, Justify::Center]); + t.set_paragraph_styles(vec![justified(Justify::Center); 9]); + assert!(t.paras.is_empty() && t.para.justify == Justify::Center); + // Old documents (no `paras`) load; new ones keep paragraph 0 in `para`. + t.edit_paras(Some(3..4), |p| p.space_before = 4.0); + let json = serde_json::to_value(&t).unwrap(); + assert_eq!(json["para"]["justify"], json["paras"][0]["justify"]); + let mut old = json.clone(); + old.as_object_mut().unwrap().remove("paras"); + let back: TextObject = serde_json::from_value(old).unwrap(); + assert!(back.paras.is_empty() && back.para_at(3).justify == Justify::Center); + let back: TextObject = serde_json::from_value(json).unwrap(); + assert_eq!(back.para_at(3).space_before, 4.0); +} + +/// 120 × 40 area type at (40, 40), its text drawn at twice its size. +fn area_type() -> TextObject { + let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default()); + t.kind = TextKind::Area { frame: vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 20.0)) }; + t.xf = Affine::translate((40.0, 40.0)) * Affine::scale(2.0); + t +} + +#[test] +fn area_resizes_its_frame_and_keeps_its_type() { + let mut t = area_type(); + assert_eq!(t.bounds(), Some(Rect::new(40.0, 40.0, 160.0, 80.0))); + // Bottom-right handle to (200, 140), about the top-left corner. + let o = Affine::translate((40.0, 40.0)); + assert!(t.transform_area(o * Affine::scale_non_uniform(160.0 / 120.0, 100.0 / 40.0) * o.inverse())); + assert_eq!(t.xf, Affine::translate((40.0, 40.0)) * Affine::scale(2.0), "the type keeps its size"); + let b = t.bounds().unwrap(); + assert!((b.x1 - 200.0).abs() < 1e-9 && (b.y1 - 140.0).abs() < 1e-9 && b.x0 == 40.0, "{b:?}"); + assert_eq!(t.area_frame().unwrap().bounds(), Some(b)); + // Point type has no area; a degenerate transform or a non-finite frame changes nothing. + let mut p = TextObject::point(Point::ZERO, "x", CharStyle::default()); + assert!(!p.transform_area(Affine::scale(2.0)) && p.area_frame().is_none()); + let before = t.clone(); + assert!(!t.transform_area(Affine::scale(f64::INFINITY))); + t.xf = Affine::scale(0.0); + assert!(!t.transform_area(Affine::scale(2.0))); + t.xf = before.xf; + assert_eq!(t, before); +} + +#[test] +fn area_anchors_move_in_document_space() { + let mut t = area_type(); + // The bottom-right corner (anchor 2) 20 pt right: 10 pt in text space at 2×. + assert!(t.move_area_anchors(&[(0, 2)], Vec2::new(20.0, 0.0))); + let TextKind::Area { frame } = &t.kind else { panic!() }; + assert_eq!(frame.subpaths[0].anchors[2].p, Point::new(70.0, 20.0)); + assert_eq!(frame.subpaths[0].anchors[1].p, Point::new(60.0, 0.0), "the others stay"); + // A missing anchor changes nothing. + let before = t.clone(); + assert!(!t.move_area_anchors(&[(0, 1), (0, 9)], Vec2::new(5.0, 5.0))); + assert!(!t.move_area_anchors(&[(3, 0)], Vec2::new(5.0, 5.0))); + assert_eq!(t, before); +} + +/// Builds from before [`Justify::Auto`] read new type's alignment as Left or Right (and ignore +/// `justify_auto`); this build reads Auto back. +#[test] +fn auto_alignment_saves_readable_by_older_builds() { + #[derive(Deserialize, Debug, PartialEq)] + enum OldJustify { + Left, + Center, + Right, + JustifyLeft, + JustifyCenter, + JustifyRight, + JustifyAll, + } + #[derive(Deserialize)] + struct OldPara { + justify: OldJustify, + } + #[derive(Deserialize)] + struct OldText { + para: OldPara, + } + for (direction, physical) in + [(Some(ParaDirection::RightToLeft), OldJustify::Right), (Some(ParaDirection::LeftToRight), OldJustify::Left), (None, OldJustify::Left)] + { + let mut t = TextObject::point(Point::ZERO, "שלום", CharStyle::default()); + t.para = ParaStyle { justify: Justify::Auto, direction, ..Default::default() }; + let json = serde_json::to_string(&t).unwrap(); + let old: OldText = serde_json::from_str(&json).unwrap(); + assert_eq!(old.para.justify, physical, "{json}"); + assert_eq!(serde_json::from_str::(&json).unwrap(), t); + } + // Other alignments save as before, without the flag. + let p = ParaStyle { justify: Justify::Right, ..Default::default() }; + let json = serde_json::to_string(&p).unwrap(); + assert!(!json.contains("justify_auto"), "{json}"); + assert_eq!(serde_json::from_str::(&json).unwrap(), p); + // Files from before the flag keep their alignment. + assert_eq!(serde_json::from_str::(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center); +} diff --git a/crates/doc/src/trace.rs b/crates/doc/src/trace.rs index 5155cc21fd..042d6b3ada 100644 --- a/crates/doc/src/trace.rs +++ b/crates/doc/src/trace.rs @@ -89,4 +89,54 @@ mod tests { g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "sepia"}))); assert_eq!(g.trace_view(), TraceView::Result); } + #[test] + fn live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle() { + use crate::{Appearance, Document, ImageObject, NodeId, NodeKind}; + use std::sync::Arc; + use vectorcraft_geom::{Affine, PathData, Point, Rect, SubPath}; + let mut source = Node::new( + NodeId(2), + NodeKind::Image(Box::new(ImageObject { + key: "synthetic".into(), + width: 200, + height: 200, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + })), + ); + source.visible = false; + let art = Node::path( + NodeId(3), + PathData::single(SubPath::polyline( + &[Point::new(20.0, 30.0), Point::new(80.0, 30.0), Point::new(80.0, 90.0), Point::new(20.0, 90.0)], + true, + )), + Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0), + ); + let mut group = Node::group(NodeId(1), vec![Arc::new(source), Arc::new(art.clone())]); + group.extras_mut().trace = Some(Box::new(serde_json::json!({}))); + let doc = Document::new(300.0, 300.0); + for view in TraceView::ALL { + group.extras_mut().trace = Some(Box::new(serde_json::json!({"view":view.id()}))); + let want = if view.shows_source() { Rect::new(0.0, 0.0, 200.0, 200.0) } else { Rect::new(20.0, 30.0, 80.0, 90.0) }; + assert_eq!(group.geometric_bounds(), Some(want)); + assert_eq!(group.visual_bounds(), Some(want)); + if !view.shows_source() { + for angle in [0.0_f64, 30.0, 90.0] { + let xf = Affine::rotate(angle.to_radians()); + for visual in [false, true] { + assert_eq!(group.bounds_in(&doc.symbol_boxes(), xf, visual), art.bounds_in(&doc.symbol_boxes(), xf, visual)); + } + } + } + } + group.extras_mut().trace = None; + assert_eq!( + group.geometric_bounds(), + Some(Rect::new(0.0, 0.0, 200.0, 200.0)), + "ordinary hidden group members retain their existing bounds policy" + ); + } } diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs new file mode 100644 index 0000000000..1b09c4e7b3 --- /dev/null +++ b/crates/doc/src/units.rs @@ -0,0 +1,293 @@ +use super::*; + +/// Measurement units (display only; the model is always in points). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum Unit { + #[default] + Points, + Picas, + Inches, + Millimeters, + Centimeters, + Pixels, + FeetInches, + Meters, + Yards, + Feet, +} + +impl Unit { + pub const ALL: [Unit; 10] = [ + Unit::Points, + Unit::Picas, + Unit::Inches, + Unit::Millimeters, + Unit::Centimeters, + Unit::Pixels, + Unit::FeetInches, + Unit::Meters, + Unit::Yards, + Unit::Feet, + ]; + /// Points per unit. + pub fn points(self) -> f64 { + match self { + Unit::Points | Unit::Pixels => 1.0, + Unit::Picas => 12.0, + Unit::Inches => 72.0, + Unit::Millimeters => 72.0 / 25.4, + Unit::Centimeters => 72.0 / 2.54, + Unit::Meters => 72.0 / 0.0254, + Unit::Yards => 72.0 * 36.0, + Unit::Feet | Unit::FeetInches => 72.0 * 12.0, + } + } + pub fn suffix(self) -> &'static str { + match self { + Unit::Points => "pt", + Unit::Picas => "p", + Unit::Inches => "in", + Unit::Millimeters => "mm", + Unit::Centimeters => "cm", + Unit::Pixels => "px", + Unit::FeetInches | Unit::Feet => "ft", + Unit::Meters => "m", + Unit::Yards => "yd", + } + } + pub fn label(self) -> &'static str { + match self { + Unit::Points => "Points", + Unit::Picas => "Picas", + Unit::Inches => "Inches", + Unit::Millimeters => "Millimeters", + Unit::Centimeters => "Centimeters", + Unit::Pixels => "Pixels", + Unit::FeetInches => "Feet & Inches", + Unit::Meters => "Meters", + Unit::Yards => "Yards", + Unit::Feet => "Feet", + } + } + /// The rulers' label step at `zoom` (screen pixels per point), in this unit: the first of + /// 1, 2, 5 × 10ⁿ that puts labels at least 50 pixels apart. Ticks mark every tenth of it. + pub fn ruler_step(self, zoom: f64) -> f64 { + const DECIMAL: [f64; 19] = + [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0]; + // An inch is divided in half, not in ten: a tenth of an inch is not a mark an inch ruler + // carries, so below an inch the steps are binary fractions (#2827). Labelling stops at a + // sixteenth; zooming in past that leaves the labels where they are and only the ticks + // between them grow denser, down to a hundred and twenty-eighth + // ([`Self::ruler_minor`]). A label is at most six characters that way ("0.0625"), which + // the left ruler has room for when it spells one down the ruler a character at a time. + // From an inch up the ladder is the shared one. + const BINARY: [f64; 15] = [1.0 / 16.0, 0.125, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 10000.0]; + let steps: &[f64] = if self.ruler_halves() { &BINARY } else { &DECIMAL }; + steps.iter().copied().find(|s| s * self.points() * zoom >= 50.0).unwrap_or(10000.0) + } + /// Does this unit's ruler divide a step in half rather than in ten? Inches do; the metric + /// units, points, pixels and picas are read in tenths. + fn ruler_halves(self) -> bool { + matches!(self, Unit::Inches) + } + /// The unlabelled ticks between two labels, `step` apart ([`Self::ruler_step`]): an eighth of + /// the step on an inch ruler, so every tick is a binary fraction of an inch and they stay about + /// as dense as the tenths elsewhere; a tenth of it otherwise. + pub fn ruler_minor(self, step: f64) -> f64 { + if self.ruler_halves() { step / 8.0 } else { step / 10.0 } + } + /// `v` (points) on the nearest ruler tick at `zoom` ([`Self::ruler_step`]). + pub fn snap_to_ruler_tick(self, v: f64, zoom: f64) -> f64 { + let tick = self.ruler_minor(self.ruler_step(zoom)) * self.points(); + (v / tick).round() * tick + } + pub fn from_pt(self, v: f64) -> f64 { + v / self.points() + } + pub fn to_pt(self, v: f64) -> f64 { + v * self.points() + } + /// Format a point value in this unit the way fields show it (e.g. `12.5 pt`, `3 in`). + pub fn format(self, pt: f64) -> String { + format!("{} {}", self.number(pt), self.suffix()) + } + /// [`Unit::format`] without the suffix (`12.5`), for narrow fields. + pub fn number(self, pt: f64) -> String { + // Three decimals for the small units (`595.276 pt`), four for the large ones (`8.2677 in`, + // `35.2778 mm`, the `0.0078 in` stroke preset); trailing zeros are trimmed (`1 pt` is `1`). + let decimals = if matches!(self, Unit::Points | Unit::Pixels | Unit::Picas) { 3 } else { 4 }; + let s = format!("{:.*}", decimals, self.from_pt(pt)); + let s = s.trim_end_matches('0').trim_end_matches('.'); + if s == "-0" { "0".into() } else { s.into() } + } + /// Parse `12`, `12pt`, `1in`, `3 mm`, `2p6` (picas+points), simple `+ - * /` arithmetic. + /// + /// A unit after a `*` or `/` operand measures the whole expression (`1080/2 px` is 540 px), so + /// math typed before a field's unit suffix works. After `*` or `/`, a percentage scales the term + /// before it (`3cm*50%` is 1.5 cm, `3cm/50%` is 6 cm). After `+` or `-`, it adds or takes away + /// that share of everything before it (`50pt+25%` is 62.5 pt, `100pt+20pt-50%` is 60 pt). A + /// percentage on its own (`50%`) reads as nothing. + pub fn parse(self, s: &str) -> Option { + parse_measure(s, self).filter(|v| v.is_finite()) + } + /// The value naming this unit in the Units preferences (`points`, `millimeters`, + /// `feetInches`). + pub fn key(self) -> &'static str { + match self { + Unit::Points => "points", + Unit::Picas => "picas", + Unit::Inches => "inches", + Unit::Millimeters => "millimeters", + Unit::Centimeters => "centimeters", + Unit::Pixels => "pixels", + Unit::FeetInches => "feetInches", + Unit::Meters => "meters", + Unit::Yards => "yards", + Unit::Feet => "feet", + } + } + /// The unit `name` names: its label, suffix or [`Unit::key`] in any case, ignoring spaces and + /// punctuation (`Millimeters`, `mm`, `Feet & Inches`, `feetInches`). + pub fn named(name: &str) -> Option { + let letters = |s: &'static str| s.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()); + let given = || name.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()); + // Feet and Feet & Inches share the suffix `ft`: it names the plain unit, so Feet & Inches + // is left to its label and key. + Unit::ALL + .into_iter() + .find(|u| letters(u.label()).eq(given())) + .or_else(|| Unit::ALL.into_iter().filter(|u| *u != Unit::FeetInches).find(|u| u.suffix().chars().eq(given()))) + } + /// A point value as the canvas measurement labels show it: two decimals and the suffix + /// (`12.50 mm`). + pub fn readout(self, pt: f64) -> String { + format!("{:.2} {}", self.from_pt(pt), self.suffix()) + } +} + +fn parse_measure(s: &str, default: Unit) -> Option { + let s = s.trim(); + // Simple arithmetic on the right (Illustrator fields accept "10+5", "100/2", "3in*2"). + // `+` and `-` share one precedence level, as do `*` and `/`, so each level splits at the last + // of its operators (left to right). + for ops in [&['+', '-'][..], &['*', '/'][..]] { + // Past the first character, so a leading sign isn't an operator. + let skip = s.chars().next().map_or(0, char::len_utf8); + // A `+` or `-` right after another operator is the sign of its operand (`10*-2`, `5--3`). + let is_sign = |i: usize| { + s.get(i..).and_then(|r| r.chars().next()).is_some_and(|c| matches!(c, '+' | '-')) + && s.get(..i).and_then(|l| l.trim_end().chars().last()).is_some_and(|c| "+-*/".contains(c)) + }; + let found = s.char_indices().rev().find(|&(i, c)| i >= skip && ops.contains(&c) && !is_sign(i)); + if let Some(i) = found.map(|(i, _)| i) { + let (l, r) = (&s[..i], &s[i + 1..]); + if l.trim().is_empty() { + continue; + } + let Some(op) = s[i..].chars().next() else { continue }; + return match op { + '+' | '-' => { + let a = parse_measure(l, default)?; + // A percentage added or taken away is a share of everything before it: + // `50pt+25%` is 62.5 pt, `100pt+20%-10pt` is 110 pt. + let b = match percent(r) { + Some(k) => a * k, + None => parse_measure(r, default)?, + }; + Some(if op == '+' { a + b } else { a - b }) + } + _ => { + // A factor or divisor is a plain number or a percentage (`3cm*50%` is 1.5 cm); + // a unit after it is the expression's. + let (k, unit) = match percent(r) { + Some(k) => (k, None), + None => number_unit(r)?, + }; + let a = parse_measure(l, unit.unwrap_or(default))?; + if op == '*' { + Some(a * k) + } else if k == 0.0 { + None + } else { + Some(a / k) + } + } + }; + } + } + // Plain decimals only, as in `number_unit` (`str::parse` would accept `1e5`, `inf`, `nan`). + let plain = |t: &str| t.trim().chars().all(|c| c.is_ascii_digit() || c == '.' || c == '-') && t.trim().parse::().is_ok(); + if let Some((p, pt)) = s.split_once('p') + && !p.is_empty() + && plain(p) + && (pt.is_empty() || plain(pt)) + && !s.ends_with("pt") + && !s.ends_with("px") + { + // The sign belongs to the whole value: `-2p6` is -(2 picas + 6 points). + let sign = if p.trim_start().starts_with('-') { -1.0 } else { 1.0 }; + let picas = p.trim().parse::().ok()?.abs(); + return Some(sign * (picas * 12.0 + pt.trim().parse::().unwrap_or(0.0))); + } + let (v, unit) = number_unit(s)?; + Some(unit.unwrap_or(default).to_pt(v)) +} + +/// A number with an optional unit suffix (`12`, `3 mm`, `2in`) → (the number, its unit). +fn number_unit(s: &str) -> Option<(f64, Option)> { + let s = s.trim(); + // A leading `+` is a sign (`+5`), like `-`. + let sign = usize::from(s.starts_with('+')); + let num_end = s.get(sign..)?.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).map_or(s.len(), |i| i + sign); + let v: f64 = s.get(..num_end)?.trim().parse().ok()?; + let unit = match s.get(num_end..)?.trim() { + "" => None, + "pt" => Some(Unit::Points), + "px" => Some(Unit::Pixels), + "in" | "\"" => Some(Unit::Inches), + "mm" => Some(Unit::Millimeters), + "cm" => Some(Unit::Centimeters), + "m" => Some(Unit::Meters), + "ft" | "'" => Some(Unit::Feet), + "yd" => Some(Unit::Yards), + "p" | "pc" => Some(Unit::Picas), + _ => return None, + }; + Some((v, unit)) +} + +/// A number followed by `%` (`50%`, `12.5 %`) → its fraction (`0.5`, `0.125`). +fn percent(s: &str) -> Option { + match number_unit(s.trim().strip_suffix('%')?)? { + (p, None) => Some(p / 100.0), + _ => None, + } +} + +/// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as +/// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing. +pub fn parse_number(s: &str) -> Option { + if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/".contains(c)) { + return None; + } + // A leading `+` is a sign (`+5`), as a plain number read it. + let s = s.trim(); + Unit::Points.parse(s.strip_prefix('+').unwrap_or(s)) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ColorMode { + #[default] + Rgb, + Cmyk, +} + +impl ColorMode { + /// The colour model new colours take in a document of this mode. + pub fn model(self) -> vectorcraft_color::cms::Model { + match self { + ColorMode::Rgb => vectorcraft_color::cms::Model::Rgb, + ColorMode::Cmyk => vectorcraft_color::cms::Model::Cmyk, + } + } +} diff --git a/crates/doc/src/xml_id.rs b/crates/doc/src/xml_id.rs index eced91be16..08dd5edbe8 100644 --- a/crates/doc/src/xml_id.rs +++ b/crates/doc/src/xml_id.rs @@ -31,8 +31,14 @@ pub fn to_object_name(id: &str) -> String { /// since a bare `_` would read back as a space. pub fn from_object_name(name: &str) -> String { let mut out = String::with_capacity(name.len().saturating_mul(2)); - for (i, c) in name.chars().enumerate() { - if c == ' ' { + let last = name.chars().count().saturating_sub(1); + let chars: Vec = name.chars().collect(); + for (i, &c) in chars.iter().enumerate() { + if c == ' ' && (i == last || starts_fake_escape(chars.get(i + 1..).unwrap_or_default())) { + // A trailing bare `_` could read back as the end of a uniqueness suffix, and a bare + // `_` before `x_` would read back as an `_xHH_` escape. + out.push_str("_x20_"); + } else if c == ' ' { out.push('_'); } else if c == '_' { out.push_str("_x5F_"); @@ -64,12 +70,25 @@ pub fn is_valid(id: &str) -> bool { chars.all(|c| c.is_alphanumeric() || matches!(c, '_' | '.' | '-' | ':')) } +/// Whether the encoded `rest` (after a space) starts with `x`, 1 to 6 hex digits and a character +/// whose encoding begins with `_`, so that a bare `_` before it would form an escape. +fn starts_fake_escape(rest: &[char]) -> bool { + let Some(('x', digits)) = rest.split_first() else { + return false; + }; + let n = digits.iter().take_while(|c| c.is_ascii_hexdigit()).count(); + if n == 0 || n > 6 { + return false; + } + digits.get(n).is_some_and(|&c| c == ' ' || c == '_' || !(c.is_alphanumeric() || matches!(c, '.' | '-' | ':'))) +} + /// `_xHHHH_` at the start of `s`: the character and the escape's length. fn escaped(s: &str) -> Option<(char, usize)> { let body = s.strip_prefix("_x")?; let end = body.find('_')?; let hex = body.get(..end)?; - if hex.is_empty() || hex.len() > 6 { + if hex.is_empty() || hex.len() > 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } let c = char::from_u32(u32::from_str_radix(hex, 16).ok()?)?; @@ -109,12 +128,31 @@ mod tests { assert!(!is_valid("My Rect") && !is_valid("1abc") && !is_valid("")); } + #[test] + fn sign_is_not_a_hex_digit_in_escapes() { + assert_eq!(to_object_name("a_x+41_b"), "a x+41 b"); + assert_eq!(to_object_name("a_x-41_b"), "a x-41 b"); + } + + #[test] + fn space_before_x_hex_and_underscore_is_not_an_escape() { + for name in ["layer x1 copy", "a xa b", "a xe b", "a xb b", "a x1(b", "a x1_b", "a x123456 c"] { + let id = from_object_name(name); + assert_eq!(to_object_name(&id), name, "name {name:?} -> id {id:?}"); + } + assert_eq!(from_object_name("layer x1 copy"), "layer_x20_x1_copy"); + } + #[test] fn round_trip_names_that_cannot_start_an_xml_name() { for name in ["-abc", ".5 mm", "²x", "Ⅷ", "", "1abc", "Layer 1", " lead", "_a", ":a", "#"] { let id = from_object_name(name); assert_eq!(to_object_name(&id), name, "name {name:?} -> id {id:?}"); } + let name = "Scan 12345678901234567890 "; + let id = from_object_name(name); + assert!(id.ends_with("_x20_"), "{id:?}"); + assert_eq!(to_object_name(&id), name); assert_eq!(from_object_name("-abc"), "_x2D_abc"); assert_eq!(from_object_name(".5 mm"), "_x2E_5_mm"); assert_eq!(from_object_name("²x"), "_xB2_x"); diff --git a/crates/effects/src/adjust.rs b/crates/effects/src/adjust.rs index d4f156d392..faa7a5a7c5 100644 --- a/crates/effects/src/adjust.rs +++ b/crates/effects/src/adjust.rs @@ -415,7 +415,7 @@ pub fn adjust_in_document(d: &mut Document, n: &Node) -> Option { let src = match &n.kind { NodeKind::SymbolInstance { symbol, .. } if has_adjustment(n) => { let symbol = d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()); - art = crate::reshape::as_art(n, symbol.as_deref())?; + art = crate::reshape::as_art(Some(d), n, symbol.as_deref())?; &art } _ => n, diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 2bdd0f2888..4e07df30ce 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -104,7 +104,7 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { return Some(bake_pieces(d, m)); } if let Some(m) = crate::revolve_art(n).or_else(|| crate::solid_art(n)) { - let m = evaluate_container(&m).unwrap_or(m); + let m = evaluate_container(Some(d), &m).unwrap_or(m); return Some(bake_pieces(d, m)); } // Type, images, symbol instances and live objects: reshaped through their outlines, and so are @@ -119,20 +119,21 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()), _ => None, }; - let m = reshape(n, symbol.as_deref())?; + let m = reshape(Some(d), n, symbol.as_deref())?; return Some(bake_node(d, &m).unwrap_or(m)); } - // A path whose Transform effect copies it with a gradient: each copy an object of its own, so - // its gradient fits it rather than spanning every copy. - if crate::has_gradient_copies(n) - && let Some(m) = reshape(n, None) + // 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 + // every copy and its strokes and patterns can differ from the others'. + if crate::has_transform_art(n) + && let Some(m) = reshape(Some(d), n, None) { return Some(bake_pieces(d, m)); } // Groups and layers: Pathfinder, geometry effects and their own fills and strokes (type that // Transform effects only move stays type). The new pieces (results, outlines, copies, the // fills' and strokes' art) get ids of their own. - if let Some(m) = container_keeping_type(n).or_else(|| evaluate_container(n)) { + if let Some(m) = container_keeping_type(d, n).or_else(|| evaluate_container(Some(d), n)) { return Some(bake_pieces(d, m)); } if let Some(ch) = n.children() { @@ -151,17 +152,19 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { bake_leaf(d, n) } -/// `m`, art evaluated from an object, with its children baked and given ids of their own (the -/// pieces copied from the source keep the source's ids until then). +/// `m`, art evaluated from an object, with its children baked and then given ids of their own (the +/// pieces copied from the source keep the source's ids until then). The pieces are baked with the +/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id. fn bake_pieces(d: &mut Document, mut m: Node) -> Node { let mut seen = std::collections::HashSet::from([m.id]); let children = m.children().cloned().unwrap_or_default(); let children = children .into_iter() .map(|c| { - let mut c = Arc::unwrap_or_clone(c); + let c = Arc::unwrap_or_clone(c); + let mut c = bake_node(d, &c).unwrap_or(c); fresh_ids(d, &mut c, &mut seen); - Arc::new(bake_node(d, &c).unwrap_or(c)) + Arc::new(c) }) .collect(); if let Some(ch) = m.children_mut() { @@ -321,7 +324,7 @@ fn moved_type_group(n: &Node) -> Option { /// objects or inside groups with Pathfinder or geometry effects or fills and strokes that paint, is /// outlined as [`evaluate_container`] outlines it, and the other members become what it makes of /// them. `None` when no type stays type. -fn container_keeping_type(n: &Node) -> Option { +fn container_keeping_type(d: &Document, n: &Node) -> Option { fn keep(n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) { let clips = n.clips(); let Some(ch) = n.children_mut() else { return }; @@ -346,7 +349,7 @@ fn container_keeping_type(n: &Node) -> Option { } } None if clipping => outline_text(c).map(|o| Node { visible: c.visible, ..o }), - None => as_art(c, None), + None => as_art(None, c, None), }; if let Some(o) = art { *c = Arc::new(o); @@ -363,8 +366,7 @@ fn container_keeping_type(n: &Node) -> Option { if !text { return None; } - let hook: &dyn Fn(&Node) -> Option = &outline_text; - let mut m = vectorcraft_doc::live::expand_deep(n, Some(hook)); + let mut m = crate::reshape::evaluated(Some(d), n); let mut kept = false; keep(&mut m, &moves, false, &mut kept); if !kept { @@ -452,7 +454,7 @@ pub type StrokeArt<'a> = &'a mut dyn FnMut(&mut Document, &PathData, FillRule, & /// effects are dropped. `None` for other kinds of objects. pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option { if let Some(m) = crate::revolve::expand_revolve_art(n).or_else(|| crate::solid_art(n)) { - let m = evaluate_container(&m).unwrap_or(m); + let m = evaluate_container(Some(d), &m).unwrap_or(m); return Some(bake_pieces(d, m)); } let (g, rule, ctx, mut m) = leaf_base(n)?; @@ -563,7 +565,7 @@ pub fn bake_appearance(n: &Node) -> Option { } None => { let effects = st.effects.clone(); - let fill = FillLayer { opacity: st.opacity, blend: st.blend, effects, ..FillLayer::new(st.paint.clone()) }; + let fill = FillLayer { opacity: st.opacity, blend: st.blend, effects, ..FillLayer::new(st.paint.stroke_as_fill()) }; piece(outline, FillRule::NonZero, AppearanceItem::Fill(fill)) } } @@ -595,469 +597,4 @@ pub fn bake_document(doc: &Document) -> Option { } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - use vectorcraft_color::{Color, Paint}; - use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject}; - use vectorcraft_geom::{Point, Rect, shapes}; - - /// Type tests need glyph outlines, which only the optional craft-fonts build input provides. - fn skip_without_craft_fonts() -> bool { - let skip = vectorcraft_text::CRAFT_FONTS.is_empty(); - if skip { - eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); - } - skip - } - - fn fx(id: &str, params: serde_json::Value) -> Effect { - Effect { id: id.into(), params, visible: true } - } - - fn doc_with(n: Node) -> Document { - let mut d = Document::new(400.0, 400.0); - let l = d.layers[0].id; - d.insert(Some(l), 0, n).unwrap(); - d - } - - #[test] - fn plain_documents_are_not_copied() { - let mut d = Document::new(100.0, 100.0); - let id = d.alloc_id(); - let d = doc_with(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art())); - assert!(bake_document(&d).is_none()); - } - - #[test] - fn object_effects_become_geometry_and_raster_effects_stay() { - let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); - n.appearance.effects.push(fx("path.offsetPath", json!({"offset": 10.0}))); - n.appearance.effects.push(fx("stylize.dropShadow", json!({}))); - let d = bake_document(&doc_with(n)).unwrap(); - let m = d.node(NodeId(50)).unwrap(); - let b = m.geometric_bounds().unwrap(); - assert!((b.width() - 120.0).abs() < 0.5, "{b:?}"); - assert_eq!(m.appearance.effects.len(), 1); - assert_eq!(m.appearance.effects[0].id, "stylize.dropShadow"); - } - - #[test] - fn item_effects_split_into_one_path_per_item() { - let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); - if let AppearanceItem::Stroke(s) = &mut n.appearance.items[1] { - s.effects.push(fx("path.offsetPath", json!({"offset": 5.0}))); - } - let d = bake_document(&doc_with(n)).unwrap(); - let m = d.node(NodeId(50)).unwrap(); - let ch = m.children().unwrap(); - assert_eq!(ch.len(), 2); - assert!((ch[0].geometric_bounds().unwrap().width() - 100.0).abs() < 1e-6); - assert!((ch[1].geometric_bounds().unwrap().width() - 110.0).abs() < 0.5); - assert!(ch[0].id != ch[1].id && ch[0].id != NodeId(50)); - } - - #[test] - fn a_baked_stroke_keeps_its_raster_effects() { - let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); - if let AppearanceItem::Stroke(s) = &mut n.appearance.items[1] { - s.effects.push(fx("path.offsetPath", json!({"offset": 5.0}))); - s.effects.push(fx("stylize.dropShadow", json!({}))); - } - let m = bake_appearance(&n).unwrap(); - let ch = m.children().unwrap(); - let Some(AppearanceItem::Fill(f)) = ch[1].appearance.items.first() else { panic!("the outline is filled") }; - assert_eq!(f.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.dropShadow"]); - } - - #[test] - fn a_baked_stroke_with_a_gradient_along_it_becomes_meshes_clipped_to_its_outline() { - let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); - if let AppearanceItem::Stroke(s) = &mut n.appearance.items[1] { - s.width = 10.0; - s.paint = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(Default::default()))); - s.gradient_mode = vectorcraft_doc::StrokeGradientMode::Along; - s.opacity = 0.5; - } - let m = bake_appearance(&n).unwrap(); - let ch = m.children().unwrap(); - let NodeKind::Group { children, clip: true } = &ch[1].kind else { panic!("a clip group: {:?}", ch[1].kind) }; - assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); - assert!(children.len() > 1 && children[1..].iter().all(|c| matches!(c.kind, NodeKind::Mesh(_))), "gradient meshes"); - assert_eq!(ch[1].opacity, 0.5); - } - - /// Black 24 pt "Type" with its baseline at (20, 60). - fn type_node(id: u64) -> Node { - let style = CharStyle { size: 24.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; - Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 60.0), "Type", style)))) - } - - /// The origins of the type objects in `d`, in paint order. - fn type_origins(d: &Document) -> Vec<(f64, f64)> { - let mut out = vec![]; - d.walk(|n| { - if let NodeKind::Text(t) = &n.kind { - let c = t.xf.as_coeffs(); - out.push((c[4], c[5])); - } - }); - out - } - - /// A group of the type and a 10 pt square with `effects`. - fn type_group(effects: Vec) -> Node { - let square = Node::path(NodeId(51), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); - let mut g = Node::group(NodeId(52), vec![Arc::new(type_node(50)), Arc::new(square)]); - g.appearance.effects = effects; - g - } - - #[test] - fn type_moved_or_copied_by_a_groups_transform_effect_stays_type() { - if skip_without_craft_fonts() { - return; - } - for (params, origins, square) in [ - (json!({"moveH": 30}), vec![(50.0, 60.0)], Rect::new(30.0, 0.0, 40.0, 10.0)), - (json!({"moveH": 200, "copies": 1}), vec![(20.0, 60.0), (220.0, 60.0)], Rect::new(0.0, 0.0, 210.0, 10.0)), - (json!({"moveV": 50, "copies": 2}), vec![(20.0, 60.0), (20.0, 110.0), (20.0, 160.0)], Rect::new(0.0, 0.0, 10.0, 110.0)), - ] { - let g = type_group(vec![fx("distort.transform", params.clone()), fx("stylize.dropShadow", json!({}))]); - let d = bake_document(&doc_with(g.clone())).unwrap(); - assert_eq!(type_origins(&d), origins, "{params}"); - let baked = d.node(NodeId(52)).unwrap(); - assert_eq!(baked.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.dropShadow"]); - // The square moves with the type, as one path holding its copies. - let b = baked.children().unwrap().last().and_then(|s| s.geometric_bounds()).unwrap(); - assert!([b.x0 - square.x0, b.y0 - square.y0, b.x1 - square.x1, b.y1 - square.y1].iter().all(|v| v.abs() < 1e-9), "{params}: {b:?}"); - let mut ids = std::collections::HashSet::new(); - baked.walk(&mut |n| assert!(ids.insert(n.id), "{params}: duplicate id {}", n.id)); - // The renderer and Expand Appearance still draw it as outlines. - let mut text = 0; - evaluate_container(&g).unwrap().walk(&mut |n| text += usize::from(matches!(n.kind, NodeKind::Text(_)))); - assert_eq!(text, 0, "{params}"); - } - // Stacked effects that only move: every copy of a copy. - let d = bake_document(&doc_with(type_group(vec![ - fx("distort.transform", json!({"moveH": 100, "copies": 1})), - fx("distort.transform", json!({"moveV": 100, "copies": 1})), - ]))) - .unwrap(); - assert_eq!(type_origins(&d), [(20.0, 60.0), (120.0, 60.0), (20.0, 160.0), (120.0, 160.0)]); - } - - #[test] - fn hidden_type_in_a_group_that_keeps_its_type_stays_hidden() { - if skip_without_craft_fonts() { - return; - } - let mut g = type_group(vec![fx("distort.transform", json!({"moveH": 200, "copies": 1}))]); - let mut hidden = type_node(55); - hidden.visible = false; - g.children_mut().unwrap().push(Arc::new(hidden)); - let d = bake_document(&doc_with(g)).unwrap(); - assert_eq!(type_origins(&d), [(20.0, 60.0), (220.0, 60.0)]); - assert!(!d.node(NodeId(55)).unwrap().visible); - } - - #[test] - fn type_outlined_next_to_type_that_stays_type_keeps_its_look() { - if skip_without_craft_fonts() { - return; - } - let mut g = type_group(vec![fx("distort.transform", json!({"moveH": 200, "copies": 1}))]); - let mut shadowed = type_node(55); - shadowed.opacity = 0.5; - shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({}))); - // Type that clips a group is outlined as the plain outlines it clips by. - let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); - let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(type_node(56)), Arc::new(square)], clip: true }); - g.children_mut().unwrap().extend([Arc::new(shadowed), Arc::new(clip)]); - let d = bake_document(&doc_with(g)).unwrap(); - assert_eq!(type_origins(&d), [(20.0, 60.0), (220.0, 60.0)]); - let o = d.node(NodeId(55)).unwrap(); - assert!(matches!(o.kind, NodeKind::Group { .. }) && o.opacity == 0.5, "{o:?}"); - assert_eq!(o.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.dropShadow"]); - // The outlines are copied with the type. - let b = o.geometric_bounds().unwrap(); - assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}"); - let clipped = d.node(NodeId(58)).and_then(|n| n.children()).and_then(|c| c.first()).unwrap(); - assert!(matches!(clipped.kind, NodeKind::Group { .. }) && clipped.opacity == 1.0, "{clipped:?}"); - } - - #[test] - fn type_in_a_clipping_group_with_a_fill_of_its_own_is_outlined_plain() { - if skip_without_craft_fonts() { - return; - } - let mut g = type_group(vec![fx("distort.transform", json!({"moveH": 200, "copies": 1}))]); - // The clipping path is a group with a fill of its own, holding type with an effect of its own. - let mut moved = type_node(60); - moved.appearance.effects.push(fx("distort.transform", json!({"moveV": 300}))); - let mut path = Node::group(NodeId(59), vec![Arc::new(moved)]); - path.appearance.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::BLACK)))); - let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); - let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(path), Arc::new(square)], clip: true }); - g.children_mut().unwrap().push(Arc::new(clip)); - let d = bake_document(&doc_with(g)).unwrap(); - assert_eq!(type_origins(&d), [(20.0, 60.0), (220.0, 60.0)]); - // The type clips by its plain outlines, as the canvas clips by them: its own effect is left out. - let b = d.node(NodeId(59)).and_then(|n| n.geometric_bounds()).unwrap(); - assert!(b.y0 > 30.0 && b.y1 < 70.0, "{b:?}"); - } - - #[test] - fn type_with_its_own_transform_effect_copies_stays_type() { - if skip_without_craft_fonts() { - return; - } - let mut n = type_node(50); - n.opacity = 0.5; - n.appearance.effects = vec![fx("distort.transform", json!({"moveV": 50, "copies": 2})), fx("stylize.dropShadow", json!({}))]; - let d = bake_document(&doc_with(n)).unwrap(); - assert_eq!(type_origins(&d), [(20.0, 60.0), (20.0, 110.0), (20.0, 160.0)]); - // One group keeps the object's transparency and its other effects; the copies are plain. - let g = d.node(NodeId(50)).unwrap(); - assert!(matches!(g.kind, NodeKind::Group { .. }) && g.opacity == 0.5); - assert_eq!(g.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.dropShadow"]); - for c in g.children().unwrap() { - assert!(c.opacity == 1.0 && c.appearance.effects.is_empty() && c.id != g.id, "{c:?}"); - } - // Hidden type stays hidden. - let mut n = type_node(50); - n.visible = false; - n.appearance.effects = vec![fx("distort.transform", json!({"moveV": 50, "copies": 1}))]; - let d = bake_document(&doc_with(n)).unwrap(); - assert_eq!(type_origins(&d).len(), 2); - assert!(!d.node(NodeId(50)).unwrap().visible); - } - - #[test] - fn type_under_other_geometry_effects_is_still_outlined() { - for effects in [ - vec![fx("distort.transform", json!({"moveH": 30, "random": true}))], - vec![fx("distort.transform", json!({"moveH": 30, "scaleH": 50}))], - vec![fx("distort.transform", json!({"moveH": 30, "rotate": 10, "copies": 1}))], - vec![fx("distort.transform", json!({"moveH": 30, "reflectX": true}))], - vec![fx("distort.transform", json!({"moveH": 30})), fx("distort.roughen", json!({"size": 4}))], - // Copies that would reach past the effect's limit, which stops them early. - vec![fx("distort.transform", json!({"moveH": 1.0e7, "copies": 1000}))], - // Copies that overlap, or land on each other. - vec![fx("distort.transform", json!({"moveH": 5, "copies": 1}))], - vec![fx("distort.transform", json!({"moveH": 100, "copies": 1})), fx("distort.transform", json!({"moveH": -100, "copies": 1}))], - ] { - let mut own = type_node(50); - own.appearance.effects = effects.clone(); - for n in [type_group(effects.clone()), own] { - let d = bake_document(&doc_with(n)).unwrap(); - assert!(type_origins(&d).is_empty(), "{effects:?}"); - } - } - } - - #[test] - fn type_whose_copies_paint_over_each_other_is_still_outlined() { - if skip_without_craft_fonts() { - return; - } - let moves = vec![fx("distort.transform", json!({"moveV": 40, "copies": 1}))]; - assert_eq!(type_origins(&bake_document(&doc_with(type_group(moves.clone()))).unwrap()).len(), 2); - // A 20 pt stroke on the characters reaches the copy below. - let mut stroked = type_node(50); - if let NodeKind::Text(t) = &mut stroked.kind { - t.runs[0].style.stroke = Paint::solid(Color::BLACK); - t.runs[0].style.stroke_width = 20.0; - } - let mut g = type_group(moves); - g.children_mut().unwrap()[0] = Arc::new(stroked); - assert!(type_origins(&bake_document(&doc_with(g)).unwrap()).is_empty()); - } - - #[test] - fn type_with_a_look_of_its_own_in_a_moved_group_is_still_outlined() { - if skip_without_craft_fonts() { - return; - } - let moves = vec![fx("distort.transform", json!({"moveV": 40, "copies": 1}))]; - let mut translucent = type_node(50); - translucent.opacity = 0.5; - let mut underlined = type_node(50); - if let NodeKind::Text(t) = &mut underlined.kind { - t.runs[0].style.underline = true; - } - let mut shadowed = type_node(50); - shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({}))); - let mut gradient = type_node(50); - if let NodeKind::Text(t) = &mut gradient.kind { - t.runs[0].style.fill = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default()))); - } - let mut reshaped = type_node(50); - let mut fill = FillLayer::new(Paint::solid(Color::BLACK)); - fill.effects.push(fx("path.offsetPath", json!({"offset": 2}))); - reshaped.appearance.items.push(AppearanceItem::Fill(fill)); - // A stroke of the type object's own (beyond its characters'). - let mut stroked = type_node(50); - stroked.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 1.0))); - // Character strokes scale with type scaled by its transform, where the outlines keep theirs. - let mut scaled = type_node(50); - if let NodeKind::Text(t) = &mut scaled.kind { - t.runs[0].style.stroke = Paint::solid(Color::BLACK); - t.runs[0].style.stroke_width = 1.0; - t.xf *= Affine::scale(2.0); - } - let mut turned = scaled.clone(); - if let NodeKind::Text(t) = &mut turned.kind { - t.xf = Affine::translate((20.0, 60.0)) * Affine::rotate(0.5); - } - let far = vec![fx("distort.transform", json!({"moveH": 300, "copies": 1}))]; - for (t, kept) in [(turned, 2), (scaled, 0)] { - let mut g = type_group(far.clone()); - g.children_mut().unwrap()[0] = Arc::new(t); - assert_eq!(type_origins(&bake_document(&doc_with(g)).unwrap()).len(), kept); - } - for t in [translucent, underlined, shadowed, gradient, reshaped, stroked] { - let mut g = type_group(moves.clone()); - g.children_mut().unwrap()[0] = Arc::new(t); - assert!(type_origins(&bake_document(&doc_with(g)).unwrap()).is_empty()); - } - } - - #[test] - fn type_in_a_moved_group_with_a_fill_of_its_own_is_still_outlined() { - let moves = vec![fx("distort.transform", json!({"moveV": 100, "copies": 1}))]; - let fill = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::BLACK))); - let mut g = type_group(moves.clone()); - g.appearance.items.push(fill.clone()); - assert!(type_origins(&bake_document(&doc_with(g)).unwrap()).is_empty()); - // A group with a fill of its own inside the moved group. - let mut inner = type_group(vec![]); - inner.id = NodeId(53); - inner.appearance.items.push(fill); - let mut outer = Node::group(NodeId(54), vec![Arc::new(inner)]); - outer.appearance.effects = moves; - assert!(type_origins(&bake_document(&doc_with(outer)).unwrap()).is_empty()); - } - - #[test] - fn type_in_a_moved_group_inside_a_moved_group_is_still_outlined() { - // The inner copy lands back on the original. - let mut inner = type_group(vec![fx("distort.transform", json!({"moveH": -200, "copies": 1}))]); - inner.id = NodeId(53); - let mut outer = Node::group(NodeId(54), vec![Arc::new(inner)]); - outer.appearance.effects.push(fx("distort.transform", json!({"moveH": 200, "copies": 1}))); - assert!(type_origins(&bake_document(&doc_with(outer)).unwrap()).is_empty()); - } - - #[test] - fn type_whose_copies_hold_too_much_is_still_outlined() { - if skip_without_craft_fonts() { - return; - } - let spaced = |spaces: usize| { - let mut n = type_node(50); - if let NodeKind::Text(t) = &mut n.kind { - t.runs[0].text = format!("a{}", " ".repeat(spaces)); - } - Arc::new(n) - }; - // 1001 copies of about 2,000 bytes stay type; of about 21,000 bytes each, past 20,000,000 - // bytes together, they are outlined. - let copies = vec![fx("distort.transform", json!({"moveH": 100, "copies": 1000}))]; - for (spaces, kept) in [(1000, 1001), (20_000, 0)] { - let mut g = type_group(copies.clone()); - g.children_mut().unwrap()[0] = spaced(spaces); - assert_eq!(type_origins(&bake_document(&doc_with(g)).unwrap()).len(), kept, "{spaces} spaces"); - } - // 1001 × 21 copies, past 10,000. - let mut g = type_group(vec![ - fx("distort.transform", json!({"moveH": 100, "copies": 1000})), - fx("distort.transform", json!({"moveV": 100, "copies": 20})), - ]); - g.children_mut().unwrap()[0] = spaced(0); - assert!(type_origins(&bake_document(&doc_with(g)).unwrap()).is_empty()); - } - - #[test] - fn copies_are_apart_when_their_boxes_only_touch() { - let b = Rect::new(0.0, 0.0, 10.0, 5.0); - assert!(apart(&[Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(0.0, 5.0), Vec2::new(-10.0, -5.0)], b)); - assert!(!apart(&[Vec2::ZERO, Vec2::new(9.0, 4.0)], b)); - assert!(!apart(&[Vec2::new(100.0, 0.0), Vec2::new(30.0, 0.0), Vec2::new(100.0, 0.0)], b)); - assert!(!apart(&[Vec2::new(-1.0, -1.0), Vec2::new(8.5, 3.5)], b)); - // Offsets too far for the cells' range count as overlapping. - assert!(!apart(&[Vec2::ZERO, Vec2::new(1.0e9, 0.0)], Rect::new(0.0, 0.0, 1.0e-9, 1.0))); - } - - #[test] - fn type_in_a_pathfinder_group_inside_a_moved_group_is_still_outlined() { - if skip_without_craft_fonts() { - return; - } - let mut inner = type_group(vec![fx("pathfinder.add", json!({}))]); - inner.id = NodeId(53); - let mut outer = Node::group(NodeId(54), vec![Arc::new(inner)]); - outer.appearance.effects.push(fx("distort.transform", json!({"moveV": 100, "copies": 1}))); - let d = bake_document(&doc_with(outer)).unwrap(); - assert!(type_origins(&d).is_empty()); - // The glyphs take part in Add: the result reaches past the 10 pt square. - let b = d.node(NodeId(54)).and_then(|n| n.geometric_bounds()).unwrap(); - assert!(b.width() > 30.0, "{b:?}"); - } - - #[test] - fn type_is_copied_only_when_the_effect_makes_every_copy() { - // A 10 pt line with `n` anchors. - let line = |n: usize| { - let pts: Vec = (0..n).map(|i| Point::new(i as f64 * 10.0 / n as f64, 0.0)).collect(); - PathData::new(vec![vectorcraft_geom::SubPath::polyline(&pts, false)]) - }; - let right = json!({"moveH": 10, "copies": 1000}); - let down = json!({"moveV": 10, "copies": 1}); - // 1000 copies of a path stay within 2,000,000 anchors up to 1998 anchors. - assert_eq!(transform_offsets(std::slice::from_ref(&right), &line(1998)).map(|o| o.len()), Some(1001)); - assert!(transform_offsets(std::slice::from_ref(&right), &line(1999)).is_none()); - // A second effect copies every copy. - assert_eq!(transform_offsets(&[right.clone(), down.clone()], &line(999)).map(|o| o.len()), Some(2002)); - assert!(transform_offsets(&[right, down], &line(1000)).is_none()); - // Copies stop before one reaches 1,000,000,000 pt from the origin. - let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); - assert_eq!(transform_offsets(&[json!({"moveH": 1.0e7, "copies": 99})], &square).map(|o| o.len()), Some(100)); - assert!(transform_offsets(&[json!({"moveH": 1.0e7, "copies": 100})], &square).is_none()); - // An effect that also scales. - assert!(transform_offsets(&[json!({"moveH": 10, "scaleH": 50})], &square).is_none()); - } - /// A 10 pt square painted with a red to blue gradient and a Transform effect with 2 copies. - fn gradient_copies(id: u64) -> Node { - use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; - let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; - let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient { kind: GradientKind::Linear, stops }))); - let mut n = Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(paint, Paint::None, 0.0)); - n.appearance.effects.push(fx("distort.transform", json!({"moveH": 30, "copies": 2}))); - n - } - - /// The paths under `n` that paint a gradient fitted to their own 10 pt box, left to right. - fn gradient_pieces(n: &Node) -> Vec { - let mut out = vec![]; - let mut walk = vec![n]; - while let Some(n) = walk.pop() { - match n.children() { - Some(ch) if !matches!(n.kind, NodeKind::Compound { .. }) => walk.extend(ch.iter().map(|c| &**c)), - _ => { - assert!(matches!(n.appearance.fill_paint(), Paint::Gradient(_)), "{n:?}"); - out.extend(n.geometric_bounds().map(|b| b.width())); - } - } - } - out - } - - #[test] - fn exporting_a_path_with_a_transform_gives_each_copy_its_own_gradient() { - let d = bake_document(&doc_with(gradient_copies(50))).unwrap(); - // Three squares of their own, not one path spanning all three. - assert_eq!(gradient_pieces(d.node(NodeId(50)).unwrap()), vec![10.0; 3]); - } -} +mod tests; diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs new file mode 100644 index 0000000000..b150f2004d --- /dev/null +++ b/crates/effects/src/bake/tests.rs @@ -0,0 +1,480 @@ +use super::*; +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject}; +use vectorcraft_geom::{Point, Rect, shapes}; + +/// Type tests need glyph outlines, which only the optional craft-fonts build input provides. +fn skip_without_craft_fonts() -> bool { + let skip = vectorcraft_text::CRAFT_FONTS.is_empty(); + if skip { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + } + skip +} + +fn fx(id: &str, params: serde_json::Value) -> Effect { + Effect { id: id.into(), params, visible: true } +} + +fn doc_with(n: Node) -> Document { + let mut d = Document::new(400.0, 400.0); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d +} + +#[test] +fn plain_documents_are_not_copied() { + let mut d = Document::new(100.0, 100.0); + let id = d.alloc_id(); + let d = doc_with(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art())); + assert!(bake_document(&d).is_none()); +} + +#[test] +fn object_effects_become_geometry_and_raster_effects_stay() { + let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); + n.appearance.effects.push(fx("path.offsetPath", json!({"offset": 10.0}))); + n.appearance.effects.push(fx("stylize.dropShadow", json!({}))); + let d = bake_document(&doc_with(n)).unwrap(); + let m = d.node(NodeId(50)).unwrap(); + let b = m.geometric_bounds().unwrap(); + assert!((b.width() - 120.0).abs() < 0.5, "{b:?}"); + assert_eq!(m.appearance.effects.len(), 1); + assert_eq!(m.appearance.effects[0].id, "stylize.dropShadow"); +} + +#[test] +fn item_effects_split_into_one_path_per_item() { + let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); + if let AppearanceItem::Stroke(s) = &mut n.appearance.items[1] { + s.effects.push(fx("path.offsetPath", json!({"offset": 5.0}))); + } + let d = bake_document(&doc_with(n)).unwrap(); + let m = d.node(NodeId(50)).unwrap(); + let ch = m.children().unwrap(); + assert_eq!(ch.len(), 2); + assert!((ch[0].geometric_bounds().unwrap().width() - 100.0).abs() < 1e-6); + assert!((ch[1].geometric_bounds().unwrap().width() - 110.0).abs() < 0.5); + assert!(ch[0].id != ch[1].id && ch[0].id != NodeId(50)); +} + +#[test] +fn a_baked_stroke_keeps_its_raster_effects() { + let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); + if let AppearanceItem::Stroke(s) = &mut n.appearance.items[1] { + s.effects.push(fx("path.offsetPath", json!({"offset": 5.0}))); + s.effects.push(fx("stylize.dropShadow", json!({}))); + } + let m = bake_appearance(&n).unwrap(); + let ch = m.children().unwrap(); + let Some(AppearanceItem::Fill(f)) = ch[1].appearance.items.first() else { panic!("the outline is filled") }; + assert_eq!(f.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.dropShadow"]); +} + +#[test] +fn a_baked_stroke_leaves_dither_behind() { + // Strokes ignore dither, so the filled outline goes without it and looks as the stroke did. + let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); + if let AppearanceItem::Stroke(s) = &mut n.appearance.items[1] { + let mut g = vectorcraft_color::GradientPaint::new(Default::default()); + g.gradient.dither = true; + s.paint = Paint::Gradient(Box::new(g)); + } + let m = bake_appearance(&n).unwrap(); + let ch = m.children().unwrap(); + let Some(AppearanceItem::Fill(f)) = ch[1].appearance.items.first() else { panic!("the outline is filled") }; + let Paint::Gradient(g) = &f.paint else { panic!("a gradient fill") }; + assert!(!g.gradient.dither); +} + +#[test] +fn a_baked_stroke_with_a_gradient_along_it_becomes_meshes_clipped_to_its_outline() { + let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); + if let AppearanceItem::Stroke(s) = &mut n.appearance.items[1] { + s.width = 10.0; + s.paint = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(Default::default()))); + s.gradient_mode = vectorcraft_doc::StrokeGradientMode::Along; + s.opacity = 0.5; + } + let m = bake_appearance(&n).unwrap(); + let ch = m.children().unwrap(); + let NodeKind::Group { children, clip: true } = &ch[1].kind else { panic!("a clip group: {:?}", ch[1].kind) }; + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); + assert!(children.len() > 1 && children[1..].iter().all(|c| matches!(c.kind, NodeKind::Mesh(_))), "gradient meshes"); + assert_eq!(ch[1].opacity, 0.5); +} + +/// Black 24 pt "Type" with its baseline at (20, 60). +fn type_node(id: u64) -> Node { + let style = CharStyle { size: 24.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 60.0), "Type", style)))) +} + +/// The origins of the type objects in `d`, in paint order. +fn type_origins(d: &Document) -> Vec<(f64, f64)> { + let mut out = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + let c = t.xf.as_coeffs(); + out.push((c[4], c[5])); + } + }); + out +} + +/// A group of the type and a 10 pt square with `effects`. +fn type_group(effects: Vec) -> Node { + let square = Node::path(NodeId(51), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + let mut g = Node::group(NodeId(52), vec![Arc::new(type_node(50)), Arc::new(square)]); + g.appearance.effects = effects; + g +} + +#[test] +fn type_moved_or_copied_by_a_groups_transform_effect_stays_type() { + if skip_without_craft_fonts() { + return; + } + for (params, origins, square) in [ + (json!({"moveH": 30}), vec![(50.0, 60.0)], Rect::new(30.0, 0.0, 40.0, 10.0)), + (json!({"moveH": 200, "copies": 1}), vec![(20.0, 60.0), (220.0, 60.0)], Rect::new(0.0, 0.0, 210.0, 10.0)), + (json!({"moveV": 50, "copies": 2}), vec![(20.0, 60.0), (20.0, 110.0), (20.0, 160.0)], Rect::new(0.0, 0.0, 10.0, 110.0)), + ] { + let g = type_group(vec![fx("distort.transform", params.clone()), fx("stylize.dropShadow", json!({}))]); + let d = bake_document(&doc_with(g.clone())).unwrap(); + assert_eq!(type_origins(&d), origins, "{params}"); + let baked = d.node(NodeId(52)).unwrap(); + assert_eq!(baked.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.dropShadow"]); + // The square moves with the type, as one path holding its copies. + let b = baked.children().unwrap().last().and_then(|s| s.geometric_bounds()).unwrap(); + assert!([b.x0 - square.x0, b.y0 - square.y0, b.x1 - square.x1, b.y1 - square.y1].iter().all(|v| v.abs() < 1e-9), "{params}: {b:?}"); + let mut ids = std::collections::HashSet::new(); + baked.walk(&mut |n| assert!(ids.insert(n.id), "{params}: duplicate id {}", n.id)); + // The renderer and Expand Appearance still draw it as outlines. + let mut text = 0; + evaluate_container(None, &g).unwrap().walk(&mut |n| text += usize::from(matches!(n.kind, NodeKind::Text(_)))); + assert_eq!(text, 0, "{params}"); + } + // Stacked effects that only move: every copy of a copy. + let d = bake_document(&doc_with(type_group(vec![ + fx("distort.transform", json!({"moveH": 100, "copies": 1})), + fx("distort.transform", json!({"moveV": 100, "copies": 1})), + ]))) + .unwrap(); + assert_eq!(type_origins(&d), [(20.0, 60.0), (120.0, 60.0), (20.0, 160.0), (120.0, 160.0)]); +} + +#[test] +fn hidden_type_in_a_group_that_keeps_its_type_stays_hidden() { + if skip_without_craft_fonts() { + return; + } + let mut g = type_group(vec![fx("distort.transform", json!({"moveH": 200, "copies": 1}))]); + let mut hidden = type_node(55); + hidden.visible = false; + g.children_mut().unwrap().push(Arc::new(hidden)); + let d = bake_document(&doc_with(g)).unwrap(); + assert_eq!(type_origins(&d), [(20.0, 60.0), (220.0, 60.0)]); + assert!(!d.node(NodeId(55)).unwrap().visible); +} + +#[test] +fn type_outlined_next_to_type_that_stays_type_keeps_its_look() { + if skip_without_craft_fonts() { + return; + } + let mut g = type_group(vec![fx("distort.transform", json!({"moveH": 200, "copies": 1}))]); + let mut shadowed = type_node(55); + shadowed.opacity = 0.5; + shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({}))); + // Type that clips a group is outlined as the plain outlines it clips by. + let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); + let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(type_node(56)), Arc::new(square)], clip: true }); + g.children_mut().unwrap().extend([Arc::new(shadowed), Arc::new(clip)]); + let d = bake_document(&doc_with(g)).unwrap(); + assert_eq!(type_origins(&d), [(20.0, 60.0), (220.0, 60.0)]); + let o = d.node(NodeId(55)).unwrap(); + assert!(matches!(o.kind, NodeKind::Group { .. }) && o.opacity == 0.5, "{o:?}"); + assert_eq!(o.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.dropShadow"]); + // The outlines are copied with the type. + let b = o.geometric_bounds().unwrap(); + assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}"); + let clipped = d.node(NodeId(58)).and_then(|n| n.children()).and_then(|c| c.first()).unwrap(); + assert!(matches!(clipped.kind, NodeKind::Group { .. }) && clipped.opacity == 1.0, "{clipped:?}"); +} + +#[test] +fn type_in_a_clipping_group_with_a_fill_of_its_own_is_outlined_plain() { + if skip_without_craft_fonts() { + return; + } + let mut g = type_group(vec![fx("distort.transform", json!({"moveH": 200, "copies": 1}))]); + // The clipping path is a group with a fill of its own, holding type with an effect of its own. + let mut moved = type_node(60); + moved.appearance.effects.push(fx("distort.transform", json!({"moveV": 300}))); + let mut path = Node::group(NodeId(59), vec![Arc::new(moved)]); + path.appearance.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::BLACK)))); + let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); + let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(path), Arc::new(square)], clip: true }); + g.children_mut().unwrap().push(Arc::new(clip)); + let d = bake_document(&doc_with(g)).unwrap(); + assert_eq!(type_origins(&d), [(20.0, 60.0), (220.0, 60.0)]); + // The type clips by its plain outlines, as the canvas clips by them: its own effect is left out. + let b = d.node(NodeId(59)).and_then(|n| n.geometric_bounds()).unwrap(); + assert!(b.y0 > 30.0 && b.y1 < 70.0, "{b:?}"); +} + +#[test] +fn type_with_its_own_transform_effect_copies_stays_type() { + if skip_without_craft_fonts() { + return; + } + let mut n = type_node(50); + n.opacity = 0.5; + n.appearance.effects = vec![fx("distort.transform", json!({"moveV": 50, "copies": 2})), fx("stylize.dropShadow", json!({}))]; + let d = bake_document(&doc_with(n)).unwrap(); + assert_eq!(type_origins(&d), [(20.0, 60.0), (20.0, 110.0), (20.0, 160.0)]); + // One group keeps the object's transparency and its other effects; the copies are plain. + let g = d.node(NodeId(50)).unwrap(); + assert!(matches!(g.kind, NodeKind::Group { .. }) && g.opacity == 0.5); + assert_eq!(g.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.dropShadow"]); + for c in g.children().unwrap() { + assert!(c.opacity == 1.0 && c.appearance.effects.is_empty() && c.id != g.id, "{c:?}"); + } + // Hidden type stays hidden. + let mut n = type_node(50); + n.visible = false; + n.appearance.effects = vec![fx("distort.transform", json!({"moveV": 50, "copies": 1}))]; + let d = bake_document(&doc_with(n)).unwrap(); + assert_eq!(type_origins(&d).len(), 2); + assert!(!d.node(NodeId(50)).unwrap().visible); +} + +#[test] +fn type_under_other_geometry_effects_is_still_outlined() { + for effects in [ + vec![fx("distort.transform", json!({"moveH": 30, "random": true}))], + vec![fx("distort.transform", json!({"moveH": 30, "scaleH": 50}))], + vec![fx("distort.transform", json!({"moveH": 30, "rotate": 10, "copies": 1}))], + vec![fx("distort.transform", json!({"moveH": 30, "reflectX": true}))], + vec![fx("distort.transform", json!({"moveH": 30})), fx("distort.roughen", json!({"size": 4}))], + // Copies that would reach past the effect's limit, which stops them early. + vec![fx("distort.transform", json!({"moveH": 1.0e7, "copies": 1000}))], + // Copies that overlap, or land on each other. + vec![fx("distort.transform", json!({"moveH": 5, "copies": 1}))], + vec![fx("distort.transform", json!({"moveH": 100, "copies": 1})), fx("distort.transform", json!({"moveH": -100, "copies": 1}))], + ] { + let mut own = type_node(50); + own.appearance.effects = effects.clone(); + for n in [type_group(effects.clone()), own] { + let d = bake_document(&doc_with(n)).unwrap(); + assert!(type_origins(&d).is_empty(), "{effects:?}"); + } + } +} + +#[test] +fn type_whose_copies_paint_over_each_other_is_still_outlined() { + if skip_without_craft_fonts() { + return; + } + let moves = vec![fx("distort.transform", json!({"moveV": 40, "copies": 1}))]; + assert_eq!(type_origins(&bake_document(&doc_with(type_group(moves.clone()))).unwrap()).len(), 2); + // A 20 pt stroke on the characters reaches the copy below. + let mut stroked = type_node(50); + if let NodeKind::Text(t) = &mut stroked.kind { + t.runs[0].style.stroke = Paint::solid(Color::BLACK); + t.runs[0].style.stroke_width = 20.0; + } + let mut g = type_group(moves); + g.children_mut().unwrap()[0] = Arc::new(stroked); + assert!(type_origins(&bake_document(&doc_with(g)).unwrap()).is_empty()); +} + +#[test] +fn type_with_a_look_of_its_own_in_a_moved_group_is_still_outlined() { + if skip_without_craft_fonts() { + return; + } + let moves = vec![fx("distort.transform", json!({"moveV": 40, "copies": 1}))]; + let mut translucent = type_node(50); + translucent.opacity = 0.5; + let mut underlined = type_node(50); + if let NodeKind::Text(t) = &mut underlined.kind { + t.runs[0].style.underline = true; + } + let mut shadowed = type_node(50); + shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({}))); + let mut gradient = type_node(50); + if let NodeKind::Text(t) = &mut gradient.kind { + t.runs[0].style.fill = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default()))); + } + let mut reshaped = type_node(50); + let mut fill = FillLayer::new(Paint::solid(Color::BLACK)); + fill.effects.push(fx("path.offsetPath", json!({"offset": 2}))); + reshaped.appearance.items.push(AppearanceItem::Fill(fill)); + // A stroke of the type object's own (beyond its characters'). + let mut stroked = type_node(50); + stroked.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 1.0))); + // Character strokes scale with type scaled by its transform, where the outlines keep theirs. + let mut scaled = type_node(50); + if let NodeKind::Text(t) = &mut scaled.kind { + t.runs[0].style.stroke = Paint::solid(Color::BLACK); + t.runs[0].style.stroke_width = 1.0; + t.xf *= Affine::scale(2.0); + } + let mut turned = scaled.clone(); + if let NodeKind::Text(t) = &mut turned.kind { + t.xf = Affine::translate((20.0, 60.0)) * Affine::rotate(0.5); + } + let far = vec![fx("distort.transform", json!({"moveH": 300, "copies": 1}))]; + for (t, kept) in [(turned, 2), (scaled, 0)] { + let mut g = type_group(far.clone()); + g.children_mut().unwrap()[0] = Arc::new(t); + assert_eq!(type_origins(&bake_document(&doc_with(g)).unwrap()).len(), kept); + } + for t in [translucent, underlined, shadowed, gradient, reshaped, stroked] { + let mut g = type_group(moves.clone()); + g.children_mut().unwrap()[0] = Arc::new(t); + assert!(type_origins(&bake_document(&doc_with(g)).unwrap()).is_empty()); + } +} + +#[test] +fn type_in_a_moved_group_with_a_fill_of_its_own_is_still_outlined() { + let moves = vec![fx("distort.transform", json!({"moveV": 100, "copies": 1}))]; + let fill = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::BLACK))); + let mut g = type_group(moves.clone()); + g.appearance.items.push(fill.clone()); + assert!(type_origins(&bake_document(&doc_with(g)).unwrap()).is_empty()); + // A group with a fill of its own inside the moved group. + let mut inner = type_group(vec![]); + inner.id = NodeId(53); + inner.appearance.items.push(fill); + let mut outer = Node::group(NodeId(54), vec![Arc::new(inner)]); + outer.appearance.effects = moves; + assert!(type_origins(&bake_document(&doc_with(outer)).unwrap()).is_empty()); +} + +#[test] +fn type_in_a_moved_group_inside_a_moved_group_is_still_outlined() { + // The inner copy lands back on the original. + let mut inner = type_group(vec![fx("distort.transform", json!({"moveH": -200, "copies": 1}))]); + inner.id = NodeId(53); + let mut outer = Node::group(NodeId(54), vec![Arc::new(inner)]); + outer.appearance.effects.push(fx("distort.transform", json!({"moveH": 200, "copies": 1}))); + assert!(type_origins(&bake_document(&doc_with(outer)).unwrap()).is_empty()); +} + +#[test] +fn type_whose_copies_hold_too_much_is_still_outlined() { + if skip_without_craft_fonts() { + return; + } + let spaced = |spaces: usize| { + let mut n = type_node(50); + if let NodeKind::Text(t) = &mut n.kind { + t.runs[0].text = format!("a{}", " ".repeat(spaces)); + } + Arc::new(n) + }; + // 1001 copies of about 2,000 bytes stay type; of about 21,000 bytes each, past 20,000,000 + // bytes together, they are outlined. + let copies = vec![fx("distort.transform", json!({"moveH": 100, "copies": 1000}))]; + for (spaces, kept) in [(1000, 1001), (20_000, 0)] { + let mut g = type_group(copies.clone()); + g.children_mut().unwrap()[0] = spaced(spaces); + assert_eq!(type_origins(&bake_document(&doc_with(g)).unwrap()).len(), kept, "{spaces} spaces"); + } + // 1001 × 21 copies, past 10,000. + let mut g = type_group(vec![ + fx("distort.transform", json!({"moveH": 100, "copies": 1000})), + fx("distort.transform", json!({"moveV": 100, "copies": 20})), + ]); + g.children_mut().unwrap()[0] = spaced(0); + assert!(type_origins(&bake_document(&doc_with(g)).unwrap()).is_empty()); +} + +#[test] +fn copies_are_apart_when_their_boxes_only_touch() { + let b = Rect::new(0.0, 0.0, 10.0, 5.0); + assert!(apart(&[Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(0.0, 5.0), Vec2::new(-10.0, -5.0)], b)); + assert!(!apart(&[Vec2::ZERO, Vec2::new(9.0, 4.0)], b)); + assert!(!apart(&[Vec2::new(100.0, 0.0), Vec2::new(30.0, 0.0), Vec2::new(100.0, 0.0)], b)); + assert!(!apart(&[Vec2::new(-1.0, -1.0), Vec2::new(8.5, 3.5)], b)); + // Offsets too far for the cells' range count as overlapping. + assert!(!apart(&[Vec2::ZERO, Vec2::new(1.0e9, 0.0)], Rect::new(0.0, 0.0, 1.0e-9, 1.0))); +} + +#[test] +fn type_in_a_pathfinder_group_inside_a_moved_group_is_still_outlined() { + if skip_without_craft_fonts() { + return; + } + let mut inner = type_group(vec![fx("pathfinder.add", json!({}))]); + inner.id = NodeId(53); + let mut outer = Node::group(NodeId(54), vec![Arc::new(inner)]); + outer.appearance.effects.push(fx("distort.transform", json!({"moveV": 100, "copies": 1}))); + let d = bake_document(&doc_with(outer)).unwrap(); + assert!(type_origins(&d).is_empty()); + // The glyphs take part in Add: the result reaches past the 10 pt square. + let b = d.node(NodeId(54)).and_then(|n| n.geometric_bounds()).unwrap(); + assert!(b.width() > 30.0, "{b:?}"); +} + +#[test] +fn type_is_copied_only_when_the_effect_makes_every_copy() { + // A 10 pt line with `n` anchors. + let line = |n: usize| { + let pts: Vec = (0..n).map(|i| Point::new(i as f64 * 10.0 / n as f64, 0.0)).collect(); + PathData::new(vec![vectorcraft_geom::SubPath::polyline(&pts, false)]) + }; + let right = json!({"moveH": 10, "copies": 1000}); + let down = json!({"moveV": 10, "copies": 1}); + // 1000 copies of a path stay within 2,000,000 anchors up to 1998 anchors. + assert_eq!(transform_offsets(std::slice::from_ref(&right), &line(1998)).map(|o| o.len()), Some(1001)); + assert!(transform_offsets(std::slice::from_ref(&right), &line(1999)).is_none()); + // A second effect copies every copy. + assert_eq!(transform_offsets(&[right.clone(), down.clone()], &line(999)).map(|o| o.len()), Some(2002)); + assert!(transform_offsets(&[right, down], &line(1000)).is_none()); + // Copies stop before one reaches 1,000,000,000 pt from the origin. + let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + assert_eq!(transform_offsets(&[json!({"moveH": 1.0e7, "copies": 99})], &square).map(|o| o.len()), Some(100)); + assert!(transform_offsets(&[json!({"moveH": 1.0e7, "copies": 100})], &square).is_none()); + // An effect that also scales. + assert!(transform_offsets(&[json!({"moveH": 10, "scaleH": 50})], &square).is_none()); +} +/// A 10 pt square painted with a red to blue gradient and a Transform effect with 2 copies. +fn gradient_copies(id: u64) -> Node { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut n = Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(paint, Paint::None, 0.0)); + n.appearance.effects.push(fx("distort.transform", json!({"moveH": 30, "copies": 2}))); + n +} + +/// The paths under `n` that paint a gradient fitted to their own 10 pt box, left to right. +fn gradient_pieces(n: &Node) -> Vec { + let mut out = vec![]; + let mut walk = vec![n]; + while let Some(n) = walk.pop() { + match n.children() { + Some(ch) if !matches!(n.kind, NodeKind::Compound { .. }) => walk.extend(ch.iter().map(|c| &**c)), + _ => { + assert!(matches!(n.appearance.fill_paint(), Paint::Gradient(_)), "{n:?}"); + out.extend(n.geometric_bounds().map(|b| b.width())); + } + } + } + out +} + +#[test] +fn exporting_a_path_with_a_transform_gives_each_copy_its_own_gradient() { + let d = bake_document(&doc_with(gradient_copies(50))).unwrap(); + // Three squares of their own, not one path spanning all three. + assert_eq!(gradient_pieces(d.node(NodeId(50)).unwrap()), vec![10.0; 3]); +} diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs new file mode 100644 index 0000000000..14fd90c139 --- /dev/null +++ b/crates/effects/src/catalog.rs @@ -0,0 +1,829 @@ +use super::*; + +/// Catalogue entry for one effect. +#[derive(Clone, Debug, PartialEq)] +pub struct EffectInfo { + /// Stable id, e.g. `distort.roughen`. + pub id: &'static str, + /// Menu label (with the ellipsis when the effect has a dialog). + pub label: &'static str, + /// Effect-menu path, e.g. `["Effect", "Distort & Transform"]`. + pub menu: &'static [&'static str], + /// Human/agent-readable parameter documentation. + pub params: &'static str, + /// Dialog defaults. + pub defaults: Value, + /// Raster (painted) rather than geometry effect. + pub raster: bool, + /// The parameters that are distances in points (Scale Strokes & Effects scales them). + pub lengths: Lengths, +} + +/// Which of an effect's parameters are distances in points. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Lengths { + /// Always distances. + pub always: &'static [&'static str], + /// Distances while the effect's `relative` parameter is false (percentages of the object's + /// size otherwise). + pub absolute: &'static [&'static str], +} + +impl Lengths { + /// The distance parameters while the effect's `relative` parameter is `relative`. + pub fn keys(&self, relative: bool) -> impl Iterator + '_ { + self.always.iter().chain(if relative { &[][..] } else { self.absolute }).copied() + } +} + +/// Is parameter `key` of effect `id` a distance in points while its `relative` parameter is +/// `relative`? +pub fn is_length(id: &str, key: &str, relative: bool) -> bool { + catalog_index().get(id).is_some_and(|info| info.lengths.keys(relative).any(|k| k == key)) +} + +/// The distance parameters of effect `id` (none for unknown effects). +fn lengths_of(id: &str) -> Lengths { + let always = |always| Lengths { always, absolute: &[] }; + match id { + "convertToShape.rectangle" | "convertToShape.ellipse" => always(&["extraW", "extraH", "width", "height"]), + "convertToShape.roundedRectangle" => always(&["extraW", "extraH", "width", "height", "radius"]), + "distort.roughen" | "distort.zigZag" => Lengths { always: &[], absolute: &["size"] }, + "distort.tweak" => Lengths { always: &[], absolute: &["h", "v"] }, + "distort.transform" => always(&["moveH", "moveV"]), + "path.offsetPath" => always(&["offset"]), + "threeD.revolve" => always(&["offset"]), + "threeD.extrude" => always(&["depth", "bevelWidth", "bevelHeight"]), + "threeD.inflate" => always(&["depth"]), + "path.outlineStroke" => always(&["width"]), + "stylize.roundCorners" | "stylize.feather" | "blur.gaussian" | "blur.smart" | "sharpen.unsharpMask" => always(&["radius"]), + "stylize.scribble" => always(&["overlap", "overlapVariation", "strokeWidth", "spacing", "spacingVariation"]), + "stylize.dropShadow" => always(&["x", "y", "blur"]), + "stylize.innerGlow" | "stylize.outerGlow" => always(&["blur"]), + "stylize.glowingEdges" => always(&["edgeWidth", "smoothness"]), + "brushStrokes.accentedEdges" => always(&["edgeWidth"]), + "artistic.paletteKnife" => always(&["strokeSize"]), + "brushStrokes.angledStrokes" | "brushStrokes.crosshatch" | "brushStrokes.inkOutlines" => always(&["strokeLength"]), + "brushStrokes.spatter" => always(&["sprayRadius"]), + "brushStrokes.sprayedStrokes" => always(&["strokeLength", "sprayRadius"]), + "brushStrokes.sumiE" => always(&["strokeWidth"]), + "pixelate.colorHalftone" => always(&["maxRadius"]), + "pixelate.crystallize" | "pixelate.pointillize" => always(&["cellSize"]), + "texture.craquelure" => always(&["crackSpacing"]), + "texture.mosaicTiles" => always(&["tileSize"]), + "texture.patchwork" => always(&["squareSize"]), + "texture.stainedGlass" => always(&["cellSize"]), + "sketch.graphicPen" => always(&["strokeLength"]), + "sketch.halftonePattern" => always(&["size"]), + "sketch.notePaper" => always(&["relief"]), + "sketch.tornEdges" => always(&["smoothness"]), + "sketch.waterPaper" => always(&["fiberLength"]), + TRAP => always(&["thickness", "precision"]), + RASTERIZE => always(&["addAround"]), + _ => Lengths::default(), + } +} + +const WARP_DOC: &str = + "{bend: % (-100..100, 50), horizontal: % distortion (0), vertical: % distortion (0), orientation: \"horizontal\"|\"vertical\"}"; + +const DT: &[&str] = &["Effect", "Distort & Transform"]; + +const PATH: &[&str] = &["Effect", "Path"]; + +const SHAPE: &[&str] = &["Effect", "Convert to Shape"]; + +const STYLIZE: &[&str] = &["Effect", "Stylize"]; + +const WARP: &[&str] = &["Effect", "Warp"]; + +const BLUR: &[&str] = &["Effect", "Blur"]; + +const ARTISTIC: &[&str] = &["Effect", "Artistic"]; + +const BRUSH_STROKES: &[&str] = &["Effect", "Brush Strokes"]; + +const DISTORT: &[&str] = &["Effect", "Distort"]; + +const SHARPEN: &[&str] = &["Effect", "Sharpen"]; + +const SKETCH: &[&str] = &["Effect", "Sketch"]; + +const PIXELATE: &[&str] = &["Effect", "Pixelate"]; + +const TEXTURE: &[&str] = &["Effect", "Texture"]; + +const VIDEO: &[&str] = &["Effect", "Video"]; + +const PATHFINDER: &[&str] = &["Effect", "Pathfinder"]; + +const PLUGINS: &[&str] = &["Effect", "Plug-ins"]; + +const ADJUST: &[&str] = &["Effect", "Color Adjustments"]; + +/// The warp styles in Illustrator's Style menu order: (id suffix, label). +pub const WARP_STYLES: [(&str, &str); 15] = [ + ("arc", "Arc…"), + ("arcLower", "Arc Lower…"), + ("arcUpper", "Arc Upper…"), + ("arch", "Arch…"), + ("bulge", "Bulge…"), + ("shellLower", "Shell Lower…"), + ("shellUpper", "Shell Upper…"), + ("flag", "Flag…"), + ("wave", "Wave…"), + ("fish", "Fish…"), + ("rise", "Rise…"), + ("fisheye", "Fisheye…"), + ("inflate", "Inflate…"), + ("squeeze", "Squeeze…"), + ("twist", "Twist…"), +]; + +/// Every supported effect with its dialog defaults. +pub fn effect_catalog() -> Vec { + let g = |id, label, menu, params, defaults| EffectInfo { id, label, menu, params, defaults, raster: false, lengths: lengths_of(id) }; + let r = |id, label, menu, params, defaults| EffectInfo { id, label, menu, params, defaults, raster: true, lengths: lengths_of(id) }; + let mut v = vec![ + g( + 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}), + ), + 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}), + ), + 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}), + ), + 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}), + ), + g( + "convertToShape.rectangle", + "Rectangle…", + SHAPE, + "{relative: bool (true), extraW: pt (18), extraH: pt (18), width: pt (absolute, 100), height: pt (absolute, 100)}", + json!({"relative": true, "extraW": 18.0, "extraH": 18.0, "width": 100.0, "height": 100.0}), + ), + g( + "convertToShape.roundedRectangle", + "Rounded Rectangle…", + SHAPE, + "{relative: bool (true), extraW: pt (18), extraH: pt (18), width, height (absolute), radius: pt (9)}", + json!({"relative": true, "extraW": 18.0, "extraH": 18.0, "width": 100.0, "height": 100.0, "radius": 9.0}), + ), + g( + "convertToShape.ellipse", + "Ellipse…", + SHAPE, + "{relative: bool (true), extraW: pt (18), extraH: pt (18), width, height (absolute)}", + json!({"relative": true, "extraW": 18.0, "extraH": 18.0, "width": 100.0, "height": 100.0}), + ), + g( + "distort.freeDistort", + "Free Distort…", + DT, + "{corners: [[x,y]×4] (new positions of the bounding-box corners TL, TR, BR, BL in unit box coordinates; identity [[0,0],[1,0],[1,1],[0,1]])}", + json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}), + ), + g("distort.puckerBloat", "Pucker & Bloat…", DT, "{amount: % (-200 pucker … 200 bloat, default 0)}", json!({"amount": 0.0})), + g( + "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)}", + 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), copies: 0..1000 (0; each copy transforms the last again), 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)}", + 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( + "distort.tweak", + "Tweak…", + DT, + "{h: amount (10), v: amount (10), relative: bool (true: % of size), anchors: bool (true), in: bool (true), out: bool (true), seed: int (0)}", + json!({"h": 10.0, "v": 10.0, "relative": true, "anchors": true, "in": true, "out": true, "seed": 0}), + ), + g("distort.twist", "Twist…", DT, "{angle: deg (-3600..3600, 10)}", json!({"angle": 10.0})), + g( + "distort.zigZag", + "Zig Zag…", + DT, + "{size: (10), relative: bool (false: pt; true: % of size), ridges: per segment 0..100 (4), points: \"smooth\"|\"corner\"}", + json!({"size": 10.0, "relative": false, "ridges": 4, "points": "smooth"}), + ), + g( + "path.offsetPath", + "Offset Path…", + PATH, + "{offset: pt (10; negative insets), joins: \"miter\"|\"round\"|\"bevel\", miterLimit: (4)}", + json!({"offset": 10.0, "joins": "miter", "miterLimit": 4.0}), + ), + g( + "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", + json!({}), + ), + g( + "path.outlineStroke", + "Outline Stroke", + PATH, + "{width?: pt (defaults to the stroke's weight)} the outline of the stroke the effect is on (on a fill or the object: the top stroke), with its caps, joins, dashes, alignment, width profile and arrowheads", + json!({}), + ), + g("stylize.roundCorners", "Round Corners…", STYLIZE, "{radius: pt (10)}", json!({"radius": 10.0})), + g( + "stylize.scribble", + "Scribble…", + STYLIZE, + "{angle: deg (30; stored above -180 and up to 180: 270 becomes -90, -180 becomes 180), overlap: pt (0; Path Overlap: a positive value extends each line beyond the path, a negative one ends it inside), overlapVariation: pt (0..100, 0.5; how far each line's ends move along it), strokeWidth: pt (3), curviness: % (5), curvinessVariation: % (0..100, 0; how far each turn's curviness moves from curviness), spacing: pt (5), spacingVariation: pt (0..100, 0.5; how far each line's ends move across it), variation: pt (the earlier form, read as overlapVariation and spacingVariation unless those are given), seed: int (0)} (simplified: a single hatching scribble outlined to a filled shape)", + json!({"angle": 30.0, "overlap": 0.0, "overlapVariation": 0.5, "strokeWidth": 3.0, "curviness": 5.0, "curvinessVariation": 0.0, "spacing": 5.0, "spacingVariation": 0.5, "seed": 0}), + ), + r( + "stylize.dropShadow", + "Drop Shadow…", + STYLIZE, + "{mode: blend mode (\"multiply\"), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": the shadow is the object's own colors with `darkness` percent of black added instead of `color`: in a CMYK document their cyan, magenta and yellow stay and their black K becomes K + darkness × (1 − K); in an RGB document each channel is multiplied by 1 − darkness)", + json!({"mode": "multiply", "opacity": 75.0, "x": 7.0, "y": 7.0, "blur": 5.0, "shade": "color", "color": "#000000", "darkness": 100.0}), + ), + r( + "stylize.innerGlow", + "Inner Glow…", + STYLIZE, + "{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}", + json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffffff", "source": "edge"}), + ), + r( + "stylize.outerGlow", + "Outer Glow…", + STYLIZE, + "{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}", + json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}), + ), + r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})), + r("blur.gaussian", "Gaussian Blur…", BLUR, "{radius: pt (5)}", json!({"radius": 5.0})), + r( + "artistic.coloredPencil", + "Colored Pencil…", + ARTISTIC, + "{pencilWidth: 1..24 (5; stroke spacing in document units), strokePressure: 0..15 (5; how heavily the strokes darken), paperBrightness: 0..50 (25; lifts lighter areas toward the paper)} redraws the object in coloured pencil strokes along its edges, keeping its hues and coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"pencilWidth": 5.0, "strokePressure": 5.0, "paperBrightness": 25.0}), + ), + r( + "artistic.cutout", + "Cutout…", + ARTISTIC, + "{levels: 2..8 (4; steps per colour channel: more levels, more flat colours), edgeSimplicity: 0..10 (4; simpler, smoother edges), edgeFidelity: 1..3 (2; keeps more of the edges' detail)} redraws the object as flat pieces of coloured paper, each piece painted in the average colour that falls into it, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"levels": 4.0, "edgeSimplicity": 4.0, "edgeFidelity": 2.0}), + ), + r( + "artistic.dryBrush", + "Dry Brush…", + ARTISTIC, + "{brushSize: 1..10 (2; length of the brush strokes), brushDetail: 0..10 (10; more detail keeps finer structure), texture: 1..3 (1; stronger edges and bristle grain at 3)} repaints the object with short strokes along its form and darkens its edges, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"brushSize": 2.0, "brushDetail": 10.0, "texture": 1.0}), + ), + r( + "artistic.filmGrain", + "Film Grain…", + ARTISTIC, + "{grain: 0..20 (4; monochrome noise in shadows and midtones), highlightArea: 0..20 (0; widens the bright highlight area), intensity: 0..10 (10; highlight strength and quieter highlight grain)}. Smooth document-space grain follows translations; minification uses approximate footprint filtering. Coverage and pure white are preserved; black takes light speckles, and saturated colour channels may clip. Grain 0 with either highlightArea 0 or intensity 0 leaves the art unchanged. Original visual approximation; chosen VectorCraft defaults.", + json!({"grain": 4.0, "highlightArea": 0.0, "intensity": 10.0}), + ), + r( + "artistic.fresco", + "Fresco…", + ARTISTIC, + "{brushSize: 1..10 (2; wider brush dabs), brushDetail: 0..10 (10; sharper edges and less smoothing), texture: 1..3 (1; deeper plaster relief)} repaints the object as coarse pigment on a textured wall, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"brushSize": 2.0, "brushDetail": 10.0, "texture": 1.0}), + ), + r( + "artistic.neonGlow", + "Neon Glow…", + ARTISTIC, + "{glowSize: -24..24 (5; above 0 the light areas glow, below 0 the dark ones; farther from 0 spreads the glow wider), glowBrightness: 0..50 (15; a stronger glow over dimmer greys), color: \"#rrggbb\" (\"#4da6ff\"; the glow's colour)} redraws the object in greys lit by a coloured glow, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"glowSize": 5.0, "glowBrightness": 15.0, "color": "#4da6ff"}), + ), + r( + "artistic.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.", + json!({"brushSize": 10.0, "sharpness": 25.0, "brushType": "simple"}), + ), + r( + "artistic.paletteKnife", + "Palette Knife…", + ARTISTIC, + "{strokeSize: 1..50 (10; length of the knife strokes in document units), strokeDetail: 1..3 (2; more detail keeps more of the original), softness: 0..10 (3; softens the strokes)} smears the object's colours with short angled knife strokes, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"strokeSize": 10.0, "strokeDetail": 2.0, "softness": 3.0}), + ), + r( + "artistic.plasticWrap", + "Plastic Wrap…", + ARTISTIC, + "{highlightStrength: 0..20 (20; brighter specular highlights), detail: 0..15 (12; finer wrinkles in document space), smoothness: 1..15 (15; softer folds)} coats the object in shiny plastic, keeping its coverage. highlightStrength 0 leaves the art unchanged. Original visual approximation; chosen VectorCraft defaults.", + json!({"highlightStrength": 20.0, "detail": 12.0, "smoothness": 15.0}), + ), + r( + "artistic.posterEdges", + "Poster Edges…", + ARTISTIC, + "{edgeThickness: 0..10 (2; wider lines), edgeIntensity: 0..10 (1; darker lines, on fainter edges too), posterization: 0..6 (2; posterization + 2 levels per colour channel)} reduces the object's colours and draws black lines on its edges, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"edgeThickness": 2.0, "edgeIntensity": 1.0, "posterization": 2.0}), + ), + r( + "artistic.roughPastels", + "Rough Pastels…", + ARTISTIC, + "{strokeLength: 0..40 (6; longer pastel strokes), strokeDetail: 1..20 (10; bristle texture along the strokes), texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\" (\"canvas\"), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false)} repaints the object in soft diagonal pastel strokes over a textured surface, keeping its coverage. Slider ranges follow the documented controls; numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults.", + json!({ + "strokeLength": 6.0, + "strokeDetail": 10.0, + "texture": "canvas", + "scaling": 100.0, + "relief": 4.0, + "lightDirection": "top", + "invert": false + }), + ), + r( + "artistic.smudgeStick", + "Smudge Stick…", + ARTISTIC, + "{strokeLength: 0..10 (2; length of the short diagonal strokes), highlightArea: 0..20 (12; widens the area counted as light), intensity: 0..10 (10; how far the light areas are lightened)} smudges the dark areas along short diagonal strokes; the lighter areas become brighter and lose detail. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"strokeLength": 2.0, "highlightArea": 12.0, "intensity": 10.0}), + ), + r( + "artistic.sponge", + "Sponge…", + ARTISTIC, + "{brushSize: 0..10 (2; size of the sponge's pores), definition: 0..25 (12; how strongly lighter and darker blobs contrast), smoothness: 1..15 (5; softer blob edges)} paints the object as if dabbed with a sponge, in highly textured areas of contrasting colour. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"brushSize": 2.0, "definition": 12.0, "smoothness": 5.0}), + ), + r( + "artistic.underpainting", + "Underpainting…", + ARTISTIC, + "{brushSize: 0..40 (6; wider, softer strokes), textureCoverage: 0..40 (16; more of the relief texture on the strokes), texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\" (\"canvas\"; surfaces made in code), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false; turns the surface's heights over)} paints the object with broad strokes over a textured ground, keeping its coverage. Slider ranges follow the documented controls; numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults. Original visual approximation.", + json!({ + "brushSize": 6.0, + "textureCoverage": 16.0, + "texture": "canvas", + "scaling": 100.0, + "relief": 4.0, + "lightDirection": "top", + "invert": false + }), + ), + r( + "artistic.watercolor", + "Watercolor…", + ARTISTIC, + "{brushDetail: 1..14 (9; the larger, the more detail stays), shadowIntensity: 0..10 (1; deepens the shadows), texture: 1..3 (1; paper grain, whole numbers)} paints the object in a watercolor style: detail simplified, colour saturated and darker where tones change at edges. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"brushDetail": 9.0, "shadowIntensity": 1.0, "texture": 1.0}), + ), + r( + "blur.radial", + "Radial Blur…", + BLUR, + "{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples)} blurs around the object's centre", + json!({"amount": 10.0, "method": "spin", "quality": "good"}), + ), + r( + "blur.smart", + "Smart Blur…", + BLUR, + "{radius: pt 0.1..100 (3), threshold: levels 0.1..100 (25; only colours closer than this blur together, so edges stay sharp), quality: \"low\"|\"medium\"|\"high\" (\"medium\"; 5, 7 or 9 samples across), blurMode: \"normal\"|\"edgeOnly\"|\"overlayEdge\" (\"normal\"; edgeOnly: the edges in white on black, overlayEdge: the edges in white over the blur)}. A pixel is on an edge when one of the pixels the search reads within the radius (all of them for a small radius, a grid of samples for a wide one) or one of its four nearest pixels differs from it by more than the threshold in a channel and its channels (alpha included) add up to at least that pixel's, so a step gives a line about as wide as the radius, and at least one pixel wide, on the side with the larger sum; the white and the black keep each pixel's coverage", + json!({"radius": 3.0, "threshold": 25.0, "quality": "medium", "blurMode": "normal"}), + ), + r( + "brushStrokes.accentedEdges", + "Accented Edges…", + BRUSH_STROKES, + "{edgeWidth: pt 1..14 (2), edgeBrightness: 0..50 (38; high: white chalk, low: black ink), smoothness: 1..15 (5; softens the object first and leaves its faint edges out)} accentuates the object's edges", + json!({"edgeWidth": 2.0, "edgeBrightness": 38.0, "smoothness": 5.0}), + ), + r( + "brushStrokes.angledStrokes", + "Angled Strokes…", + BRUSH_STROKES, + "{directionBalance: 0..100 (50; 0: every stroke a left diagonal, 100: every stroke a right diagonal, between: light areas right, dark areas left), strokeLength: pt 3..50 (15), sharpness: 0..10 (3)} repaints the object with diagonal strokes, the light areas' going the opposite way to the dark areas'", + json!({"directionBalance": 50.0, "strokeLength": 15.0, "sharpness": 3.0}), + ), + r( + "brushStrokes.crosshatch", + "Crosshatch…", + BRUSH_STROKES, + "{strokeLength: pt 3..50 (9), sharpness: 0..20 (6), strength: 1..3 (1; passes of hatching)} keeps the object's detail under pencil hatching along both diagonals and roughens its edges", + json!({"strokeLength": 9.0, "sharpness": 6.0, "strength": 1.0}), + ), + r( + "brushStrokes.darkStrokes", + "Dark Strokes…", + BRUSH_STROKES, + "{balance: 0..10 (5; the higher, the more of the object counts as dark), blackIntensity: 0..10 (6), whiteIntensity: 0..10 (2)} paints the dark areas closer to black with short strokes and the light areas with long white strokes", + json!({"balance": 5.0, "blackIntensity": 6.0, "whiteIntensity": 2.0}), + ), + r( + "brushStrokes.inkOutlines", + "Ink Outlines…", + BRUSH_STROKES, + "{strokeLength: pt 1..50 (4), darkIntensity: 0..50 (20), lightIntensity: 0..50 (10)} redraws the object in pen and ink: fine outlines over its edges and ink strokes in its shadows", + json!({"strokeLength": 4.0, "darkIntensity": 20.0, "lightIntensity": 10.0}), + ), + r( + "brushStrokes.spatter", + "Spatter…", + BRUSH_STROKES, + "{sprayRadius: pt 0..25 (10; colours scattered up to 0.4 × this), smoothness: 1..15 (5; larger, smoother grains)} renders the object as if sprayed with a spatter airbrush", + json!({"sprayRadius": 10.0, "smoothness": 5.0}), + ), + r( + "brushStrokes.sprayedStrokes", + "Sprayed Strokes…", + BRUSH_STROKES, + "{strokeLength: pt 0..20 (12), sprayRadius: pt 0..25 (7; strokes scattered up to 0.3 × this), strokeDirection: \"rightDiagonal\"|\"horizontal\"|\"leftDiagonal\"|\"vertical\" (\"rightDiagonal\")} repaints the object with sprayed, angled strokes of its main colours", + json!({"strokeLength": 12.0, "sprayRadius": 7.0, "strokeDirection": "rightDiagonal"}), + ), + r( + "brushStrokes.sumiE", + "Sumi-e…", + BRUSH_STROKES, + "{strokeWidth: pt 3..15 (10), strokePressure: 0..15 (2; more ink), contrast: 0..40 (16)} paints the object in the Japanese style, as if with a wet brush full of black ink on rice paper: soft, blurred edges and rich blacks, the colours keeping their hue and the object its shape", + json!({"strokeWidth": 10.0, "strokePressure": 2.0, "contrast": 16.0}), + ), + r( + "distort.diffuseGlow", + "Diffuse Glow…", + DISTORT, + "{graininess: 0..10 (6; white grain, thicker in the glow), glowAmount: 0..20 (10), clearAmount: 0..20 (15; the higher, the more of the image stays clear of glow)} renders the object as if seen through a soft diffusion filter: its highlights glow white under see-through white grain", + json!({"graininess": 6.0, "glowAmount": 10.0, "clearAmount": 15.0}), + ), + r( + "distort.glass", + "Glass…", + DISTORT, + "{distortion: 0..20 (5), smoothness: 1..15 (3), texture: \"blocks\"|\"canvas\"|\"frosted\"|\"tinyLens\"|\"loaded\" (\"frosted\"; \"loaded\" draws the image in textureImage and draws Frosted when there is none; the others are surfaces made in code), textureImage?: {path} | {name?, dataBase64} | string (Load Texture…: an image file that File › Place reads, within the renderer's pixel allowance, stored as its gray levels in a grayscale PNG in base64; a file sets texture to \"loaded\" unless texture is given, and the stored string, as effect.list gives it, is kept as it is), scaling: % 50..200 (100), invert: bool (false; turns the surface's heights over)} makes the object look as if seen through glass. A loaded texture lies one image pixel per point at 100 %, centered on the object's center and repeated; each pixel's luma is the surface's height, from 0 for black to 1 pt for white, and a transparent pixel counts as middle gray", + json!({"distortion": 5.0, "smoothness": 3.0, "texture": "frosted", "scaling": 100.0, "invert": false}), + ), + r( + "distort.oceanRipple", + "Ocean Ripple…", + DISTORT, + "{rippleSize: 1..15 (9), rippleMagnitude: 0..20 (9)} adds randomly spaced ripples, as if the object were under water", + json!({"rippleSize": 9.0, "rippleMagnitude": 9.0}), + ), + r( + "sharpen.unsharpMask", + "Unsharp Mask…", + SHARPEN, + "{amount: % 1..500 (50), radius: pt 0.1..250 (1; σ of the blur edges are found against), threshold: levels 0..255 (0; smaller differences are left alone)}", + json!({"amount": 50.0, "radius": 1.0, "threshold": 0.0}), + ), + r( + "sketch.basRelief", + "Bas Relief…", + SKETCH, + "{detail: 1..15 (13; the larger, the finer the features that stay), smoothness: 1..15 (3; rounds the carving), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"bottom\"; where the light comes from)} carves the object in low relief in black and white: surfaces facing the light turn white, those turned away black, flat areas grey. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"detail": 13.0, "smoothness": 3.0, "lightDirection": "bottom"}), + ), + r( + "sketch.chalkCharcoal", + "Chalk & Charcoal…", + SKETCH, + "{chalkArea: 0..20 (6; chalk in light areas), charcoalArea: 0..20 (6; charcoal in dark areas), strokePressure: 0..5 (2)} redraws the object with chalk highlights and charcoal strokes on white paper, keeping its coverage. Original visual approximation from public documentation; slider ranges and defaults are VectorCraft choices, not verified proprietary values.", + json!({"chalkArea": 6.0, "charcoalArea": 6.0, "strokePressure": 2.0}), + ), + r( + "sketch.charcoal", + "Charcoal…", + SKETCH, + "{thickness: 1..7 (1; width of the bold edges and of the strokes' spacing), detail: 0..5 (1; the larger, the finer the edges), lightDarkBalance: 0..100 (50; how far into the lights the charcoal reaches)} redraws the object in black charcoal on white paper: bold edges and diagonal strokes over the midtones. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"thickness": 1.0, "detail": 1.0, "lightDarkBalance": 50.0}), + ), + r( + "sketch.chrome", + "Chrome…", + SKETCH, + "{detail: 0..10 (4; finer surface texture), smoothness: 0..10 (4; softer relief before the highlights and shadows)} treats the object as polished chrome lit from the top left: bright highlights on high points and dark shadows in low ones, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"detail": 4.0, "smoothness": 4.0}), + ), + r( + "sketch.conteCrayon", + "Conté Crayon…", + SKETCH, + "{foregroundLevel: 0..20 (12; how far the black crayon reaches from the shadows into the midtones), backgroundLevel: 0..20 (10; how far the white crayon reaches from the highlights into the midtones), texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\" (\"canvas\"; the paper's surface, made in code), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false; turns the surface's heights over)} redraws the object in a dense black crayon in its dark areas and a pure white crayon in its light areas, on mid-grey paper whose texture breaks the strokes and stands in relief, keeping its coverage. Public help names Foreground Level, Background Level and the texture options but not slider ranges or dialog defaults; ranges and defaults here are unverified VectorCraft choices. Original visual approximation, not a proprietary reproduction.", + json!({ + "foregroundLevel": 12.0, + "backgroundLevel": 10.0, + "texture": "canvas", + "scaling": 100.0, + "relief": 4.0, + "lightDirection": "top", + "invert": false + }), + ), + r( + "sketch.graphicPen", + "Graphic Pen…", + SKETCH, + "{strokeLength: pt 1..15 (5; the longest ink stroke), lightDarkBalance: 0..100 (50; more black when higher), strokeDirection: \"rightDiagonal\"|\"horizontal\"|\"leftDiagonal\"|\"vertical\" (\"rightDiagonal\")} redraws the object in fine linear black ink on white paper, with strokes denser in darker areas. Control names and ranges follow the public documentation; the defaults are unverified.", + json!({"strokeLength": 5.0, "lightDarkBalance": 50.0, "strokeDirection": "rightDiagonal"}), + ), + r( + "sketch.halftonePattern", + "Halftone Pattern…", + SKETCH, + "{size: pt 1..12 (1; how far apart the screen's dots, rings or lines are), contrast: 0..50 (5; 50 draws pure black and white), patternType: \"circle\"|\"dot\"|\"line\" (\"dot\"; rings round the object's centre, dots on a square grid, horizontal lines)} redraws the object in black ink on white paper through a halftone screen whose ink covers as much as the colour is dark, keeping its coverage. Original visual approximation from the public Sketch effects reference; slider ranges follow the documented control names, numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults (the public help pages give no numbers).", + json!({"size": 1.0, "contrast": 5.0, "patternType": "dot"}), + ), + r( + "sketch.notePaper", + "Note Paper…", + SKETCH, + "{imageBalance: 0..50 (25; lower tones darken the emboss, higher lighten it), graininess: 0..10 (0; fibrous paper texture), relief: 0..50 (4; emboss strength in points)} embosses the object's tones on warm paper, keeping its coverage. Original visual approximation from the public Sketch effects reference; slider ranges follow the documented control names, numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults (the public help pages give no numbers).", + json!({"imageBalance": 25.0, "graininess": 0.0, "relief": 4.0}), + ), + r( + "sketch.photocopy", + "Photocopy…", + SKETCH, + "{detail: 1..24 (7; the larger, the finer the features that copy), darkness: 1..50 (25; the larger, the more of the dark copies)} copies the object in black on white: large dark areas copy only around their edges and midtones go to black or white. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"detail": 7.0, "darkness": 25.0}), + ), + r( + "sketch.plaster", + "Plaster…", + SKETCH, + "{imageBalance: 1..50 (20; higher values sink more of the image), smoothness: 1..15 (8; higher values soften the relief), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\")} molds the object in relief plaster and lights it from that direction; dark areas are raised and light areas recessed, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"imageBalance": 20.0, "smoothness": 8.0, "lightDirection": "top"}), + ), + r( + "sketch.reticulation", + "Reticulation…", + SKETCH, + "{density: 0..50 (12; finer grain at higher values), foregroundLevel: 0..50 (6; pulls shadows toward black ink), backgroundLevel: 0..50 (6; pulls highlights toward white paper)} redraws the object in black ink on white paper through a high-contrast film-grain screen, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"density": 12.0, "foregroundLevel": 6.0, "backgroundLevel": 6.0}), + ), + r( + "sketch.stamp", + "Stamp…", + SKETCH, + "{lightDarkBalance: 0..50 (25; the larger, the more of the object prints black), smoothness: 1..50 (5; rounds the shapes)} simplifies the object to solid black and white, as a rubber stamp would print it. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"lightDarkBalance": 25.0, "smoothness": 5.0}), + ), + r( + "sketch.tornEdges", + "Torn Edges…", + SKETCH, + "{imageBalance: 0..50 (25; lower leaves more midtones as ink, higher as paper), smoothness: 0..15 (11; softens tones and the ragged edges), contrast: 0..20 (17; 20 is pure black and white)} redraws the object in high-contrast black and white with torn, ragged edges along its tones, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"imageBalance": 25.0, "smoothness": 11.0, "contrast": 17.0}), + ), + r( + "sketch.waterPaper", + "Water Paper…", + SKETCH, + "{fiberLength: pt 3..50 (15; scale of paper fibers and blotchy daubs), brightness: 0..100 (50), contrast: 0..100 (50)} washes the object's colours as if painted on damp fibrous paper, with soft flow and a fibrous modulation. Public helpx names Fiber Length, Brightness and Contrast but not slider ranges or dialog defaults; ranges and defaults here are unverified VectorCraft choices. Original visual approximation, not a proprietary reproduction.", + json!({"fiberLength": 15.0, "brightness": 50.0, "contrast": 50.0}), + ), + r( + "stylize.glowingEdges", + "Glowing Edges…", + STYLIZE, + "{edgeWidth: pt 1..14 (2), edgeBrightness: 0..20 (6), smoothness: pt 1..15 (5)} finds alpha-weighted Sobel edges and draws bright coloured outlines on black", + json!({"edgeWidth": 2.0, "edgeBrightness": 6.0, "smoothness": 5.0}), + ), + r( + "pixelate.colorHalftone", + "Color Halftone…", + PIXELATE, + "{maxRadius: pt 4..127 (8; the radius of a dot at full strength, which fills its square cell), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell", + json!({"maxRadius": 8.0, "channel1": 108.0, "channel2": 162.0, "channel3": 90.0, "channel4": 45.0}), + ), + r( + "pixelate.crystallize", + "Crystallize…", + PIXELATE, + "{cellSize: pt 3..300 (10)} redraws the object as polygon crystals of solid colour around random points about cellSize apart", + json!({"cellSize": 10.0}), + ), + r( + "pixelate.mezzotint", + "Mezzotint…", + PIXELATE, + "{type: \"fineDots\"|\"mediumDots\"|\"grainyDots\"|\"coarseDots\"|\"shortLines\"|\"mediumLines\"|\"longLines\"|\"shortStrokes\"|\"mediumStrokes\"|\"longStrokes\" (\"fineDots\")} turns each colour channel fully on or off against a random pattern of dots, lines or strokes: fully saturated colours", + json!({"type": "fineDots"}), + ), + r( + "pixelate.pointillize", + "Pointillize…", + PIXELATE, + "{cellSize: pt 3..300 (5)} redraws the object as randomly placed dots of its colours on a white canvas", + json!({"cellSize": 5.0}), + ), + r( + "texture.craquelure", + "Craquelure…", + TEXTURE, + "{crackSpacing: pt 2..100 (15; how far apart the cracks are), crackDepth: 0..10 (6; how deep and wide the cracks are, and how high the plates and the tones stand), crackBrightness: 0..10 (9; how brightly the plaster is lit)} paints the object on relief plaster cracked into plates and along the contours of its tones", + json!({"crackSpacing": 15.0, "crackDepth": 6.0, "crackBrightness": 9.0}), + ), + r( + "texture.grain", + "Grain…", + TEXTURE, + "{intensity: 0..100 (40), contrast: 0..100 (50; the image's contrast, 50 leaves it as it is), grainType: \"regular\"|\"soft\"|\"sprinkles\"|\"clumped\"|\"contrasty\"|\"enlarged\"|\"stippled\"|\"horizontal\"|\"vertical\"|\"speckle\" (\"regular\")} adds grain in 1 pt grains (2 pt Enlarged, clumps Clumped, streaks Horizontal and Vertical); Sprinkles and Stippled use the background colour, white", + json!({"intensity": 40.0, "contrast": 50.0, "grainType": "regular"}), + ), + r( + "texture.mosaicTiles", + "Mosaic Tiles…", + TEXTURE, + "{tileSize: pt 2..100 (12), groutWidth: 1..15 (3; the grout is half a point wide per step), lightenGrout: 0..10 (9; how light the grout is)} lays the object in irregular tiles bevelled at their edges, with sunken grout between them", + json!({"tileSize": 12.0, "groutWidth": 3.0, "lightenGrout": 9.0}), + ), + r( + "texture.patchwork", + "Patchwork…", + TEXTURE, + "{squareSize: pt 0..10 (4; 0 draws 1 pt squares), relief: 0..25 (8)} redraws the object in squares of the colour around their centres, raised to heights that follow its highlights and shadows, a little more or less at random, lit from the top left", + json!({"squareSize": 4.0, "relief": 8.0}), + ), + r( + "texture.stainedGlass", + "Stained Glass…", + TEXTURE, + "{cellSize: pt 2..50 (10), borderThickness: 1..20 (4; the lead between the panes, half a point wide per step, in the foreground colour: black), lightIntensity: 0..10 (3; a light behind the object's centre, fading out towards its corners)} redraws the object as single-coloured panes around random points about cellSize apart", + json!({"cellSize": 10.0, "borderThickness": 4.0, "lightIntensity": 3.0}), + ), + r( + "texture.texturizer", + "Texturizer…", + TEXTURE, + "{texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\"|\"loaded\" (\"canvas\"; \"loaded\" draws the image in textureImage and draws Canvas when there is none; the others are surfaces made in code), textureImage?: {path} | {name?, dataBase64} | string (Load Texture…: an image file that File › Place reads, within the renderer's pixel allowance, stored as its gray levels in a grayscale PNG in base64; a file sets texture to \"loaded\" unless texture is given, and the stored string, as effect.list gives it, is kept as it is), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false; turns the surface's heights over)} paints the object on a surface in relief. A loaded texture lies one image pixel per point at 100 %, centered on the object's center and repeated; each pixel's luma is the surface's height, from 0 for black to 1 pt for white, and a transparent pixel counts as middle gray", + json!({"texture": "canvas", "scaling": 100.0, "relief": 4.0, "lightDirection": "top", "invert": false}), + ), + r( + "video.deinterlace", + "De-Interlace…", + VIDEO, + "{eliminate: \"odd\"|\"even\" (\"odd\"; which field lines are taken out), create: \"duplication\"|\"interpolation\" (\"duplication\"; a line taken out becomes a copy of the line above, or the average of the lines above and below)} the field lines are the rows of the document's raster grid (Document Raster Effects Settings › Resolution), numbered from 1 at the top of the page", + json!({"eliminate": "odd", "create": "duplication"}), + ), + r( + "video.ntscColors", + "NTSC Colors", + VIDEO, + "{} makes colours a television signal can't carry (luma plus chroma past 110 % of white, or luma minus chroma below −20 %) less saturated, keeping their brightness", + json!({}), + ), + ]; + v.extend([ + g( + "adjust.brightnessContrast", + "Brightness/Contrast…", + ADJUST, + "{brightness: -100..100 (0; bends the tones, black and white stay), contrast: -100..100 (0)} recolours the object's fills, strokes, type, meshes and embedded images (each colour keeps its model)", + json!({"brightness": 0.0, "contrast": 0.0}), + ), + g( + "adjust.curves", + "Curves…", + ADJUST, + "{points: \"x,y x,y …\" or [[x, y], …] (input, output 0..255; a smooth monotone curve through them, flat past the ends; \"0,0 128,128 255,255\"), channel: \"rgb\"|\"red\"|\"green\"|\"blue\" (\"rgb\")} recolours as Brightness/Contrast does", + json!({"points": "0,0 128,128 255,255", "channel": "rgb"}), + ), + g( + "adjust.hueSaturation", + "Hue/Saturation…", + ADJUST, + "{hue: deg -180..180 (0), saturation: -100..100 (0), lightness: -100..100 (0), colorize: bool (false; true: every colour takes hue `hue` (0..360) at saturation (100 + saturation) / 2 %)} recolours as Brightness/Contrast does", + json!({"hue": 0.0, "saturation": 0.0, "lightness": 0.0, "colorize": false}), + ), + g( + "adjust.levels", + "Levels…", + ADJUST, + "{inputBlack: 0..255 (0), inputWhite: 0..255 (255), gamma: 0.1..10 (1; above 1 lightens the midtones), outputBlack: 0..255 (0), outputWhite: 0..255 (255), channel: \"rgb\"|\"red\"|\"green\"|\"blue\" (\"rgb\")} recolours as Brightness/Contrast does", + json!({"inputBlack": 0.0, "inputWhite": 255.0, "gamma": 1.0, "outputBlack": 0.0, "outputWhite": 255.0, "channel": "rgb"}), + ), + g( + "adjust.shiftToColor", + "Shift to Color…", + ADJUST, + "{color: \"#rrggbb\" (\"#ff8000\"), amount: 0..100 % (50), preserveLightness: bool (true: colours take the target's hue and saturation and keep their lightness; false: they mix with it)} recolours as Brightness/Contrast does", + json!({"color": "#ff8000", "amount": 50.0, "preserveLightness": true}), + ), + g( + "adjust.temperatureTint", + "Temperature/Tint…", + ADJUST, + "{temperature: -100 (cooler) .. 100 (warmer) (0), tint: -100 (greener) .. 100 (more magenta) (0)} recolours as Brightness/Contrast does", + json!({"temperature": 0.0, "tint": 0.0}), + ), + ]); + for (suffix, label) in WARP_STYLES { + let id: &'static str = match suffix { + "arc" => "warp.arc", + "arcLower" => "warp.arcLower", + "arcUpper" => "warp.arcUpper", + "arch" => "warp.arch", + "bulge" => "warp.bulge", + "shellLower" => "warp.shellLower", + "shellUpper" => "warp.shellUpper", + "flag" => "warp.flag", + "wave" => "warp.wave", + "fish" => "warp.fish", + "rise" => "warp.rise", + "fisheye" => "warp.fisheye", + "inflate" => "warp.inflate", + "squeeze" => "warp.squeeze", + _ => "warp.twist", + }; + v.push(g(id, label, WARP, WARP_DOC, json!({"bend": 50.0, "horizontal": 0.0, "vertical": 0.0, "orientation": "horizontal"}))); + } + for (id, label, _) in PATHFINDER_EFFECTS { + if id == "pathfinder.softMix" { + v.push(g( + id, + label, + PATHFINDER, + "{mixingRate?: 1..100 % (50)} blend overlapping fills in CMYK bottom to top (groups and layers: live Pathfinder over the members)", + json!({"mixingRate": 50.0}), + )); + } else { + v.push(g(id, label, PATHFINDER, "{} (groups and layers: live Pathfinder over the members)", json!({}))); + } + } + v.push(g(TRAP, "Trap…", PATHFINDER, trap::EFFECT_PARAMS_DOC, trap::effect_defaults())); + v.push(g( + CROP_MARKS, + "Crop Marks", + &["Effect"], + "{style?: \"roman\"|\"japanese\" (default: the japaneseCropMarks preference when applied)} trim marks in [Registration] around the object's bounds, following it", + json!({}), + )); + v.push(r( + RASTERIZE, + "Rasterize…", + &["Effect"], + "{colorModel: \"document\" (the document's mode, RGB or CMYK)|\"grayscale\"|\"bitmap\" (\"document\"), useDocumentResolution: bool (true: Document Raster Effects Settings › Resolution), resolution: ppi 1..2400 (72; with useDocumentResolution false), background: \"white\"|\"transparent\" (\"transparent\"), antiAlias: \"none\"|\"art\"|\"type\" (\"art\"; none: hard edges), clippingMask: bool (false; the image clipped to the art's outline), addAround: pt 0..1000 (0; room around the art)} draws the object as an image of square pixels over its bounds and the room around them, leaving its paths, type and other art as they are; when it is the object's only raster effect, Expand Appearance makes the image Object › Rasterize makes", + json!({"colorModel": "document", "useDocumentResolution": true, "resolution": 72.0, "background": "transparent", "antiAlias": "art", "clippingMask": false, "addAround": 0.0}), + )); + v +} + +/// The catalogue built once, indexed by id (lookups run per effect per rendered frame). +pub(crate) fn catalog_index() -> &'static std::collections::HashMap<&'static str, EffectInfo> { + static INDEX: std::sync::OnceLock> = std::sync::OnceLock::new(); + INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect()) +} + +/// Catalogue entry for `id` (built-in, or an installed plug-in effect). +pub fn effect_info(id: &str) -> Option { + catalog_index().get(id).cloned().or_else(|| plugin_info(id)) +} + +/// The catalogue entry of the installed effect plug-in with effect id `id` (`plugin.`). +pub(crate) fn plugin_info(id: &str) -> Option { + use vectorcraft_plugins::registry::intern; + let p = vectorcraft_plugins::effect::installed(id)?; + let m = p.manifest(); + let dots = if m.params.is_empty() || m.name.ends_with('…') { "" } else { "…" }; + Some(EffectInfo { + id: intern(id), + label: intern(&format!("{}{dots}", m.name)), + menu: PLUGINS, + params: intern(&m.params_doc()), + defaults: Value::Object(m.defaults()), + raster: false, + lengths: Lengths::default(), + }) +} + +/// The installed effect plug-ins as catalogue entries (Effect › Plug-ins), by plug-in id. +pub fn plugin_effects() -> Vec { + vectorcraft_plugins::registry::list().iter().filter_map(|p| plugin_info(&vectorcraft_plugins::effect::effect_id(p.id()))).collect() +} diff --git a/crates/effects/src/distort.rs b/crates/effects/src/distort.rs index 502cf962a4..b7430e0c79 100644 --- a/crates/effects/src/distort.rs +++ b/crates/effects/src/distort.rs @@ -10,8 +10,9 @@ fn diag(b: Rect) -> f64 { b.width().hypot(b.height()).max(1e-6) } -/// Free Distort: bilinear map of the bounding box onto four new corners (unit box coordinates). -pub fn free_distort(path: &PathData, b: Rect, p: &Value) -> PathData { +/// Free Distort: bilinear map of the bounding box onto four new corners (unit box coordinates), +/// making at most `max` anchors ([`map_nonlinear_within`]). +pub fn free_distort(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData { let mut c = [Point::new(0.0, 0.0), Point::new(1.0, 0.0), Point::new(1.0, 1.0), Point::new(0.0, 1.0)]; if let Some(arr) = p.get("corners").and_then(Value::as_array) { for (i, v) in arr.iter().take(4).enumerate() { @@ -34,7 +35,7 @@ pub fn free_distort(path: &PathData, b: Rect, p: &Value) -> PathData { let bot = c[3].lerp(c[2], u); top.lerp(bot, v) }; - map_nonlinear(path, diag(b) / 16.0, f) + map_nonlinear_within(path, diag(b) / 16.0, max, f) } /// Pucker & Bloat: anchors move toward (bloat) or away from (pucker) the centre, handles the @@ -67,21 +68,29 @@ pub fn pucker_bloat(path: &PathData, b: Rect, amount: f64) -> PathData { } } -/// Roughen: resample at `detail` points per inch and jitter each point by up to `size`. -pub fn roughen(path: &PathData, b: Rect, p: &Value) -> PathData { +/// Most points Roughen resamples one segment into. +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). +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 }; let detail = num(p, "detail", 10.0).clamp(0.0, 100.0); let spacing = if detail > 0.0 { 72.0 / detail } else { f64::INFINITY }; + // A segment of k points adds k - 1 anchors to the path. + let lens: Vec = 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(); let smooth = smooth_points(p); let seed = seed(p); let mut subs = vec![]; for (si, sp) in path.subpaths.iter().enumerate() { let mut pts = vec![]; - for i in 0..sp.segment_count() { + for (i, &len) in (0..sp.segment_count()).zip(&mut lens) { let c = sp.segment(i); - let len = vectorcraft_geom::kurbo::ParamCurveArclen::arclen(&c, 0.1); - let k = if spacing.is_finite() { ((len / spacing).ceil() as usize).clamp(1, 2000) } else { 1 }; + let k = pieces(len, spacing, MAX_ROUGHEN_POINTS); for j in 0..k { pts.push(c.eval(j as f64 / k as f64)); } @@ -105,11 +114,16 @@ pub fn roughen(path: &PathData, b: Rect, p: &Value) -> PathData { /// 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 by a random share, or moves pattern paints along (Transform Patterns), or scales +/// strokes while leaving the geometry (Scale Strokes & Effects with Transform Objects off). pub(crate) fn transform_move(p: &Value) -> Option<(Vec2, usize)> { let (m, copies) = transform_map(Rect::ZERO, p, 0); let [a, b, c, d, x, y] = m.as_coeffs(); - (!flag(p, "random", false) && [a, b, c, d] == [1.0, 0.0, 0.0, 1.0]).then_some((Vec2::new(x, y), copies)) + // Transform Patterns moves the patterns along; with Transform Objects off, Scale Strokes & + // Effects still scales the strokes by the map the geometry doesn't take. + let o = TransformOptions::of(p); + let plain = !flag(p, "random", false) && !o.patterns && (o.objects || !o.strokes); + (plain && [a, b, c, d] == [1.0, 0.0, 0.0, 1.0]).then_some((Vec2::new(x, y), copies)) } /// The offsets at which Transform effects with params `ps`, applied in order, place `path`, the @@ -161,7 +175,9 @@ pub(crate) fn within_reach(r: Rect) -> bool { /// (the 9-point grid, 4 = centre), then move; `copies` more times, each from the last. With /// `random`, each scale goes a random share of the way from 100 % to its value and each move and /// the angle a share of theirs, drawn from `seed` (the object's), so an object keeps its result -/// on every redraw while each object varies its own way. +/// on every redraw while each object varies its own way. With Transform Objects off the path stays +/// as it is; Transform Patterns and Scale Strokes & Effects reach the appearance through the +/// object's art ([`crate::has_transform_art`]). pub fn transform(path: &PathData, b: Rect, p: &Value, seed: u64) -> PathData { transform_within(path, b, p, seed, MAX_COPY_ANCHORS) } @@ -192,12 +208,49 @@ pub(crate) fn transform_within(path: &PathData, b: Rect, p: &Value, seed: u64, m out } +/// The Transform effect's options beyond its geometry (#885). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct TransformOptions { + /// Transform Objects (default on): the geometry transforms and is copied. Off, it stays where + /// it is and only the two options below apply, once. + pub objects: bool, + /// Transform Patterns (default off): pattern fills and strokes transform along. + pub patterns: bool, + /// Scale Strokes & Effects (default off): stroke weights and dashes, and the distances of the + /// effects on the fills and strokes, scale by the map's mean scale (`√|det|`). + pub strokes: bool, +} + +impl TransformOptions { + /// The options of a Transform effect with params `p`. Missing keys take their defaults, so + /// effects saved before the options existed draw as they did. + pub fn of(p: &Value) -> Self { + Self { objects: flag(p, "objects", true), patterns: flag(p, "patterns", false), strokes: flag(p, "strokes", false) } + } + + /// Do they reach past the geometry (Transform Patterns or Scale Strokes & Effects)? + pub fn reach_appearance(self) -> bool { + self.patterns || self.strokes + } +} + /// The Transform effect's map and how many copies of what it is applied to it makes, for bounds /// `b` (the reference point lies on them), params `p` and the object's `seed` for Random: the map /// applies to the object itself when `copies` is 0, and once more to each of `copies` copies /// otherwise (see [`transform_within`], and images, whose copies count nodes against -/// [`MAX_COPY_OBJECTS`]). +/// [`MAX_COPY_OBJECTS`]). With Transform Objects off the geometry stays: the identity and no +/// copies ([`transform_affine`] is the map its other options still use). pub(crate) fn transform_map(b: Rect, p: &Value, seed: u64) -> (Affine, usize) { + if !TransformOptions::of(p).objects { + return (Affine::IDENTITY, 0); + } + (transform_affine(b, p, seed), num(p, "copies", 0.0).clamp(0.0, 1000.0) as usize) +} + +/// The one transformation of the Transform effect with params `p` on an object of bounds `b` +/// (the reference point lies on them; `seed` for Random), whatever Transform Objects says. Each +/// copy applies it once more to the last. +pub(crate) fn transform_affine(b: Rect, p: &Value, seed: u64) -> Affine { let random = flag(p, "random", false); // The share (0..1) of value `k` applied. let share = |k: u64| if random { (noise(seed, k, 0, 0) + 1.0) / 2.0 } else { 1.0 }; @@ -206,12 +259,10 @@ pub(crate) fn transform_map(b: Rect, p: &Value, seed: u64) -> (Affine, usize) { let reflect = |key: &str| if flag(p, key, false) { -1.0 } else { 1.0 }; let o = vectorcraft_geom::reference_point(b, num(p, "reference", 4.0).clamp(0.0, 8.0) as usize).to_vec2(); // Reflect X flips the x coordinates (left to right), Reflect Y the y coordinates. - let m = Affine::translate(Vec2::new(moved("moveH", 2), moved("moveV", 3)) + o) + Affine::translate(Vec2::new(moved("moveH", 2), moved("moveV", 3)) + o) * Affine::rotate(-(num(p, "rotate", 0.0) * share(4)).to_radians()) * Affine::scale_non_uniform(scale("scaleH", 0) * reflect("reflectX"), scale("scaleV", 1) * reflect("reflectY")) - * Affine::translate(-o); - let copies = num(p, "copies", 0.0).clamp(0.0, 1000.0) as usize; - (m, copies) + * Affine::translate(-o) } /// Tweak: random displacement of anchors and/or control points. @@ -246,8 +297,9 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData { out } -/// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle. -pub fn twist(path: &PathData, b: Rect, angle: f64) -> PathData { +/// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle, +/// making at most `max` anchors ([`map_nonlinear_within`]). +pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { let ang = angle.clamp(-3600.0, 3600.0).to_radians(); if ang == 0.0 { return path.clone(); @@ -261,8 +313,8 @@ pub fn twist(path: &PathData, b: Rect, angle: f64) -> PathData { let (s, co) = a.sin_cos(); c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co) }; - let pieces = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0)); - map_nonlinear(path, pieces, f) + let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0)); + map_nonlinear_within(path, piece, max, f) } const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4; @@ -280,11 +332,17 @@ struct Ridge { /// displaced along the normal. Corner points join them with straight lines. Smooth points make a /// wave: every peak and valley is a smooth point whose handles run along the path, a third of the /// way to the next ridge, so each span between them follows a half cosine (an S through the path) -/// whatever the size of the ridges (#2343). -pub fn zig_zag(path: &PathData, b: Rect, p: &Value) -> PathData { +/// whatever the size of the ridges (#2343). Where `ridges` would make more than `max` anchors, +/// each segment gets as many as fit (stacked Zig Zags multiply their points, #3578). +pub fn zig_zag(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData { let size = num(p, "size", 10.0).clamp(-1e4, 1e4); let amp = if flag(p, "relative", false) { size / 100.0 * mean_size(b) } else { size }; - let ridges = num(p, "ridges", 4.0).clamp(0.0, 100.0) as usize; + // Each segment makes `ridges + 1` points, and an open path's end one more (all its anchors + // when it has no segment). With no ridges, that is at most the path's own anchors. + let segs = path.subpaths.iter().map(SubPath::segment_count).fold(0, usize::saturating_add); + let ends: usize = path.subpaths.iter().filter(|sp| !sp.closed).map(|sp| if sp.segment_count() > 0 { 1 } else { sp.anchors.len() }).sum(); + let fit = (max.saturating_sub(ends) / segs.max(1)).saturating_sub(1); + let ridges = (num(p, "ridges", 4.0).clamp(0.0, 100.0) as usize).min(fit); let smooth = smooth_points(p); let mut subs = vec![]; for sp in &path.subpaths { diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs new file mode 100644 index 0000000000..7d25d19552 --- /dev/null +++ b/crates/effects/src/geometry.rs @@ -0,0 +1,219 @@ +use super::params::{is_geometry, merged_params}; +use super::*; + +/// Context the geometry effects may need from the object's appearance. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct GeomContext<'a> { + /// The stroke `path.outlineStroke` outlines (its weight, caps, joins, dashes, alignment, + /// profile and arrowheads): the stroke the effect sits on, else the object's top painted + /// stroke. `None` outlines a plain 1 pt stroke. + pub stroke: Option<&'a StrokeLayer>, + /// The object's fill rule (inside and outside alignment). + pub rule: FillRule, + /// The seed of the Transform effect's Random: the object's id, so each object varies its own + /// way and keeps its result on every redraw. + pub seed: u64, + /// The object's appearance, which live-effect plug-ins are given read only (their fills and + /// strokes). + pub appearance: Option<&'a Appearance>, + /// The index in `appearance.items` of the fill or stroke whose own effects these are; `None`: + /// the object's effects. + pub item: Option, +} + +impl<'a> GeomContext<'a> { + /// The context of `n`'s object-level effects. + pub fn of(n: &'a Node) -> Self { + let rule = match &n.kind { + NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. } => *rule, + _ => FillRule::NonZero, + }; + let stroke = n.appearance.stroke().filter(|s| !s.paint.is_none() && s.width > 0.0); + Self { stroke, rule, seed: n.id.0, appearance: Some(&n.appearance), item: None } + } + + /// The context of the effects on `item`, one of the same object's appearance items: a + /// stroke's own effects outline that stroke, and a plug-in is told which item it is on. + pub fn item(self, item: &'a AppearanceItem) -> Self { + let at = self.appearance.and_then(|a| a.items.iter().position(|i| std::ptr::eq(i, item))); + match item { + AppearanceItem::Stroke(s) => Self { stroke: Some(s), item: at, ..self }, + AppearanceItem::Fill(_) => Self { item: at, ..self }, + } + } +} + +/// Most anchors a chain of geometry effects makes of one path, or of all the paths of a type, +/// symbol or image art together; a path that already has more keeps its own count as the limit. +/// Roughen resamples each segment into up to 2000 points, Zig Zag into up to 101 and the warps +/// into up to 64, so stacked effects multiply: three Roughens of a rectangle needed tens of +/// gigabytes (#3578). Each effect builds within it, and one whose result would still pass it is +/// left out. +pub(crate) const MAX_EFFECT_ANCHORS: usize = 2_000_000; + +/// Most lines the renderer is estimated to draw a chain of geometry effects' result with at +/// 1 px/pt ([`util::line_estimate`]), or the path's own estimate when that is more. A large +/// Roughen or Zig Zag makes segments thousands of points long, each drawn as up to hundreds of +/// lines: two million anchors of them came to 141 million lines, 7 GB in the renderer and past +/// the 2²⁷ lines vello takes of one path (#3578). Art of small curves draws its anchors as a few +/// lines each, so this rarely binds before [`MAX_EFFECT_ANCHORS`] does. +pub(crate) const MAX_EFFECT_LINES: usize = 8_000_000; + +/// What geometry effects may make of a path, or what a path costs: its anchors and the lines the +/// renderer is estimated to draw it with. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Budget { + pub anchors: usize, + pub lines: usize, +} + +impl Budget { + /// The budget of a chain of geometry effects. + pub(crate) const EFFECTS: Self = Self { anchors: MAX_EFFECT_ANCHORS, lines: MAX_EFFECT_LINES }; + + /// What `path` costs. + pub(crate) fn of(path: &PathData) -> Self { + Self { anchors: path.anchor_count(), lines: util::line_estimate(path) } + } + + /// This budget, raised to `cost` where that is more. + pub(crate) fn at_least(self, cost: Self) -> Self { + Self { anchors: self.anchors.max(cost.anchors), lines: self.lines.max(cost.lines) } + } + + /// Does `cost` fit this budget? + pub(crate) fn fits(self, cost: Self) -> bool { + cost.anchors <= self.anchors && cost.lines <= self.lines + } + + /// What is left of this budget once `cost` is spent. + pub(crate) fn minus(self, cost: Self) -> Self { + Self { anchors: self.anchors.saturating_sub(cost.anchors), lines: self.lines.saturating_sub(cost.lines) } + } + + /// This cost and `cost` together. + pub(crate) fn plus(self, cost: Self) -> Self { + Self { anchors: self.anchors.saturating_add(cost.anchors), lines: self.lines.saturating_add(cost.lines) } + } +} + +/// Evaluate the visible geometry effects of `effects` on `path`, in order. `bounds` is the +/// reference box of the first effect (usually the object's geometric bounds); each later effect +/// uses the bounds of its input. Raster and unknown effects are skipped, and so is an effect +/// whose result would pass 2 million anchors or 8 million lines drawn (or the path's own counts, +/// when they are more). +pub fn apply_geometry(effects: &[Effect], path: &PathData, bounds: Rect) -> PathData { + apply_geometry_with(effects, path, bounds, &GeomContext::default()) +} + +/// [`apply_geometry`] with an explicit [`GeomContext`]. +pub fn apply_geometry_with(effects: &[Effect], path: &PathData, bounds: Rect, ctx: &GeomContext) -> PathData { + apply_geometry_within(effects, path, bounds, ctx, Budget::EFFECTS) +} + +/// [`apply_geometry_with`] whose effects keep to `budget`, raised to what `path` costs where that +/// is more. +pub(crate) fn apply_geometry_within(effects: &[Effect], path: &PathData, bounds: Rect, ctx: &GeomContext, budget: Budget) -> PathData { + // `budget` raised to what `path` costs, measured once, and only for a path that has geometry + // effects. + let mut limit = None; + let mut cur = path.clone(); + let mut b = bounds; + let mut first = true; + for e in effects.iter().filter(|e| e.visible && is_geometry(&e.id)) { + if !first { + b = cur.bounds().unwrap_or(b); + } + first = false; + if cur.is_empty() { + break; + } + let p = merged_params(&e.id, &e.params); + let limit = *limit.get_or_insert_with(|| budget.at_least(Budget::of(path))); + if let Some(next) = apply_one(&e.id, &p, &cur, b, ctx, limit) { + cur = next; + } + } + cur +} + +/// Convenience wrapper on kurbo paths. +pub fn apply_geometry_bez(effects: &[Effect], path: &BezPath, bounds: Rect, ctx: &GeomContext) -> BezPath { + apply_geometry_with(effects, &PathData::from_bezpath(path), bounds, ctx).to_bezpath() +} + +/// Geometry effect `id` with params `p` on `path`, whose reference box is `b`; `None` when its +/// result would not fit `budget` (the effects that multiply anchors build within its anchors). +pub(crate) fn apply_one(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext, budget: Budget) -> Option { + let out = apply_unchecked(id, p, path, b, ctx, budget.anchors); + let cost = Budget::of(&out); + if budget.fits(cost) { + return Some(out); + } + if cost.lines <= budget.lines || !builds_within(id) { + return None; + } + // Anchors drawn as many lines each (a large Roughen or Zig Zag): once more with as many fewer + // anchors as there were lines too many, and a tenth to spare, as segments vary in their lines. + let fewer = (cost.anchors as f64 * 0.9 * (budget.lines as f64 / cost.lines as f64)) as usize; + let out = apply_unchecked(id, p, path, b, ctx, fewer.min(budget.anchors)); + budget.fits(Budget::of(&out)).then_some(out) +} + +/// Does geometry effect `id` build within the anchors it is given? +fn builds_within(id: &str) -> bool { + matches!(id, "distort.freeDistort" | "distort.roughen" | "distort.transform" | "distort.twist" | "distort.zigZag") || id.starts_with("warp.") +} + +/// [`apply_one`] whose result may pass `max` when the effect doesn't build within it. +fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext, max: usize) -> PathData { + use util::*; + if let Some(plugin) = vectorcraft_plugins::effect::plugin_id(id) { + let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item }; + return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints).unwrap_or_else(|| path.clone()); + } + match id { + "distort.freeDistort" => distort::free_distort(path, b, p, max), + "distort.puckerBloat" => distort::pucker_bloat(path, b, num(p, "amount", 0.0)), + "distort.roughen" => distort::roughen(path, b, p, max), + "distort.transform" => distort::transform_within(path, b, p, ctx.seed, max), + "distort.tweak" => distort::tweak(path, b, p), + "distort.twist" => distort::twist(path, b, num(p, "angle", 10.0), max), + "distort.zigZag" => distort::zig_zag(path, b, p, max), + "path.offsetPath" => { + let off = num(p, "offset", 10.0).clamp(-1e5, 1e5); + if off.abs() < 1e-9 { + return path.clone(); + } + vectorcraft_pathops::offset_path(path, off, join(p, "joins"), num(p, "miterLimit", 4.0).clamp(1.0, 500.0)) + } + // Outline Object returns the geometry unchanged. Type reaches every geometry effect as its + // glyph outlines (`reshape::reshape`), so type that carries it is drawn as those outlines. + "path.outlineObject" => path.clone(), + "path.outlineStroke" => { + let fallback; + let base = match ctx.stroke { + Some(s) => s, + None => { + fallback = StrokeLayer::new(vectorcraft_doc::color::Paint::None, 1.0); + &fallback + } + }; + let st = match p.get("width").and_then(Value::as_f64) { + Some(w) => std::borrow::Cow::Owned(StrokeLayer { width: w, ..base.clone() }), + None => std::borrow::Cow::Borrowed(base), + }; + if st.width.is_nan() || st.width <= 0.0 { + return path.clone(); + } + stroke::outline_region(path, ctx.rule, &st) + } + "convertToShape.rectangle" | "convertToShape.roundedRectangle" | "convertToShape.ellipse" => stylize::convert_to_shape(id, b, p), + "stylize.roundCorners" => stylize::round_corners(path, num(p, "radius", 10.0)), + "stylize.scribble" => stylize::scribble(path, b, p), + _ => match id.strip_prefix("warp.").and_then(WarpStyle::from_id) { + Some(style) => warp::warp(path, b, style, p, max), + None => path.clone(), + }, + } +} diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 2211a4364d..ad59278507 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -4,7 +4,8 @@ //! children are the Pathfinder stack (back → front). In the shape modes (Add, Subtract, Intersect, //! Exclude, Minus Back) a child group acts as one shape — the union of its leaves, styled like its //! top leaf — as in the Pathfinder panel. The result replaces the children at render time; each -//! result keeps the appearance of the object whose paint it takes. +//! result keeps the appearance of the object whose paint it takes. Trap ([`crate::trap`]) keeps the +//! children and adds its traps above them. //! //! **Container appearance** ([`evaluate_container`]): a group's or layer's own fills and strokes //! paint every member's geometry, below or above the members as its contents slot says @@ -13,12 +14,14 @@ use std::sync::Arc; -use vectorcraft_doc::{Appearance, AppearanceItem, Node, NodeId, NodeKind, StrokeLayer}; +use serde_json::Value; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, StrokeLayer}; use vectorcraft_geom::{FillRule, PathData, Rect}; use vectorcraft_pathops::{self as po, PathfinderOp}; /// Effect ids of the Pathfinder submenu with their operation, in Illustrator's menu order. -pub const PATHFINDER_EFFECTS: [(&str, &str, PathfinderOp); 10] = [ +pub const PATHFINDER_EFFECTS: [(&str, &str, PathfinderOp); 12] = [ ("pathfinder.add", "Add", PathfinderOp::Unite), ("pathfinder.intersect", "Intersect", PathfinderOp::Intersect), ("pathfinder.exclude", "Exclude", PathfinderOp::Exclude), @@ -29,6 +32,8 @@ pub const PATHFINDER_EFFECTS: [(&str, &str, PathfinderOp); 10] = [ ("pathfinder.merge", "Merge", PathfinderOp::Merge), ("pathfinder.crop", "Crop", PathfinderOp::Crop), ("pathfinder.outline", "Outline", PathfinderOp::Outline), + ("pathfinder.hardMix", "Hard Mix", PathfinderOp::HardMix), + ("pathfinder.softMix", "Soft Mix", PathfinderOp::SoftMix), ]; /// Is `id` an Effect → Pathfinder effect? @@ -100,23 +105,136 @@ fn styled(src: &Node, path: PathData, outline: bool) -> Node { n } +/// Most segments a live Pathfinder effect takes in, as for the Shape Builder. +pub const PATHFINDER_MAX_SEGMENTS: usize = po::SHAPE_BUILDER_MAX_SEGMENTS; + +/// Most pairs of input paths whose bounds overlap a live Pathfinder effect takes in. Crossings, +/// and so the pieces of the result, grow with these pairs (n bars crossing n make n² crossings) +/// and the effect runs on every draw: past this the group draws its art unprocessed (#3591). +pub const PATHFINDER_MAX_OVERLAPS: usize = 16_384; + +/// Fenwick tree of counts over `n` slots, for counting the active boxes of [`within_budget`]. +struct Counts(Vec); + +// `isolate_lowest_one` is still unstable in Rust 1.96, and the workspace builds on 1.95 (rust-version). +#[allow(unknown_lints, clippy::manual_isolate_lowest_one)] +impl Counts { + fn add(&mut self, slot: usize, d: isize) { + let mut i = slot + 1; + while let Some(c) = self.0.get_mut(i) { + *c += d; + i += i & i.wrapping_neg(); + } + } + + /// Sum of the slots before `end`. + fn before(&self, end: usize) -> isize { + let (mut i, mut s) = (end.min(self.0.len().saturating_sub(1)), 0); + while i > 0 { + s += self.0.get(i).copied().unwrap_or(0); + i -= i & i.wrapping_neg(); + } + s + } +} + +/// Can a live Pathfinder evaluate `leaves` within [`PATHFINDER_MAX_SEGMENTS`] and +/// [`PATHFINDER_MAX_OVERLAPS`]? The overlapping pairs of bounds are counted exactly by a sweep +/// in x that keeps the active boxes in two Fenwick trees over their y extents, so the check costs +/// O(n log n) however the boxes are laid out. +fn within_budget<'a>(leaves: impl IntoIterator) -> bool { + let mut segments = 0usize; + let mut boxes: Vec = vec![]; + for l in leaves { + let Some((path, _)) = geometry(l) else { continue }; + segments += path.subpaths.iter().map(|sp| sp.segment_count()).sum::(); + if segments > PATHFINDER_MAX_SEGMENTS { + return false; + } + boxes.extend(path.bounds()); + } + let mut ys: Vec = boxes.iter().flat_map(|b| [b.y0, b.y1]).collect(); + ys.sort_by(f64::total_cmp); + ys.dedup_by(|a, b| a.total_cmp(b).is_eq()); + // Slots of the y values below `y`, and of those at or below it. + let below = |y: f64| ys.partition_point(|v| v.total_cmp(&y).is_lt()); + let upto = |y: f64| ys.partition_point(|v| v.total_cmp(&y).is_le()); + // (x, is end, box); starts sort before ends at the same x since touching boxes overlap. + let mut events: Vec<(f64, bool, usize)> = boxes.iter().enumerate().flat_map(|(i, b)| [(b.x0, false, i), (b.x1, true, i)]).collect(); + events.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + // Active boxes counted by the slot of their y0 and of their y1. + let mut by_y0 = Counts(vec![0; ys.len() + 1]); + let mut by_y1 = Counts(vec![0; ys.len() + 1]); + let (mut active, mut overlaps) = (0isize, 0usize); + for (_, end, i) in events { + let Some(b) = boxes.get(i) else { continue }; + if end { + by_y0.add(below(b.y0), -1); + by_y1.add(below(b.y1), -1); + active -= 1; + continue; + } + // Active boxes not entirely below b (y1 < b.y0) nor entirely above it (y0 > b.y1). + let above = active - by_y0.before(upto(b.y1)); + let under = by_y1.before(below(b.y0)); + overlaps += usize::try_from(active - above - under).unwrap_or(0); + if overlaps > PATHFINDER_MAX_OVERLAPS { + return false; + } + by_y0.add(below(b.y0), 1); + by_y1.add(below(b.y1), 1); + active += 1; + } + true +} + /// Evaluate the visible Pathfinder effects of `group` in order: the resulting child objects. -/// `None` when the group has no Pathfinder effect. +/// `None` when the group has no Pathfinder effect. Past the budget ([`PATHFINDER_MAX_SEGMENTS`], +/// [`PATHFINDER_MAX_OVERLAPS`]) it returns the children as they are. pub fn pathfinder_children(group: &Node, hook: Option) -> Option>> { if !has_pathfinder(group) { return None; } - let mut stack: Vec> = group.children()?.to_vec(); + let source: &[Arc] = group.children()?; + let mut stack: Vec> = source.to_vec(); for e in group.appearance.effects.iter().filter(|e| e.visible) { + if e.id == crate::trap::TRAP { + let mut lv = vec![]; + for c in &stack { + leaves(c, hook, &mut lv); + } + if !within_budget(&lv) { + return Some(source.to_vec()); + } + let (ids, srcs): (Vec, Vec) = lv + .iter() + .filter_map(|l| { + let (path, rule) = geometry(l)?; + Some((l.id, crate::trap::TrapSource { path, rule, fill: l.appearance.fill_paint() })) + }) + .unzip(); + let made = crate::trap::traps(&srcs, &crate::trap::TrapOptions::from_params(&e.params)); + stack.extend(made.into_iter().map(|p| Arc::new(crate::trap::trap_node(ids.get(p.from).copied().unwrap_or(NodeId(0)), p)))); + continue; + } let Some(op) = op_of(&e.id) else { continue }; let shape_mode = matches!(op, PathfinderOp::Unite | PathfinderOp::MinusFront | PathfinderOp::Intersect | PathfinderOp::Exclude | PathfinderOp::MinusBack); + let all: Vec> = stack + .iter() + .map(|c| { + let mut lv = vec![]; + leaves(c, hook, &mut lv); + lv + }) + .collect(); + if !within_budget(all.iter().flatten()) { + return Some(source.to_vec()); + } // (style source, shape) per stack entry; keys index `sources`. let mut sources: Vec = vec![]; let mut shapes: Vec = vec![]; - for c in &stack { - let mut lv = vec![]; - leaves(c, hook, &mut lv); + for mut lv in all { if shape_mode && lv.len() > 1 { let parts: Vec<(PathData, FillRule)> = lv.iter().filter_map(geometry).collect(); let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect(); @@ -138,15 +256,88 @@ pub fn pathfinder_children(group: &Node, hook: Option) -> Option f64 { + params.get("mixingRate").and_then(|v| v.as_f64()).filter(|r| r.is_finite() && *r > 0.0 && *r <= 100.0).map(|r| r / 100.0).unwrap_or(0.5) +} + +fn fill_cmyk(src: &Node) -> Option<[f32; 4]> { + let paint = src.appearance.fill_paint(); + let color = paint.color()?; + let tinted = match paint { + Paint::Solid { tint, .. } => color.tinted(tint), + _ => color, + }; + Some(tinted.to_cmyk()) +} + +/// One face of a Soft Mix: CMYK blended bottom to top at `rate`; no stroke. +fn soft_mix_face(path: PathData, covering: &[usize], rate: f64, shapes: &[po::Shape], sources: &[Node]) -> Node { + let rate = rate as f32; + let mut cmyk: Option<[f32; 4]> = None; + for &si in covering { + let Some(ch) = fill_cmyk(&sources[shapes[si].key as usize]) else { continue }; + cmyk = Some(match cmyk { + None => ch, + Some(acc) => { + let t = rate; + let u = 1.0 - t; + [acc[0] * u + ch[0] * t, acc[1] * u + ch[1] * t, acc[2] * u + ch[2] * t, acc[3] * u + ch[3] * t] + } + }); + } + let fill = cmyk.map(|c| Paint::solid(Color::cmyk(c[0], c[1], c[2], c[3]))).unwrap_or(Paint::None); + soft_mix_styled(path, covering, shapes, sources, fill) +} + +/// One face of a Hard Mix: the max of each CMYK channel over every covering shape's fill; no stroke. +fn hard_mix_face(path: PathData, covering: &[usize], shapes: &[po::Shape], sources: &[Node]) -> Node { + let mut cmyk = [0.0f32; 4]; + let mut painted = false; + for &si in covering { + let Some(ch) = fill_cmyk(&sources[shapes[si].key as usize]) else { continue }; + for (out, v) in cmyk.iter_mut().zip(ch) { + *out = out.max(v); + } + painted = true; + } + let fill = if painted { Paint::solid(Color::cmyk(cmyk[0], cmyk[1], cmyk[2], cmyk[3])) } else { Paint::None }; + soft_mix_styled(path, covering, shapes, sources, fill) +} + +fn soft_mix_styled(path: PathData, covering: &[usize], shapes: &[po::Shape], sources: &[Node], fill: Paint) -> Node { + let top = covering.last().and_then(|&si| sources.get(shapes[si].key as usize)); + let mut n = Node::path(top.map_or(NodeId(0), |s| s.id), path, Appearance::basic(fill, Paint::None, 0.0)); + if let Some(src) = top { + n.opacity = src.opacity; + n.blend = src.blend; + } + n +} + fn is_container(n: &Node) -> bool { matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) } @@ -175,9 +366,10 @@ pub fn has_container_appearance(n: &Node) -> bool { /// The regions a group's or layer's own fills and strokes paint, in document space, each with its /// fill rule: every visible member path and compound path, type as its glyph outlines and live /// objects evaluated; the members of a clip group or clipping layer without its clipping path. -/// Images, symbol instances and guides add nothing. -pub fn member_shapes(n: &Node) -> Vec<(PathData, FillRule)> { - fn push(n: &Node, out: &mut Vec<(PathData, FillRule)>) { +/// Images, symbol instances and guides add nothing. A Repeat counts the Repeats in the art of +/// `doc`'s symbols that its instances show toward its instance budget. +pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRule)> { + fn push(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) { if !n.visible { return; } @@ -189,19 +381,19 @@ pub fn member_shapes(n: &Node) -> Vec<(PathData, FillRule)> { out.push((PathData::from_bezpath(&all).transformed(t.xf), FillRule::NonZero)); } } - NodeKind::Group { .. } | NodeKind::Layer { .. } => members(n, out), - _ if vectorcraft_doc::live::is_live(n) => members(&crate::reshape::outlined_members(n), out), + NodeKind::Group { .. } | NodeKind::Layer { .. } => members(doc, n, out), + _ if vectorcraft_doc::live::is_live(n) => members(doc, &crate::reshape::outlined_members(doc, n), out), _ => {} } } - fn members(n: &Node, out: &mut Vec<(PathData, FillRule)>) { + fn members(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) { let clip = usize::from(n.clips()); for c in n.children().into_iter().flatten().skip(clip) { - push(c, out); + push(doc, c, out); } } let mut out = vec![]; - members(n, &mut out); + members(doc, n, &mut out); out } @@ -243,8 +435,9 @@ fn item_art(id: NodeId, item: &AppearanceItem, shapes: &[(PathData, FillRule)], /// reshaping all its members as one piece (the whole art's bounds as their reference box), 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. -pub fn evaluate_container(n: &Node) -> Option { +/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live +/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]). +pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { if !is_container(n) { return None; } @@ -263,12 +456,12 @@ pub fn evaluate_container(n: &Node) -> Option { } } if !fx.is_empty() { - m = crate::reshape::outlined_members(&m); + m = crate::reshape::outlined_members(doc, &m); crate::reshape::reshape_leaves(&mut m, &fx); } m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !crate::is_geometry(&e.id)); if paint { - let shapes = member_shapes(&m); + let shapes = member_shapes(doc, &m); let bounds = m.geometric_bounds(); let art = |items: &[AppearanceItem]| -> Vec> { items.iter().filter_map(|i| item_art(n.id, i, &shapes, bounds)).map(Arc::new).collect() }; @@ -287,236 +480,4 @@ pub fn evaluate_container(n: &Node) -> Option { } #[cfg(test)] -mod tests { - use super::*; - use vectorcraft_color::{BlendMode, Color, Paint}; - use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject}; - use vectorcraft_geom::{Point, Rect, shapes}; - - /// Type tests need glyph outlines, which only the optional craft-fonts build input provides. - fn skip_without_craft_fonts() -> bool { - let skip = vectorcraft_text::CRAFT_FONTS.is_empty(); - if skip { - eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); - } - skip - } - - fn sq(id: u64, x: f64, color: Color) -> Arc { - Arc::new(Node::path( - NodeId(id), - shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), - Appearance::basic(Paint::solid(color), Paint::None, 0.0), - )) - } - - fn group_with(effect: &str) -> Node { - let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0))]); - g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({}), visible: true }); - g - } - - fn area(n: &Node) -> f64 { - po::area(n.path_data().unwrap(), FillRule::NonZero).abs() - } - - #[test] - fn shape_modes_follow_the_pathfinder_panel() { - let add = pathfinder_children(&group_with("pathfinder.add"), None).unwrap(); - assert_eq!(add.len(), 1); - assert!((area(&add[0]) - 150.0).abs() < 1e-3); - // Add keeps the front object's paint, Subtract the back one's. - assert_eq!(add[0].id, NodeId(2)); - let sub = pathfinder_children(&group_with("pathfinder.subtract"), None).unwrap(); - assert_eq!(sub[0].id, NodeId(1)); - assert!((area(&sub[0]) - 50.0).abs() < 1e-3); - let int = pathfinder_children(&group_with("pathfinder.intersect"), None).unwrap(); - assert!((area(&int[0]) - 50.0).abs() < 1e-3); - let div = pathfinder_children(&group_with("pathfinder.divide"), None).unwrap(); - assert_eq!(div.len(), 3); - } - - /// Returns an "H" in blue type at 100 pt on a baseline at y = 80, with its stems on either - /// side of x = 100. - fn type_h() -> Node { - let style = CharStyle { size: 100.0, fill: Paint::solid(Color::rgb(0.0, 0.0, 1.0)), ..CharStyle::default() }; - Node::new(NodeId(2), NodeKind::Text(Box::new(TextObject::point(Point::new(70.0, 80.0), "H", style)))) - } - - /// Returns a group with `effect` that holds a red 100 x 100 square and `front` in front of it. - fn square_and(front: Option, effect: &str) -> Node { - let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); - let square = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), red); - let mut g = Node::group(NodeId(10), [Some(square), front].into_iter().flatten().map(Arc::new).collect()); - g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({}), visible: true }); - g - } - - /// Returns the Pathfinder results of `g`, with type outlined as the renderer outlines it. - fn results(g: &Node) -> Vec> { - pathfinder_children(g, crate::text_outliner()).unwrap() - } - - #[test] - fn type_changes_the_result_of_every_pathfinder_effect() { - if skip_without_craft_fonts() { - return; - } - let glyphs = crate::outline_text(&type_h()).unwrap(); - let b = glyphs.geometric_bounds().unwrap(); - assert!(b.x0 < 100.0 && b.x1 > 100.0 && b.y0 > 0.0 && b.y1 < 100.0, "{b:?}"); - // `measure` gives the number of results and their total area. - let measure = |front: Option, effect: &str| { - let r = results(&square_and(front, effect)); - (r.len(), r.iter().map(|n| area(n)).sum::()) - }; - let unchanged: Vec<_> = PATHFINDER_EFFECTS - .iter() - .map(|(id, label, _)| (label, measure(Some(type_h()), id), measure(None, id))) - .filter(|(_, with, without)| with.0 == without.0 && (with.1 - without.1).abs() <= 1.0) - .collect(); - assert!(unchanged.is_empty(), "(label, with the type, without): {unchanged:?}"); - // The shape modes take the glyph's whole area: the part inside the square and the part outside. - let glyph_area: f64 = glyphs.children().unwrap().iter().map(|n| area(n)).sum(); - let with_type = |id: &str| measure(Some(type_h()), id).1; - assert!((with_type("pathfinder.add") - with_type("pathfinder.subtract") - glyph_area).abs() < 0.5, "{glyph_area}"); - assert!((with_type("pathfinder.intersect") + with_type("pathfinder.minusBack") - glyph_area).abs() < 0.5, "{glyph_area}"); - // Outline art nested one group deeper takes part as well. - let nested: OutlineHook = &|n: &Node| crate::outline_text(n).map(|g| Node::group(n.id, vec![Arc::new(g)])); - let sub = pathfinder_children(&square_and(Some(type_h()), "pathfinder.subtract"), Some(nested)).unwrap(); - assert!((sub.iter().map(|n| area(n)).sum::() - with_type("pathfinder.subtract")).abs() < 1e-6); - } - - #[test] - fn pieces_of_type_keep_its_paint_opacity_and_blend_mode() { - if skip_without_craft_fonts() { - return; - } - let mut t = type_h(); - (t.opacity, t.blend) = (0.5, BlendMode::Multiply); - let look = |p: &Arc| (p.appearance.fill_paint(), p.opacity, p.blend); - let square = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0, BlendMode::Normal); - let glyph = (Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 0.5, BlendMode::Multiply); - let looks: Vec<_> = results(&square_and(Some(t.clone()), "pathfinder.divide")).iter().map(look).collect(); - assert!(looks.contains(&square) && looks.contains(&glyph) && looks.iter().all(|l| *l == square || *l == glyph), "{looks:?}"); - // In the shape modes a group with the type in front is one shape, styled like the type. - let green = Appearance::basic(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0); - let behind = Node::path(NodeId(3), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), green); - let both = Node::group(NodeId(4), vec![Arc::new(behind), Arc::new(t)]); - let added: Vec<_> = results(&square_and(Some(both), "pathfinder.add")).iter().map(look).collect(); - assert_eq!(added, [glyph]); - } - - #[test] - fn a_random_transform_on_a_group_moves_its_members_together() { - let mut g = group_with("distort.transform"); - g.appearance.effects[0].params = serde_json::json!({"moveH": 100, "moveV": 100, "random": true}); - let art = evaluate_container(&g).unwrap(); - let corner = |i: usize| art.children().and_then(|c| c.get(i)).and_then(|n| n.geometric_bounds()).map(|b| (b.x0, b.y0)).unwrap(); - let (a, b) = (corner(0), corner(1)); - assert!(a.0 > 0.0 && a.0 < 100.0, "moved by a share of the value: {a:?}"); - assert!((b.0 - a.0 - 5.0).abs() < 1e-9 && (b.1 - a.1).abs() < 1e-9, "{a:?} {b:?}"); - } - - /// What [`evaluate_container`] makes of black 40 pt type "IIII" (id 3), changed by `style`, - /// in a group with a square and Offset Path 0, which leaves every path as it is. - fn type_in_group(style: impl FnOnce(&mut Node)) -> Node { - let ts = vectorcraft_doc::CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; - let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", ts); - let mut t = Node::new(NodeId(3), NodeKind::Text(Box::new(text))); - style(&mut t); - let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::BLACK), Arc::new(t)]); - g.appearance.effects.push(Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 0}), visible: true }); - let art = evaluate_container(&g).unwrap(); - (*art.children().unwrap()[1]).clone() - } - - #[test] - fn type_in_a_group_keeps_its_look_when_the_groups_geometry_effects_outline_it() { - if skip_without_craft_fonts() { - return; - } - use vectorcraft_color::BlendMode; - let art = type_in_group(|t| (t.opacity, t.blend) = (0.5, BlendMode::Multiply)); - assert!(art.id == NodeId(3) && !matches!(art.kind, NodeKind::Text(_)), "{art:?}"); - assert_eq!((art.opacity, art.blend), (0.5, BlendMode::Multiply)); - // Its opacity mask, its own shadow, its knockout shape option and its visibility stay. - let mask_art = Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default()); - let mask = vectorcraft_doc::OpacityMask::new(mask_art, true); - assert_eq!(type_in_group(|t| t.extras_mut().mask = Some(Box::new(mask.clone()))).extras().mask.as_deref(), Some(&mask)); - let shadow = Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({}), visible: true }; - assert_eq!(type_in_group(|t| t.appearance.effects.push(shadow.clone())).appearance.effects, vec![shadow]); - assert!(type_in_group(|t| t.knockout_shape = true).knockout_shape); - assert!(!type_in_group(|t| t.visible = false).visible); - // Its own Transform moves its outlines 30 pt before the group's effect reshapes them. - let x0 = |n: Node| n.geometric_bounds().unwrap().x0; - let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30}), visible: true }; - let moved = x0(type_in_group(|t| t.appearance.effects.push(transform))); - assert!((moved - x0(type_in_group(|_| {})) - 30.0).abs() < 1e-6, "{moved}"); - } - - #[test] - fn hidden_effect_or_plain_group_is_untouched() { - let mut g = group_with("pathfinder.add"); - g.appearance.effects[0].visible = false; - assert!(pathfinder_children(&g, None).is_none()); - assert!(!has_pathfinder(&sq(1, 0.0, Color::BLACK))); - } - - #[test] - fn a_transform_on_a_group_moves_the_gradients_of_its_type_and_not_those_placed_on_its_paths() { - if skip_without_craft_fonts() { - return; - } - use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; - let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; - let ramp = GradientPaint::new(Gradient { kind: GradientKind::Linear, stops }); - // The type's characters fit the gradient to its layout; the square has it placed across itself. - let style = vectorcraft_doc::CharStyle { size: 40.0, fill: Paint::Gradient(Box::new(ramp.clone())), ..Default::default() }; - let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", style); - let t = Arc::new(Node::new(NodeId(3), NodeKind::Text(Box::new(text)))); - let geom = GradientGeom { start: (0.0, 5.0).into(), end: (10.0, 5.0).into(), aspect: 1.0, focal: None }; - let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp })); - let square = Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(placed, Paint::None, 0.0))); - let start = |n: &Node| match n.appearance.fill_paint() { - Paint::Gradient(g) => g.geom.unwrap().start.x, - p => panic!("a gradient: {p:?}"), - }; - let before = start(&crate::outline_text(&t).unwrap().children().unwrap()[0]); - let mut g = Node::group(NodeId(10), vec![square, t]); - g.appearance.effects.push(Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30}), visible: true }); - let art = evaluate_container(&g).unwrap(); - let members = art.children().unwrap(); - let after = start(&members[1].children().unwrap()[0]); - assert!((after - before - 30.0).abs() < 1e-6, "the type's gradient starts at {before}, then {after}"); - assert_eq!(start(&members[0]), 0.0, "the square's gradient stays where it was placed"); - } - - #[test] - fn a_transform_on_a_group_paints_each_copy_with_its_own_gradient() { - use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; - let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; - let ramp = GradientPaint::new(Gradient { kind: GradientKind::Linear, stops }); - let geom = GradientGeom { start: (0.0, 5.0).into(), end: (10.0, 5.0).into(), aspect: 1.0, focal: None }; - let paints = [Paint::Gradient(Box::new(ramp.clone())), Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }))]; - for (k, paint) in paints.into_iter().enumerate() { - let square = - Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(paint, Paint::None, 0.0))); - let mut g = Node::group(NodeId(10), vec![square]); - 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(&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 (i, c) in copies.iter().enumerate() { - // Each copy's own box: an unplaced gradient fits it, a placed one moved with it. - assert!((c.geometric_bounds().unwrap().x0 - 30.0 * i as f64).abs() < 1e-6); - match c.appearance.fill_paint() { - Paint::Gradient(g) if k == 0 => assert!(g.geom.is_none(), "copy {i} fits its own box"), - Paint::Gradient(g) => assert!((g.geom.unwrap().start.x - 30.0 * i as f64).abs() < 1e-6, "copy {i}"), - p => panic!("a gradient: {p:?}"), - } - } - } - } -} +mod tests; diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs new file mode 100644 index 0000000000..c3bf4bfe3f --- /dev/null +++ b/crates/effects/src/group/tests.rs @@ -0,0 +1,349 @@ +use super::*; +use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject}; +use vectorcraft_geom::{Point, Rect, shapes}; + +/// Type tests need glyph outlines, which only the optional craft-fonts build input provides. +fn skip_without_craft_fonts() -> bool { + let skip = vectorcraft_text::CRAFT_FONTS.is_empty(); + if skip { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + } + skip +} + +fn sq(id: u64, x: f64, color: Color) -> Arc { + Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::basic(Paint::solid(color), Paint::None, 0.0))) +} + +fn group_with(effect: &str) -> Node { + let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0))]); + g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({}), visible: true }); + g +} + +fn area(n: &Node) -> f64 { + po::area(n.path_data().unwrap(), FillRule::NonZero).abs() +} + +fn overlap_cmyk(g: &Node) -> [f32; 4] { + let faces = pathfinder_children(g, None).unwrap(); + assert_eq!(faces.len(), 3); + let overlap = faces + .iter() + .find(|n| { + let b = n.geometric_bounds().unwrap(); + b.x0 >= 4.9 && b.x1 <= 10.1 && b.y0 <= 0.1 && b.y1 >= 9.9 + }) + .expect("overlap face"); + assert!(overlap.appearance.stroke_paint().is_none()); + overlap.appearance.fill_paint().color().unwrap().to_cmyk() +} + +fn two_overlapping_cmyk_squares() -> Node { + let a = Appearance::basic(Paint::solid(Color::cmyk(0.2, 0.66, 0.4, 0.0)), Paint::solid(Color::BLACK), 2.0); + let b = Appearance::basic(Paint::solid(Color::cmyk(0.4, 0.2, 0.3, 0.1)), Paint::solid(Color::BLACK), 2.0); + Node::group( + NodeId(10), + vec![ + Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), a)), + Arc::new(Node::path(NodeId(2), shapes::rectangle(Rect::new(5.0, 0.0, 15.0, 10.0)), b)), + ], + ) +} + +/// Effect › Pathfinder › Trap keeps the members and adds an overprinting strip of the lighter +/// colour inside the darker one along the edge where they meet. +#[test] +fn trap_effect_adds_an_overprinting_strip_above_the_members() { + let yellow = Color::cmyk(0.0, 0.0, 1.0, 0.0); + let blue = Color::cmyk(1.0, 0.6, 0.0, 0.0); + let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, yellow), sq(2, 10.0, blue)]); + let params = serde_json::json!({"thickness": 1.0, "tintReduction": 100}); + g.appearance.effects.push(Effect { id: crate::trap::TRAP.into(), params, visible: true }); + let out = pathfinder_children(&g, None).unwrap(); + assert_eq!(out.len(), 3, "both squares and one trap"); + assert_eq!((out[0].id, out[1].id), (NodeId(1), NodeId(2))); + let b = out[2].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0).abs() < 0.02 && (b.x1 - 11.0).abs() < 0.02 && b.y0.abs() < 0.02 && (b.y1 - 10.0).abs() < 0.02, "{b:?}"); + let fill = out[2].appearance.fill().unwrap(); + assert!(fill.overprint); + assert_eq!(fill.paint.color(), Some(yellow)); +} + +#[test] +fn hard_mix_takes_the_highest_of_each_cmyk_channel_and_drops_strokes() { + let mut g = two_overlapping_cmyk_squares(); + g.appearance.effects.push(Effect { id: "pathfinder.hardMix".into(), params: serde_json::json!({}), visible: true }); + let [c, m, y, k] = overlap_cmyk(&g); + assert!((c - 0.4).abs() < 0.02 && (m - 0.66).abs() < 0.02 && (y - 0.4).abs() < 0.02 && (k - 0.1).abs() < 0.02, "{c} {m} {y} {k}"); +} + +#[test] +fn soft_mix_blends_cmyk_bottom_to_top_and_drops_strokes() { + let mut g = two_overlapping_cmyk_squares(); + g.appearance.effects.push(Effect { id: "pathfinder.softMix".into(), params: serde_json::json!({"mixingRate": 50.0}), visible: true }); + let [c, m, y, k] = overlap_cmyk(&g); + assert!((c - 0.3).abs() < 0.02 && (m - 0.43).abs() < 0.02 && (y - 0.35).abs() < 0.02 && (k - 0.05).abs() < 0.02, "{c} {m} {y} {k}"); +} + +#[test] +fn shape_modes_follow_the_pathfinder_panel() { + let add = pathfinder_children(&group_with("pathfinder.add"), None).unwrap(); + assert_eq!(add.len(), 1); + assert!((area(&add[0]) - 150.0).abs() < 1e-3); + // Add keeps the front object's paint, Subtract the back one's. + assert_eq!(add[0].id, NodeId(2)); + let sub = pathfinder_children(&group_with("pathfinder.subtract"), None).unwrap(); + assert_eq!(sub[0].id, NodeId(1)); + assert!((area(&sub[0]) - 50.0).abs() < 1e-3); + let int = pathfinder_children(&group_with("pathfinder.intersect"), None).unwrap(); + assert!((area(&int[0]) - 50.0).abs() < 1e-3); + let div = pathfinder_children(&group_with("pathfinder.divide"), None).unwrap(); + assert_eq!(div.len(), 3); +} + +/// Returns an "H" in blue type at 100 pt on a baseline at y = 80, with its stems on either +/// side of x = 100. +fn type_h() -> Node { + let style = CharStyle { size: 100.0, fill: Paint::solid(Color::rgb(0.0, 0.0, 1.0)), ..CharStyle::default() }; + Node::new(NodeId(2), NodeKind::Text(Box::new(TextObject::point(Point::new(70.0, 80.0), "H", style)))) +} + +/// Returns a group with `effect` that holds a red 100 x 100 square and `front` in front of it. +fn square_and(front: Option, effect: &str) -> Node { + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let square = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), red); + let mut g = Node::group(NodeId(10), [Some(square), front].into_iter().flatten().map(Arc::new).collect()); + g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({}), visible: true }); + g +} + +/// Returns the Pathfinder results of `g`, with type outlined as the renderer outlines it. +fn results(g: &Node) -> Vec> { + pathfinder_children(g, crate::text_outliner()).unwrap() +} + +#[test] +fn type_changes_the_result_of_every_pathfinder_effect() { + if skip_without_craft_fonts() { + return; + } + let glyphs = crate::outline_text(&type_h()).unwrap(); + let b = glyphs.geometric_bounds().unwrap(); + assert!(b.x0 < 100.0 && b.x1 > 100.0 && b.y0 > 0.0 && b.y1 < 100.0, "{b:?}"); + // `measure` gives the number of results and their total area. + let measure = |front: Option, effect: &str| { + let r = results(&square_and(front, effect)); + (r.len(), r.iter().map(|n| area(n)).sum::()) + }; + let unchanged: Vec<_> = PATHFINDER_EFFECTS + .iter() + .map(|(id, label, _)| (label, measure(Some(type_h()), id), measure(None, id))) + .filter(|(_, with, without)| with.0 == without.0 && (with.1 - without.1).abs() <= 1.0) + .collect(); + assert!(unchanged.is_empty(), "(label, with the type, without): {unchanged:?}"); + // The shape modes take the glyph's whole area: the part inside the square and the part outside. + let glyph_area: f64 = glyphs.children().unwrap().iter().map(|n| area(n)).sum(); + let with_type = |id: &str| measure(Some(type_h()), id).1; + assert!((with_type("pathfinder.add") - with_type("pathfinder.subtract") - glyph_area).abs() < 0.5, "{glyph_area}"); + assert!((with_type("pathfinder.intersect") + with_type("pathfinder.minusBack") - glyph_area).abs() < 0.5, "{glyph_area}"); + // Outline art nested one group deeper takes part as well. + let nested: OutlineHook = &|n: &Node| crate::outline_text(n).map(|g| Node::group(n.id, vec![Arc::new(g)])); + let sub = pathfinder_children(&square_and(Some(type_h()), "pathfinder.subtract"), Some(nested)).unwrap(); + assert!((sub.iter().map(|n| area(n)).sum::() - with_type("pathfinder.subtract")).abs() < 1e-6); +} + +#[test] +fn pieces_of_type_keep_its_paint_opacity_and_blend_mode() { + if skip_without_craft_fonts() { + return; + } + let mut t = type_h(); + (t.opacity, t.blend) = (0.5, BlendMode::Multiply); + let look = |p: &Arc| (p.appearance.fill_paint(), p.opacity, p.blend); + let square = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0, BlendMode::Normal); + let glyph = (Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 0.5, BlendMode::Multiply); + let looks: Vec<_> = results(&square_and(Some(t.clone()), "pathfinder.divide")).iter().map(look).collect(); + assert!(looks.contains(&square) && looks.contains(&glyph) && looks.iter().all(|l| *l == square || *l == glyph), "{looks:?}"); + // In the shape modes a group with the type in front is one shape, styled like the type. + let green = Appearance::basic(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0); + let behind = Node::path(NodeId(3), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), green); + let both = Node::group(NodeId(4), vec![Arc::new(behind), Arc::new(t)]); + let added: Vec<_> = results(&square_and(Some(both), "pathfinder.add")).iter().map(look).collect(); + assert_eq!(added, [glyph]); +} + +#[test] +fn a_random_transform_on_a_group_moves_its_members_together() { + let mut g = group_with("distort.transform"); + g.appearance.effects[0].params = serde_json::json!({"moveH": 100, "moveV": 100, "random": true}); + let art = evaluate_container(None, &g).unwrap(); + let corner = |i: usize| art.children().and_then(|c| c.get(i)).and_then(|n| n.geometric_bounds()).map(|b| (b.x0, b.y0)).unwrap(); + let (a, b) = (corner(0), corner(1)); + assert!(a.0 > 0.0 && a.0 < 100.0, "moved by a share of the value: {a:?}"); + assert!((b.0 - a.0 - 5.0).abs() < 1e-9 && (b.1 - a.1).abs() < 1e-9, "{a:?} {b:?}"); +} + +/// What [`evaluate_container`] makes of black 40 pt type "IIII" (id 3), changed by `style`, +/// in a group with a square and Offset Path 0, which leaves every path as it is. +fn type_in_group(style: impl FnOnce(&mut Node)) -> Node { + let ts = vectorcraft_doc::CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", ts); + let mut t = Node::new(NodeId(3), NodeKind::Text(Box::new(text))); + style(&mut t); + let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::BLACK), Arc::new(t)]); + g.appearance.effects.push(Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 0}), visible: true }); + let art = evaluate_container(None, &g).unwrap(); + (*art.children().unwrap()[1]).clone() +} + +#[test] +fn type_in_a_group_keeps_its_look_when_the_groups_geometry_effects_outline_it() { + if skip_without_craft_fonts() { + return; + } + use vectorcraft_color::BlendMode; + let art = type_in_group(|t| (t.opacity, t.blend) = (0.5, BlendMode::Multiply)); + assert!(art.id == NodeId(3) && !matches!(art.kind, NodeKind::Text(_)), "{art:?}"); + assert_eq!((art.opacity, art.blend), (0.5, BlendMode::Multiply)); + // Its opacity mask, its own shadow, its knockout shape option and its visibility stay. + let mask_art = Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default()); + let mask = vectorcraft_doc::OpacityMask::new(mask_art, true); + assert_eq!(type_in_group(|t| t.extras_mut().mask = Some(Box::new(mask.clone()))).extras().mask.as_deref(), Some(&mask)); + let shadow = Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({}), visible: true }; + assert_eq!(type_in_group(|t| t.appearance.effects.push(shadow.clone())).appearance.effects, vec![shadow]); + assert!(type_in_group(|t| t.knockout_shape = true).knockout_shape); + assert!(!type_in_group(|t| t.visible = false).visible); + // Its own Transform moves its outlines 30 pt before the group's effect reshapes them. + let x0 = |n: Node| n.geometric_bounds().unwrap().x0; + let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30}), visible: true }; + let moved = x0(type_in_group(|t| t.appearance.effects.push(transform))); + assert!((moved - x0(type_in_group(|_| {})) - 30.0).abs() < 1e-6, "{moved}"); +} + +#[test] +fn hidden_effect_or_plain_group_is_untouched() { + let mut g = group_with("pathfinder.add"); + g.appearance.effects[0].visible = false; + assert!(pathfinder_children(&g, None).is_none()); + assert!(!has_pathfinder(&sq(1, 0.0, Color::BLACK))); +} + +#[test] +fn a_transform_on_a_group_moves_the_gradients_of_its_type_and_not_those_placed_on_its_paths() { + if skip_without_craft_fonts() { + return; + } + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); + // The type's characters fit the gradient to its layout; the square has it placed across itself. + let style = vectorcraft_doc::CharStyle { size: 40.0, fill: Paint::Gradient(Box::new(ramp.clone())), ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", style); + let t = Arc::new(Node::new(NodeId(3), NodeKind::Text(Box::new(text)))); + let geom = GradientGeom { start: (0.0, 5.0).into(), end: (10.0, 5.0).into(), aspect: 1.0, focal: None }; + let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp })); + let square = Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(placed, Paint::None, 0.0))); + let start = |n: &Node| match n.appearance.fill_paint() { + Paint::Gradient(g) => g.geom.unwrap().start.x, + p => panic!("a gradient: {p:?}"), + }; + let before = start(&crate::outline_text(&t).unwrap().children().unwrap()[0]); + let mut g = Node::group(NodeId(10), vec![square, t]); + g.appearance.effects.push(Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30}), visible: true }); + let art = evaluate_container(None, &g).unwrap(); + let members = art.children().unwrap(); + let after = start(&members[1].children().unwrap()[0]); + assert!((after - before - 30.0).abs() < 1e-6, "the type's gradient starts at {before}, then {after}"); + assert_eq!(start(&members[0]), 0.0, "the square's gradient stays where it was placed"); +} + +#[test] +fn a_transform_on_a_group_paints_each_copy_with_its_own_gradient() { + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); + let geom = GradientGeom { start: (0.0, 5.0).into(), end: (10.0, 5.0).into(), aspect: 1.0, focal: None }; + let paints = [Paint::Gradient(Box::new(ramp.clone())), Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }))]; + for (k, paint) in paints.into_iter().enumerate() { + let square = Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(paint, Paint::None, 0.0))); + let mut g = Node::group(NodeId(10), vec![square]); + 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 (i, c) in copies.iter().enumerate() { + // Each copy's own box: an unplaced gradient fits it, a placed one moved with it. + assert!((c.geometric_bounds().unwrap().x0 - 30.0 * i as f64).abs() < 1e-6); + match c.appearance.fill_paint() { + Paint::Gradient(g) if k == 0 => assert!(g.geom.is_none(), "copy {i} fits its own box"), + Paint::Gradient(g) => assert!((g.geom.unwrap().start.x - 30.0 * i as f64).abs() < 1e-6, "copy {i}"), + p => panic!("a gradient: {p:?}"), + } + } + } +} + +/// 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 { + let len = 4.0 * n as f64; + let paint = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let mut children = vec![]; + for i in 0..n { + let at = 4.0 * i as f64; + children.push(Arc::new(Node::path(NodeId(100 + i as u64), shapes::rectangle(Rect::new(at, 0.0, at + 2.0, len)), paint.clone()))); + } + for i in 0..n { + let at = 4.0 * i as f64; + let id = NodeId(100 + (n + i) as u64); + children.push(Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, at, len, at + 2.0)), paint.clone()))); + } + let mut g = Node::group(NodeId(10), children); + g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({}), visible: true }); + g +} + +#[test] +fn pathfinder_past_its_budget_draws_the_source_art() { + // n² crossings past the cap: no evaluation (#3591), the source art as it is. + for n in [130, 800] { + let g = crossing_bars(n, "pathfinder.divide"); + let out = pathfinder_children(&g, None).unwrap(); + assert_eq!(out.len(), 2 * n, "{n} x {n} bars"); + let ids: Vec = out.iter().map(|c| c.id).collect(); + let src: Vec = g.children().unwrap().iter().map(|c| c.id).collect(); + assert_eq!(ids, src, "{n} x {n} bars"); + assert!(out.iter().zip(g.children().unwrap()).all(|(a, b)| a.path_data() == b.path_data())); + } +} + +#[test] +fn pathfinder_within_its_budget_still_divides() { + // Each bar is cut into one piece per crossing plus the n pieces between and past them, so + // n x n bars divide into 3·n² pieces, and 128 x 128 bars, which overlap in exactly + // `PATHFINDER_MAX_OVERLAPS` pairs, must still divide. + for n in [8, 128] { + let out = pathfinder_children(&crossing_bars(n, "pathfinder.divide"), None).unwrap(); + assert_eq!(out.len(), 3 * n * n, "{n} x {n} bars"); + } +} + +#[test] +fn pathfinder_on_many_stacked_bars_still_runs() { + // 3000 bars stacked in y all overlap in x, but each overlaps only the next one in y: 2999 + // overlapping pairs are within the budget, so Add still merges them into one path. + let paint = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let children = (0..3000) + .map(|i| { + let at = 1.5 * i as f64; + Arc::new(Node::path(NodeId(100 + i as u64), shapes::rectangle(Rect::new(0.0, at, 100.0, at + 2.0)), paint.clone())) + }) + .collect(); + let mut g = Node::group(NodeId(10), children); + g.appearance.effects.push(Effect { id: "pathfinder.add".into(), params: serde_json::json!({}), visible: true }); + let out = pathfinder_children(&g, None).unwrap(); + assert_eq!(out.len(), 1); +} diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 45b50d5f97..e3055da0bc 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -20,6 +20,8 @@ //! art painting its members (its raster effects then apply to the composite). //! - [`clip_outline`] is the region a clip group clips to, shared by the renderer and the SVG and //! PDF writers. +//! - [`preview`] measures objects as they are drawn, with their geometry effects (Use Preview +//! Bounds). //! - **Plug-in effects** (`plugin.`, Effect › Plug-ins) are geometry effects run by an //! installed WebAssembly plug-in (`vectorcraft-plugins`); [`effect_info`] describes them like //! built-in ones, and an effect whose plug-in isn't installed leaves the geometry as it is. @@ -38,22 +40,23 @@ mod clip; mod distort; mod group; mod lighting; +mod lighting_presets; mod live; mod marks; pub mod pixel; +pub mod preview; mod raster; mod reshape; mod revolve; mod solids; pub mod stroke; mod stylize; +pub mod trap; mod util; mod warp; #[cfg(test)] mod tests; -#[cfg(test)] -mod tests_scale; use serde_json::{Map, Value, json}; use vectorcraft_doc::{Appearance, AppearanceItem, Effect, Node, NodeKind, StrokeLayer}; @@ -69,987 +72,33 @@ pub use group::{ OutlineHook, PATHFINDER_EFFECTS, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_shapes, paints, pathfinder_children, }; +pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset}; pub use live::{expand_live, expand_live_deep, expanded_live_group, text_outliner}; pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; pub use raster::{RASTERIZE, RasterFx, Rasterize, outset, raster_effects}; -pub use reshape::{expand_outlined, has_gradient_copies, has_item_geometry, image_paint, needs_outline, outline_art, outline_text, reshape}; +pub use reshape::{ + expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_options, image_paint, needs_outline, outline_art, + outline_text, reshape, +}; pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve}; pub use solids::{ EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SOLIDS, extrude_options, has_solid, inflate_options, is_three_d, solid_art, validate_solid, - view_options, + validate_three_d, view_options, }; +pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; +pub use trap::TRAP; pub use warp::{WarpStyle, warp_point}; -/// Catalogue entry for one effect. -#[derive(Clone, Debug, PartialEq)] -pub struct EffectInfo { - /// Stable id, e.g. `distort.roughen`. - pub id: &'static str, - /// Menu label (with the ellipsis when the effect has a dialog). - pub label: &'static str, - /// Effect-menu path, e.g. `["Effect", "Distort & Transform"]`. - pub menu: &'static [&'static str], - /// Human/agent-readable parameter documentation. - pub params: &'static str, - /// Dialog defaults. - pub defaults: Value, - /// Raster (painted) rather than geometry effect. - pub raster: bool, - /// The parameters that are distances in points (Scale Strokes & Effects scales them). - pub lengths: Lengths, -} +mod catalog; +mod geometry; +mod params; -/// Which of an effect's parameters are distances in points. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct Lengths { - /// Always distances. - pub always: &'static [&'static str], - /// Distances while the effect's `relative` parameter is false (percentages of the object's - /// size otherwise). - pub absolute: &'static [&'static str], -} - -impl Lengths { - /// The distance parameters while the effect's `relative` parameter is `relative`. - pub fn keys(&self, relative: bool) -> impl Iterator + '_ { - self.always.iter().chain(if relative { &[][..] } else { self.absolute }).copied() - } -} - -/// Is parameter `key` of effect `id` a distance in points while its `relative` parameter is -/// `relative`? -pub fn is_length(id: &str, key: &str, relative: bool) -> bool { - catalog_index().get(id).is_some_and(|info| info.lengths.keys(relative).any(|k| k == key)) -} - -/// The distance parameters of effect `id` (none for unknown effects). -fn lengths_of(id: &str) -> Lengths { - let always = |always| Lengths { always, absolute: &[] }; - match id { - "convertToShape.rectangle" | "convertToShape.ellipse" => always(&["extraW", "extraH", "width", "height"]), - "convertToShape.roundedRectangle" => always(&["extraW", "extraH", "width", "height", "radius"]), - "distort.roughen" | "distort.zigZag" => Lengths { always: &[], absolute: &["size"] }, - "distort.tweak" => Lengths { always: &[], absolute: &["h", "v"] }, - "distort.transform" => always(&["moveH", "moveV"]), - "path.offsetPath" => always(&["offset"]), - "threeD.revolve" => always(&["offset"]), - "threeD.extrude" => always(&["depth", "bevelWidth", "bevelHeight"]), - "threeD.inflate" => always(&["depth"]), - "path.outlineStroke" => always(&["width"]), - "stylize.roundCorners" | "stylize.feather" | "blur.gaussian" | "blur.smart" | "sharpen.unsharpMask" => always(&["radius"]), - "stylize.scribble" => always(&["overlap", "overlapVariation", "strokeWidth", "spacing", "spacingVariation"]), - "stylize.dropShadow" => always(&["x", "y", "blur"]), - "stylize.innerGlow" | "stylize.outerGlow" => always(&["blur"]), - "stylize.glowingEdges" => always(&["edgeWidth", "smoothness"]), - "brushStrokes.accentedEdges" => always(&["edgeWidth"]), - "brushStrokes.angledStrokes" | "brushStrokes.crosshatch" | "brushStrokes.inkOutlines" => always(&["strokeLength"]), - "brushStrokes.spatter" => always(&["sprayRadius"]), - "brushStrokes.sprayedStrokes" => always(&["strokeLength", "sprayRadius"]), - "brushStrokes.sumiE" => always(&["strokeWidth"]), - "pixelate.colorHalftone" => always(&["maxRadius"]), - "pixelate.crystallize" | "pixelate.pointillize" => always(&["cellSize"]), - "texture.craquelure" => always(&["crackSpacing"]), - "texture.mosaicTiles" => always(&["tileSize"]), - "texture.patchwork" => always(&["squareSize"]), - "texture.stainedGlass" => always(&["cellSize"]), - "sketch.graphicPen" => always(&["strokeLength"]), - "sketch.halftonePattern" => always(&["size"]), - "sketch.notePaper" => always(&["relief"]), - RASTERIZE => always(&["addAround"]), - _ => Lengths::default(), - } -} - -const WARP_DOC: &str = - "{bend: % (-100..100, 50), horizontal: % distortion (0), vertical: % distortion (0), orientation: \"horizontal\"|\"vertical\"}"; -const DT: &[&str] = &["Effect", "Distort & Transform"]; -const PATH: &[&str] = &["Effect", "Path"]; -const SHAPE: &[&str] = &["Effect", "Convert to Shape"]; -const STYLIZE: &[&str] = &["Effect", "Stylize"]; -const WARP: &[&str] = &["Effect", "Warp"]; -const BLUR: &[&str] = &["Effect", "Blur"]; -const ARTISTIC: &[&str] = &["Effect", "Artistic"]; -const BRUSH_STROKES: &[&str] = &["Effect", "Brush Strokes"]; -const DISTORT: &[&str] = &["Effect", "Distort"]; -const SHARPEN: &[&str] = &["Effect", "Sharpen"]; -const SKETCH: &[&str] = &["Effect", "Sketch"]; -const PIXELATE: &[&str] = &["Effect", "Pixelate"]; -const TEXTURE: &[&str] = &["Effect", "Texture"]; -const VIDEO: &[&str] = &["Effect", "Video"]; -const PATHFINDER: &[&str] = &["Effect", "Pathfinder"]; -const PLUGINS: &[&str] = &["Effect", "Plug-ins"]; -const ADJUST: &[&str] = &["Effect", "Color Adjustments"]; - -/// The warp styles in Illustrator's Style menu order: (id suffix, label). -pub const WARP_STYLES: [(&str, &str); 15] = [ - ("arc", "Arc…"), - ("arcLower", "Arc Lower…"), - ("arcUpper", "Arc Upper…"), - ("arch", "Arch…"), - ("bulge", "Bulge…"), - ("shellLower", "Shell Lower…"), - ("shellUpper", "Shell Upper…"), - ("flag", "Flag…"), - ("wave", "Wave…"), - ("fish", "Fish…"), - ("rise", "Rise…"), - ("fisheye", "Fisheye…"), - ("inflate", "Inflate…"), - ("squeeze", "Squeeze…"), - ("twist", "Twist…"), -]; - -/// Every supported effect with its dialog defaults. -pub fn effect_catalog() -> Vec { - let g = |id, label, menu, params, defaults| EffectInfo { id, label, menu, params, defaults, raster: false, lengths: lengths_of(id) }; - let r = |id, label, menu, params, defaults| EffectInfo { id, label, menu, params, defaults, raster: true, lengths: lengths_of(id) }; - let mut v = vec![ - g( - 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}), - ), - 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}), - ), - 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}), - ), - 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}), - ), - g( - "convertToShape.rectangle", - "Rectangle…", - SHAPE, - "{relative: bool (true), extraW: pt (18), extraH: pt (18), width: pt (absolute, 100), height: pt (absolute, 100)}", - json!({"relative": true, "extraW": 18.0, "extraH": 18.0, "width": 100.0, "height": 100.0}), - ), - g( - "convertToShape.roundedRectangle", - "Rounded Rectangle…", - SHAPE, - "{relative: bool (true), extraW: pt (18), extraH: pt (18), width, height (absolute), radius: pt (9)}", - json!({"relative": true, "extraW": 18.0, "extraH": 18.0, "width": 100.0, "height": 100.0, "radius": 9.0}), - ), - g( - "convertToShape.ellipse", - "Ellipse…", - SHAPE, - "{relative: bool (true), extraW: pt (18), extraH: pt (18), width, height (absolute)}", - json!({"relative": true, "extraW": 18.0, "extraH": 18.0, "width": 100.0, "height": 100.0}), - ), - g( - "distort.freeDistort", - "Free Distort…", - DT, - "{corners: [[x,y]×4] (new positions of the bounding-box corners TL, TR, BR, BL in unit box coordinates; identity [[0,0],[1,0],[1,1],[0,1]])}", - json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}), - ), - g("distort.puckerBloat", "Pucker & Bloat…", DT, "{amount: % (-200 pucker … 200 bloat, default 0)}", json!({"amount": 0.0})), - g( - "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)}", - 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), copies: 0..1000 (0; each copy transforms the last again), 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)}", - 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}), - ), - g( - "distort.tweak", - "Tweak…", - DT, - "{h: amount (10), v: amount (10), relative: bool (true: % of size), anchors: bool (true), in: bool (true), out: bool (true), seed: int (0)}", - json!({"h": 10.0, "v": 10.0, "relative": true, "anchors": true, "in": true, "out": true, "seed": 0}), - ), - g("distort.twist", "Twist…", DT, "{angle: deg (-3600..3600, 10)}", json!({"angle": 10.0})), - g( - "distort.zigZag", - "Zig Zag…", - DT, - "{size: (10), relative: bool (false: pt; true: % of size), ridges: per segment 0..100 (4), points: \"smooth\"|\"corner\"}", - json!({"size": 10.0, "relative": false, "ridges": 4, "points": "smooth"}), - ), - g( - "path.offsetPath", - "Offset Path…", - PATH, - "{offset: pt (10; negative insets), joins: \"miter\"|\"round\"|\"bevel\", miterLimit: (4)}", - json!({"offset": 10.0, "joins": "miter", "miterLimit": 4.0}), - ), - g( - "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", - json!({}), - ), - g( - "path.outlineStroke", - "Outline Stroke", - PATH, - "{width?: pt (defaults to the stroke's weight)} the outline of the stroke the effect is on (on a fill or the object: the top stroke), with its caps, joins, dashes, alignment, width profile and arrowheads", - json!({}), - ), - g("stylize.roundCorners", "Round Corners…", STYLIZE, "{radius: pt (10)}", json!({"radius": 10.0})), - g( - "stylize.scribble", - "Scribble…", - STYLIZE, - "{angle: deg (30; stored above -180 and up to 180: 270 becomes -90, -180 becomes 180), overlap: pt (0; Path Overlap: a positive value extends each line beyond the path, a negative one ends it inside), overlapVariation: pt (0..100, 0.5; how far each line's ends move along it), strokeWidth: pt (3), curviness: % (5), curvinessVariation: % (0..100, 0; how far each turn's curviness moves from curviness), spacing: pt (5), spacingVariation: pt (0..100, 0.5; how far each line's ends move across it), variation: pt (the earlier form, read as overlapVariation and spacingVariation unless those are given), seed: int (0)} (simplified: a single hatching scribble outlined to a filled shape)", - json!({"angle": 30.0, "overlap": 0.0, "overlapVariation": 0.5, "strokeWidth": 3.0, "curviness": 5.0, "curvinessVariation": 0.0, "spacing": 5.0, "spacingVariation": 0.5, "seed": 0}), - ), - r( - "stylize.dropShadow", - "Drop Shadow…", - STYLIZE, - "{mode: blend mode (\"multiply\"), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": the shadow is the object's own colors with `darkness` percent of black added instead of `color`: in a CMYK document their cyan, magenta and yellow stay and their black K becomes K + darkness × (1 − K); in an RGB document each channel is multiplied by 1 − darkness)", - json!({"mode": "multiply", "opacity": 75.0, "x": 7.0, "y": 7.0, "blur": 5.0, "shade": "color", "color": "#000000", "darkness": 100.0}), - ), - r( - "stylize.innerGlow", - "Inner Glow…", - STYLIZE, - "{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}", - json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffffff", "source": "edge"}), - ), - r( - "stylize.outerGlow", - "Outer Glow…", - STYLIZE, - "{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}", - json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}), - ), - r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})), - r("blur.gaussian", "Gaussian Blur…", BLUR, "{radius: pt (5)}", json!({"radius": 5.0})), - r( - "artistic.cutout", - "Cutout…", - ARTISTIC, - "{levels: 2..8 (4; steps per colour channel: more levels, more flat colours), edgeSimplicity: 0..10 (4; simpler, smoother edges), edgeFidelity: 1..3 (2; keeps more of the edges' detail)} redraws the object as flat pieces of coloured paper, each piece painted in the average colour that falls into it, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", - json!({"levels": 4.0, "edgeSimplicity": 4.0, "edgeFidelity": 2.0}), - ), - r( - "artistic.filmGrain", - "Film Grain…", - ARTISTIC, - "{grain: 0..20 (4; monochrome noise in shadows and midtones), highlightArea: 0..20 (0; widens the bright highlight area), intensity: 0..10 (10; highlight strength and quieter highlight grain)}. Smooth document-space grain follows translations; minification uses approximate footprint filtering. Coverage and pure white are preserved; black takes light speckles, and saturated colour channels may clip. Grain 0 with either highlightArea 0 or intensity 0 leaves the art unchanged. Original visual approximation; chosen VectorCraft defaults.", - json!({"grain": 4.0, "highlightArea": 0.0, "intensity": 10.0}), - ), - r( - "artistic.neonGlow", - "Neon Glow…", - ARTISTIC, - "{glowSize: -24..24 (5; above 0 the light areas glow, below 0 the dark ones; farther from 0 spreads the glow wider), glowBrightness: 0..50 (15; a stronger glow over dimmer greys), color: \"#rrggbb\" (\"#4da6ff\"; the glow's colour)} redraws the object in greys lit by a coloured glow, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", - json!({"glowSize": 5.0, "glowBrightness": 15.0, "color": "#4da6ff"}), - ), - r( - "artistic.plasticWrap", - "Plastic Wrap…", - ARTISTIC, - "{highlightStrength: 0..20 (20; brighter specular highlights), detail: 0..15 (12; finer wrinkles in document space), smoothness: 1..15 (15; softer folds)} coats the object in shiny plastic, keeping its coverage. highlightStrength 0 leaves the art unchanged. Original visual approximation; chosen VectorCraft defaults.", - json!({"highlightStrength": 20.0, "detail": 12.0, "smoothness": 15.0}), - ), - r( - "artistic.posterEdges", - "Poster Edges…", - ARTISTIC, - "{edgeThickness: 0..10 (2; wider lines), edgeIntensity: 0..10 (1; darker lines, on fainter edges too), posterization: 0..6 (2; posterization + 2 levels per colour channel)} reduces the object's colours and draws black lines on its edges, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", - json!({"edgeThickness": 2.0, "edgeIntensity": 1.0, "posterization": 2.0}), - ), - r( - "artistic.smudgeStick", - "Smudge Stick…", - ARTISTIC, - "{strokeLength: 0..10 (2; length of the short diagonal strokes), highlightArea: 0..20 (12; widens the area counted as light), intensity: 0..10 (10; how far the light areas are lightened)} smudges the dark areas along short diagonal strokes; the lighter areas become brighter and lose detail. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", - json!({"strokeLength": 2.0, "highlightArea": 12.0, "intensity": 10.0}), - ), - r( - "artistic.sponge", - "Sponge…", - ARTISTIC, - "{brushSize: 0..10 (2; size of the sponge's pores), definition: 0..25 (12; how strongly lighter and darker blobs contrast), smoothness: 1..15 (5; softer blob edges)} paints the object as if dabbed with a sponge, in highly textured areas of contrasting colour. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", - json!({"brushSize": 2.0, "definition": 12.0, "smoothness": 5.0}), - ), - r( - "artistic.watercolor", - "Watercolor…", - ARTISTIC, - "{brushDetail: 1..14 (9; the larger, the more detail stays), shadowIntensity: 0..10 (1; deepens the shadows), texture: 1..3 (1; paper grain, whole numbers)} paints the object in a watercolor style: detail simplified, colour saturated and darker where tones change at edges. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", - json!({"brushDetail": 9.0, "shadowIntensity": 1.0, "texture": 1.0}), - ), - r( - "blur.radial", - "Radial Blur…", - BLUR, - "{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples)} blurs around the object's centre", - json!({"amount": 10.0, "method": "spin", "quality": "good"}), - ), - r( - "blur.smart", - "Smart Blur…", - BLUR, - "{radius: pt 0.1..100 (3), threshold: levels 0.1..100 (25; only colours closer than this blur together, so edges stay sharp), quality: \"low\"|\"medium\"|\"high\" (\"medium\"; 5, 7 or 9 samples across), blurMode: \"normal\"|\"edgeOnly\"|\"overlayEdge\" (\"normal\"; edgeOnly: the edges in white on black, overlayEdge: the edges in white over the blur)}. A pixel is on an edge when one of the pixels the search reads within the radius (all of them for a small radius, a grid of samples for a wide one) or one of its four nearest pixels differs from it by more than the threshold in a channel and its channels (alpha included) add up to at least that pixel's, so a step gives a line about as wide as the radius, and at least one pixel wide, on the side with the larger sum; the white and the black keep each pixel's coverage", - json!({"radius": 3.0, "threshold": 25.0, "quality": "medium", "blurMode": "normal"}), - ), - r( - "brushStrokes.accentedEdges", - "Accented Edges…", - BRUSH_STROKES, - "{edgeWidth: pt 1..14 (2), edgeBrightness: 0..50 (38; high: white chalk, low: black ink), smoothness: 1..15 (5; softens the object first and leaves its faint edges out)} accentuates the object's edges", - json!({"edgeWidth": 2.0, "edgeBrightness": 38.0, "smoothness": 5.0}), - ), - r( - "brushStrokes.angledStrokes", - "Angled Strokes…", - BRUSH_STROKES, - "{directionBalance: 0..100 (50; 0: every stroke a left diagonal, 100: every stroke a right diagonal, between: light areas right, dark areas left), strokeLength: pt 3..50 (15), sharpness: 0..10 (3)} repaints the object with diagonal strokes, the light areas' going the opposite way to the dark areas'", - json!({"directionBalance": 50.0, "strokeLength": 15.0, "sharpness": 3.0}), - ), - r( - "brushStrokes.crosshatch", - "Crosshatch…", - BRUSH_STROKES, - "{strokeLength: pt 3..50 (9), sharpness: 0..20 (6), strength: 1..3 (1; passes of hatching)} keeps the object's detail under pencil hatching along both diagonals and roughens its edges", - json!({"strokeLength": 9.0, "sharpness": 6.0, "strength": 1.0}), - ), - r( - "brushStrokes.darkStrokes", - "Dark Strokes…", - BRUSH_STROKES, - "{balance: 0..10 (5; the higher, the more of the object counts as dark), blackIntensity: 0..10 (6), whiteIntensity: 0..10 (2)} paints the dark areas closer to black with short strokes and the light areas with long white strokes", - json!({"balance": 5.0, "blackIntensity": 6.0, "whiteIntensity": 2.0}), - ), - r( - "brushStrokes.inkOutlines", - "Ink Outlines…", - BRUSH_STROKES, - "{strokeLength: pt 1..50 (4), darkIntensity: 0..50 (20), lightIntensity: 0..50 (10)} redraws the object in pen and ink: fine outlines over its edges and ink strokes in its shadows", - json!({"strokeLength": 4.0, "darkIntensity": 20.0, "lightIntensity": 10.0}), - ), - r( - "brushStrokes.spatter", - "Spatter…", - BRUSH_STROKES, - "{sprayRadius: pt 0..25 (10; colours scattered up to 0.4 × this), smoothness: 1..15 (5; larger, smoother grains)} renders the object as if sprayed with a spatter airbrush", - json!({"sprayRadius": 10.0, "smoothness": 5.0}), - ), - r( - "brushStrokes.sprayedStrokes", - "Sprayed Strokes…", - BRUSH_STROKES, - "{strokeLength: pt 0..20 (12), sprayRadius: pt 0..25 (7; strokes scattered up to 0.3 × this), strokeDirection: \"rightDiagonal\"|\"horizontal\"|\"leftDiagonal\"|\"vertical\" (\"rightDiagonal\")} repaints the object with sprayed, angled strokes of its main colours", - json!({"strokeLength": 12.0, "sprayRadius": 7.0, "strokeDirection": "rightDiagonal"}), - ), - r( - "brushStrokes.sumiE", - "Sumi-e…", - BRUSH_STROKES, - "{strokeWidth: pt 3..15 (10), strokePressure: 0..15 (2; more ink), contrast: 0..40 (16)} paints the object in the Japanese style, as if with a wet brush full of black ink on rice paper: soft, blurred edges and rich blacks, the colours keeping their hue and the object its shape", - json!({"strokeWidth": 10.0, "strokePressure": 2.0, "contrast": 16.0}), - ), - r( - "distort.diffuseGlow", - "Diffuse Glow…", - DISTORT, - "{graininess: 0..10 (6; white grain, thicker in the glow), glowAmount: 0..20 (10), clearAmount: 0..20 (15; the higher, the more of the image stays clear of glow)} renders the object as if seen through a soft diffusion filter: its highlights glow white under see-through white grain", - json!({"graininess": 6.0, "glowAmount": 10.0, "clearAmount": 15.0}), - ), - r( - "distort.glass", - "Glass…", - DISTORT, - "{distortion: 0..20 (5), smoothness: 1..15 (3), texture: \"blocks\"|\"canvas\"|\"frosted\"|\"tinyLens\"|\"loaded\" (\"frosted\"; \"loaded\" draws the image in textureImage and draws Frosted when there is none; the others are surfaces made in code), textureImage?: {path} | {name?, dataBase64} | string (Load Texture…: an image file that File › Place reads, within the renderer's pixel allowance, stored as its gray levels in a grayscale PNG in base64; a file sets texture to \"loaded\" unless texture is given, and the stored string, as effect.list gives it, is kept as it is), scaling: % 50..200 (100), invert: bool (false; turns the surface's heights over)} makes the object look as if seen through glass. A loaded texture lies one image pixel per point at 100 %, centered on the object's center and repeated; each pixel's luma is the surface's height, from 0 for black to 1 pt for white, and a transparent pixel counts as middle gray", - json!({"distortion": 5.0, "smoothness": 3.0, "texture": "frosted", "scaling": 100.0, "invert": false}), - ), - r( - "distort.oceanRipple", - "Ocean Ripple…", - DISTORT, - "{rippleSize: 1..15 (9), rippleMagnitude: 0..20 (9)} adds randomly spaced ripples, as if the object were under water", - json!({"rippleSize": 9.0, "rippleMagnitude": 9.0}), - ), - r( - "sharpen.unsharpMask", - "Unsharp Mask…", - SHARPEN, - "{amount: % 1..500 (50), radius: pt 0.1..250 (1; σ of the blur edges are found against), threshold: levels 0..255 (0; smaller differences are left alone)}", - json!({"amount": 50.0, "radius": 1.0, "threshold": 0.0}), - ), - r( - "sketch.basRelief", - "Bas Relief…", - SKETCH, - "{detail: 1..15 (13; the larger, the finer the features that stay), smoothness: 1..15 (3; rounds the carving), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"bottom\"; where the light comes from)} carves the object in low relief in black and white: surfaces facing the light turn white, those turned away black, flat areas grey. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", - json!({"detail": 13.0, "smoothness": 3.0, "lightDirection": "bottom"}), - ), - r( - "sketch.chalkCharcoal", - "Chalk & Charcoal…", - SKETCH, - "{chalkArea: 0..20 (6; chalk in light areas), charcoalArea: 0..20 (6; charcoal in dark areas), strokePressure: 0..5 (2)} redraws the object with chalk highlights and charcoal strokes on white paper, keeping its coverage. Original visual approximation from public documentation; slider ranges and defaults are VectorCraft choices, not verified proprietary values.", - json!({"chalkArea": 6.0, "charcoalArea": 6.0, "strokePressure": 2.0}), - ), - r( - "sketch.charcoal", - "Charcoal…", - SKETCH, - "{thickness: 1..7 (1; width of the bold edges and of the strokes' spacing), detail: 0..5 (1; the larger, the finer the edges), lightDarkBalance: 0..100 (50; how far into the lights the charcoal reaches)} redraws the object in black charcoal on white paper: bold edges and diagonal strokes over the midtones. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", - json!({"thickness": 1.0, "detail": 1.0, "lightDarkBalance": 50.0}), - ), - r( - "sketch.chrome", - "Chrome…", - SKETCH, - "{detail: 0..10 (4; finer surface texture), smoothness: 0..10 (4; softer relief before the highlights and shadows)} treats the object as polished chrome lit from the top left: bright highlights on high points and dark shadows in low ones, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", - json!({"detail": 4.0, "smoothness": 4.0}), - ), - r( - "sketch.graphicPen", - "Graphic Pen…", - SKETCH, - "{strokeLength: pt 1..15 (5; the longest ink stroke), lightDarkBalance: 0..100 (50; more black when higher), strokeDirection: \"rightDiagonal\"|\"horizontal\"|\"leftDiagonal\"|\"vertical\" (\"rightDiagonal\")} redraws the object in fine linear black ink on white paper, with strokes denser in darker areas. Control names and ranges follow the public documentation; the defaults are unverified.", - json!({"strokeLength": 5.0, "lightDarkBalance": 50.0, "strokeDirection": "rightDiagonal"}), - ), - r( - "sketch.halftonePattern", - "Halftone Pattern…", - SKETCH, - "{size: pt 1..12 (1; how far apart the screen's dots, rings or lines are), contrast: 0..50 (5; 50 draws pure black and white), patternType: \"circle\"|\"dot\"|\"line\" (\"dot\"; rings round the object's centre, dots on a square grid, horizontal lines)} redraws the object in black ink on white paper through a halftone screen whose ink covers as much as the colour is dark, keeping its coverage. Original visual approximation from the public Sketch effects reference; slider ranges follow the documented control names, numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults (the public help pages give no numbers).", - json!({"size": 1.0, "contrast": 5.0, "patternType": "dot"}), - ), - r( - "sketch.notePaper", - "Note Paper…", - SKETCH, - "{imageBalance: 0..50 (25; lower tones darken the emboss, higher lighten it), graininess: 0..10 (0; fibrous paper texture), relief: 0..50 (4; emboss strength in points)} embosses the object's tones on warm paper, keeping its coverage. Original visual approximation from the public Sketch effects reference; slider ranges follow the documented control names, numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults (the public help pages give no numbers).", - json!({"imageBalance": 25.0, "graininess": 0.0, "relief": 4.0}), - ), - r( - "sketch.photocopy", - "Photocopy…", - SKETCH, - "{detail: 1..24 (7; the larger, the finer the features that copy), darkness: 1..50 (25; the larger, the more of the dark copies)} copies the object in black on white: large dark areas copy only around their edges and midtones go to black or white. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", - json!({"detail": 7.0, "darkness": 25.0}), - ), - r( - "sketch.plaster", - "Plaster…", - SKETCH, - "{imageBalance: 1..50 (20; higher values sink more of the image), smoothness: 1..15 (8; higher values soften the relief), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\")} molds the object in relief plaster and lights it from that direction; dark areas are raised and light areas recessed, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", - json!({"imageBalance": 20.0, "smoothness": 8.0, "lightDirection": "top"}), - ), - r( - "sketch.reticulation", - "Reticulation…", - SKETCH, - "{density: 0..50 (12; finer grain at higher values), foregroundLevel: 0..50 (6; pulls shadows toward black ink), backgroundLevel: 0..50 (6; pulls highlights toward white paper)} redraws the object in black ink on white paper through a high-contrast film-grain screen, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", - json!({"density": 12.0, "foregroundLevel": 6.0, "backgroundLevel": 6.0}), - ), - r( - "sketch.stamp", - "Stamp…", - SKETCH, - "{lightDarkBalance: 0..50 (25; the larger, the more of the object prints black), smoothness: 1..50 (5; rounds the shapes)} simplifies the object to solid black and white, as a rubber stamp would print it. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", - json!({"lightDarkBalance": 25.0, "smoothness": 5.0}), - ), - r( - "stylize.glowingEdges", - "Glowing Edges…", - STYLIZE, - "{edgeWidth: pt 1..14 (2), edgeBrightness: 0..20 (6), smoothness: pt 1..15 (5)} finds alpha-weighted Sobel edges and draws bright coloured outlines on black", - json!({"edgeWidth": 2.0, "edgeBrightness": 6.0, "smoothness": 5.0}), - ), - r( - "pixelate.colorHalftone", - "Color Halftone…", - PIXELATE, - "{maxRadius: pt 4..127 (8; the radius of a dot at full strength, which fills its square cell), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell", - json!({"maxRadius": 8.0, "channel1": 108.0, "channel2": 162.0, "channel3": 90.0, "channel4": 45.0}), - ), - r( - "pixelate.crystallize", - "Crystallize…", - PIXELATE, - "{cellSize: pt 3..300 (10)} redraws the object as polygon crystals of solid colour around random points about cellSize apart", - json!({"cellSize": 10.0}), - ), - r( - "pixelate.mezzotint", - "Mezzotint…", - PIXELATE, - "{type: \"fineDots\"|\"mediumDots\"|\"grainyDots\"|\"coarseDots\"|\"shortLines\"|\"mediumLines\"|\"longLines\"|\"shortStrokes\"|\"mediumStrokes\"|\"longStrokes\" (\"fineDots\")} turns each colour channel fully on or off against a random pattern of dots, lines or strokes: fully saturated colours", - json!({"type": "fineDots"}), - ), - r( - "pixelate.pointillize", - "Pointillize…", - PIXELATE, - "{cellSize: pt 3..300 (5)} redraws the object as randomly placed dots of its colours on a white canvas", - json!({"cellSize": 5.0}), - ), - r( - "texture.craquelure", - "Craquelure…", - TEXTURE, - "{crackSpacing: pt 2..100 (15; how far apart the cracks are), crackDepth: 0..10 (6; how deep and wide the cracks are, and how high the plates and the tones stand), crackBrightness: 0..10 (9; how brightly the plaster is lit)} paints the object on relief plaster cracked into plates and along the contours of its tones", - json!({"crackSpacing": 15.0, "crackDepth": 6.0, "crackBrightness": 9.0}), - ), - r( - "texture.grain", - "Grain…", - TEXTURE, - "{intensity: 0..100 (40), contrast: 0..100 (50; the image's contrast, 50 leaves it as it is), grainType: \"regular\"|\"soft\"|\"sprinkles\"|\"clumped\"|\"contrasty\"|\"enlarged\"|\"stippled\"|\"horizontal\"|\"vertical\"|\"speckle\" (\"regular\")} adds grain in 1 pt grains (2 pt Enlarged, clumps Clumped, streaks Horizontal and Vertical); Sprinkles and Stippled use the background colour, white", - json!({"intensity": 40.0, "contrast": 50.0, "grainType": "regular"}), - ), - r( - "texture.mosaicTiles", - "Mosaic Tiles…", - TEXTURE, - "{tileSize: pt 2..100 (12), groutWidth: 1..15 (3; the grout is half a point wide per step), lightenGrout: 0..10 (9; how light the grout is)} lays the object in irregular tiles bevelled at their edges, with sunken grout between them", - json!({"tileSize": 12.0, "groutWidth": 3.0, "lightenGrout": 9.0}), - ), - r( - "texture.patchwork", - "Patchwork…", - TEXTURE, - "{squareSize: pt 0..10 (4; 0 draws 1 pt squares), relief: 0..25 (8)} redraws the object in squares of the colour around their centres, raised to heights that follow its highlights and shadows, a little more or less at random, lit from the top left", - json!({"squareSize": 4.0, "relief": 8.0}), - ), - r( - "texture.stainedGlass", - "Stained Glass…", - TEXTURE, - "{cellSize: pt 2..50 (10), borderThickness: 1..20 (4; the lead between the panes, half a point wide per step, in the foreground colour: black), lightIntensity: 0..10 (3; a light behind the object's centre, fading out towards its corners)} redraws the object as single-coloured panes around random points about cellSize apart", - json!({"cellSize": 10.0, "borderThickness": 4.0, "lightIntensity": 3.0}), - ), - r( - "texture.texturizer", - "Texturizer…", - TEXTURE, - "{texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\" (\"canvas\"; surfaces made in code), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false; turns the surface's heights over)} paints the object on a surface in relief", - json!({"texture": "canvas", "scaling": 100.0, "relief": 4.0, "lightDirection": "top", "invert": false}), - ), - r( - "video.deinterlace", - "De-Interlace…", - VIDEO, - "{eliminate: \"odd\"|\"even\" (\"odd\"; which field lines are taken out), create: \"duplication\"|\"interpolation\" (\"duplication\"; a line taken out becomes a copy of the line above, or the average of the lines above and below)} the field lines are the rows of the document's raster grid (Document Raster Effects Settings › Resolution), numbered from 1 at the top of the page", - json!({"eliminate": "odd", "create": "duplication"}), - ), - r( - "video.ntscColors", - "NTSC Colors", - VIDEO, - "{} makes colours a television signal can't carry (luma plus chroma past 110 % of white, or luma minus chroma below −20 %) less saturated, keeping their brightness", - json!({}), - ), - ]; - v.extend([ - g( - "adjust.brightnessContrast", - "Brightness/Contrast…", - ADJUST, - "{brightness: -100..100 (0; bends the tones, black and white stay), contrast: -100..100 (0)} recolours the object's fills, strokes, type, meshes and embedded images (each colour keeps its model)", - json!({"brightness": 0.0, "contrast": 0.0}), - ), - g( - "adjust.curves", - "Curves…", - ADJUST, - "{points: \"x,y x,y …\" or [[x, y], …] (input, output 0..255; a smooth monotone curve through them, flat past the ends; \"0,0 128,128 255,255\"), channel: \"rgb\"|\"red\"|\"green\"|\"blue\" (\"rgb\")} recolours as Brightness/Contrast does", - json!({"points": "0,0 128,128 255,255", "channel": "rgb"}), - ), - g( - "adjust.hueSaturation", - "Hue/Saturation…", - ADJUST, - "{hue: deg -180..180 (0), saturation: -100..100 (0), lightness: -100..100 (0), colorize: bool (false; true: every colour takes hue `hue` (0..360) at saturation (100 + saturation) / 2 %)} recolours as Brightness/Contrast does", - json!({"hue": 0.0, "saturation": 0.0, "lightness": 0.0, "colorize": false}), - ), - g( - "adjust.levels", - "Levels…", - ADJUST, - "{inputBlack: 0..255 (0), inputWhite: 0..255 (255), gamma: 0.1..10 (1; above 1 lightens the midtones), outputBlack: 0..255 (0), outputWhite: 0..255 (255), channel: \"rgb\"|\"red\"|\"green\"|\"blue\" (\"rgb\")} recolours as Brightness/Contrast does", - json!({"inputBlack": 0.0, "inputWhite": 255.0, "gamma": 1.0, "outputBlack": 0.0, "outputWhite": 255.0, "channel": "rgb"}), - ), - g( - "adjust.shiftToColor", - "Shift to Color…", - ADJUST, - "{color: \"#rrggbb\" (\"#ff8000\"), amount: 0..100 % (50), preserveLightness: bool (true: colours take the target's hue and saturation and keep their lightness; false: they mix with it)} recolours as Brightness/Contrast does", - json!({"color": "#ff8000", "amount": 50.0, "preserveLightness": true}), - ), - g( - "adjust.temperatureTint", - "Temperature/Tint…", - ADJUST, - "{temperature: -100 (cooler) .. 100 (warmer) (0), tint: -100 (greener) .. 100 (more magenta) (0)} recolours as Brightness/Contrast does", - json!({"temperature": 0.0, "tint": 0.0}), - ), - ]); - for (suffix, label) in WARP_STYLES { - let id: &'static str = match suffix { - "arc" => "warp.arc", - "arcLower" => "warp.arcLower", - "arcUpper" => "warp.arcUpper", - "arch" => "warp.arch", - "bulge" => "warp.bulge", - "shellLower" => "warp.shellLower", - "shellUpper" => "warp.shellUpper", - "flag" => "warp.flag", - "wave" => "warp.wave", - "fish" => "warp.fish", - "rise" => "warp.rise", - "fisheye" => "warp.fisheye", - "inflate" => "warp.inflate", - "squeeze" => "warp.squeeze", - _ => "warp.twist", - }; - v.push(g(id, label, WARP, WARP_DOC, json!({"bend": 50.0, "horizontal": 0.0, "vertical": 0.0, "orientation": "horizontal"}))); - } - for (id, label, _) in PATHFINDER_EFFECTS { - v.push(g(id, label, PATHFINDER, "{} (groups and layers: live Pathfinder over the members)", json!({}))); - } - v.push(g( - CROP_MARKS, - "Crop Marks", - &["Effect"], - "{style?: \"roman\"|\"japanese\" (default: the japaneseCropMarks preference when applied)} trim marks in [Registration] around the object's bounds, following it", - json!({}), - )); - v.push(r( - RASTERIZE, - "Rasterize…", - &["Effect"], - "{colorModel: \"document\" (the document's mode, RGB or CMYK)|\"grayscale\"|\"bitmap\" (\"document\"), useDocumentResolution: bool (true: Document Raster Effects Settings › Resolution), resolution: ppi 1..2400 (72; with useDocumentResolution false), background: \"white\"|\"transparent\" (\"transparent\"), antiAlias: \"none\"|\"art\"|\"type\" (\"art\"; none: hard edges), clippingMask: bool (false; the image clipped to the art's outline), addAround: pt 0..1000 (0; room around the art)} draws the object as an image of square pixels over its bounds and the room around them, leaving its paths, type and other art as they are; when it is the object's only raster effect, Expand Appearance makes the image Object › Rasterize makes", - json!({"colorModel": "document", "useDocumentResolution": true, "resolution": 72.0, "background": "transparent", "antiAlias": "art", "clippingMask": false, "addAround": 0.0}), - )); - v -} - -/// The catalogue built once, indexed by id (lookups run per effect per rendered frame). -fn catalog_index() -> &'static std::collections::HashMap<&'static str, EffectInfo> { - static INDEX: std::sync::OnceLock> = std::sync::OnceLock::new(); - INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect()) -} - -/// Catalogue entry for `id` (built-in, or an installed plug-in effect). -pub fn effect_info(id: &str) -> Option { - catalog_index().get(id).cloned().or_else(|| plugin_info(id)) -} - -/// The catalogue entry of the installed effect plug-in with effect id `id` (`plugin.`). -fn plugin_info(id: &str) -> Option { - use vectorcraft_plugins::registry::intern; - let p = vectorcraft_plugins::effect::installed(id)?; - let m = p.manifest(); - let dots = if m.params.is_empty() || m.name.ends_with('…') { "" } else { "…" }; - Some(EffectInfo { - id: intern(id), - label: intern(&format!("{}{dots}", m.name)), - menu: PLUGINS, - params: intern(&m.params_doc()), - defaults: Value::Object(m.defaults()), - raster: false, - lengths: Lengths::default(), - }) -} - -/// The installed effect plug-ins as catalogue entries (Effect › Plug-ins), by plug-in id. -pub fn plugin_effects() -> Vec { - vectorcraft_plugins::registry::list().iter().filter_map(|p| plugin_info(&vectorcraft_plugins::effect::effect_id(p.id()))).collect() -} - -/// Dialog defaults for `id` (`None` for unknown effects). -pub fn default_params(id: &str) -> Option { - match catalog_index().get(id) { - Some(e) => Some(e.defaults.clone()), - None => plugin_info(id).map(|e| e.defaults), - } -} - -/// `params` layered over the defaults of `id` (unknown keys are kept), in their current form (see -/// [`upgrade_params`]). The 3D effects' earlier `perspective` is read as `perspectiveAngle`, and -/// Scribble's earlier `variation` is read as `overlapVariation` and `spacingVariation`. -pub fn merged_params(id: &str, params: &Value) -> Value { - let mut out = match catalog_index().get(id).map(|e| &e.defaults) { - Some(Value::Object(m)) => m.clone(), - Some(_) => Map::new(), - None => vectorcraft_plugins::effect::installed(id).map(|p| p.manifest().defaults()).unwrap_or_default(), - }; - // Upgraded before the defaults are under it: a default angle is no angle given. - if let Value::Object(p) = upgrade_params(id, params) { - out.extend(p); - } - Value::Object(out) -} - -/// `params` for effect `id` in their current form. The 3D effects took Perspective as a 0–100 % -/// strength, `perspective`, before the documented 0°–160° angle, `perspectiveAngle`, and the light -/// as `lightAzimuth` and `lightElevation` before the documented Rotation and Height -/// (`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°). -pub fn upgrade_params(id: &str, params: &Value) -> Value { - match params { - Value::Object(m) => { - let mut m = m.clone(); - upgrade_perspective(id, &mut m); - upgrade_light(id, &mut m); - upgrade_scribble(id, &mut m); - Value::Object(m) - } - other => other.clone(), - } -} - -fn upgrade_light(id: &str, m: &mut Map) { - if !is_three_d(id) { - return; - } - let (azimuth, elevation) = (m.remove("lightAzimuth"), m.remove("lightElevation")); - if azimuth.is_none() && elevation.is_none() || m.contains_key("lightRotation") || m.contains_key("lightHeight") { - return; - } - let degrees = |v: Option, default: f64| v.and_then(|v| v.as_f64()).unwrap_or(default); - let (rotation, height, behind) = vectorcraft_three_d::light_from_azimuth_elevation(degrees(azimuth, -45.0), degrees(elevation, 45.0)); - m.insert("lightRotation".into(), json!(rotation)); - m.insert("lightHeight".into(), json!(height)); - m.insert("lightBehind".into(), json!(behind)); -} - -fn upgrade_perspective(id: &str, m: &mut Map) { - if !is_three_d(id) { - return; - } - let Some(strength) = m.remove("perspective") else { return }; - if !m.contains_key("perspectiveAngle") { - let angle = vectorcraft_three_d::perspective_from_strength(strength.as_f64().unwrap_or(0.0) / 100.0); - m.insert("perspectiveAngle".into(), json!(angle)); - } -} - -fn upgrade_scribble(id: &str, m: &mut Map) { - if id != "stylize.scribble" { - return; - } - if let Some(variation) = m.remove("variation") { - for key in ["overlapVariation", "spacingVariation"] { - m.entry(key).or_insert_with(|| variation.clone()); - } - } - if let Some(angle) = m.get("angle").and_then(Value::as_f64).filter(|a| a.is_finite() && (*a <= -180.0 || *a > 180.0)) { - let wrapped = angle.rem_euclid(360.0); - m.insert("angle".into(), json!(if wrapped > 180.0 { wrapped - 360.0 } else { wrapped })); - } -} - -/// A new effect record with default parameters (overridden by `params`). -pub fn new_effect(id: &str, params: &Value) -> Option { - if !catalog_index().contains_key(id) { - vectorcraft_plugins::effect::installed(id)?; - } - Some(Effect { id: id.to_string(), params: merged_params(id, params), visible: true }) -} - -/// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see -/// [`EffectInfo::lengths`]). A distance left at its default is written out scaled; one the -/// effect doesn't have (Outline Stroke's weight following its stroke) stays absent. -pub fn scale_effect(e: &mut Effect, s: f64) { - let Some(info) = catalog_index().get(e.id.as_str()) else { return }; - let merged = merged_params(&e.id, &e.params); - let relative = util::flag(&merged, "relative", false); - for k in info.lengths.keys(relative) { - let v = util::num(&merged, k, f64::NAN); - if v.is_finite() { - if !e.params.is_object() { - e.params = Value::Object(Map::new()); - } - e.params[k] = json!(v * s); - } - } -} - -/// Is `id` a raster (painted) effect? -pub fn is_raster(id: &str) -> bool { - matches!(id, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow" | "stylize.feather" | "blur.gaussian" | RASTERIZE) - || PIXEL_EFFECTS.contains(&id) -} - -/// Does `id` change geometry? (Crop Marks adds art of its own instead, [`crop_marks_art`]; colour -/// adjustments recolour, [`adjust`].) Plug-in effects do, installed or not (a missing plug-in -/// leaves the geometry as it is). -pub fn is_geometry(id: &str) -> bool { - !is_raster(id) - && !is_pathfinder(id) - && !is_adjustment(id) - && id != CROP_MARKS - && !is_three_d(id) - && (catalog_index().contains_key(id) || vectorcraft_plugins::effect::plugin_id(id).is_some()) -} - -/// Any visible geometry effect in the list? -pub fn has_geometry(effects: &[Effect]) -> bool { - effects.iter().any(|e| e.visible && is_geometry(&e.id)) -} - -/// Does `n` have a visible plug-in effect, its own or a fill's or stroke's? Such an effect draws -/// what the plug-in installed under its id draws ([`plugin_revision`]). -pub fn has_plugin_effect(n: &Node) -> bool { - let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some(); - n.appearance.effects.iter().any(plugin) || n.appearance.items.iter().any(|i| i.effects().iter().any(plugin)) -} - -/// The plug-in registry's revision, which changes whenever a plug-in is installed or removed. -pub fn plugin_revision() -> u64 { - vectorcraft_plugins::registry::revision() -} - -/// Context the geometry effects may need from the object's appearance. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct GeomContext<'a> { - /// The stroke `path.outlineStroke` outlines (its weight, caps, joins, dashes, alignment, - /// profile and arrowheads): the stroke the effect sits on, else the object's top painted - /// stroke. `None` outlines a plain 1 pt stroke. - pub stroke: Option<&'a StrokeLayer>, - /// The object's fill rule (inside and outside alignment). - pub rule: FillRule, - /// The seed of the Transform effect's Random: the object's id, so each object varies its own - /// way and keeps its result on every redraw. - pub seed: u64, - /// The object's appearance, which live-effect plug-ins are given read only (their fills and - /// strokes). - pub appearance: Option<&'a Appearance>, - /// The index in `appearance.items` of the fill or stroke whose own effects these are; `None`: - /// the object's effects. - pub item: Option, -} - -impl<'a> GeomContext<'a> { - /// The context of `n`'s object-level effects. - pub fn of(n: &'a Node) -> Self { - let rule = match &n.kind { - NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. } => *rule, - _ => FillRule::NonZero, - }; - let stroke = n.appearance.stroke().filter(|s| !s.paint.is_none() && s.width > 0.0); - Self { stroke, rule, seed: n.id.0, appearance: Some(&n.appearance), item: None } - } - - /// The context of the effects on `item`, one of the same object's appearance items: a - /// stroke's own effects outline that stroke, and a plug-in is told which item it is on. - pub fn item(self, item: &'a AppearanceItem) -> Self { - let at = self.appearance.and_then(|a| a.items.iter().position(|i| std::ptr::eq(i, item))); - match item { - AppearanceItem::Stroke(s) => Self { stroke: Some(s), item: at, ..self }, - AppearanceItem::Fill(_) => Self { item: at, ..self }, - } - } -} - -/// Evaluate the visible geometry effects of `effects` on `path`, in order. `bounds` is the -/// reference box of the first effect (usually the object's geometric bounds); each later effect -/// uses the bounds of its input. Raster and unknown effects are skipped. -pub fn apply_geometry(effects: &[Effect], path: &PathData, bounds: Rect) -> PathData { - apply_geometry_with(effects, path, bounds, &GeomContext::default()) -} - -/// [`apply_geometry`] with an explicit [`GeomContext`]. -pub fn apply_geometry_with(effects: &[Effect], path: &PathData, bounds: Rect, ctx: &GeomContext) -> PathData { - let mut cur = path.clone(); - let mut b = bounds; - let mut first = true; - for e in effects.iter().filter(|e| e.visible && is_geometry(&e.id)) { - if !first { - b = cur.bounds().unwrap_or(b); - } - first = false; - if cur.is_empty() { - break; - } - let p = merged_params(&e.id, &e.params); - cur = apply_one(&e.id, &p, &cur, b, ctx); - } - cur -} - -/// Convenience wrapper on kurbo paths. -pub fn apply_geometry_bez(effects: &[Effect], path: &BezPath, bounds: Rect, ctx: &GeomContext) -> BezPath { - apply_geometry_with(effects, &PathData::from_bezpath(path), bounds, ctx).to_bezpath() -} - -pub(crate) fn apply_one(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext) -> PathData { - use util::*; - if let Some(plugin) = vectorcraft_plugins::effect::plugin_id(id) { - let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item }; - return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints).unwrap_or_else(|| path.clone()); - } - match id { - "distort.freeDistort" => distort::free_distort(path, b, p), - "distort.puckerBloat" => distort::pucker_bloat(path, b, num(p, "amount", 0.0)), - "distort.roughen" => distort::roughen(path, b, p), - "distort.transform" => distort::transform(path, b, p, ctx.seed), - "distort.tweak" => distort::tweak(path, b, p), - "distort.twist" => distort::twist(path, b, num(p, "angle", 10.0)), - "distort.zigZag" => distort::zig_zag(path, b, p), - "path.offsetPath" => { - let off = num(p, "offset", 10.0).clamp(-1e5, 1e5); - if off.abs() < 1e-9 { - return path.clone(); - } - vectorcraft_pathops::offset_path(path, off, join(p, "joins"), num(p, "miterLimit", 4.0).clamp(1.0, 500.0)) - } - // Outline Object returns the geometry unchanged. Type reaches every geometry effect as its - // glyph outlines (`reshape::reshape`), so type that carries it is drawn as those outlines. - "path.outlineObject" => path.clone(), - "path.outlineStroke" => { - let fallback; - let base = match ctx.stroke { - Some(s) => s, - None => { - fallback = StrokeLayer::new(vectorcraft_doc::color::Paint::None, 1.0); - &fallback - } - }; - let st = match p.get("width").and_then(Value::as_f64) { - Some(w) => std::borrow::Cow::Owned(StrokeLayer { width: w, ..base.clone() }), - None => std::borrow::Cow::Borrowed(base), - }; - if st.width.is_nan() || st.width <= 0.0 { - return path.clone(); - } - stroke::outline_region(path, ctx.rule, &st) - } - "convertToShape.rectangle" | "convertToShape.roundedRectangle" | "convertToShape.ellipse" => stylize::convert_to_shape(id, b, p), - "stylize.roundCorners" => stylize::round_corners(path, num(p, "radius", 10.0)), - "stylize.scribble" => stylize::scribble(path, b, p), - _ => match id.strip_prefix("warp.").and_then(WarpStyle::from_id) { - Some(style) => warp::warp(path, b, style, p), - None => path.clone(), - }, - } -} +pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, plugin_effects}; +pub(crate) use geometry::{Budget, apply_one}; +pub use geometry::{GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_with}; +#[cfg(test)] +pub(crate) use geometry::{MAX_EFFECT_LINES, apply_geometry_within}; +pub use params::{ + default_params, has_geometry, has_plugin_effect, is_geometry, is_raster, merged_params, new_effect, plugin_revision, scale_effect, upgrade_params, +}; diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 6f1242b6ea..9a352189d1 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -71,7 +71,7 @@ pub(crate) fn shade(c: Color, rgb: [f64; 3]) -> Color { pub(crate) fn smooth_paint(g: vectorcraft_three_d::LightGradient, color: Color) -> Paint { use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; let stops = g.stops().into_iter().map(|(at, rgb)| GradientStop::new(at, shade(color, rgb))).collect(); - let mut p = GradientPaint::new(Gradient { kind: GradientKind::Linear, stops }); + let mut p = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); p.geom = Some(GradientGeom { start: g.diffuse.start, end: g.diffuse.end, aspect: 1.0, focal: None }); Paint::Gradient(Box::new(p)) } @@ -334,7 +334,7 @@ mod tests { stop.opacity = 0.4; stop.midpoint = 0.3; let g = GradientPaint { - gradient: Gradient { kind: GradientKind::Linear, stops: vec![stop, GradientStop::new(1.0, Color::BLACK)] }, + gradient: Gradient::new(GradientKind::Linear, vec![stop, GradientStop::new(1.0, Color::BLACK)]), geom: Some(GradientGeom { start: Point::new(20.0, 30.0), end: Point::new(100.0, 30.0), aspect: 1.0, focal: None }), angle: 0.0, swatch: None, diff --git a/crates/effects/src/lighting_presets.rs b/crates/effects/src/lighting_presets.rs new file mode 100644 index 0000000000..bf6371224c --- /dev/null +++ b/crates/effects/src/lighting_presets.rs @@ -0,0 +1,112 @@ +//! Original lighting rigs for the publicly documented 3D preset names. +//! Adobe publishes the names, not numeric settings. These values are our own; Standard +//! retains the existing default. A preset replaces the light rig and ambient only. + +use serde_json::{Value, json}; +use vectorcraft_three_d::{DEFAULT_LIGHT, Light}; + +#[derive(Clone, Copy, Debug)] +pub struct LightingPreset { + pub id: &'static str, + pub label: &'static str, + rotation: f64, + height: f64, + softness: f64, + ambient: f64, +} + +pub const LIGHTING_PRESETS: [LightingPreset; 4] = [ + LightingPreset { id: "standard", label: "Standard", rotation: DEFAULT_LIGHT.0, height: DEFAULT_LIGHT.1, softness: 0.0, ambient: 25.0 }, + LightingPreset { id: "diffuse", label: "Diffuse", rotation: DEFAULT_LIGHT.0, height: DEFAULT_LIGHT.1, softness: 100.0, ambient: 35.0 }, + LightingPreset { id: "topLeft", label: "Top Left", rotation: 135.0, height: 45.0, softness: 0.0, ambient: 25.0 }, + LightingPreset { id: "right", label: "Right", rotation: 0.0, height: 30.0, softness: 0.0, ambient: 25.0 }, +]; + +impl LightingPreset { + /// The same patch is used by commands and the dialog's preview transaction. Null + /// `lights` replaces an explicit multi-light rig with this single white light. + pub fn params(self) -> Value { + json!({ + "lights": null, "lightColor": "#ffffff", "lightIntensity": 80.0, + "lightRotation": self.rotation, "lightHeight": self.height, + "lightSoftness": self.softness, "lightBehind": false, "ambient": self.ambient, + }) + } + + fn matches(self, light: Light, ambient: f64) -> bool { + let close = |a: f64, b: f64| (a - b).abs() < 1e-6; + !light.behind + && light.color.iter().all(|c| close(*c, 1.0)) + && close(light.intensity, 0.8) + && close(light.rotation, self.rotation) + && close(light.height, self.height) + && close(light.softness, self.softness / 100.0) + && close(ambient, self.ambient / 100.0) + } +} + +pub fn lighting_preset_params(id: &str) -> Option { + LIGHTING_PRESETS.iter().find(|p| p.id == id).map(|p| p.params()) +} + +/// Identify the effective rig, including an equivalent explicit single light. Names +/// are UI state derived from settings, so edits and older files cannot leave stale names. +pub fn matching_lighting_preset(params: &Value) -> Option { + let upgraded = crate::upgrade_params(crate::REVOLVE, params); + let o = crate::revolve_options(&upgraded); + let light = if let Some(lights) = &o.lights { + let mut entries = lights.iter(); + let light = *entries.next()?; + if entries.next().is_some() { + return None; + } + light + } else { + Light { + rotation: o.light_rotation, + height: o.light_height, + behind: o.light_behind, + color: o.light_color, + intensity: o.light_intensity, + softness: o.light_softness, + } + }; + LIGHTING_PRESETS.iter().position(|preset| preset.matches(light, o.ambient)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lighting_presets_are_valid_unique_and_standard_preserves_the_default() { + for (i, preset) in LIGHTING_PRESETS.iter().enumerate() { + let patch = preset.params(); + crate::lighting::validate(&patch).unwrap(); + assert_eq!(lighting_preset_params(preset.id), Some(patch.clone())); + assert_eq!(matching_lighting_preset(&patch), Some(i)); + assert!(!patch.as_object().unwrap().contains_key("shade")); + assert!(!patch.as_object().unwrap().contains_key("rotationX")); + } + assert_eq!(matching_lighting_preset(&json!({})), Some(0)); + assert!(lighting_preset_params("unknown").is_none()); + assert_eq!(crate::revolve_options(&LIGHTING_PRESETS[0].params()).light_direction(), crate::revolve_options(&json!({})).light_direction()); + } + + #[test] + fn lighting_preset_matching_uses_effective_lights_and_detects_custom_edits() { + let mut p = LIGHTING_PRESETS[3].params(); + p["lightColor"] = json!("#ff0000"); + p["lights"] = json!([{"rotation":0,"height":30}]); + assert_eq!(matching_lighting_preset(&p), Some(3), "explicit light overrides stale legacy color"); + p["lights"][0]["color"] = json!("#4080ff"); + assert_eq!(matching_lighting_preset(&p), None); + p["lights"] = json!([{}, {}]); + assert_eq!(matching_lighting_preset(&p), None); + for (key, value) in [("ambient", json!(26)), ("lightIntensity", json!(79)), ("lightBehind", json!(true))] { + let mut p = LIGHTING_PRESETS[0].params(); + p[key] = value; + assert_eq!(matching_lighting_preset(&p), None, "{key}"); + } + } +} diff --git a/crates/effects/src/live.rs b/crates/effects/src/live.rs index 7d03068c00..aad8d8edd9 100644 --- a/crates/effects/src/live.rs +++ b/crates/effects/src/live.rs @@ -37,7 +37,7 @@ fn outline(doc: Option<&Document>, n: &Node) -> Option { fn with_hooks(doc: Option<&Document>, f: impl FnOnce(Hooks) -> R) -> R { let outline = |n: &Node| outline(doc, n); let tiles = |name: &str, xf: Affine, region: Rect| Some(doc?.pattern(name)?.instances_in(xf, region)); - f(Hooks { outline: Some(&outline), appearance: Some(&bake_appearance), pattern: Some(&tiles) }) + f(Hooks { outline: Some(&outline), appearance: Some(&bake_appearance), pattern: Some(&tiles), symbols: doc }) } /// One level of evaluation of live object `n` ([`live::expand_live_hooks`]). diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs new file mode 100644 index 0000000000..dc54e8b51f --- /dev/null +++ b/crates/effects/src/params.rs @@ -0,0 +1,148 @@ +use super::catalog::{catalog_index, plugin_info}; +use super::*; + +/// Dialog defaults for `id` (`None` for unknown effects). +pub fn default_params(id: &str) -> Option { + match catalog_index().get(id) { + Some(e) => Some(e.defaults.clone()), + None => plugin_info(id).map(|e| e.defaults), + } +} + +/// `params` layered over the defaults of `id` (unknown keys are kept), in their current form (see +/// [`upgrade_params`]). The 3D effects' earlier `perspective` is read as `perspectiveAngle`, and +/// Scribble's earlier `variation` is read as `overlapVariation` and `spacingVariation`. +pub fn merged_params(id: &str, params: &Value) -> Value { + let mut out = match catalog_index().get(id).map(|e| &e.defaults) { + Some(Value::Object(m)) => m.clone(), + Some(_) => Map::new(), + None => vectorcraft_plugins::effect::installed(id).map(|p| p.manifest().defaults()).unwrap_or_default(), + }; + // Upgraded before the defaults are under it: a default angle is no angle given. + if let Value::Object(p) = upgrade_params(id, params) { + out.extend(p); + } + Value::Object(out) +} + +/// `params` for effect `id` in their current form. The 3D effects took Perspective as a 0–100 % +/// strength, `perspective`, before the documented 0°–160° angle, `perspectiveAngle`, and the light +/// as `lightAzimuth` and `lightElevation` before the documented Rotation and Height +/// (`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°). +pub fn upgrade_params(id: &str, params: &Value) -> Value { + match params { + Value::Object(m) => { + let mut m = m.clone(); + upgrade_perspective(id, &mut m); + upgrade_light(id, &mut m); + upgrade_scribble(id, &mut m); + Value::Object(m) + } + other => other.clone(), + } +} + +fn upgrade_light(id: &str, m: &mut Map) { + if !is_three_d(id) { + return; + } + let (azimuth, elevation) = (m.remove("lightAzimuth"), m.remove("lightElevation")); + if azimuth.is_none() && elevation.is_none() || m.contains_key("lightRotation") || m.contains_key("lightHeight") { + return; + } + let degrees = |v: Option, default: f64| v.and_then(|v| v.as_f64()).unwrap_or(default); + let (rotation, height, behind) = vectorcraft_three_d::light_from_azimuth_elevation(degrees(azimuth, -45.0), degrees(elevation, 45.0)); + m.insert("lightRotation".into(), json!(rotation)); + m.insert("lightHeight".into(), json!(height)); + m.insert("lightBehind".into(), json!(behind)); +} + +fn upgrade_perspective(id: &str, m: &mut Map) { + if !is_three_d(id) { + return; + } + let Some(strength) = m.remove("perspective") else { return }; + if !m.contains_key("perspectiveAngle") { + let angle = vectorcraft_three_d::perspective_from_strength(strength.as_f64().unwrap_or(0.0) / 100.0); + m.insert("perspectiveAngle".into(), json!(angle)); + } +} + +fn upgrade_scribble(id: &str, m: &mut Map) { + if id != "stylize.scribble" { + return; + } + if let Some(variation) = m.remove("variation") { + for key in ["overlapVariation", "spacingVariation"] { + m.entry(key).or_insert_with(|| variation.clone()); + } + } + if let Some(angle) = m.get("angle").and_then(Value::as_f64).filter(|a| a.is_finite() && (*a <= -180.0 || *a > 180.0)) { + let wrapped = angle.rem_euclid(360.0); + m.insert("angle".into(), json!(if wrapped > 180.0 { wrapped - 360.0 } else { wrapped })); + } +} + +/// A new effect record with default parameters (overridden by `params`). +pub fn new_effect(id: &str, params: &Value) -> Option { + if !catalog_index().contains_key(id) { + vectorcraft_plugins::effect::installed(id)?; + } + Some(Effect { id: id.to_string(), params: merged_params(id, params), visible: true }) +} + +/// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see +/// [`EffectInfo::lengths`]). A distance left at its default is written out scaled; one the +/// effect doesn't have (Outline Stroke's weight following its stroke) stays absent. +pub fn scale_effect(e: &mut Effect, s: f64) { + let Some(info) = catalog_index().get(e.id.as_str()) else { return }; + let merged = merged_params(&e.id, &e.params); + let relative = util::flag(&merged, "relative", false); + for k in info.lengths.keys(relative) { + let v = util::num(&merged, k, f64::NAN); + if v.is_finite() { + if !e.params.is_object() { + e.params = Value::Object(Map::new()); + } + e.params[k] = json!(v * s); + } + } +} + +/// Is `id` a raster (painted) effect? +pub fn is_raster(id: &str) -> bool { + matches!(id, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow" | "stylize.feather" | "blur.gaussian" | RASTERIZE) + || PIXEL_EFFECTS.contains(&id) +} + +/// Does `id` change geometry? (Crop Marks adds art of its own instead, [`crop_marks_art`]; colour +/// adjustments recolour, [`adjust`].) Plug-in effects do, installed or not (a missing plug-in +/// leaves the geometry as it is). +pub fn is_geometry(id: &str) -> bool { + !is_raster(id) + && !is_pathfinder(id) + && !is_adjustment(id) + && id != CROP_MARKS + && !is_three_d(id) + && (catalog_index().contains_key(id) || vectorcraft_plugins::effect::plugin_id(id).is_some()) +} + +/// Any visible geometry effect in the list? +pub fn has_geometry(effects: &[Effect]) -> bool { + effects.iter().any(|e| e.visible && is_geometry(&e.id)) +} + +/// Does `n` have a visible plug-in effect, its own or a fill's or stroke's? Such an effect draws +/// what the plug-in installed under its id draws ([`plugin_revision`]). +pub fn has_plugin_effect(n: &Node) -> bool { + let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some(); + n.appearance.effects.iter().any(plugin) || n.appearance.items.iter().any(|i| i.effects().iter().any(plugin)) +} + +/// The plug-in registry's revision, which changes whenever a plug-in is installed or removed. +pub fn plugin_revision() -> u64 { + vectorcraft_plugins::registry::revision() +} diff --git a/crates/effects/src/pixel/mod.rs b/crates/effects/src/pixel.rs similarity index 78% rename from crates/effects/src/pixel/mod.rs rename to crates/effects/src/pixel.rs index 051278eb11..8885c9def4 100644 --- a/crates/effects/src/pixel/mod.rs +++ b/crates/effects/src/pixel.rs @@ -1,9 +1,9 @@ -//! Photoshop-style raster effects (Effect › Artistic › Cutout, Film Grain, Neon Glow, Plastic Wrap and -//! Poster Edges, Smudge Stick, Sponge and Watercolor, Blur › Radial Blur and Smart Blur, Brush Strokes › Accented Edges, Angled Strokes, +//! Photoshop-style raster effects (Effect › Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Plastic Wrap and +//! Poster Edges, Rough Pastels, Smudge Stick, Sponge and Watercolor, Blur › Radial Blur and Smart Blur, Brush Strokes › Accented Edges, Angled Strokes, //! Crosshatch, Dark Strokes, Ink Outlines, Spatter, Sprayed Strokes and Sumi-e, Distort › Diffuse //! Glow, Glass and Ocean Ripple, Pixelate › Color Halftone, Crystallize, Mezzotint and Pointillize, -//! Sharpen › Unsharp Mask, Sketch › Chalk & Charcoal, Graphic Pen, Halftone Pattern, Note Paper, Plaster and -//! Reticulation, Stylize › +//! Sharpen › Unsharp Mask, Sketch › Bas Relief, Chalk & Charcoal, Charcoal, Chrome, Conté Crayon, Graphic Pen, Halftone Pattern, +//! Note Paper, Photocopy, Plaster, Reticulation, Stamp, Torn Edges and Water Paper, Stylize › //! Glowing Edges, Texture //! › Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass and Texturizer, and Video › //! De-Interlace and NTSC Colors): filters over premultiplied RGBA8 pixels. @@ -34,23 +34,31 @@ use vectorcraft_geom::{Affine, Point, Rect}; use crate::util::{flag, num, text}; +pub use artistic::{PAINT_DAUB_BRUSH_TYPES, PaintDaubBrush}; pub use blur::{SMART_BLUR_MODES, SmartBlurMode}; pub use brushstrokes::{STROKE_DIRECTIONS, StrokeDirection}; pub use distort::{GLASS_TEXTURES, GLASS_TEXTURES_LOADED, GlassTexture}; pub use loaded::{LOADED, LoadedTexture, TEXTURE_IMAGE, texture}; pub use pixelate::{MEZZOTINT_TYPES, Mezzotint}; pub use sketch::{HALFTONE_TYPES, HalftonePattern}; -pub use texture::{GRAIN_TYPES, Grain, LIGHT_DIRECTIONS, Light, TEXTURES, Texture}; +pub use texture::{GRAIN_TYPES, Grain, LIGHT_DIRECTIONS, Light, TEXTURES, TEXTURES_LOADED, Texture}; /// The Photoshop-style effect ids (all raster effects, see [`crate::is_raster`]). -pub const PIXEL_EFFECTS: [&str; 46] = [ +pub const PIXEL_EFFECTS: [&str; 56] = [ + "artistic.coloredPencil", "artistic.cutout", + "artistic.dryBrush", "artistic.filmGrain", + "artistic.fresco", "artistic.neonGlow", + "artistic.paintDaubs", + "artistic.paletteKnife", "artistic.plasticWrap", "artistic.posterEdges", + "artistic.roughPastels", "artistic.smudgeStick", "artistic.sponge", + "artistic.underpainting", "artistic.watercolor", "blur.radial", "blur.smart", @@ -74,6 +82,7 @@ pub const PIXEL_EFFECTS: [&str; 46] = [ "sketch.chalkCharcoal", "sketch.charcoal", "sketch.chrome", + "sketch.conteCrayon", "sketch.graphicPen", "sketch.halftonePattern", "sketch.notePaper", @@ -81,6 +90,8 @@ pub const PIXEL_EFFECTS: [&str; 46] = [ "sketch.plaster", "sketch.reticulation", "sketch.stamp", + "sketch.tornEdges", + "sketch.waterPaper", "stylize.glowingEdges", "texture.craquelure", "texture.grain", @@ -96,12 +107,22 @@ pub const PIXEL_EFFECTS: [&str; 46] = [ /// are in document units. #[derive(Clone, Debug, PartialEq)] pub enum PixelFx { + /// Artistic › Colored Pencil: coloured strokes `width` (1..24) apart, as heavy as `pressure` + /// (0..15), on paper lifted by `paper` (0..50). + ColoredPencil { width: f64, pressure: f64, paper: f64 }, /// Artistic › Cutout: flat pieces of colour in `levels` (2..8) steps per channel, their /// edges as simple as `simplicity` (0..10) and as faithful as `fidelity` (1..3) say. Cutout { levels: f64, simplicity: f64, fidelity: f64 }, + /// Artistic › Dry Brush: short strokes along the form with darkened edges; `size` (1..10) is the + /// brush length, `detail` (0..10) how much detail is kept, `texture` (1..3) the edge and bristle + /// contrast. + DryBrush { size: f64, detail: f64, texture: f64 }, /// Artistic › Film Grain: monochrome grain in shadows and midtones, a wider bright /// highlight area (0..20), and tonal intensity (0..10), preserving coverage. FilmGrain { grain: f64, highlight: f64, intensity: f64 }, + /// Artistic › Fresco: coarse brush dabs on plaster; `brush_size` (1..10), `brush_detail` + /// (0..10) and `texture` (1..3). + Fresco { brush_size: f64, brush_detail: f64, texture: f64 }, /// Artistic › Smudge Stick: the dark areas smudged along short diagonal strokes `stroke` /// (0..10) long, the light areas (widened by `highlight`, 0..20) smudged longer and lightened /// by up to `intensity` (0..10). @@ -116,12 +137,27 @@ pub enum PixelFx { /// light areas (`size` above 0) or the dark ones (below 0), spread by |`size`| (-24..24), as /// strong as `brightness` (0..50). NeonGlow { size: f64, brightness: f64, colour: [f32; 3] }, + /// Artistic › Paint Daubs: dabs `size` (1..50) points apart, as sharp as `sharpness` (0..40), + /// with brush `kind`. + PaintDaubs { size: f64, sharpness: f64, kind: PaintDaubBrush }, + /// Artistic › Palette Knife: knife strokes `stroke_size` (1..50) long smear the colours; + /// `stroke_detail` (1..3) keeps more original detail when higher; `softness` (0..10) softens + /// the strokes. + PaletteKnife { stroke_size: f64, stroke_detail: f64, softness: f64 }, /// Artistic › Plastic Wrap: specular highlights as strong as `highlight` (0..20) on a relief /// wrinkled by `detail` (0..15) and softened by `smoothness` (1..15). PlasticWrap { highlight: f64, detail: f64, smoothness: f64 }, /// Artistic › Poster Edges: colours posterized to `posterization` + 2 levels (0..6) with black /// lines on the edges, as thick as `thickness` (0..10) and as dark as `intensity` (0..10). PosterEdges { thickness: f64, intensity: f64, posterization: f64 }, + /// Artistic › Underpainting: colours softened as widely as `brush_size` (0..40), then a + /// `texture` surface (`scaling`, `relief`, `light`, `invert`) blended in as strongly as + /// `texture_coverage` (0..40) says. + Underpainting { brush_size: f64, texture_coverage: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool }, + /// Artistic › Rough Pastels: diagonal pastel strokes `length` (0..40) long, bristle detail + /// (1..20), then a [`Texture`] surface scaled by `scaling` (0.5..2), in relief as strong as + /// `relief` (0..50) and lit from `light`; `invert` turns the surface's heights over. + RoughPastels { length: f64, detail: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool }, /// Blur › Radial Blur around the object's centre: along arcs (spin, an arc of `amount`°) or /// along rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples. RadialBlur { amount: f64, zoom: bool, passes: u32 }, @@ -175,6 +211,11 @@ pub enum PixelFx { ChalkCharcoal { chalk: f64, charcoal: f64, pressure: f64 }, /// Sketch › Chrome: polished chrome relief with `detail` (0..10) and `smoothness` (0..10). Chrome { detail: f64, smoothness: f64 }, + /// Sketch › Conté Crayon: dark areas in a black crayon, light areas in a white one, on mid-grey + /// paper; `foreground` and `background` (0..20) set how far each crayon reaches into the + /// midtones, and the paper is a `texture` surface scaled by `scaling` (0.5..2), in relief as + /// strong as `relief` (0..50), lit from `light`, its heights turned over when `invert`. + ConteCrayon { foreground: f64, background: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool }, /// Sketch › Graphic Pen: fine linear ink strokes along `dir`, each `length` (1..15) points long /// on white paper; `balance` (0..100) sets how much of the tone range becomes black ink. GraphicPen { length: f64, balance: f64, direction: StrokeDirection }, @@ -202,6 +243,14 @@ pub enum PixelFx { /// Sketch › Reticulation: black ink on white paper through a high-contrast film-grain screen; /// `density` (0..50), `foreground` and `background` (0..50) pull tones before the grain. Reticulation { density: f64, foreground: f64, background: f64 }, + /// Sketch › Torn Edges: high-contrast black and white with ragged edges; `image_balance` + /// (0..50) shifts ink versus paper, `smoothness` (0..15) softens tones and fraying, `contrast` + /// (0..20) hardens the split. + TornEdges { image_balance: f64, smoothness: f64, contrast: f64 }, + /// Sketch › Water Paper: colours flow on damp fibrous paper; `fiber_length` (3..50) sets the + /// fibers and daubs, `brightness` and `contrast` (0..100) adjust the wash. Ranges and defaults + /// are unverified VectorCraft choices (helpx documents the controls only). + WaterPaper { fiber_length: f64, brightness: f64, contrast: f64 }, /// Stylize › Glowing Edges: bright coloured Sobel outlines on black. GlowingEdges { width: f64, brightness: f64, smoothness: f64 }, /// Pixelate › Color Halftone: each colour channel screened at its angle (`angles`° of channels @@ -282,16 +331,31 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { levels.iter().find(|(name, _)| name.eq_ignore_ascii_case(q)).map_or(default, |(_, v)| *v) }; Some(match id { + "artistic.coloredPencil" => PixelFx::ColoredPencil { + width: num(p, "pencilWidth", 5.0).clamp(1.0, 24.0), + pressure: num(p, "strokePressure", 5.0).clamp(0.0, 15.0), + paper: num(p, "paperBrightness", 25.0).clamp(0.0, 50.0), + }, "artistic.cutout" => PixelFx::Cutout { levels: num(p, "levels", 4.0).round().clamp(2.0, 8.0), simplicity: num(p, "edgeSimplicity", 4.0).clamp(0.0, 10.0), fidelity: num(p, "edgeFidelity", 2.0).round().clamp(1.0, 3.0), }, + "artistic.dryBrush" => PixelFx::DryBrush { + size: num(p, "brushSize", 2.0).clamp(1.0, 10.0), + detail: num(p, "brushDetail", 10.0).clamp(0.0, 10.0), + texture: num(p, "texture", 1.0).round().clamp(1.0, 3.0), + }, "artistic.neonGlow" => PixelFx::NeonGlow { size: num(p, "glowSize", 5.0).clamp(-24.0, 24.0), brightness: num(p, "glowBrightness", 15.0).clamp(0.0, 50.0), colour: crate::raster::color_param(p, vectorcraft_doc::color::Color::rgb(0.3, 0.65, 1.0)).to_rgb(), }, + "artistic.paletteKnife" => PixelFx::PaletteKnife { + stroke_size: num(p, "strokeSize", 10.0).clamp(1.0, 50.0), + stroke_detail: num(p, "strokeDetail", 2.0).clamp(1.0, 3.0), + softness: num(p, "softness", 3.0).clamp(0.0, 10.0), + }, "artistic.posterEdges" => PixelFx::PosterEdges { thickness: num(p, "edgeThickness", 2.0).clamp(0.0, 10.0), intensity: num(p, "edgeIntensity", 1.0).clamp(0.0, 10.0), @@ -302,6 +366,29 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { highlight: num(p, "highlightArea", 0.0).clamp(0.0, 20.0), intensity: num(p, "intensity", 10.0).clamp(0.0, 10.0), }, + "artistic.underpainting" => PixelFx::Underpainting { + brush_size: num(p, "brushSize", 6.0).clamp(0.0, 40.0), + texture_coverage: num(p, "textureCoverage", 16.0).clamp(0.0, 40.0), + texture: Texture::parse(text(p, "texture", "canvas")), + scaling: num(p, "scaling", 100.0).clamp(50.0, 200.0) / 100.0, + relief: num(p, "relief", 4.0).clamp(0.0, 50.0), + light: Light::parse(text(p, "lightDirection", "top")), + invert: flag(p, "invert", false), + }, + "artistic.roughPastels" => PixelFx::RoughPastels { + length: num(p, "strokeLength", 6.0).clamp(0.0, 40.0), + detail: num(p, "strokeDetail", 10.0).clamp(1.0, 20.0), + texture: Texture::parse(text(p, "texture", "canvas")), + scaling: num(p, "scaling", 100.0).clamp(50.0, 200.0) / 100.0, + relief: num(p, "relief", 4.0).clamp(0.0, 50.0), + light: Light::parse(text(p, "lightDirection", "top")), + invert: flag(p, "invert", false), + }, + "artistic.fresco" => PixelFx::Fresco { + brush_size: num(p, "brushSize", 2.0).clamp(1.0, 10.0), + brush_detail: num(p, "brushDetail", 10.0).clamp(0.0, 10.0), + texture: num(p, "texture", 1.0).round().clamp(1.0, 3.0), + }, "artistic.smudgeStick" => PixelFx::SmudgeStick { stroke: num(p, "strokeLength", 2.0).clamp(0.0, 10.0), highlight: num(p, "highlightArea", 12.0).clamp(0.0, 20.0), @@ -317,6 +404,11 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { shadow: num(p, "shadowIntensity", 1.0).clamp(0.0, 10.0), texture: num(p, "texture", 1.0).clamp(1.0, 3.0).round() as u32, }, + "artistic.paintDaubs" => PixelFx::PaintDaubs { + size: num(p, "brushSize", 10.0).clamp(1.0, 50.0), + sharpness: num(p, "sharpness", 25.0).clamp(0.0, 40.0), + kind: PaintDaubBrush::parse(text(p, "brushType", "simple")), + }, "artistic.plasticWrap" => PixelFx::PlasticWrap { highlight: num(p, "highlightStrength", 20.0).clamp(0.0, 20.0), detail: num(p, "detail", 12.0).clamp(0.0, 15.0), @@ -397,6 +489,15 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { pressure: num(p, "strokePressure", 2.0).clamp(0.0, 5.0), }, "sketch.chrome" => PixelFx::Chrome { detail: num(p, "detail", 4.0).clamp(0.0, 10.0), smoothness: num(p, "smoothness", 4.0).clamp(0.0, 10.0) }, + "sketch.conteCrayon" => PixelFx::ConteCrayon { + foreground: num(p, "foregroundLevel", 12.0).clamp(0.0, 20.0), + background: num(p, "backgroundLevel", 10.0).clamp(0.0, 20.0), + texture: Texture::parse(text(p, "texture", "canvas")), + scaling: num(p, "scaling", 100.0).clamp(50.0, 200.0) / 100.0, + relief: num(p, "relief", 4.0).clamp(0.0, 50.0), + light: Light::parse(text(p, "lightDirection", "top")), + invert: flag(p, "invert", false), + }, "sketch.graphicPen" => PixelFx::GraphicPen { length: num(p, "strokeLength", 5.0).clamp(1.0, 15.0), balance: num(p, "lightDarkBalance", 50.0).clamp(0.0, 100.0), @@ -438,6 +539,16 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { foreground: num(p, "foregroundLevel", 6.0).clamp(0.0, 50.0), background: num(p, "backgroundLevel", 6.0).clamp(0.0, 50.0), }, + "sketch.tornEdges" => PixelFx::TornEdges { + image_balance: num(p, "imageBalance", 25.0).clamp(0.0, 50.0), + smoothness: num(p, "smoothness", 11.0).clamp(0.0, 15.0), + contrast: num(p, "contrast", 17.0).clamp(0.0, 20.0), + }, + "sketch.waterPaper" => PixelFx::WaterPaper { + fiber_length: num(p, "fiberLength", 15.0).clamp(3.0, 50.0), + brightness: num(p, "brightness", 50.0).clamp(0.0, 100.0), + contrast: num(p, "contrast", 50.0).clamp(0.0, 100.0), + }, "stylize.glowingEdges" => PixelFx::GlowingEdges { width: num(p, "edgeWidth", 2.0).clamp(1.0, 14.0), brightness: num(p, "edgeBrightness", 6.0).clamp(0.0, 20.0), @@ -475,7 +586,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { light: num(p, "lightIntensity", 3.0).clamp(0.0, 10.0), }, "texture.texturizer" => PixelFx::Texturizer { - texture: Texture::parse(text(p, "texture", "canvas")), + texture: Texture::parse_with(text(p, "texture", "canvas"), p.get(TEXTURE_IMAGE).and_then(Value::as_str)), scaling: num(p, "scaling", 100.0).clamp(50.0, 200.0) / 100.0, relief: num(p, "relief", 4.0).clamp(0.0, 50.0), light: Light::parse(text(p, "lightDirection", "top")), @@ -503,9 +614,11 @@ impl PixelFx { PixelFx::SmartBlur { radius, .. } => radius, PixelFx::AccentedEdges { .. } => 0.0, // Strokes reach out of the object as far as they reach into it. - PixelFx::AngledStrokes { length, .. } | PixelFx::GraphicPen { length, .. } | PixelFx::InkOutlines { length, .. } => { - brushstrokes::stroke_reach(length) - } + PixelFx::PaletteKnife { stroke_size, softness, .. } => artistic::palette_knife_reach(stroke_size, softness), + PixelFx::AngledStrokes { length, .. } + | PixelFx::GraphicPen { length, .. } + | PixelFx::InkOutlines { length, .. } + | PixelFx::RoughPastels { length, .. } => brushstrokes::stroke_reach(length), PixelFx::Crosshatch { length, .. } => brushstrokes::stroke_reach(length) + brushstrokes::rough(length), PixelFx::DarkStrokes { .. } => brushstrokes::stroke_reach(brushstrokes::LIGHT_LENGTH), PixelFx::Spatter { radius, .. } => brushstrokes::spatter_shift(radius), @@ -519,19 +632,27 @@ impl PixelFx { PixelFx::UnsharpMask { .. } | PixelFx::ChalkCharcoal { .. } | PixelFx::Chrome { .. } + | PixelFx::ConteCrayon { .. } | PixelFx::HalftonePattern { .. } | PixelFx::NotePaper { .. } | PixelFx::Plaster { .. } - | PixelFx::Reticulation { .. } => 0.0, + | PixelFx::Reticulation { .. } + | PixelFx::TornEdges { .. } => 0.0, PixelFx::BasRelief { .. } | PixelFx::Charcoal { .. } | PixelFx::Photocopy { .. } | PixelFx::Stamp { .. } => 0.0, + PixelFx::WaterPaper { fiber_length, .. } => sketch::water_paper_shift(fiber_length), PixelFx::GlowingEdges { width, smoothness, .. } => width.max(smoothness * 3.0), + PixelFx::PaintDaubs { size, .. } => artistic::paint_daub_radius(size), // These three keep the object's coverage. PixelFx::SmudgeStick { .. } | PixelFx::Sponge { .. } | PixelFx::Watercolor { .. } => 0.0, PixelFx::FilmGrain { .. } + | PixelFx::ColoredPencil { .. } + | PixelFx::Fresco { .. } | PixelFx::Cutout { .. } + | PixelFx::DryBrush { .. } | PixelFx::NeonGlow { .. } | PixelFx::PlasticWrap { .. } | PixelFx::PosterEdges { .. } + | PixelFx::Underpainting { .. } | PixelFx::ColorHalftone { .. } | PixelFx::Mezzotint { .. } | PixelFx::Craquelure { .. } @@ -559,9 +680,11 @@ impl PixelFx { PixelFx::Watercolor { detail, .. } => Some(paint::watercolor_reach(detail)), PixelFx::AccentedEdges { width, smoothness, .. } => Some(brushstrokes::accent_reach(width, smoothness)), // The strokes, and the softened tones that choose them. + PixelFx::PaletteKnife { stroke_size, softness, .. } => Some(artistic::palette_knife_reach(stroke_size, softness)), PixelFx::AngledStrokes { length, .. } | PixelFx::GraphicPen { length, .. } => { Some(brushstrokes::stroke_reach(length).max(brushstrokes::TONE_REACH)) } + PixelFx::RoughPastels { length, .. } => Some(artistic::rough_pastels_reach(length)), PixelFx::Crosshatch { length, .. } => { Some((brushstrokes::stroke_reach(length) + brushstrokes::rough(length)).max(brushstrokes::TONE_REACH)) } @@ -582,21 +705,30 @@ impl PixelFx { // The cells around the pixel's, and the cells around theirs. PixelFx::ColorHalftone { max_radius, .. } => Some(3.0 * std::f64::consts::SQRT_2 * max_radius), PixelFx::Crystallize { cell } => Some(1.5 * cell), + PixelFx::ColoredPencil { width, .. } => Some(artistic::colored_pencil_reach(width)), PixelFx::ChalkCharcoal { .. } => Some(sketch::CHALK_CHARCOAL_REACH), PixelFx::Chrome { smoothness, .. } => Some(sketch::chrome_reach(smoothness)), + PixelFx::ConteCrayon { .. } => Some(sketch::CONTE_REACH), PixelFx::FilmGrain { .. } | PixelFx::Mezzotint { .. } | PixelFx::HalftonePattern { .. } | PixelFx::NotePaper { .. } | PixelFx::Reticulation { .. } => Some(0.0), + PixelFx::Fresco { brush_size, brush_detail, .. } => Some(artistic::fresco_reach(brush_size, brush_detail)), + PixelFx::DryBrush { size, detail, .. } => Some(artistic::dry_brush_reach(size, detail)), PixelFx::Plaster { smoothness, .. } => Some(sketch::plaster_reach(smoothness)), - // Cutout's palette comes from the whole object. - PixelFx::Cutout { .. } => None, + PixelFx::PaintDaubs { size, .. } => Some(artistic::paint_daub_radius(size) + size * 0.15), + PixelFx::WaterPaper { fiber_length, .. } => { + Some(sketch::water_paper_shift(fiber_length) + 3.0 * (0.06 * fiber_length.clamp(3.0, 50.0)).max(0.35)) + } + // Cutout's palette and Torn Edges' peak-normalised edges come from the whole object. + PixelFx::Cutout { .. } | PixelFx::TornEdges { .. } => None, // The softened tones around the pixel. PixelFx::NeonGlow { size, .. } => Some(3.0 * artistic::glow_spread(size)), PixelFx::PlasticWrap { smoothness, .. } => Some(artistic::plastic_reach(smoothness)), // The edges' lines, spread round them. PixelFx::PosterEdges { thickness, .. } => Some(3.0 * (0.3 + 0.25 * thickness) + 1.0), + PixelFx::Underpainting { brush_size, .. } => Some(3.0 * (0.1 * brush_size.max(0.25)) + 1.0), // The dots' points, and the softened colour around them. PixelFx::Pointillize { cell } => Some(2.5 * cell), // The softened tones around the pixel. @@ -617,16 +749,29 @@ impl PixelFx { let Some(px) = pixels(data, w, h) else { return }; let to_px = |len: f64| len / space.px.max(1e-9); match *self { + PixelFx::ColoredPencil { width, pressure, paper } => artistic::colored_pencil(px, w, h, space, width, pressure, paper), PixelFx::Cutout { levels, simplicity, fidelity } => artistic::cutout(px, w, h, space, levels, simplicity, fidelity), + PixelFx::DryBrush { size, detail, texture } => artistic::dry_brush(px, w, h, space, size, detail, texture), PixelFx::FilmGrain { grain, highlight, intensity } => artistic::film_grain(px, w, h, space, grain, highlight, intensity), + PixelFx::Fresco { brush_size, brush_detail, texture } => artistic::fresco(px, w, h, space, brush_size, brush_detail, texture), PixelFx::SmudgeStick { stroke, highlight, intensity } => paint::smudge_stick(px, w, h, space, stroke, highlight, intensity), PixelFx::Sponge { brush, definition, smoothness } => paint::sponge(px, w, h, space, brush, definition, smoothness), PixelFx::Watercolor { detail, shadow, texture } => paint::watercolor(px, w, h, space, detail, shadow, texture), + PixelFx::PaintDaubs { size, sharpness, kind } => artistic::paint_daubs(px, w, h, space, size, sharpness, kind), PixelFx::PlasticWrap { highlight, detail, smoothness } => artistic::plastic_wrap(px, w, h, space, highlight, detail, smoothness), PixelFx::NeonGlow { size, brightness, colour } => artistic::neon_glow(px, w, h, space, size, brightness, colour), + PixelFx::PaletteKnife { stroke_size, stroke_detail, softness } => { + artistic::palette_knife(px, w, h, space, stroke_size, stroke_detail, softness) + } PixelFx::PosterEdges { thickness, intensity, posterization } => { artistic::poster_edges(px, w, h, space, thickness, intensity, posterization) } + PixelFx::Underpainting { brush_size, texture_coverage, ref texture, scaling, relief, light, invert } => { + artistic::underpainting(px, w, h, space, brush_size, texture_coverage, texture, scaling, relief, light, invert) + } + PixelFx::RoughPastels { length, detail, ref texture, scaling, relief, light, invert } => { + artistic::rough_pastels(px, w, h, space, length, detail, texture, scaling, relief, light, invert) + } PixelFx::RadialBlur { amount, zoom, passes } => blur::radial(px, w, h, space, amount, zoom, passes), PixelFx::SmartBlur { radius, threshold, samples, mode: SmartBlurMode::Normal } => { blur::smart(px, w, h, to_px(radius), threshold, samples) @@ -650,6 +795,9 @@ impl PixelFx { PixelFx::UnsharpMask { amount, radius, threshold } => sharpen::unsharp(px, w, h, amount, to_px(radius), threshold), PixelFx::ChalkCharcoal { chalk, charcoal, pressure } => sketch::chalk_charcoal(px, w, h, space, chalk, charcoal, pressure), PixelFx::Chrome { detail, smoothness } => sketch::chrome(px, w, h, space, detail, smoothness), + PixelFx::ConteCrayon { foreground, background, ref texture, scaling, relief, light, invert } => { + sketch::conte_crayon(px, w, h, space, foreground, background, texture, scaling, relief, light, invert) + } PixelFx::GraphicPen { length, balance, direction } => brushstrokes::graphic_pen(px, w, h, space, length, balance, direction), PixelFx::HalftonePattern { size, contrast, kind } => sketch::halftone_pattern(px, w, h, space, size, contrast, kind), PixelFx::NotePaper { balance, graininess, relief } => sketch::note_paper(px, w, h, space, balance, graininess, relief), @@ -659,6 +807,8 @@ impl PixelFx { PixelFx::Stamp { balance, smoothness } => sketch_ink::stamp(px, w, h, space, balance, smoothness), PixelFx::Plaster { image_balance, smoothness, light } => sketch::plaster(px, w, h, space, image_balance, smoothness, light), PixelFx::Reticulation { density, foreground, background } => sketch::reticulation(px, w, h, space, density, foreground, background), + PixelFx::TornEdges { image_balance, smoothness, contrast } => sketch::torn_edges(px, w, h, space, image_balance, smoothness, contrast), + PixelFx::WaterPaper { fiber_length, brightness, contrast } => sketch::water_paper(px, w, h, space, fiber_length, brightness, contrast), PixelFx::GlowingEdges { width, brightness, smoothness } => edges::glow(px, w, h, to_px(width), brightness, to_px(smoothness)), PixelFx::ColorHalftone { max_radius, angles } => pixelate::color_halftone(px, w, h, space, max_radius, angles), PixelFx::Crystallize { cell } => pixelate::crystallize(px, w, h, space, cell), @@ -669,7 +819,7 @@ impl PixelFx { PixelFx::MosaicTiles { tile, grout, lighten } => texture::mosaic_tiles(px, w, h, space, tile, grout, lighten), PixelFx::Patchwork { square, relief } => texture::patchwork(px, w, h, space, square, relief), PixelFx::StainedGlass { cell, border, light } => texture::stained_glass(px, w, h, space, cell, border, light), - PixelFx::Texturizer { texture, scaling, relief, light, invert } => { + PixelFx::Texturizer { ref texture, scaling, relief, light, invert } => { texture::texturizer(px, w, h, space, texture, scaling, relief, light, invert) } PixelFx::DeInterlace { even, interpolate } => video::deinterlace(px, w, h, space, even, interpolate), @@ -782,22 +932,41 @@ pub fn dilate_plane(a: &mut Vec, w: usize, h: usize, radius: f64) { /// One horizontal pass of [`dilate_plane`] over the rows of `w` values of a plane: the largest /// value within `whole`, blended by `frac` towards the largest within `whole + 1`. fn max_plane(src: &[f32], dst: &mut [f32], w: usize, whole: usize, frac: f32) { + let (mut inner, mut ring) = (vec![0.0f32; w], vec![0.0f32; w]); for (row, out) in src.chunks_exact(w).zip(dst.chunks_exact_mut(w)) { - for (x, o) in out.iter_mut().enumerate() { - let lo = x.saturating_sub(whole + 1); - let hi = (x + whole + 1).min(w - 1); - let (mut inner, mut ring) = (row[x], row[x]); - for (j, v) in row[lo..=hi].iter().enumerate() { - if (lo + j).abs_diff(x) <= whole { - inner = inner.max(*v); - } - ring = ring.max(*v); - } - *o = inner + (ring - inner) * frac; + window_max(row, whole, &mut inner); + window_max(row, whole + 1, &mut ring); + for ((o, i), r) in out.iter_mut().zip(&inner).zip(&ring) { + *o = i + (r - i) * frac; } } } +/// For each `x`, the largest of `row[x - radius..=x + radius]` (cut at the row's ends) into `out`, +/// in time linear in the row (a sliding window, not a scan of the window for each `x`). +fn window_max(row: &[f32], radius: usize, out: &mut [f32]) { + use std::collections::VecDeque; + // Indices of the window's values that can still be its largest, falling in value. + let mut keep: VecDeque = VecDeque::new(); + let mut next = 0; + for (x, o) in out.iter_mut().enumerate().take(row.len()) { + let hi = x.saturating_add(radius).min(row.len().saturating_sub(1)); + while next <= hi { + let v = row[next]; + while keep.back().is_some_and(|&b| row[b] <= v) { + keep.pop_back(); + } + keep.push_back(next); + next += 1; + } + let lo = x.saturating_sub(radius); + while keep.front().is_some_and(|&f| f < lo) { + keep.pop_front(); + } + *o = keep.front().map_or(row[x], |&f| row[f]); + } +} + /// Premultiplied RGBA at 16 bits (×257): blurs and averages that keep their tones. pub(super) type Px16 = [u16; 4]; @@ -911,3 +1080,22 @@ mod tests; mod tests_paint; #[cfg(test)] mod tests_sketch; + +#[cfg(test)] +mod window_max_tests { + use super::window_max; + + #[test] + fn the_sliding_maximum_matches_a_scan_of_each_window() { + let row: Vec = (0..40u32).map(|i| ((i * 7919) % 31) as f32).collect(); + for radius in [0, 1, 2, 5, 39, 100] { + let mut out = vec![0.0; row.len()]; + window_max(&row, radius, &mut out); + for (x, got) in out.iter().enumerate() { + let (lo, hi) = (x.saturating_sub(radius), (x + radius).min(row.len() - 1)); + let want = row[lo..=hi].iter().copied().fold(f32::MIN, f32::max); + assert_eq!(*got, want, "radius {radius} at {x}"); + } + } + } +} diff --git a/crates/effects/src/pixel/artistic.rs b/crates/effects/src/pixel/artistic.rs index 0d6764feb6..039a0db139 100644 --- a/crates/effects/src/pixel/artistic.rs +++ b/crates/effects/src/pixel/artistic.rs @@ -1,18 +1,78 @@ -//! Effect › Artistic (Cutout, Film Grain, Neon Glow, Plastic Wrap, Poster Edges). Original filters built from +//! Effect › Artistic (Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Plastic Wrap, Poster +//! Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor). Original filters built from //! public behaviour documentation: //! and //! . //! These are visual approximations, not reproductions of a proprietary algorithm. -use super::edges::sobel; -use super::pixelate::{Place, cell, rand}; +use std::f64::consts::TAU; +use super::brushstrokes::{LEFT, RIGHT, Smear, TONE_SOFTNESS, mix, streak, stroke_reach, unit, unpremultiply}; +use super::edges::sobel; +use super::pixelate::{Around, Place, Soft, cell, point_in, rand, value_noise}; +use super::texture::{self, Light, Texture, Tones, luma, premultiply, smooth_noise, straight, texturizer}; +use super::{PixelSpace, blur_plane, pick}; +use vectorcraft_geom::{Point, Vec2}; + +const SALT_DRY: u64 = 264; +const MARGIN: f64 = 1.0; const SALT_PLASTIC: u64 = 512; -use super::texture::{luma, premultiply, straight}; -use super::{PixelSpace, blur_plane}; -use vectorcraft_geom::Point; + +const SALT_PASTEL: u64 = 200; const SALT_FILM: u64 = 256; +const SALT_DAUB: u64 = 272; + +/// Paint Daubs' brush types, in the Brush Type menu's order: (label, parameter value). +/// Illustrator's list: . +pub const PAINT_DAUB_BRUSH_TYPES: [(&str, &str); 6] = [ + ("Simple", "simple"), + ("Light Rough", "lightRough"), + ("Dark Rough", "darkRough"), + ("Wide Sharp", "wideSharp"), + ("Wide Blurry", "wideBlurry"), + ("Sparkle", "sparkle"), +]; + +/// A Paint Daubs brush ([`PAINT_DAUB_BRUSH_TYPES`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PaintDaubBrush { + Simple, + LightRough, + DarkRough, + WideSharp, + WideBlurry, + Sparkle, +} + +impl PaintDaubBrush { + const ALL: [PaintDaubBrush; 6] = [ + PaintDaubBrush::Simple, + PaintDaubBrush::LightRough, + PaintDaubBrush::DarkRough, + PaintDaubBrush::WideSharp, + PaintDaubBrush::WideBlurry, + PaintDaubBrush::Sparkle, + ]; + + /// The brush of Brush Type `value` (a [`PAINT_DAUB_BRUSH_TYPES`] value, any case); Simple otherwise. + pub fn parse(value: &str) -> Self { + if value.eq_ignore_ascii_case("wideRough") { + return PaintDaubBrush::WideSharp; + } + if value.eq_ignore_ascii_case("hue") { + return PaintDaubBrush::WideBlurry; + } + pick(&PAINT_DAUB_BRUSH_TYPES, &Self::ALL, value, PaintDaubBrush::Simple) + } +} + +/// How far (document units) a dab reaches past its centre at `size` (1..50). +pub(super) fn paint_daub_radius(size: f64) -> f64 { + size.clamp(1.0, 50.0) * 0.48 +} +const SALT_PENCIL: u64 = 304; +const SALT_FRESCO: u64 = 320; /// Keep the last cell's four corner values: magnified adjacent pixels often share a cell. /// The cache changes only cost, never the field, and needs constant storage per raster. @@ -161,6 +221,55 @@ fn planes(px: &[[u8; 4]]) -> ([Vec; 3], Vec) { (std::array::from_fn(|k| colours.iter().map(|c| c[k]).collect()), px.iter().map(|p| f32::from(p[3]) / 255.0).collect()) } +/// How far (document units) Colored Pencil reaches at pencil width `width`: soften at +/// `0.12 * width` and the Sobel neighbourhood around it. +pub(super) fn colored_pencil_reach(width: f64) -> f64 { + 3.0 * 0.12 * width.clamp(1.0, 24.0) + 1.0 +} + +/// Colored Pencil: the object redrawn with coloured pencil strokes along local edges, keeping its +/// hues. `width` (1..24) sets the stroke spacing in document units; `pressure` (0..15) darkens +/// along the strokes; `paper` (0..50) lifts lighter areas toward the paper. Coverage is kept. +pub(super) fn colored_pencil(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, width: f64, pressure: f64, paper: f64) { + if !([width, pressure, paper].iter().all(|v| v.is_finite()) && space.px.is_finite() && space.px > 0.0) { + return; + } + let width = width.clamp(1.0, 24.0); + let pressure = (pressure / 15.0).clamp(0.0, 1.0) as f32; + let paper_lift = (paper / 50.0).clamp(0.0, 1.0) as f32; + if pressure == 0.0 && paper_lift == 0.0 { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let (mut colour, alpha) = planes(px); + soften(&mut colour, &alpha, w, h, (0.12 * width) / space.px); + let tones: Vec = (0..px.len()).map(|k| luma([colour[0][k], colour[1][k], colour[2][k]])).collect(); + let mut edges = vec![0.0f32; px.len()]; + for (e, s) in edges.iter_mut().zip(sobel(&tones, w, h)) { + *e = (s / 4.0).min(1.0); + } + let spacing = (0.35 * width).max(1.0); + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let k = y * w + x; + let c = [colour[0][k], colour[1][k], colour[2][k]]; + let gx = tone_at(&tones, w, h, x as isize + 1, y as isize) - tone_at(&tones, w, h, x as isize - 1, y as isize); + let gy = tone_at(&tones, w, h, x as isize, y as isize + 1) - tone_at(&tones, w, h, x as isize, y as isize - 1); + let angle = gy.atan2(gx) + std::f32::consts::FRAC_PI_2; + let (dx, dy) = (angle.cos() as f64, angle.sin() as f64); + let q = place.at(x, y); + let along = q.x * dx + q.y * dy; + let grain = value_noise(SALT_PENCIL, along / spacing, (q.x * 0.37 + q.y * 0.11) / spacing); + let stroke = (0.5 + 0.5 * (along / spacing * TAU + grain * 3.0).sin()) as f32; + let ink = pressure * (0.3 + 0.55 * stroke) * (0.55 + 0.45 * edges[k]); + let lift = paper_lift * (1.0 - luma(c)) * 0.35; + let c = c.map(|v| (v * (1.0 - ink * 0.45) + lift * (1.0 - v)).clamp(0.0, 1.0)); + *p = premultiply(c, f32::from(p[3]) / 255.0); + }); +} + /// Cutout: the object as flat pieces of coloured paper. Its colours, softened as `simplicity` /// (0..10) asks and less as `fidelity` (1..3) keeps detail, fall into `levels` (2..8) steps per /// colour channel; each step's piece is painted in the average colour of what falls into it, so @@ -241,6 +350,136 @@ pub(super) fn poster_edges(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pixel } } +/// Paint Daubs: thick round dabs on a grid `size` (1..50) points apart, each dab painted in the +/// local colour around its centre, with edges as sharp as `sharpness` (0..40) and a profile from +/// `kind`. Coverage is kept. +pub(super) fn paint_daubs(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, size: f64, sharpness: f64, kind: PaintDaubBrush) { + if !([size, sharpness].iter().all(|v| v.is_finite()) && size > 0.0) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let spacing = size.clamp(1.0, 50.0); + let brush_r = paint_daub_radius(size); + let edge = 1.0 + 2.5 * (sharpness.clamp(0.0, 40.0) / 40.0); + let soft = Soft::new(px, w, (spacing * 0.15) / place.px); + let dab = |i: i64, j: i64| { + let at = point_in(SALT_DAUB, i, j); + let center = Point::new(at.x * spacing, at.y * spacing); + (center, soft.at(place.index(center))) + }; + let cover = |q: Point, center: Point, colour: [f32; 4]| -> f32 { + if colour[3] <= 0.0 { + return 0.0; + } + let (dx, dy) = (q.x - center.x, q.y - center.y); + let (dx, dy) = match kind { + PaintDaubBrush::WideSharp | PaintDaubBrush::WideBlurry => (dx * 0.65, dy * 1.35), + _ => (dx, dy), + }; + let t = (dx.hypot(dy) / brush_r).clamp(0.0, 1.0); + let edge_k = match kind { + PaintDaubBrush::WideSharp => edge * 1.35, + PaintDaubBrush::WideBlurry => edge * 0.55, + _ => edge, + }; + let mut c = (1.0 - t).powf(edge_k) as f32; + let tone = luma(unpremultiply(colour).0); + match kind { + PaintDaubBrush::LightRough => c *= 0.7 + 0.35 * rough_bristle(q, 0), + PaintDaubBrush::DarkRough => c *= 0.55 + 0.45 * (1.0 - rough_bristle(q, 1)), + PaintDaubBrush::Sparkle if rough_bristle(center, 2) > 0.92 && tone > 0.55 => c = c.max(0.85), + PaintDaubBrush::Simple | PaintDaubBrush::WideSharp | PaintDaubBrush::WideBlurry | PaintDaubBrush::Sparkle => {} + } + c + }; + let mut around = Around::new(); + place.each(px, |x, y, out| { + if out[3] == 0 { + return; + } + let q = place.at(x, y); + let (u, v) = (q.x / spacing, q.y / spacing); + let (Some(i), Some(j)) = (cell(u), cell(v)) else { return }; + let mut sum = [0.0f32; 3]; + let mut weight = 0.0f32; + for k in 0..9 { + let Some((center, colour)) = around.get((i, j), k, dab) else { continue }; + let w = cover(q, center, colour); + if w <= 0.0 { + continue; + } + let c = unpremultiply(colour).0; + for (s, v) in sum.iter_mut().zip(c) { + *s += v * w; + } + weight += w; + } + if weight <= 1e-6 { + return; + } + let c = sum.map(|v| (v / weight).clamp(0.0, 1.0)); + *out = premultiply(c, f32::from(out[3]) / 255.0); + }); +} + +fn rough_bristle(p: Point, k: u64) -> f32 { + let (Some(i), Some(j)) = (cell(p.x * 3.7), cell(p.y * 3.7)) else { return 0.5 }; + rand(SALT_DAUB + 3, i, j, k) as f32 +} + +/// Fresco: coarse brush dabs on a plaster wall. `brush_size` (1..10) sets dab spacing, +/// `brush_detail` (0..10) keeps sharper edges when high, and `texture` (1..3) deepens the +/// relief. Coverage is kept. +pub(super) fn fresco(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, brush_size: f64, brush_detail: f64, texture: f64) { + if !([brush_size, brush_detail, texture].iter().all(|v| v.is_finite()) && space.px.is_finite() && space.px > 0.0) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let brush_size = brush_size.clamp(1.0, 10.0); + let brush_detail = brush_detail.clamp(0.0, 10.0); + let texture = texture.round().clamp(1.0, 3.0); + let side = 2.0 + 1.8 * brush_size; + let sigma = (0.15 * (10.0 - brush_detail) * brush_size / place.px).max(0.0); + let soft = Soft::new(px, w, sigma); + let tex_strength = 0.08 + 0.07 * (texture - 1.0); + let tex_scale = 3.0 / texture; + let streak_mix = 0.25 * (1.0 - brush_detail / 10.0); + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let q = place.at(x, y); + let (Some(i), Some(j)) = (cell(q.x / side), cell(q.y / side)) else { return }; + let jx = (rand(SALT_FRESCO, i, j, 0) - 0.5) * 0.35 * side; + let jy = (rand(SALT_FRESCO, i, j, 1) - 0.5) * 0.35 * side; + let sample = Point::new(q.x + jx, q.y + jy); + let mut sampled = soft.at(place.index(sample)); + if sampled[3] <= 0.0 { + sampled = soft.at(place.index(q)); + } + if sampled[3] <= 0.0 { + return; + } + let [r, g, b, alpha] = sampled; + let c = [r, g, b].map(|v| v / alpha); + let angle = TAU * rand(SALT_FRESCO, i, j, 2); + let (fx, fy) = (q.x - i as f64 * side, q.y - j as f64 * side); + let along = fx * angle.cos() + fy * angle.sin(); + let streak = (1.0 - streak_mix * (0.5 + 0.5 * (along / side).sin().powi(2))) as f32; + let bump = (1.0 + tex_strength * smooth_noise(SALT_FRESCO + 3, q, tex_scale * side)) as f32; + let lit = c.map(|v| (v * streak * bump).clamp(0.0, 1.0)); + *p = premultiply(lit, f32::from(p[3]) / 255.0); + }); +} + +/// How far (document units) a Fresco dab can reach from a pixel. +pub(super) fn fresco_reach(brush_size: f64, brush_detail: f64) -> f64 { + let brush_size = brush_size.clamp(1.0, 10.0); + let brush_detail = brush_detail.clamp(0.0, 10.0); + let side = 2.0 + 1.8 * brush_size; + side + 0.15 * (10.0 - brush_detail) * brush_size +} + /// How far (document units) Plastic Wrap's softened relief is sampled at `smoothness` (1..15). pub(super) fn plastic_reach(smoothness: f64) -> f64 { 3.0 * (0.15 + 0.35 * smoothness.clamp(1.0, 15.0)) @@ -314,11 +553,144 @@ pub(super) fn plastic_wrap(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pixel }); } +/// Stroke length (document units) for Dry Brush at Brush Size `size` (1..10). +fn dry_brush_length(size: f64) -> f64 { + 2.0 + 2.8 * (size.clamp(1.0, 10.0) - 1.0) +} + +/// How much Dry Brush softens before smearing at Brush Detail `detail` (0..10; 10 keeps the most detail). +fn dry_brush_sigma(detail: f64) -> f64 { + 0.22 * (10.0 - detail.clamp(0.0, 10.0)) +} + +/// How far (document units) Dry Brush reads from a pixel. +pub(super) fn dry_brush_reach(size: f64, detail: f64) -> f64 { + stroke_reach(dry_brush_length(size)) + 3.0 * dry_brush_sigma(detail) + MARGIN +} + /// How far (document units) Neon Glow's glow spreads at `size` (-24..24). pub(super) fn glow_spread(size: f64) -> f64 { 0.25 * size.abs().min(24.0) } +/// Underpainting: broad brush strokes (`brush_size`, 0..40) over a relief `texture` surface +/// (`scaling`, `relief`, `light`, `invert`, as Texturizer uses), blended in as strongly as +/// `texture_coverage` (0..40) says. Coverage is kept. +#[allow(clippy::too_many_arguments)] +pub(super) fn underpainting( + px: &mut [[u8; 4]], + w: usize, + h: usize, + space: &PixelSpace, + brush_size: f64, + texture_coverage: f64, + texture: &Texture, + scaling: f64, + relief: f64, + light: Light, + invert: bool, +) { + if !(brush_size.is_finite() && texture_coverage.is_finite() && space.px.is_finite() && space.px > 0.0) { + return; + } + let brush_size = brush_size.clamp(0.0, 40.0); + let coverage = (texture_coverage / 40.0).clamp(0.0, 1.0) as f32; + let (mut colour, alpha) = planes(px); + let sigma = (0.1 * brush_size.max(0.25)) / space.px; + if sigma > 0.0 { + soften(&mut colour, &alpha, w, h, sigma); + } + for (k, p) in px.iter_mut().enumerate() { + if p[3] == 0 { + continue; + } + let c = [colour[0][k], colour[1][k], colour[2][k]]; + *p = premultiply(c, f32::from(p[3]) / 255.0); + } + if coverage <= 0.0 { + return; + } + let softened = px.to_vec(); + texture::texturizer(px, w, h, space, texture, scaling, relief, light, invert); + if coverage >= 1.0 { + return; + } + let mix = 1.0 - coverage; + for (k, p) in px.iter_mut().enumerate() { + if p[3] == 0 { + continue; + } + let a = f32::from(p[3]) / 255.0; + let tex = straight(*p); + let soft = straight(softened[k]); + let c = [ + (soft[0] * mix + tex[0] * coverage).clamp(0.0, 1.0), + (soft[1] * mix + tex[1] * coverage).clamp(0.0, 1.0), + (soft[2] * mix + tex[2] * coverage).clamp(0.0, 1.0), + ]; + *p = premultiply(c, a); + } +} + +/// How far (document units) Rough Pastels reaches with strokes `len` long. +pub(super) fn rough_pastels_reach(len: f64) -> f64 { + super::brushstrokes::stroke_reach(len).max(super::brushstrokes::TONE_REACH) +} + +/// Rough Pastels: soft diagonal pastel strokes `length` (0..40) long with bristle `detail` (1..20), +/// then the shared Texturizer surface (`texture`, `scaling`, `relief`, `light`, `invert`). +/// Coverage is kept. +#[allow(clippy::too_many_arguments)] +pub(super) fn rough_pastels( + px: &mut [[u8; 4]], + w: usize, + h: usize, + space: &PixelSpace, + length: f64, + detail: f64, + texture: &Texture, + scaling: f64, + relief: f64, + light: Light, + invert: bool, +) { + if !([length, detail, scaling, relief].iter().all(|v| v.is_finite()) && space.px.is_finite() && space.px > 0.0) { + return; + } + let length = length.clamp(0.0, 40.0); + let detail = detail.clamp(1.0, 20.0); + if length > 0.0 { + let Some(place) = Place::new(space, w, h) else { return }; + let smear = Smear::new(px, w, h, &place, length.max(1.0)); + let tones = Tones::new(px, w, h, TONE_SOFTNESS / place.px); + let row = (0.18 * smear.len).max(1.0); + let stroke_mix = (0.35 + 0.0225 * detail).clamp(0.35, 0.8) as f32; + let bristle = (0.015 + 0.0035 * detail) as f32; + let src = px.to_vec(); + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let q = place.at(x, y); + let pm = mix(smear.stroke(SALT_PASTEL, q, RIGHT, row), smear.stroke(SALT_PASTEL + 1, q, LEFT, row), 0.5); + let orig = unit(src.get(y * w + x).copied().unwrap_or([0; 4])); + let pm = mix(orig, pm, stroke_mix); + let (mut c, a) = unpremultiply(pm); + if a <= 0.0 { + *p = [0; 4]; + return; + } + let dir = if tones.get(x, y) > 0.52 { RIGHT } else { LEFT }; + let n = bristle * streak(SALT_PASTEL + 2, q, dir, smear.len.max(1.0), row) as f32; + c = c.map(|v| (v + n).clamp(0.0, 1.0)); + *p = premultiply(c, orig[3]); + }); + } + if relief > 0.0 { + texturizer(px, w, h, space, texture, scaling, relief, light, invert); + } +} + /// Neon Glow: the object in dimmed greys, lit by `colour` glowing from its light areas (`size` /// above 0) or from its dark areas (below 0), spread as far as |`size`| (0..24) says and as /// strong as `brightness` (0..50). Coverage is kept. @@ -343,3 +715,162 @@ pub(super) fn neon_glow(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpa *p = premultiply(c, f32::from(p[3]) / 255.0); } } + +/// The tone at `(x, y)` in `tone`, `w` × `h`, or 0 outside. +fn tone_at(tone: &[f32], w: usize, h: usize, x: isize, y: isize) -> f32 { + if x < 0 || y < 0 { + return 0.0; + } + let (x, y) = (x as usize, y as usize); + if x >= w || y >= h { + return 0.0; + } + tone[y * w + x] +} + +/// A unit vector along the image gradient's tangent at `(x, y)`, or horizontal when flat. +fn dry_brush_dir(tone: &[f32], w: usize, h: usize, x: usize, y: usize) -> Vec2 { + let gx = 0.5 * (tone_at(tone, w, h, x as isize + 1, y as isize) - tone_at(tone, w, h, x as isize - 1, y as isize)); + let gy = 0.5 * (tone_at(tone, w, h, x as isize, y as isize + 1) - tone_at(tone, w, h, x as isize, y as isize - 1)); + let v = Vec2::new(-f64::from(gy), f64::from(gx)); + let len = v.hypot(); + if len > 1e-6 { v / len } else { Vec2::new(1.0, 0.0) } +} + +/// Premultiplied RGBA (0..1) at document `q`, bilinearly from `src`. +fn sample_pm(src: &[[f32; 4]], w: usize, h: usize, place: &Place, q: Point) -> [f32; 4] { + let p = place.to_px * q; + if !(p.x.is_finite() && p.y.is_finite()) { + return [0.0; 4]; + } + let (x, y) = (p.x - 0.5, p.y - 0.5); + let (i, j) = (x.floor() as isize, y.floor() as isize); + let (fx, fy) = (x - i as f64, y - j as f64); + let mut acc = [0.0f32; 4]; + for (row, wy) in [(j, 1.0 - fy), (j + 1, fy)] { + let Some(row) = usize::try_from(row).ok().filter(|r| *r < h) else { continue }; + for (col, wx) in [(i, 1.0 - fx), (i + 1, fx)] { + let Some(col) = usize::try_from(col).ok().filter(|c| *c < w) else { continue }; + let k = (wx * wy) as f32; + if let Some(p) = src.get(row * w + col) { + for (a, v) in acc.iter_mut().zip(p) { + *a += *v * k; + } + } + } + } + acc +} + +/// Dry Brush: the object repainted with short strokes along its form, edges darkened. `size` +/// (1..10) sets the stroke length, `detail` (0..10) how much is softened first (10 keeps the most +/// detail), and `texture` (1..3) how strongly edges and bristle grain contrast. Coverage is kept. +pub(super) fn dry_brush(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, size: f64, detail: f64, texture: f64) { + if !([size, detail, texture].iter().all(|v| v.is_finite()) && space.px.is_finite() && space.px > 0.0) { + return; + } + let len = dry_brush_length(size); + let sigma = dry_brush_sigma(detail); + let texture = texture.clamp(1.0, 3.0); + let edge_gain = (0.25 + 0.2 * (texture - 1.0)) as f32; + let bristle = (0.04 + 0.05 * (texture - 1.0)) as f32; + let (mut colour, alpha) = planes(px); + if sigma > 0.0 { + soften(&mut colour, &alpha, w, h, sigma); + } + let at = |k: usize| [0, 1, 2].map(|i| colour[i].get(k).copied().unwrap_or(0.0)); + let tone: Vec = (0..w * h) + .map(|k| { + let c = at(k); + let a = alpha.get(k).copied().unwrap_or(0.0); + (0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]) * a + }) + .collect(); + let edges = sobel(&tone, w, h); + let src: Vec<[f32; 4]> = (0..w * h) + .map(|k| { + let c = at(k); + let a = alpha.get(k).copied().unwrap_or(0.0); + [c[0] * a, c[1] * a, c[2] * a, a] + }) + .collect(); + let Some(place) = Place::new(space, w, h) else { return }; + const SAMPLES: usize = 5; + let mut out = px.to_vec(); + for (k, p) in out.iter_mut().enumerate() { + if p[3] == 0 { + continue; + } + let (x, y) = (k % w, k / w); + let q = place.at(x, y); + let dir = dry_brush_dir(&tone, w, h, x, y); + let mut acc = [0.0f32; 4]; + for i in 0..SAMPLES { + let t = (i as f64 / (SAMPLES - 1) as f64 - 0.5) * len; + let s = sample_pm(&src, w, h, &place, q + dir * t); + for (a, v) in acc.iter_mut().zip(s) { + *a += v; + } + } + for a in &mut acc { + *a /= SAMPLES as f32; + } + let a = acc[3].clamp(0.0, 1.0); + let c = if a > 1e-6 { [0, 1, 2].map(|i| (acc[i] / a).clamp(0.0, 1.0)) } else { straight(*p) }; + let edge = edges[k].min(1.0); + let dark = (edge_gain * edge).clamp(0.0, 0.75); + let grain = bristle * (2.0 * value_noise(SALT_DRY, q.x / (5.0 * space.px), q.y / (5.0 * space.px)) - 1.0) as f32; + let c = c.map(|v| (v * (1.0 - dark) + grain).clamp(0.0, 1.0)); + *p = premultiply(c, f32::from(p[3]) / 255.0); + } + px.copy_from_slice(&out); +} + +const SALT_KNIFE: u64 = 208; + +/// How far Palette Knife reaches with strokes `stroke_size` long and Softness `softness` (0..10). +pub(super) fn palette_knife_reach(stroke_size: f64, softness: f64) -> f64 { + stroke_reach(stroke_size) + 3.0 * 0.35 * softness.clamp(0.0, 10.0) + 1.0 +} + +/// Artistic › Palette Knife: the object repainted with short, angled knife strokes that smear its +/// colours; `stroke_size` (1..50) sets their length, `stroke_detail` (1..3) keeps more of the +/// original where it's higher, and `softness` (0..10) softens the strokes. Coverage is kept. +pub(super) fn palette_knife(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, stroke_size: f64, stroke_detail: f64, softness: f64) { + let Some(place) = Place::new(space, w, h) else { return }; + if !(stroke_size.is_finite() && stroke_detail.is_finite() && softness.is_finite()) { + return; + } + let len = stroke_size.clamp(1.0, 50.0); + let keep = ((stroke_detail.clamp(1.0, 3.0) - 1.0) / 2.0) as f32; + let smear = Smear::new(px, w, h, &place, len); + let row = (0.25 * smear.len).max(1.0); + let cell = len * 0.35; + let src = px.to_vec(); + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let q = place.at(x, y); + let angle = TAU * value_noise(SALT_KNIFE, q.x / cell, q.y / cell); + let dir = Vec2::new(angle.cos(), angle.sin()); + let pm = smear.stroke(SALT_KNIFE + 1, q, dir, row); + let orig = unit(src.get(y * w + x).copied().unwrap_or([0; 4])); + let coverage = orig[3]; + let (c, _) = unpremultiply(mix(orig, pm, 1.0 - keep)); + *p = premultiply(c, coverage); + }); + let sigma = 0.35 * softness.clamp(0.0, 10.0) / place.px; + if sigma > 0.0 { + let (mut colour, alpha) = planes(px); + let cover = alpha.clone(); + soften(&mut colour, &alpha, w, h, sigma); + for (k, p) in px.iter_mut().enumerate() { + if cover[k] == 0.0 { + continue; + } + let c = [colour[0][k], colour[1][k], colour[2][k]]; + *p = premultiply(c, cover[k]); + } + } +} diff --git a/crates/effects/src/pixel/brushstrokes.rs b/crates/effects/src/pixel/brushstrokes.rs index d496f294ed..100d4e2497 100644 --- a/crates/effects/src/pixel/brushstrokes.rs +++ b/crates/effects/src/pixel/brushstrokes.rs @@ -231,7 +231,7 @@ fn frame(q: Point, dir: Vec2) -> (f64, f64) { /// How far along `dir` the stroke through `q` is shifted: strokes `len` long lie in rows `width` /// apart across `dir`, each row starting at random, each stroke shifted by up to [`JITTER`] × /// `len`. -fn stroke_shift(salt: u64, q: Point, dir: Vec2, len: f64, width: f64) -> f64 { +pub(super) fn stroke_shift(salt: u64, q: Point, dir: Vec2, len: f64, width: f64) -> f64 { if !(len > 0.0 && width > 0.0) { return 0.0; } diff --git a/crates/effects/src/pixel/loaded.rs b/crates/effects/src/pixel/loaded.rs index f08d2ef1cf..bb885b239c 100644 --- a/crates/effects/src/pixel/loaded.rs +++ b/crates/effects/src/pixel/loaded.rs @@ -7,6 +7,7 @@ //! directions. use std::io::Cursor; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use vectorcraft_geom::Point; @@ -26,6 +27,15 @@ const RELIEF: f64 = 1.0; /// How many decoded textures [`texture`] keeps. const KEEP: usize = 4; +/// Most bytes of gray levels the loaded textures alive at once may hold, wherever they are kept +/// (the effects of every drawing hold theirs): a texture that would pass it isn't decoded. Each +/// one is decoded within [`vectorcraft_doc::MAX_RASTER_ALLOC`], but a document's many Glass +/// effects each kept their own. +const MAX_LIVE: usize = 512 << 20; + +/// Bytes of gray levels the [`LoadedTexture`]s alive hold ([`MAX_LIVE`]). +static LIVE: AtomicUsize = AtomicUsize::new(0); + /// A loaded texture: `width` × `height` gray levels, row by row from the top. #[derive(Debug, PartialEq, Eq)] pub struct LoadedTexture { @@ -34,7 +44,19 @@ pub struct LoadedTexture { gray: Vec, } +impl Drop for LoadedTexture { + fn drop(&mut self) { + LIVE.fetch_sub(self.gray.len(), Ordering::Relaxed); + } +} + impl LoadedTexture { + /// A texture of `gray`, counted in [`LIVE`]. + fn new(width: u32, height: u32, gray: Vec) -> Self { + LIVE.fetch_add(gray.len(), Ordering::Relaxed); + Self { width, height, gray } + } + /// The texture of `width` × `height` straight (not premultiplied) RGBA pixels: each pixel's /// luma over middle gray, as much as its alpha covers it (a transparent pixel is middle gray). /// `None` when the image is empty or `rgba` doesn't hold exactly that many pixels. @@ -52,7 +74,7 @@ impl LoadedTexture { ((a * l + (1.0 - a) * 0.5) * 255.0).round().clamp(0.0, 255.0) as u8 }) .collect(); - Some(Self { width, height, gray }) + Some(Self::new(width, height, gray)) } /// The size in pixels. @@ -71,14 +93,23 @@ impl LoadedTexture { /// The texture of a PNG's gray levels, decoded within [`vectorcraft_doc::MAX_RASTER_ALLOC`]; /// `None` when `png` isn't a PNG or holds no pixels. + /// `None` too when its gray levels would take the live textures past [`MAX_LIVE`]. fn from_png(png: &[u8]) -> Option { - let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png); - let mut limits = image::Limits::default(); - limits.max_alloc = Some(vectorcraft_doc::MAX_RASTER_ALLOC); - reader.limits(limits); - let img = reader.decode().ok()?.to_luma8(); + let reader = || { + let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png); + let mut limits = image::Limits::default(); + limits.max_alloc = Some(vectorcraft_doc::MAX_RASTER_ALLOC); + reader.limits(limits); + reader + }; + let (w, h) = reader().into_dimensions().ok()?; + let gray = (w as usize).checked_mul(h as usize)?; + if LIVE.load(Ordering::Relaxed).saturating_add(gray) > MAX_LIVE { + return None; + } + let img = reader().decode().ok()?.to_luma8(); let (width, height) = img.dimensions(); - (width > 0 && height > 0).then(|| Self { width, height, gray: img.into_raw() }) + (width > 0 && height > 0).then(|| Self::new(width, height, img.into_raw())) } /// The surface's height (points) at `p` (points at 100 %, from the object's center): the gray @@ -99,24 +130,26 @@ impl LoadedTexture { } } -/// The textures [`texture`] decoded last, with their stored form, the newest last. -static DECODED: Mutex)>> = Mutex::new(Vec::new()); +/// The textures [`texture`] decoded last, with their PNG, the newest last. +static DECODED: Mutex, Arc)>> = Mutex::new(Vec::new()); /// The texture a [`TEXTURE_IMAGE`] value holds; `None` when it isn't base64 of a PNG. The last -/// [`KEEP`] textures decoded are kept for the next call. +/// [`KEEP`] textures decoded are kept for the next call, found by their PNG: values that differ +/// only in how the base64 is spaced share one. pub fn texture(stored: &str) -> Option> { + let png = base64_decode(stored)?; let mut decoded = DECODED.lock().unwrap_or_else(PoisonError::into_inner); - if let Some(i) = decoded.iter().position(|(s, _)| s == stored) { + if let Some(i) = decoded.iter().position(|(p, _)| *p == png) { let entry = decoded.remove(i); let t = entry.1.clone(); decoded.push(entry); return Some(t); } - let t = Arc::new(LoadedTexture::from_png(&base64_decode(stored)?)?); + let t = Arc::new(LoadedTexture::from_png(&png)?); if decoded.len() >= KEEP { decoded.remove(0); } - decoded.push((stored.to_string(), t.clone())); + decoded.push((png, t.clone())); Some(t) } diff --git a/crates/effects/src/pixel/sketch.rs b/crates/effects/src/pixel/sketch.rs index 9f04b12770..1085e2120e 100644 --- a/crates/effects/src/pixel/sketch.rs +++ b/crates/effects/src/pixel/sketch.rs @@ -1,20 +1,28 @@ -//! Effect › Sketch (Chalk & Charcoal, Chrome, Halftone Pattern, Note Paper, Plaster and Reticulation; Graphic Pen lives in +//! Effect › Sketch (Bas Relief, Chalk & Charcoal, Charcoal, Chrome, Conté Crayon, Halftone Pattern, Note Paper, Photocopy, +//! Plaster, Reticulation, Stamp, Torn Edges and Water Paper; Graphic Pen lives in //! [`super::brushstrokes`]). Original filters built from public behaviour documentation: //! (Sketch effects redraw in -//! black and white) and the public Photoshop Elements Artistic filters guide. Visual -//! approximations, not proprietary reproductions. +//! black and white; Water Paper flows colours on damp fibrous paper; Conté Crayon draws dark areas +//! in black and light areas in white) and the public Photoshop Elements Sketch filters guide +//! (: Conté Crayon's +//! foreground and background levels and texture options). Visual approximations, not proprietary +//! reproductions. use std::f64::consts::{FRAC_1_SQRT_2, TAU}; -use vectorcraft_geom::Vec2; +use vectorcraft_geom::{Point, Vec2}; +use super::distort::displace; use super::edges::sobel; use super::pixelate::{Place, cell, rand, value_noise}; -use super::texture::{Light, Tones, luma, premultiply, smooth_noise, straight}; +use super::texture::{Light, Texture, Tones, luma, premultiply, smooth_noise, straight, texturizer}; use super::{PixelSpace, blur_plane, pick}; const SALT_CHALK: u64 = 216; const SALT_CHROME: u64 = 0xC40_4D45; +const SALT_CONTE: u64 = 0xC047E; +const SALT_TORN: u64 = 0x746f726e5f6564; +const SALT_WATER: u64 = 208; const EDGE_SOFT: f64 = 0.8; const TONE_SOFT: f64 = 1.0; /// Light from the top left (document axes, y down), as on polished relief surfaces. @@ -357,3 +365,194 @@ pub(super) fn reticulation(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pixel *p = premultiply([(1.0 - ink) as f32; 3], f32::from(p[3]) / 255.0); }); } + +/// How far (document units) Conté Crayon samples the softened tones that choose its crayons. +pub(super) const CONTE_REACH: f64 = 3.0 * TONE_SOFT + 1.0; + +/// How much of a crayon is laid down where `amount` (0..1: how dark, for the dark crayon, or how +/// light, for the light one) meets its `level` (0..1) and `grain` (0..1, the paper's tooth and the +/// stroke): at level 0 only the deepest tones take the crayon, at level 1 it reaches past the +/// middle tone; the grain breaks its edge. +fn crayon(amount: f64, level: f64, grain: f64) -> f64 { + ramp((amount - (0.9 - 0.45 * level) + 0.4 * (grain - 0.5)) / 0.12 + 0.5) +} + +/// Conté Crayon: the dark areas drawn in a dense black crayon and the light areas in a pure white +/// one, on mid-grey paper whose tooth (`texture` scaled by `scaling` (0.5..2), its heights turned +/// over when `invert`) and diagonal strokes break the crayons. `foreground` and `background` +/// (0..20) set how far the black and the white crayon reach into the midtones; the paper then +/// stands in relief as strong as `relief` (0..50), lit from `light`, as Texturizer draws it. +/// Coverage is kept. +#[allow(clippy::too_many_arguments)] // the effect's seven options +pub(super) fn conte_crayon( + px: &mut [[u8; 4]], + w: usize, + h: usize, + space: &PixelSpace, + foreground: f64, + background: f64, + texture: &Texture, + scaling: f64, + relief: f64, + light: Light, + invert: bool, +) { + if !([foreground, background, scaling, relief].iter().all(|v| v.is_finite()) && scaling > 0.0) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let fg = foreground.clamp(0.0, 20.0) / 20.0; + let bg = background.clamp(0.0, 20.0) / 20.0; + let tones = Tones::new(px, w, h, TONE_SOFT / place.px); + // The tooth: how far the surface stands above its neighbours a quarter point (or half a pixel) + // away, so that crayon catches on the peaks and leaves the hollows bare. + let step = (0.25f64).max(0.5 * place.px / scaling); + let flip = if invert { -1.0 } else { 1.0 }; + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let q = place.at(x, y); + let t = Point::new(q.x / scaling, q.y / scaling); + let tooth = if t.x.is_finite() && t.y.is_finite() { + let at = |dx: f64, dy: f64| texture.height(Point::new(t.x + dx, t.y + dy)); + let ridge = (at(0.0, 0.0) - 0.25 * (at(-step, 0.0) + at(step, 0.0) + at(0.0, -step) + at(0.0, step))) / step; + let tooth = 0.5 + 0.5 * (2.0 * flip * ridge).tanh(); + if tooth.is_finite() { tooth } else { 0.5 } + } else { + 0.5 + }; + // Strokes along the two diagonals, about a point across and several long. + let (u, v) = ((q.x + q.y) * FRAC_1_SQRT_2, (q.x - q.y) * FRAC_1_SQRT_2); + let dark_stroke = value_noise(SALT_CONTE, u * 1.2, v * 0.15); + let light_stroke = value_noise(SALT_CONTE + 1, v * 1.2, u * 0.15); + let tone = tones.get(x, y); + let black = crayon(1.0 - tone, fg, 0.55 * tooth + 0.45 * dark_stroke); + let white = crayon(tone, bg, 0.55 * tooth + 0.45 * light_stroke); + let paper = 0.4 + 0.2 * tone; + let grey = ((paper + (1.0 - paper) * white) * (1.0 - black)) as f32; + *p = premultiply([grey; 3], f32::from(p[3]) / 255.0); + }); + if relief > 0.0 { + texturizer(px, w, h, space, texture, scaling, relief, light, invert); + } +} + +/// Torn Edges: the object in high-contrast black and white with ragged edges. `image_balance` +/// (0..50) shifts whether midtones fall to ink or paper; `smoothness` (0..15) softens tones and +/// the fraying; `contrast` (0..20) hardens the split. Coverage is kept. +pub(super) fn torn_edges(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, image_balance: f64, smoothness: f64, contrast: f64) { + if !(image_balance.is_finite() && smoothness.is_finite() && contrast.is_finite()) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + if w == 0 || h == 0 || w.checked_mul(h) != Some(px.len()) { + return; + } + let mut tone: Vec = px.iter().map(|p| luma(straight(*p)) * f32::from(p[3]) / 255.0).collect(); + let cover: Vec = px.iter().map(|p| f32::from(p[3]) / 255.0).collect(); + let sigma = (0.12 * smoothness.clamp(0.0, 15.0)) / place.px.max(1e-9); + if sigma > 0.0 { + blur_plane(&mut tone, w, h, sigma); + } + let mut edges: Vec = sobel(&tone, w, h).into_iter().zip(sobel(&cover, w, h)).map(|(t, c)| t.max(c)).collect(); + let edge_soft = (0.08 * smoothness.clamp(0.0, 15.0)) / place.px.max(1e-9); + if edge_soft > 0.0 { + blur_plane(&mut edges, w, h, edge_soft); + } + let peak = edges.iter().copied().fold(0.0f32, f32::max); + let balance = image_balance.clamp(0.0, 50.0); + // Lower balance favours ink (darker result); higher balance favours paper. + let balance_tone = 0.25 + balance / 50.0 * 0.75; + let steep = 4.0 + contrast.clamp(0.0, 20.0) * 0.45; + let hard = contrast.clamp(0.0, 20.0) >= 18.0; + let fray = 0.25 + 0.05 * smoothness.clamp(0.0, 15.0); + place.each(px, |x, y, p| { + let a = f32::from(p[3]) / 255.0; + if a <= 0.0 { + *p = [0; 4]; + return; + } + let i = y * w + x; + let t = tone.get(i).copied().unwrap_or(0.0); + let e = if peak > 1e-6 { edges.get(i).copied().unwrap_or(0.0) / peak } else { 0.0 }; + let noise = smooth_noise(SALT_TORN, place.at(x, y), 2.5 + 0.3 * smoothness) as f32; + let local = (1.0 - balance_tone) as f32 + e * fray as f32 * noise; + let mut ink = 1.0 / (1.0 + (steep as f32 * (t - local)).exp()); + if hard { + ink = if ink > 0.5 { 1.0 } else { 0.0 }; + } + let paper = 1.0 - ink.clamp(0.0, 1.0); + *p = premultiply([paper, paper, paper], a); + }); +} + +/// How far Water Paper's blotchy displacement can shift content (document units). +pub(super) fn water_paper_shift(fiber_length: f64) -> f64 { + 0.12 * fiber_length.clamp(3.0, 50.0) +} + +/// Water Paper: colours flow on damp fibrous paper. `fiber_length` (3..50) sets the scale of the +/// fibers and daubs; `brightness` and `contrast` (0..100) adjust the washed result. Ranges and +/// defaults are documented in [`crate::effect_catalog`] (unverified; helpx lists the controls only). +pub(super) fn water_paper(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, fiber_length: f64, brightness: f64, contrast: f64) { + if !(fiber_length.is_finite() && brightness.is_finite() && contrast.is_finite()) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let fiber = fiber_length.clamp(3.0, 50.0); + let bright = (brightness / 100.0).clamp(0.0, 1.0); + let cont = (contrast / 100.0).clamp(0.0, 1.0); + let shift = water_paper_shift(fiber); + let wave = fiber * 0.4; + displace(px, w, h, &place, shift, |q| { + let a = 0.65 * smooth_noise(SALT_WATER, q, wave) + 0.35 * smooth_noise(SALT_WATER + 3, q, wave * 1.7); + let b = 0.65 * smooth_noise(SALT_WATER + 1, q, wave * 1.1) + 0.35 * smooth_noise(SALT_WATER + 4, q, wave * 0.85); + Vec2::new(a, b) * shift + }); + let flow = (0.06 * fiber).max(0.35) / place.px.max(1e-9); + let mut planes: [Vec; 3] = std::array::from_fn(|ch| px.iter().map(|p| straight(*p)[ch] * f32::from(p[3]) / 255.0).collect()); + for plane in &mut planes { + blur_plane(plane, w, h, flow); + } + for (i, p) in px.iter_mut().enumerate() { + if p[3] == 0 { + continue; + } + let a = f32::from(p[3]) / 255.0; + if a <= 0.0 { + continue; + } + let rgb = { + let mut rgb = [0.0f32; 3]; + let mut ok = true; + for ch in 0..3 { + let Some(v) = planes[ch].get(i) else { + ok = false; + break; + }; + rgb[ch] = (*v / a).clamp(0.0, 1.0); + } + if !ok { + continue; + } + rgb + }; + *p = premultiply(rgb, a); + } + let lift = (bright - 0.5) * 0.35; + let gain = 0.35 + 0.65 * cont; + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let q = place.at(x, y); + let along = smooth_noise(SALT_WATER + 5, q, fiber * 0.25); + let across = smooth_noise(SALT_WATER + 6, Point::new(q.y, q.x), fiber * 0.22); + let fiber_tex = (0.5 * (along + across) + 0.5).clamp(0.0, 1.0); + let paper = (0.82 + 0.18 * fiber_tex) as f32; + let mut rgb = straight(*p).map(|v| ((v + lift as f32 - 0.5) * gain as f32 + 0.5).clamp(0.0, 1.0)); + rgb = rgb.map(|v| (v * paper).clamp(0.0, 1.0)); + *p = premultiply(rgb, f32::from(p[3]) / 255.0); + }); +} diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index 7d45556c5f..fc3497ae61 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -1222,6 +1222,10 @@ fn texture_params_take_defaults_and_stay_in_range() { ("texture.grain", "grainType", GRAIN_TYPES.as_slice()), ("texture.texturizer", "texture", TEXTURES.as_slice()), ("texture.texturizer", "lightDirection", LIGHT_DIRECTIONS.as_slice()), + ("artistic.roughPastels", "texture", TEXTURES.as_slice()), + ("artistic.roughPastels", "lightDirection", LIGHT_DIRECTIONS.as_slice()), + ("sketch.conteCrayon", "texture", TEXTURES.as_slice()), + ("sketch.conteCrayon", "lightDirection", LIGHT_DIRECTIONS.as_slice()), ] { let doc = crate::effect_info(id).unwrap().params; let parsed: Vec = table.iter().map(|(_, v)| fx(id, json!({ key: v }))).collect(); @@ -1426,6 +1430,29 @@ fn texturizer_lights_each_surface_from_its_side() { assert_eq!(big, run(json!({"texture": "brick", "relief": 20}))); } +#[test] +fn texturizer_draws_a_loaded_texture_as_relief() { + let w = 64; + let mid = grey(150); + let rings = stored(12, 10, |x, y| { + let v = ((x as f64 - 5.5).hypot(y as f64 - 4.5) * 0.9).sin().abs(); + let g = (v * 255.0).round() as u8; + [g, g, g, 255] + }); + let run = |p: serde_json::Value| { + let mut d = flat(w, mid); + fx("texture.texturizer", p).apply(&mut d, w, w, &space(w, w)); + d + }; + let relief = run(json!({"texture": "loaded", "textureImage": rings, "relief": 20})); + assert_ne!(relief, flat(w, mid)); + for (_, builtin) in TEXTURES { + assert_ne!(relief, run(json!({"texture": builtin, "relief": 20})), "{builtin}"); + } + assert_eq!(run(json!({"texture": "loaded", "textureImage": rings, "relief": 0})), flat(w, mid)); + assert_eq!(fx("texture.texturizer", json!({"texture": "LOADED", "textureImage": "not a texture"})), fx("texture.texturizer", json!({}))); +} + /// The Texture filters' patterns lie in document space around the object's centre: the same at /// twice the resolution, and moving with the object. #[test] @@ -2046,6 +2073,20 @@ fn halftone(p: serde_json::Value, src: &[u8], w: usize, h: usize, s: &PixelSpace out } +/// Torn Edges of `p` over `w` × `h` pixels of `src`, laid out by `s`. +fn torn(p: serde_json::Value, src: &[u8], w: usize, h: usize, s: &PixelSpace) -> Vec { + let mut out = src.to_vec(); + fx("sketch.tornEdges", p).apply(&mut out, w, h, s); + out +} + +/// Water Paper of `p` over `w` × `h` pixels of `src`, laid out by `s`. +fn water_paper(p: serde_json::Value, src: &[u8], w: usize, h: usize, s: &PixelSpace) -> Vec { + let mut out = src.to_vec(); + fx("sketch.waterPaper", p).apply(&mut out, w, h, s); + out +} + /// The smallest period of `values` (their length when they don't repeat). fn period(values: &[u8]) -> usize { (1..values.len()).find(|p| values.iter().zip(&values[*p..]).all(|(a, b)| a == b)).unwrap_or(values.len()) @@ -2144,6 +2185,35 @@ fn note_paper_embosses_a_gradient_and_grain_changes_pixels() { assert_ne!(flat, grainy, "graininess adds fibre"); } +#[test] +fn water_paper_params_take_defaults_and_stay_in_range() { + assert_eq!(fx("sketch.waterPaper", json!({})), PixelFx::WaterPaper { fiber_length: 15.0, brightness: 50.0, contrast: 50.0 }); + assert_eq!( + fx("sketch.waterPaper", json!({"fiberLength": 1, "brightness": -5, "contrast": 200})), + PixelFx::WaterPaper { fiber_length: 3.0, brightness: 0.0, contrast: 100.0 } + ); + let f = fx("sketch.waterPaper", json!({"fiberLength": 40})); + assert!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)) > 0.0); + assert!(f.reach().unwrap_or(0.0) > 0.0); + let doc = crate::effect_info("sketch.waterPaper").unwrap().params; + assert!(doc.contains("unverified"), "{doc}"); +} + +#[test] +fn water_paper_softens_and_textures_a_flat_fill_without_losing_coverage() { + let (w, h) = (64, 64); + let src = image(w, h, |_, _| [200, 80, 40, 255]); + let out = water_paper(json!({"fiberLength": 20, "brightness": 50, "contrast": 40}), &src, w, h, &space(w, h)); + assert!(out.as_chunks::<4>().0.iter().filter(|p| p[3] > 200).count() > w * h / 2, "most of the fill stays visible"); + assert_ne!(out, src, "the wash changes pixels"); + let spread = |d: &[u8]| { + let reds: Vec = d.as_chunks::<4>().0.iter().map(|p| p[0]).collect(); + let (min, max) = (reds.iter().min().unwrap(), reds.iter().max().unwrap()); + max - min + }; + assert!(spread(&out) > spread(&src) / 2, "fibers add tonal variation"); +} + /// Line's rows repeat every Size points: Size pixels at 72 ppi, twice as many at 144 ppi. #[test] fn halftone_line_period_is_the_size_at_any_resolution() { @@ -2343,6 +2413,63 @@ fn reticulation_density_changes_the_grain() { assert_ne!(low, high); } +#[test] +fn torn_edges_params_take_defaults_and_stay_in_range() { + assert_eq!(fx("sketch.tornEdges", json!({})), PixelFx::TornEdges { image_balance: 25.0, smoothness: 11.0, contrast: 17.0 }); + assert_eq!( + fx("sketch.tornEdges", json!({"imageBalance": 0, "smoothness": 99, "contrast": -1})), + PixelFx::TornEdges { image_balance: 0.0, smoothness: 15.0, contrast: 0.0 } + ); + assert_eq!( + fx("sketch.tornEdges", json!({"imageBalance": 1e9, "smoothness": -3, "contrast": 1e9})), + PixelFx::TornEdges { image_balance: 50.0, smoothness: 0.0, contrast: 20.0 } + ); + for junk in [json!({"imageBalance": "x"}), json!({"smoothness": null})] { + assert_eq!(fx("sketch.tornEdges", junk), fx("sketch.tornEdges", json!({}))); + } + assert_eq!(fx("sketch.tornEdges", json!({})).reach(), None); +} + +#[test] +fn torn_edges_draws_in_black_and_white_and_keeps_coverage() { + let (w, h) = (64, 48); + let src = ramp(w, h); + let out = torn(json!({"imageBalance": 12, "contrast": 20, "smoothness": 5}), &src, w, h, &space(w, h)); + for (p, q) in out.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0) { + assert_eq!(p[3], q[3], "coverage kept"); + assert!(p[0] == p[1] && p[1] == p[2] && (p[0] == 0 || p[0] == p[3]), "black or white: {p:?}"); + } + assert!(share(&out, |p| p[0] == 0) > 0.05 && share(&out, |p| p[0] == p[3]) > 0.05, "ink and paper"); +} + +#[test] +fn torn_edges_image_balance_shifts_ink_on_a_grey_ramp() { + let (w, h) = (80, 16); + let src = image(w, h, |x, _| grey((x * 255 / (w - 1)) as u8)); + let params = json!({"imageBalance": 25, "contrast": 20, "smoothness": 5}); + let out = torn(params, &src, w, h, &space(w, h)); + let mut dark_ink = 0usize; + let mut bright_ink = 0usize; + for y in 0..h { + for x in 0..w / 4 { + if at(&out, w, x, y)[0] == 0 { + dark_ink += 1; + } + } + for x in 3 * w / 4..w { + if at(&out, w, x, y)[0] == 0 { + bright_ink += 1; + } + } + } + let dark_n = (w / 4) * h; + let bright_n = (w - 3 * w / 4) * h; + assert!(dark_ink as f64 / dark_n as f64 > bright_ink as f64 / bright_n as f64 + 0.2, "dark end of ramp is inkier than bright end"); + let dark = share(&torn(json!({"imageBalance": 0, "contrast": 20, "smoothness": 5}), &src, w, h, &space(w, h)), |p| p[0] == 0); + let light = share(&torn(json!({"imageBalance": 50, "contrast": 20, "smoothness": 5}), &src, w, h, &space(w, h)), |p| p[0] == 0); + assert!(dark > light + 0.15, "low balance leaves more ink: dark={dark} light={light}"); +} + /// The distinct colours of the covered pixels. fn colours(d: &[u8]) -> std::collections::BTreeSet<[u8; 4]> { d.as_chunks::<4>().0.iter().filter(|p| p[3] > 0).copied().collect() @@ -2360,11 +2487,22 @@ fn ramp(w: usize, h: usize) -> Vec { #[test] fn artistic_params_take_defaults_and_stay_in_range() { + assert_eq!(fx("artistic.coloredPencil", json!({})), PixelFx::ColoredPencil { width: 5.0, pressure: 5.0, paper: 25.0 }); + assert_eq!( + fx("artistic.coloredPencil", json!({"pencilWidth": 0, "strokePressure": 200, "paperBrightness": -5})), + PixelFx::ColoredPencil { width: 1.0, pressure: 15.0, paper: 0.0 } + ); + assert_eq!(fx("artistic.coloredPencil", json!({})).reach(), Some(artistic::colored_pencil_reach(5.0))); assert_eq!(fx("artistic.cutout", json!({})), PixelFx::Cutout { levels: 4.0, simplicity: 4.0, fidelity: 2.0 }); assert_eq!( fx("artistic.cutout", json!({"levels": 1e308, "edgeSimplicity": -5, "edgeFidelity": "NaN"})), PixelFx::Cutout { levels: 8.0, simplicity: 0.0, fidelity: 2.0 } ); + assert_eq!(fx("artistic.dryBrush", json!({})), PixelFx::DryBrush { size: 2.0, detail: 10.0, texture: 1.0 }); + assert_eq!( + fx("artistic.dryBrush", json!({"brushSize": 1e308, "brushDetail": 0, "texture": -2})), + PixelFx::DryBrush { size: 10.0, detail: 0.0, texture: 1.0 } + ); assert_eq!(fx("artistic.posterEdges", json!({})), PixelFx::PosterEdges { thickness: 2.0, intensity: 1.0, posterization: 2.0 }); assert_eq!( fx("artistic.posterEdges", json!({"edgeThickness": 99, "edgeIntensity": -1, "posterization": 6.4})), @@ -2377,14 +2515,96 @@ fn artistic_params_take_defaults_and_stay_in_range() { fx("artistic.neonGlow", json!({"glowSize": -1e308, "glowBrightness": 80, "color": "#ff0000"})), PixelFx::NeonGlow { size: -24.0, brightness: 50.0, colour: [1.0, 0.0, 0.0] } ); + let under = PixelFx::Underpainting { + brush_size: 6.0, + texture_coverage: 16.0, + texture: Texture::Canvas, + scaling: 1.0, + relief: 4.0, + light: Light::Top, + invert: false, + }; + assert_eq!(fx("artistic.underpainting", json!({})), under); + assert_eq!( + fx( + "artistic.underpainting", + json!({"brushSize": 99, "textureCoverage": -1, "texture": "brick", "scaling": 10, "relief": 60, "lightDirection": "bottomRight", "invert": true}) + ), + PixelFx::Underpainting { + brush_size: 40.0, + texture_coverage: 0.0, + texture: Texture::Brick, + scaling: 0.5, + relief: 50.0, + light: Light::BottomRight, + invert: true, + } + ); + assert_eq!( + fx("artistic.roughPastels", json!({})), + PixelFx::RoughPastels { length: 6.0, detail: 10.0, texture: Texture::Canvas, scaling: 1.0, relief: 4.0, light: Light::Top, invert: false } + ); + assert_eq!( + fx( + "artistic.roughPastels", + json!({"strokeLength": 0, "strokeDetail": 99, "texture": -3, "scaling": 10, "relief": 60, "lightDirection": "up", "invert": true}) + ), + PixelFx::RoughPastels { length: 0.0, detail: 20.0, texture: Texture::Canvas, scaling: 0.5, relief: 50.0, light: Light::Top, invert: true } + ); + assert_eq!(fx("artistic.fresco", json!({})), PixelFx::Fresco { brush_size: 2.0, brush_detail: 10.0, texture: 1.0 }); + assert_eq!( + fx("artistic.fresco", json!({"brushSize": 0, "brushDetail": 99, "texture": 4.7})), + PixelFx::Fresco { brush_size: 1.0, brush_detail: 10.0, texture: 3.0 } + ); assert_eq!(fx("artistic.plasticWrap", json!({})), PixelFx::PlasticWrap { highlight: 20.0, detail: 12.0, smoothness: 15.0 }); assert_eq!( fx("artistic.plasticWrap", json!({"highlightStrength": -1, "detail": 99, "smoothness": 0})), PixelFx::PlasticWrap { highlight: 0.0, detail: 15.0, smoothness: 1.0 } ); - for id in ["artistic.cutout", "artistic.neonGlow", "artistic.plasticWrap", "artistic.posterEdges"] { + for id in [ + "artistic.coloredPencil", + "artistic.cutout", + "artistic.dryBrush", + "artistic.fresco", + "artistic.neonGlow", + "artistic.plasticWrap", + "artistic.posterEdges", + "artistic.underpainting", + ] { assert_eq!(fx(id, json!({})).outset(Rect::new(0.0, 0.0, 40.0, 30.0)), 0.0, "{id} keeps the object's shape"); } + assert_eq!(fx("artistic.paintDaubs", json!({})), PixelFx::PaintDaubs { size: 10.0, sharpness: 25.0, kind: PaintDaubBrush::Simple }); + assert_eq!( + fx("artistic.paintDaubs", json!({"brushSize": 0, "sharpness": 99, "brushType": "wideBlurry"})), + PixelFx::PaintDaubs { size: 1.0, sharpness: 40.0, kind: PaintDaubBrush::WideBlurry } + ); + let doc = crate::effect_info("artistic.paintDaubs").unwrap().params; + assert!(PAINT_DAUB_BRUSH_TYPES.iter().all(|(_, v)| doc.contains(&format!("\"{v}\""))), "{doc}"); + assert!(fx("artistic.paintDaubs", json!({})).outset(Rect::new(0.0, 0.0, 40.0, 30.0)) > 0.0); + for (id, key, table) in + [("artistic.underpainting", "texture", TEXTURES.as_slice()), ("artistic.underpainting", "lightDirection", LIGHT_DIRECTIONS.as_slice())] + { + let doc = crate::effect_info(id).unwrap().params; + let parsed: Vec = table.iter().map(|(_, v)| fx(id, json!({ key: v }))).collect(); + for (i, (_, v)) in table.iter().enumerate() { + assert!(doc.contains(&format!("\"{v}\"")), "{id} {v}"); + assert!(parsed.iter().skip(i + 1).all(|p| *p != parsed[i]), "{id} {v}"); + } + } + assert!(fx("artistic.roughPastels", json!({})).outset(Rect::new(0.0, 0.0, 40.0, 30.0)) > 0.0); +} + +#[test] +fn colored_pencil_strokes_change_pixels_and_keep_coverage() { + let (w, h) = (48, 32); + let src = ramp(w, h); + let mut out = src.clone(); + fx("artistic.coloredPencil", json!({"strokePressure": 12})).apply(&mut out, w, h, &space(w, h)); + assert_ne!(out, src); + assert!(out.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0).all(|(o, s)| o[3] == s[3])); + let mut mild = src.clone(); + fx("artistic.coloredPencil", json!({"strokePressure": 0, "paperBrightness": 0})).apply(&mut mild, w, h, &space(w, h)); + assert_eq!(mild, src, "zero pressure and paper leaves the art unchanged"); } #[test] @@ -2399,9 +2619,21 @@ fn artistic_filters_leave_invalid_coordinate_spaces_alone() { let colour = [0.3, 0.65, 1.0]; let filters = [ PixelFx::Cutout { levels: 4.0, simplicity: 4.0, fidelity: 2.0 }, + PixelFx::DryBrush { size: 2.0, detail: 10.0, texture: 1.0 }, + PixelFx::Fresco { brush_size: 2.0, brush_detail: 10.0, texture: 1.0 }, PixelFx::NeonGlow { size: 5.0, brightness: 15.0, colour }, PixelFx::PlasticWrap { highlight: 20.0, detail: 12.0, smoothness: 15.0 }, PixelFx::PosterEdges { thickness: 2.0, intensity: 1.0, posterization: 2.0 }, + PixelFx::Underpainting { + brush_size: 6.0, + texture_coverage: 16.0, + texture: Texture::Canvas, + scaling: 1.0, + relief: 4.0, + light: Light::Top, + invert: false, + }, + PixelFx::RoughPastels { length: 6.0, detail: 10.0, texture: Texture::Canvas, scaling: 1.0, relief: 4.0, light: Light::Top, invert: false }, ]; for f in &filters { assert_ne!(run(f, &space(w, h)), src, "{f:?} changes the art in a valid space"); @@ -2423,6 +2655,27 @@ fn artistic_filters_leave_invalid_coordinate_spaces_alone() { PixelFx::PosterEdges { thickness: f64::NAN, intensity: 1.0, posterization: 2.0 }, PixelFx::PosterEdges { thickness: 2.0, intensity: f64::INFINITY, posterization: 2.0 }, PixelFx::PosterEdges { thickness: 2.0, intensity: 1.0, posterization: f64::NEG_INFINITY }, + PixelFx::Underpainting { + brush_size: f64::NAN, + texture_coverage: 16.0, + texture: Texture::Canvas, + scaling: 1.0, + relief: 4.0, + light: Light::Top, + invert: false, + }, + PixelFx::Underpainting { + brush_size: 6.0, + texture_coverage: f64::INFINITY, + texture: Texture::Canvas, + scaling: 1.0, + relief: 4.0, + light: Light::Top, + invert: false, + }, + PixelFx::Fresco { brush_size: f64::NAN, brush_detail: 10.0, texture: 1.0 }, + PixelFx::Fresco { brush_size: 2.0, brush_detail: f64::INFINITY, texture: 1.0 }, + PixelFx::Fresco { brush_size: 2.0, brush_detail: 10.0, texture: f64::NEG_INFINITY }, ] { if run(&f, &space(w, h)) != src { changed.push(format!("{f:?}")); @@ -2431,6 +2684,43 @@ fn artistic_filters_leave_invalid_coordinate_spaces_alone() { assert!(changed.is_empty(), "directly constructed non-finite parameters and invalid spaces are harmless: {changed:?}"); } +#[test] +fn underpainting_softens_more_with_a_larger_brush_and_keeps_coverage() { + let (w, h) = (48, 32); + let src = ramp(w, h); + let diff = |brush: f64| { + let mut out = src.clone(); + fx("artistic.underpainting", json!({"brushSize": brush, "textureCoverage": 0})).apply(&mut out, w, h, &space(w, h)); + out.as_chunks::<4>() + .0 + .iter() + .zip(src.as_chunks::<4>().0) + .filter(|(_, s)| s[3] == 255) + .map(|(o, s)| (0..3).map(|k| u32::from(o[k].abs_diff(s[k]))).sum::()) + .sum::() + }; + assert!(diff(40.0) > diff(2.0) * 2, "large brush {} vs small {}", diff(40.0), diff(2.0)); + let mut out = src.clone(); + fx("artistic.underpainting", json!({})).apply(&mut out, w, h, &space(w, h)); + assert!(out.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0).all(|(o, s)| o[3] == s[3])); +} + +#[test] +fn fresco_keeps_coverage_and_responds_to_texture() { + let (w, h) = (48, 32); + let src = ramp(w, h); + let mut low = src.clone(); + let mut high = src.clone(); + fx("artistic.fresco", json!({"texture": 1})).apply(&mut low, w, h, &space(w, h)); + fx("artistic.fresco", json!({"texture": 3})).apply(&mut high, w, h, &space(w, h)); + assert_ne!(low, src); + assert_ne!(high, src); + assert_ne!(low, high, "deeper texture changes the relief"); + for (a, b) in low.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0) { + assert_eq!(a[3], b[3], "alpha is preserved"); + } +} + #[test] fn plastic_wrap_adds_specular_highlights_and_keeps_coverage() { let (w, h) = (48, 32); @@ -2465,6 +2755,20 @@ fn cutout_paints_a_few_flat_colours_and_keeps_coverage() { } } +#[test] +fn rough_pastels_keeps_coverage_and_longer_strokes_smear_more() { + let (w, h) = (48, 48); + let src = ramp(w, h); + let mut short = src.clone(); + let mut long = src.clone(); + fx("artistic.roughPastels", json!({"strokeLength": 8, "strokeDetail": 18, "relief": 12})).apply(&mut short, w, h, &space(w, h)); + fx("artistic.roughPastels", json!({"strokeLength": 32, "strokeDetail": 18, "relief": 12})).apply(&mut long, w, h, &space(w, h)); + assert!(short.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0).all(|(o, s)| o[3] == s[3])); + let changed = |a: &Vec, b: &Vec| a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0).filter(|(o, s)| o != s).count(); + assert!(changed(&short, &src) > w * h / 8, "short strokes repaint many pixels"); + assert!(changed(&long, &short) > w * h / 16, "longer strokes smear differently"); +} + #[test] fn cutout_simplicity_smooths_the_pieces_edges() { // A noisy grey: simpler edges join the speckles into fewer changes between neighbours. @@ -2478,6 +2782,28 @@ fn cutout_simplicity_smooths_the_pieces_edges() { assert!(changes(10.0) * 4 < changes(0.0), "{} vs {}", changes(10.0), changes(0.0)); } +#[test] +fn paint_daubs_coarsens_a_ramp_and_keeps_coverage() { + let (w, h) = (64, 32); + let src = ramp(w, h); + let mut out = src.clone(); + fx("artistic.paintDaubs", json!({"brushSize": 28, "sharpness": 35})).apply(&mut out, w, h, &space(w, h)); + assert_ne!(out, src, "dabbed art differs from the ramp"); + assert!(out.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0).all(|(o, s)| o[3] == s[3])); +} + +#[test] +fn paint_daubs_larger_brushes_flatten_more() { + let (w, h) = (80, 40); + let src = ramp(w, h); + let dab_colours = |size: f64| { + let mut out = src.clone(); + fx("artistic.paintDaubs", json!({"brushSize": size, "sharpness": 20})).apply(&mut out, w, h, &space(w, h)); + colours(&out).len() + }; + assert!(dab_colours(35.0) < dab_colours(8.0), "{} vs {}", dab_colours(35.0), dab_colours(8.0)); +} + #[test] fn poster_edges_draw_black_lines_on_edges_and_posterize_the_rest() { let (w, h) = (40, 20); @@ -2512,6 +2838,24 @@ fn poster_edges_thickness_widens_the_lines() { assert!(dark(10.0) > dark(0.0), "{} vs {}", dark(10.0), dark(0.0)); } +#[test] +fn dry_brush_repaints_and_preserves_coverage() { + let (w, h) = (48, 24); + let src = ramp(w, h); + let mut out = src.clone(); + fx("artistic.dryBrush", json!({})).apply(&mut out, w, h, &space(w, h)); + assert_ne!(out, src); + for (a, b) in src.as_chunks::<4>().0.iter().zip(out.as_chunks::<4>().0) { + assert_eq!(a[3], b[3], "coverage preserved"); + } + let mut clear = vec![0u8; w * h * 4]; + let before = clear.clone(); + fx("artistic.dryBrush", json!({})).apply(&mut clear, w, h, &space(w, h)); + assert_eq!(clear, before); + let reach = fx("artistic.dryBrush", json!({"brushSize": 10, "brushDetail": 1})).reach(); + assert!(reach.is_some_and(|r| r > 0.0)); +} + #[test] fn neon_glow_lights_the_bright_or_the_dark_areas_in_its_colour() { let (w, h) = (40, 20); @@ -2549,6 +2893,8 @@ fn artistic_filters_look_the_same_at_any_resolution() { ("artistic.cutout", json!({"edgeSimplicity": 6})), ("artistic.neonGlow", json!({"glowSize": 12, "glowBrightness": 30})), ("artistic.posterEdges", json!({"edgeThickness": 6, "edgeIntensity": 6})), + ("artistic.underpainting", json!({"brushSize": 12, "textureCoverage": 20, "relief": 10})), + ("artistic.roughPastels", json!({"strokeLength": 12, "strokeDetail": 15, "texture": "burlap", "relief": 10})), ] { let (mut a, mut b) = (coarse.clone(), fine.clone()); fx(id, p.clone()).apply(&mut a, w, h, &space(w, h)); @@ -2564,3 +2910,30 @@ fn artistic_filters_look_the_same_at_any_resolution() { assert!(diff < 12.0, "{id}: mean difference {diff}"); } } + +#[test] +fn palette_knife_params_take_defaults_and_stay_in_range() { + assert_eq!(fx("artistic.paletteKnife", json!({})), PixelFx::PaletteKnife { stroke_size: 10.0, stroke_detail: 2.0, softness: 3.0 }); + assert_eq!( + fx("artistic.paletteKnife", json!({"strokeSize": 0, "strokeDetail": 0, "softness": 99})), + PixelFx::PaletteKnife { stroke_size: 1.0, stroke_detail: 1.0, softness: 10.0 } + ); + assert!(fx("artistic.paletteKnife", json!({})).outset(Rect::new(0.0, 0.0, 40.0, 30.0)) > 0.0); +} + +#[test] +fn palette_knife_smears_a_ramp_and_keeps_coverage() { + let (w, h) = (48, 24); + let src = ramp(w, h); + let mut out = src.clone(); + fx("artistic.paletteKnife", json!({"strokeSize": 20, "strokeDetail": 1, "softness": 0})).apply(&mut out, w, h, &space(w, h)); + assert_ne!(out, src); + assert!(out.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0).all(|(o, s)| o[3] == s[3])); + let mut gentle = src.clone(); + fx("artistic.paletteKnife", json!({"strokeSize": 20, "strokeDetail": 3, "softness": 0})).apply(&mut gentle, w, h, &space(w, h)); + let mean = |buf: &Vec| { + let n = buf.len() / 4; + buf.as_chunks::<4>().0.iter().map(|p| f64::from(p[0])).sum::() / n as f64 + }; + assert!((mean(&gentle) - mean(&src)).abs() < (mean(&out) - mean(&src)).abs()); +} diff --git a/crates/effects/src/pixel/tests_sketch.rs b/crates/effects/src/pixel/tests_sketch.rs index d97cc89f8f..2f463f52f6 100644 --- a/crates/effects/src/pixel/tests_sketch.rs +++ b/crates/effects/src/pixel/tests_sketch.rs @@ -1,4 +1,4 @@ -//! Sketch › Bas Relief, Charcoal, Photocopy and Stamp. +//! Sketch › Bas Relief, Charcoal, Conté Crayon, Photocopy and Stamp. use serde_json::json; use vectorcraft_doc::Effect; @@ -173,9 +173,123 @@ fn bas_relief_lights_the_surfaces_facing_the_light() { #[test] fn sketch_filters_reach_beyond_nothing_they_do_not_paint() { - for id in ["sketch.basRelief", "sketch.charcoal", "sketch.photocopy", "sketch.stamp"] { + for id in ["sketch.basRelief", "sketch.charcoal", "sketch.conteCrayon", "sketch.photocopy", "sketch.stamp"] { let f = fx(id, json!({})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 50.0, 50.0)), 0.0, "{id} keeps the object's coverage"); assert!(f.reach().is_some_and(|r| r.is_finite() && r > 0.0), "{id} reach"); } } + +/// The mean of channel 0 over columns `x0..x1` of every row. +fn mean(d: &[u8], w: usize, h: usize, x0: usize, x1: usize) -> f64 { + let sum: u32 = (0..h).flat_map(|y| (x0..x1).map(move |x| (x, y))).map(|(x, y)| u32::from(at(d, w, x, y))).sum(); + f64::from(sum) / ((x1 - x0) * h) as f64 +} + +/// How many pixels of channel 0 are lighter than 192. +fn white(d: &[u8]) -> usize { + d.as_chunks::<4>().0.iter().filter(|p| p[0] > 192).count() +} + +#[test] +fn conte_crayon_params_take_defaults_and_stay_in_range() { + let defaults = PixelFx::ConteCrayon { + foreground: 12.0, + background: 10.0, + texture: Texture::Canvas, + scaling: 1.0, + relief: 4.0, + light: Light::Top, + invert: false, + }; + assert_eq!(fx("sketch.conteCrayon", json!({})), defaults); + assert_eq!( + fx( + "sketch.conteCrayon", + json!({"foregroundLevel": -5, "backgroundLevel": 1e308, "texture": "Brick", "scaling": 10, "relief": 99, "lightDirection": "bottomRight", "invert": true}) + ), + PixelFx::ConteCrayon { + foreground: 0.0, + background: 20.0, + texture: Texture::Brick, + scaling: 0.5, + relief: 50.0, + light: Light::BottomRight, + invert: true + } + ); + for junk in [ + json!({"foregroundLevel": "NaN", "scaling": "1e999"}), + json!({"backgroundLevel": null, "texture": 3, "relief": [1], "lightDirection": "up", "invert": "yes"}), + ] { + assert_eq!(fx("sketch.conteCrayon", junk.clone()), defaults, "{junk}"); + } + let doc = crate::effect_info("sketch.conteCrayon").unwrap().params; + assert!(doc.contains("unverified") && doc.contains("foregroundLevel") && doc.contains("backgroundLevel"), "{doc}"); +} + +/// A grey ramp: its shadows in black crayon, its highlights in white crayon, the midtones on grey +/// paper between them; grey only, coverage kept, the same on every run. +#[test] +fn conte_crayon_draws_the_shadows_black_and_the_highlights_white() { + let (w, h) = (96, 32); + let src = image(w, h, |x, _| grey((x * 255 / (w - 1)) as u8)); + let out = run("sketch.conteCrayon", json!({"relief": 0}), &src, w, h); + for p in out.as_chunks::<4>().0 { + assert!(p[0] == p[1] && p[1] == p[2] && p[3] == 255, "{p:?}"); + } + let (shadows, mids, lights) = (mean(&out, w, h, 0, 12), mean(&out, w, h, w / 2 - 6, w / 2 + 6), mean(&out, w, h, w - 12, w)); + assert!(shadows < 40.0, "shadows {shadows}"); + assert!(lights > 215.0, "highlights {lights}"); + assert!(shadows + 30.0 < mids && mids + 30.0 < lights, "{shadows} {mids} {lights}"); + assert_eq!(out, run("sketch.conteCrayon", json!({"relief": 0}), &src, w, h), "deterministic"); + // The relief shades the paper but keeps it grey. + let lit = run("sketch.conteCrayon", json!({}), &src, w, h); + assert_ne!(lit, out); + assert!(lit.as_chunks::<4>().0.iter().all(|p| p[0] == p[1] && p[1] == p[2])); +} + +/// Foreground Level spreads the black crayon into the midtones, Background Level the white one. +#[test] +fn conte_crayon_levels_spread_each_crayon_into_the_midtones() { + let (w, h) = (64, 64); + let mid = image(w, h, |_, _| grey(128)); + let with = |p: serde_json::Value| run("sketch.conteCrayon", p, &mid, w, h); + let (few, many) = (with(json!({"foregroundLevel": 0, "relief": 0})), with(json!({"foregroundLevel": 20, "relief": 0}))); + assert!(black(&many) > black(&few) + w * h / 4, "{} vs {}", black(&many), black(&few)); + let (few, many) = ( + with(json!({"foregroundLevel": 0, "backgroundLevel": 0, "relief": 0})), + with(json!({"foregroundLevel": 0, "backgroundLevel": 20, "relief": 0})), + ); + assert!(white(&many) > white(&few) + w * h / 4, "{} vs {}", white(&many), white(&few)); +} + +/// The paper's texture, scale and inversion break the crayon differently; the relief is lit from +/// the chosen side. +#[test] +fn conte_crayon_texture_options_change_the_paper() { + let (w, h) = (64, 64); + let mid = image(w, h, |x, y| grey((64 + x + y) as u8)); + let with = |p: serde_json::Value| run("sketch.conteCrayon", p, &mid, w, h); + let canvas = with(json!({"relief": 0})); + for other in [ + json!({"relief": 0, "texture": "brick"}), + json!({"relief": 0, "texture": "sandstone"}), + json!({"relief": 0, "scaling": 200}), + json!({"relief": 0, "invert": true}), + ] { + assert_ne!(with(other.clone()), canvas, "{other}"); + } + let top = with(json!({"texture": "brick", "relief": 20, "lightDirection": "top"})); + let bottom = with(json!({"texture": "brick", "relief": 20, "lightDirection": "bottom"})); + assert_ne!(top, bottom); + assert_ne!(top, with(json!({"texture": "brick", "relief": 0, "lightDirection": "top"}))); + survives( + "sketch.conteCrayon", + &[ + json!({}), + json!({"foregroundLevel": "NaN", "backgroundLevel": 1e308, "scaling": -1e308, "relief": 1e308, "texture": "burlap", "invert": true}), + json!({"foregroundLevel": -1e308, "backgroundLevel": [1], "texture": {}, "lightDirection": 3, "relief": "NaN"}), + ], + ); +} diff --git a/crates/effects/src/pixel/texture.rs b/crates/effects/src/pixel/texture.rs index 18c95681d8..a408454530 100644 --- a/crates/effects/src/pixel/texture.rs +++ b/crates/effects/src/pixel/texture.rs @@ -7,9 +7,11 @@ //! whose slopes, taken in document units, are lit from one side. use std::f64::consts::{FRAC_1_SQRT_2, PI}; +use std::sync::Arc; use vectorcraft_geom::{Point, Vec2}; +use super::loaded::{LOADED, LoadedTexture, texture}; use super::pixelate::{AROUND, Around, Place, Soft, cell, gap, point_in, rand, value_noise}; use super::{PixelSpace, blur_plane, pick}; @@ -65,13 +67,19 @@ impl Grain { /// Texturizer's textures, in its Texture menu's order: (label, parameter value). pub const TEXTURES: [(&str, &str); 4] = [("Brick", "brick"), ("Burlap", "burlap"), ("Canvas", "canvas"), ("Sandstone", "sandstone")]; -/// A Texturizer surface ([`TEXTURES`]), made in code. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// Texturizer's Texture menu once a texture is loaded: [`TEXTURES`], then the loaded one. +pub const TEXTURES_LOADED: [(&str, &str); 5] = + [("Brick", "brick"), ("Burlap", "burlap"), ("Canvas", "canvas"), ("Sandstone", "sandstone"), ("Loaded Texture", LOADED)]; + +/// A Texturizer surface ([`TEXTURES`]), made in code or loaded from an image. +#[derive(Clone, Debug, PartialEq, Eq)] pub enum Texture { Brick, Burlap, Canvas, Sandstone, + /// An image the user loaded ([`LoadedTexture`]). + Loaded(Arc), } impl Texture { @@ -82,13 +90,23 @@ impl Texture { pick(&TEXTURES, &Self::ALL, value, Texture::Canvas) } + /// The texture of `value` with `stored` the effect's `textureImage`: the loaded texture for + /// [`LOADED`] (any case) when `stored` holds one, else as [`Texture::parse`]. + pub fn parse_with(value: &str, stored: Option<&str>) -> Self { + match stored.filter(|_| value.eq_ignore_ascii_case(LOADED)).and_then(texture) { + Some(t) => Texture::Loaded(t), + None => Self::parse(value), + } + } + /// The surface's height at `p` (points at 100 %), in points: slopes of about 1 at most. - pub(super) fn height(self, p: Point) -> f64 { + pub(super) fn height(&self, p: Point) -> f64 { match self { Texture::Brick => brick(p), Texture::Burlap => weave(p, 7.0, true), Texture::Canvas => weave(p, 4.0, false), Texture::Sandstone => sandstone(p), + Texture::Loaded(t) => t.height(p), } } } @@ -556,7 +574,7 @@ pub(super) fn texturizer( w: usize, h: usize, space: &PixelSpace, - texture: Texture, + texture: &Texture, scaling: f64, relief: f64, light: Light, diff --git a/crates/effects/src/preview.rs b/crates/effects/src/preview.rs new file mode 100644 index 0000000000..a1b8eed982 --- /dev/null +++ b/crates/effects/src/preview.rs @@ -0,0 +1,305 @@ +//! Use Preview Bounds: objects measured as they are drawn, with their geometry effects. +//! +//! [`drawn_art`] gives an object whose geometry effects change what it draws as plain art. A path +//! or compound path is given as its effected geometry, and a fill or stroke with geometry effects +//! of its own paints its own geometry. Type, images, live objects and symbol instances are given as +//! their reshaped art ([`reshape`]), and a symbol instance is also given as its reshaped art when +//! its symbol's art has geometry effects. Groups and layers with geometry or Pathfinder effects of +//! their own, or with a fill or stroke of their own that has geometry effects or paints members +//! with geometry effects, are given as their evaluated art ([`evaluate_container`]). Blends, +//! envelopes and repeats whose objects have geometry effects are given as their evaluated art +//! ([`expanded_live_group`]), with each of those objects given as its own art. A clip group or +//! layer whose clipping path has strokes with geometry effects is given as that path's geometry +//! before its effects, which the renderer clips by, and those strokes as drawn. Fills and +//! strokes that paint nothing (hidden, or painted None) are left out. [`bounds_of`], +//! [`oriented_bounds`] and [`anchor_bounds`] measure the visual bounds of that art, strokes +//! included, where [`Document::bounds_of`], [`Document::oriented_bounds`] and +//! [`Selection::anchor_bounds`] measure the objects themselves. Raster effects (shadows, glows, +//! blurs) are not measured. In one object, the art of at most 4,096 symbol instances is measured +//! with its geometry effects, and the other instances in it are measured without them. + +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; +use std::sync::Arc; + +use vectorcraft_doc::color::Paint; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, OrientedBox, Selection, SymbolBoxes}; +use vectorcraft_geom::{Affine, PathData, Rect, Shape, union_opt}; + +use crate::group::has_own_paint; +use crate::reshape::{geometry_effects, leaf_geometry}; +use crate::{ + GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, needs_outline, + outline_art, paints, reshape, +}; + +/// Most symbol instances in one object whose art [`Drawn`] measures with its geometry effects: +/// past it, the other instances in the object are measured without geometry effects. +const MAX_INSTANCES: usize = 4096; + +/// The bounds of `ids`: with `preview`, their visual bounds as drawn ([`visual_bounds`]), else +/// their geometric bounds ([`Document::bounds_of`]). +pub fn bounds_of(doc: &Document, ids: &[NodeId], preview: bool) -> Option { + if !preview { + return doc.bounds_of(ids, false); + } + let symbols = doc.symbol_boxes(); + let drawn = Drawn::new(&symbols); + ids.iter().filter_map(|id| doc.node(*id)).fold(None, |acc, n| union_opt(acc, drawn.next().visual_bounds(n))) +} + +/// The bounding box of `ids` square to their shared angle ([`Document::bbox_angle`]), measured as +/// [`bounds_of`] measures them: [`Document::oriented_bounds`] with `preview` false. +pub fn oriented_bounds(doc: &Document, ids: &[NodeId], preview: bool) -> Option { + if !preview { + return doc.oriented_bounds(ids, false); + } + let angle = doc.bbox_angle(ids); + if angle == 0.0 { + return bounds_of(doc, ids, true).map(OrientedBox::aligned); + } + let to_local = OrientedBox { angle, rect: Rect::ZERO }.to_doc().inverse(); + let symbols = doc.symbol_boxes(); + let drawn = Drawn::new(&symbols); + let rect = ids.iter().filter_map(|id| doc.node(*id)).fold(None, |acc, n| union_opt(acc, drawn.next().bounds_in(n, to_local)))?; + Some(OrientedBox { angle, rect }) +} + +/// With anchors selected with Direct Selection, the box around those anchors and the objects +/// selected whole, measured by [`bounds_of`]. `None` without any ([`Selection::anchor_bounds`]). +pub fn anchor_bounds(selection: &Selection, doc: &Document, preview: bool) -> Option { + if selection.anchors.is_empty() { + return None; + } + union_opt(bounds_of(doc, &selection.whole(), preview), selection.anchors_box(doc)) +} + +/// The visual bounds of `n` as drawn: those of its [`drawn_art`], else +/// [`Node::visual_bounds_with`]. +pub fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { + Drawn::new(symbols).visual_bounds(n) +} + +/// [`visual_bounds`] of `n` as `a` would place it, without changing it ([`Node::bounds_in`]): +/// the art is drawn where `n` is and then placed by `a`. +pub fn bounds_in(symbols: &SymbolBoxes, n: &Node, a: Affine) -> Option { + Drawn::new(symbols).bounds_in(n, a) +} + +/// `n` as plain art with the geometry effects in it applied, at every depth, symbol instances +/// measured by `symbols`. Raster effects stay on the art. A group, layer or intertwine without a +/// clip is rebuilt with the drawn art of each member that has one. A clip group or layer becomes a +/// group of its clipping path without strokes and the drawn art of the path's strokes, when they +/// have one. `None` when no geometry effect in `n` changes what it draws. +pub fn drawn_art(symbols: &SymbolBoxes, n: &Node) -> Option { + Drawn::new(symbols).drawn_art(n) +} + +/// Whether [`drawn_art`] gives `n` art of its own, or would give one to an object in it. A symbol +/// instance in `n` counts when its symbol's art has a geometry effect. +pub fn draws_geometry(symbols: &SymbolBoxes, n: &Node) -> bool { + Drawn::new(symbols).draws_geometry(n) +} + +/// One measurement: whether the art of each symbol checked so far draws geometry, by symbol name, +/// and how many more instances' art it measures with its geometry effects in the current object ([`MAX_INSTANCES`]). +struct Drawn<'s, 'd> { + symbols: &'s SymbolBoxes<'d>, + draws: RefCell>, + left: Cell, +} + +impl<'s, 'd> Drawn<'s, 'd> { + fn new(symbols: &'s SymbolBoxes<'d>) -> Self { + Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES) } + } + + /// Sets the count of instances left back to [`MAX_INSTANCES`], for the next object. + fn next(&self) -> &Self { + self.left.set(MAX_INSTANCES); + self + } + + /// See [`visual_bounds`]. + fn visual_bounds(&self, n: &Node) -> Option { + match self.drawn_art(n) { + Some(art) => art.visual_bounds_with(self.symbols), + None => n.visual_bounds_with(self.symbols), + } + } + + /// See [`bounds_in`]. + fn bounds_in(&self, n: &Node, a: Affine) -> Option { + if a == Affine::IDENTITY { + return self.visual_bounds(n); + } + match self.drawn_art(n) { + Some(art) => art.bounds_in(self.symbols, a, true), + None => n.bounds_in(self.symbols, a, true), + } + } + + /// See [`drawn_art`]. + fn drawn_art(&self, n: &Node) -> Option { + let Some(mut art) = self.own_art(n) else { return self.clip_art(n).or_else(|| self.with_drawn_members(n)) }; + // The art's members can carry geometry effects of their own: type's fills and strokes, the + // members of an evaluated group, the clipping path of an evaluated clip group and the + // objects in a symbol's art. + if let Some(m) = self.clip_art(&art).or_else(|| self.with_drawn_members(&art)) { + art = m; + } + Some(art) + } + + /// See [`draws_geometry`]. + fn draws_geometry(&self, n: &Node) -> bool { + let mut found = false; + n.walk(&mut |c| { + found = found + || match &c.kind { + NodeKind::SymbolInstance { symbol, .. } => !geometry_effects(c).is_empty() || self.symbol_draws(symbol), + _ => reshapes(c), + }; + }); + found + } + + /// Whether the art of the symbol named `name` has effects and [`Self::draws_geometry`], worked + /// out once for each name. + fn symbol_draws(&self, name: &str) -> bool { + if let Some(d) = self.draws.borrow().get(name) { + return *d; + } + let d = self.symbols.has_effects(name) && self.symbols.measure_art(name, |art| self.draws_geometry(art)).unwrap_or(false); + self.draws.borrow_mut().insert(name.to_string(), d); + d + } + + /// The art the geometry effects of `n` itself give it, or that a symbol instance gets from the + /// geometry effects in its symbol's art. A group or layer with fills or strokes of its own that + /// paint, around members with geometry effects, is evaluated too: its fills and strokes paint + /// the members' geometry before their effects. A blend, envelope or repeat whose objects have + /// geometry effects is evaluated as the renderer evaluates it ([`expanded_live_group`]), and + /// the objects in its evaluated art keep their geometry effects. `None` when it has none, and + /// for a symbol instance past [`MAX_INSTANCES`]. + fn own_art(&self, n: &Node) -> Option { + let inner = || n.children().is_some_and(|ch| ch.iter().any(|c| self.draws_geometry(c))); + let painted = || has_own_paint(n) && inner(); + match &n.kind { + NodeKind::Group { .. } | NodeKind::Layer { .. } if reshapes(n) || painted() => evaluate_container(Some(self.symbols.document()), n), + NodeKind::Path { .. } | NodeKind::Compound { .. } if reshapes(n) => path_art(n), + NodeKind::SymbolInstance { symbol, .. } => { + if geometry_effects(n).is_empty() && !self.symbol_draws(symbol) { + return None; + } + let left = self.left.get().checked_sub(1)?; + self.left.set(left); + let art = self.symbols.measure_art(symbol, Arc::clone)?; + // An instance in perspective is projected by `reshape`. + let doc = Some(self.symbols.document()); + reshape(doc, n, Some(&*art)).or_else(|| outline_art(doc, n, Some(&*art))) + } + _ if reshapes(n) => reshape(Some(self.symbols.document()), n, None), + NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) if inner() => { + Some(expanded_live_group(Some(self.symbols.document()), n)) + } + _ => None, + } + } + + /// `n`, a group, layer or intertwine without a clip, with each member that has a + /// [`Self::drawn_art`] replaced by it. `None` for any other object and when no member has one. + fn with_drawn_members(&self, n: &Node) -> Option { + if n.clips() || !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Intertwine { .. }) { + return None; + } + let drawn: Vec<(usize, Node)> = n.children()?.iter().enumerate().filter_map(|(i, c)| Some((i, self.drawn_art(c)?))).collect(); + if drawn.is_empty() { + return None; + } + let mut m = n.clone(); + let children = m.children_mut()?; + for (i, c) in drawn { + if let Some(slot) = children.get_mut(i) { + *slot = Arc::new(c); + } + } + Some(m) + } + + /// Clip group or layer `n` as its clipping path's strokes draw it: a group of the clipping path + /// without its strokes, measured as the region it clips to, and its strokes ([`Node::clip_paint`]) + /// as their [`Self::drawn_art`]. The renderer clips by the clipping path's geometry before its + /// geometry effects ([`crate::clip_outline`]) and paints the path's fills inside that region and + /// its strokes over the clipped art, unclipped. `None` for any other object, when the clipping + /// path is hidden and when its strokes have no drawn art. + fn clip_art(&self, n: &Node) -> Option { + if !n.clips() { + return None; + } + let clip = n.children()?.first().filter(|c| c.visible)?; + let strokes = self.drawn_art(&clip.clip_paint().stroke?)?; + Some(Node::group(n.id, vec![Arc::new(unstroked(clip)), Arc::new(strokes)])) + } +} + +/// Clipping path `clip` without its strokes or its characters' strokes. +fn unstroked(clip: &Node) -> Node { + let mut n = clip.clone(); + n.appearance.items.retain(AppearanceItem::is_fill); + if let NodeKind::Text(t) = &mut n.kind { + for r in &mut t.runs { + r.style.stroke = Paint::None; + } + } + n +} + +/// Whether `n` itself has a geometry effect that [`Drawn::own_art`] applies, its own or one of its +/// fill's or stroke's (a group or layer: also a Pathfinder effect; a symbol instance: only its own). +fn reshapes(n: &Node) -> bool { + match &n.kind { + NodeKind::Group { .. } | NodeKind::Layer { .. } => { + has_pathfinder(n) || !geometry_effects(n).is_empty() || n.appearance.items.iter().any(|i| paints(i) && has_geometry(i.effects())) + } + NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => { + has_geometry(&n.appearance.effects) || n.appearance.items.iter().any(|i| paints(i) && has_geometry(i.effects())) + } + _ => needs_outline(n) && (!geometry_effects(n).is_empty() || has_item_geometry(n)), + } +} + +/// Path or compound path `n` as a group of paths: its geometry after its own geometry effects +/// painted by its fills and strokes without geometry effects, and that geometry after the +/// geometry effects of each other fill or stroke that paints, painted by that fill or stroke, as +/// the renderer draws them. The first path is left out when only fills or strokes with geometry +/// effects paint. The paths keep `n`'s id and fill rule and carry no effects. +fn path_art(n: &Node) -> Option { + let (path, rule) = leaf_geometry(n)?; + let ctx = GeomContext::of(n); + let g = apply_geometry_with(&n.appearance.effects, &path, path.to_bezpath().bounding_box(), &ctx); + let piece = |geometry: PathData, items: Vec| { + let mut ap: Appearance = (*n.appearance).clone(); + ap.items = items; + ap.effects.clear(); + for i in &mut ap.items { + i.effects_mut().clear(); + } + let mut p = Node::path(n.id, geometry, ap); + if let NodeKind::Path { rule: r, .. } = &mut p.kind { + *r = rule; + } + Arc::new(p) + }; + let (own, plain): (Vec<&AppearanceItem>, Vec<&AppearanceItem>) = n.appearance.items.iter().partition(|i| paints(i) && has_geometry(i.effects())); + let mut pieces = vec![]; + if own.is_empty() || plain.iter().any(|i| paints(i)) { + pieces.push(piece(g.clone(), plain.into_iter().cloned().collect())); + } + let bounds = g.to_bezpath().bounding_box(); + for item in own { + let geometry = apply_geometry_with(item.effects(), &g, bounds, &ctx.item(item)); + pieces.push(piece(geometry, vec![item.clone()])); + } + Some(Node::group(n.id, pieces)) +} diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index ce844a0765..8cab92a699 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -13,10 +13,11 @@ use std::sync::Arc; -use vectorcraft_doc::{Appearance, AppearanceItem, Effect, Node, NodeKind}; +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 crate::{GeomContext, apply_one, is_geometry, merged_params}; +use crate::{Budget, GeomContext, apply_one, is_geometry, merged_params}; /// Can object-level effects apply to `n` only through [`outline_art`] / an offscreen layer (it is /// neither a path nor a container)? @@ -36,7 +37,7 @@ pub fn needs_outline(n: &Node) -> bool { /// Is `n` a path or compound path with a visible Transform effect that makes copies and a gradient /// in a fill or stroke? Such an object is drawn through its art ([`outline_art`]) so that each copy -/// paints its gradient by itself ([`copy_with_gradients`]), as a group's copies do. +/// paints its gradient by itself ([`copy_leaf`]), as a group's copies do. pub fn has_gradient_copies(n: &Node) -> bool { matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) && (n.appearance.has_unplaced_gradient() || n.appearance.has_placed_gradient()) @@ -45,6 +46,26 @@ pub fn has_gradient_copies(n: &Node) -> bool { .any(|e| e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0) } +/// Is `n` a path or compound path with a visible Transform effect whose Transform Patterns or +/// Scale Strokes & Effects is on (#885)? Such an effect changes the fills and strokes as well as +/// the geometry, so the object is drawn through its art ([`outline_art`]), each copy an object of +/// its own with its strokes scaled and its patterns moved ([`transform_leaf`]). +pub fn has_transform_options(n: &Node) -> bool { + matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) + && geometry_effects(n) + .iter() + // Both options default to off, so the stored params tell without merging the defaults + // (this runs for every object drawn). + .any(|e| e.id == "distort.transform" && crate::distort::TransformOptions::of(&e.params).reach_appearance()) +} + +/// Is `n` a path or compound path that its Transform effects make into art of separate objects +/// ([`has_gradient_copies`], [`has_transform_options`])? It is drawn, baked and expanded through +/// that art ([`reshape`]). +pub fn has_transform_art(n: &Node) -> bool { + has_gradient_copies(n) || has_transform_options(n) +} + /// 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 @@ -98,7 +119,7 @@ pub fn image_paint(n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { return vec![]; } - let Some(art) = reshape(n, None) else { return vec![] }; + let Some(art) = reshape(None, n, None) else { return vec![] }; let mut out = vec![]; art.walk(&mut |c| { let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return }; @@ -120,17 +141,20 @@ pub fn image_paint(n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { /// The glyph outlines of type `t` in text space with its underline and strikethrough bars: one /// path per run, and all of them as one. pub(crate) fn glyph_outlines(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::BezPath) { - let (runs, all, _) = laid_out(t); + let (runs, all, ..) = laid_out(t); (runs, all) } -/// [`glyph_outlines`] and the bounds of `t`'s layout in text space. -fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::BezPath, Rect) { +/// [`glyph_outlines`], the bounds of `t`'s layout in text space, and its colour glyphs, which have +/// no outlines, placed in the document with their runs: bitmap glyphs (emoji) as images holding +/// their pixels, then COLR and SVG glyphs as their art, as the renderer paints them. +fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::BezPath, Rect, Vec<(usize, Node)>) { let db = vectorcraft_text::FontDb::global(); let layout = vectorcraft_text::layout(db, t); let mut runs = vec![kurbo::BezPath::new(); t.runs.len()]; let mut all = kurbo::BezPath::new(); - for g in &layout.glyphs { + // Ruby (furigana) glyphs are painted with their base text's run, as the renderer paints them. + for g in layout.glyphs.iter().chain(&layout.ruby) { if let Some(r) = runs.get_mut(g.run) { r.extend(g.outline.iter()); } @@ -143,34 +167,37 @@ fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::Bez } all.extend(bar.iter()); } - (runs, all, layout.bounds) + let images = layout.glyphs.iter().filter_map(|g| Some((g.run, g.placed_image_node(t.xf)?))); + let colours = images.chain(layout.glyphs.iter().filter_map(|g| Some((g.run, g.placed_colour(t.xf)?)))).collect(); + (runs, all, layout.bounds, colours) } /// Type as glyph outlines in document space: one path per run with the run's fill and stroke, -/// and (when the object has its own fills/strokes) the whole outline with the object's items below -/// the characters under them and the others over them, as the renderer paints them. Each run's -/// path is placed by the type's transform, which also scales its stroke weights and dashes and -/// transforms its pattern tiles; its unplaced gradients are first fixed to the layout's bounds in -/// text space. The object's own unplaced gradients are fixed to the bounding box of those bounds -/// in the document. The group is marked as type's outlines +/// over its colour glyphs (images, art), and (when the object has its own fills/strokes) the whole +/// outline with the object's items below the characters under them and the others over them, as +/// the renderer paints them. Each run's path is placed by the type's transform, which also scales its stroke +/// weights and dashes and transforms its pattern tiles; its unplaced gradients are first fixed to +/// the layout's bounds in text space. The object's own unplaced gradients are fixed to the +/// bounding box of those bounds in the document. The group is marked as type's outlines /// ([`vectorcraft_doc::NodeExtras::type_outlines`]). pub fn outline_text(n: &Node) -> Option { let NodeKind::Text(t) = &n.kind else { return None }; - let (runs, all, bounds) = laid_out(t); + let (runs, all, bounds, colours) = laid_out(t); let path = |bp: &kurbo::BezPath| PathData::from_bezpath(bp).transformed(t.xf); let scaling = vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() }; - let mut children: Vec> = runs - .iter() - .zip(&t.runs) - .filter(|(bp, _)| !bp.elements().is_empty()) - .map(|(bp, run)| { - let mut ap = run.style.appearance(); - ap.pin_gradients(bounds); - let mut piece = Node::path(n.id, PathData::from_bezpath(bp), ap); - piece.transform(t.xf, scaling); - Arc::new(piece) - }) - .collect(); + let mut children: Vec> = vec![]; + for (i, (bp, run)) in runs.iter().zip(&t.runs).enumerate() { + // Colour glyphs paint themselves, under their run's fill, as the renderer paints them. + children.extend(colours.iter().filter(|(r, _)| *r == i).map(|(_, art)| Arc::new(with_id(art, n.id)))); + if bp.elements().is_empty() { + continue; + } + let mut ap = run.style.appearance(); + ap.pin_gradients(bounds); + let mut piece = Node::path(n.id, PathData::from_bezpath(bp), ap); + piece.transform(t.xf, scaling); + children.push(Arc::new(piece)); + } if !n.appearance.items.is_empty() && !all.elements().is_empty() { let (below, above) = n.appearance.split_contents(); let tb = t.xf.transform_rect_bbox(bounds); @@ -191,12 +218,23 @@ pub fn outline_text(n: &Node) -> Option { Some(g) } +/// `art` with `id` for it and all its members, as the other pieces of outlined type have the type's +/// (Expand Appearance gives them ids of their own). +fn with_id(art: &Node, id: NodeId) -> Node { + let mut art = art.clone(); + art.id = id; + for c in art.children_mut().into_iter().flatten() { + *c = Arc::new(with_id(c, id)); + } + art +} + /// `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. `None` for other kinds (images, paths, containers). -pub fn outline_art(n: &Node, symbol_art: Option<&Node>) -> Option { - let hook: &dyn Fn(&Node) -> Option = &outline_text; +/// the instance's transform. `None` for other kinds (images, paths, containers). A Repeat counts +/// the Repeats in the art of `doc`'s symbols that its instances show toward its instance budget. +pub fn outline_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { let mut art = match &n.kind { NodeKind::Text(_) => outline_text(n)?, NodeKind::SymbolInstance { xf, .. } => { @@ -205,7 +243,7 @@ pub fn outline_art(n: &Node, symbol_art: Option<&Node>) -> Option { 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_gradient_copies(n) => { + _ if has_transform_art(n) => { let mut one = n.clone(); one.opacity = 1.0; one.blend = Default::default(); @@ -214,7 +252,7 @@ pub fn outline_art(n: &Node, symbol_art: Option<&Node>) -> Option { one.appearance.effects.clear(); Node::group(n.id, vec![Arc::new(one)]) } - _ if vectorcraft_doc::live::is_live(n) => vectorcraft_doc::live::expand_deep(n, Some(hook)), + _ if vectorcraft_doc::live::is_live(n) => evaluated(doc, n), _ => return None, }; outline_nested_text(&mut art, false); @@ -228,6 +266,14 @@ pub fn outline_art(n: &Node, symbol_art: Option<&Node>) -> Option { Some(art) } +/// `n` with every live object in it evaluated, type inside them outlined ([`outline_text`]). The +/// Repeats among them count the Repeats in the art of `doc`'s symbols that their instances show +/// toward their instance budget ([`vectorcraft_doc::RepeatSpec::expand`]). +pub(crate) fn evaluated(doc: Option<&Document>, n: &Node) -> Node { + let hook: &dyn Fn(&Node) -> Option = &outline_text; + vectorcraft_doc::live::expand_deep_hooks(n, Hooks { outline: Some(hook), symbols: doc, ..Default::default() }) +} + /// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look /// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes /// its plain outlines ([`outline_text`]) with its visibility, which is what @@ -239,7 +285,7 @@ pub(crate) fn outline_nested_text(n: &mut Node, clipping: bool) { let clipping = clipping || (clips && i == 0); let art = match &c.kind { NodeKind::Text(_) if clipping => outline_text(c).map(|o| Node { visible: c.visible, ..o }), - NodeKind::Text(_) => as_art(c, None), + NodeKind::Text(_) => as_art(None, c, None), _ => None, }; if let Some(o) = art { @@ -259,21 +305,22 @@ pub(crate) fn outline_nested_text(n: &mut Node, clipping: bool) { /// and remaining (raster) effects; `None` when `n` has no visible geometry effect, no perspective /// and is not type or an image with a fill or stroke of its own that [`has_item_geometry`] counts, /// or has no art (a symbol instance without `symbol_art`). -pub fn reshape(n: &Node, symbol_art: Option<&Node>) -> Option { - if (geometry_effects(n).is_empty() && n.projection().is_none() && !has_item_geometry(n)) || !(needs_outline(n) || has_gradient_copies(n)) { +pub fn reshape(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { + if (geometry_effects(n).is_empty() && n.projection().is_none() && !has_item_geometry(n)) || !(needs_outline(n) || has_transform_art(n)) { return None; } - as_art(n, symbol_art) + as_art(doc, n, symbol_art) } -/// `n` (see [`needs_outline`], or a path with [`has_gradient_copies`]) as plain art for Expand +/// `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. -pub fn expand_outlined(n: &Node, symbol_art: Option<&Node>) -> Option { - // A path whose Transform effect copies it with a gradient: each copy an object of its own. - if has_gradient_copies(n) { - return as_art(n, symbol_art); +pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { + // 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. + if has_transform_art(n) { + return as_art(doc, n, symbol_art); } let own_paint = match n.kind { NodeKind::Text(_) => !n.appearance.items.is_empty(), @@ -282,11 +329,11 @@ pub fn expand_outlined(n: &Node, symbol_art: Option<&Node>) -> Option { if !needs_outline(n) || (geometry_effects(n).is_empty() && !own_paint) { return None; } - as_art(n, symbol_art) + as_art(doc, n, symbol_art) } /// [`reshape`] without its checks (no geometry effects: just the art). -pub(crate) fn as_art(n: &Node, symbol_art: Option<&Node>) -> Option { +pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { let fx = geometry_effects(n); let mut art = match &n.kind { NodeKind::Image(im) => { @@ -314,7 +361,7 @@ pub(crate) fn as_art(n: &Node, symbol_art: Option<&Node>) -> Option { Node::group(n.id, rows(below).into_iter().chain([Arc::new(image)]).chain(rows(above)).collect()) } } - _ => outline_art(n, symbol_art)?, + _ => outline_art(doc, n, symbol_art)?, }; reshape_leaves(&mut art, &fx); // Type and symbols in perspective: the art projected onto their plane. @@ -372,65 +419,146 @@ 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). +/// 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 +/// whose effect would pass what the others leave of it keeps its shape. pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect]) { + reshape_leaves_within(art, fx, Budget::EFFECTS); +} + +/// [`reshape_leaves`] whose paths keep to `budget` together, or to what they cost. +pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget) { + if fx.is_empty() { + return; + } let seed = art.id.0; // The placed gradients of type's outlines in `art` (`outline_text`) move and scale with the // pieces, from the outlines' bounds before the effects to their bounds after them. let mut outlines = vec![]; type_outline_bounds(art, &mut outlines); + let mut used = art_cost(art); + let max = budget.at_least(used); for e in fx { let Some(bounds) = art.geometric_bounds() else { break }; let params = merged_params(&e.id, &e.params); - let transform = (e.id == "distort.transform").then(|| crate::distort::transform_map(bounds, ¶ms, seed)); + 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)) + }); for_each_leaf(art, &mut |leaf| { let Some((path, rule)) = leaf_geometry(leaf) else { return }; - // A gradient paints each copy by itself, not the one piece the copies make together. - if let Some((m, copies)) = transform - && copies > 0 - && (leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient()) - { - copy_with_gradients(leaf, &path, m, copies); - return; + // What the other paths leave of the budget. + let before = Budget::of(&path); + let room = max.minus(used.minus(before)); + if let Some((m, copies, options, map)) = transform { + // Transform Patterns and Scale Strokes & Effects change each copy's fills and + // strokes; a gradient paints each copy by itself, not the one piece the copies + // make together. + let gradient = copies > 0 && (leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient()); + if options.reach_appearance() { + let made = transform_leaf(leaf, &path, map, copies, options, room); + used = used.minus(before).plus(made); + return; + } + if gradient { + let made = copy_leaf(leaf, &path, m, copies, vectorcraft_doc::Scaling::default(), room); + used = used.minus(before).plus(made); + return; + } } - let out = apply_one(&e.id, ¶ms, &path, bounds, &GeomContext { seed, ..GeomContext::of(leaf) }); + let Some(out) = apply_one(&e.id, ¶ms, &path, bounds, &GeomContext { seed, ..GeomContext::of(leaf) }, room) else { return }; + used = used.minus(before).plus(Budget::of(&out)); set_geometry(leaf, out, rule); }); - if let Some((m, copies)) = transform { + if let Some((m, copies, options, _)) = transform + && options.objects + { transform_placed(art, m, copies); } } - if !fx.is_empty() && outlines.iter().any(Option::is_some) { + if outlines.iter().any(Option::is_some) { rebase_type_outlines(art, &mut outlines.into_iter()); } } +/// Largest factor a Transform effect's Scale Strokes & Effects scales one object's strokes by +/// (its copies stop before one would take more), so stroke weights stay finite where the geometry +/// doesn't grow with them (a horizontal line stretched vertically). +const MAX_STROKE_SCALE: f64 = 1.0e6; + +/// 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. +fn transform_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, options: crate::distort::TransformOptions, budget: Budget) -> Budget { + let scaling = vectorcraft_doc::Scaling { + strokes: options.strokes, + effects: options.strokes.then_some(crate::scale_effect as fn(&mut Effect, f64)), + patterns: options.patterns, + ..Default::default() + }; + if !options.objects { + if options.strokes + && let Some(k) = vectorcraft_doc::Scaling::factor(m).filter(|k| k.is_finite() && *k > 0.0) + { + leaf.appearance.scale_strokes(k); + leaf.appearance.scale_effects(k, crate::scale_effect); + } + if options.patterns { + vectorcraft_doc::pattern::transform_pattern_paints(leaf, m); + } + return Budget::of(path); + } + if copies == 0 { + // A path scaled up is drawn with more lines; past the budget it keeps its shape. + let moved = path.transformed(m); + if !budget.fits(Budget::of(&moved)) { + return Budget::of(path); + } + leaf.transform(m, scaling); + return Budget::of(&moved); + } + copy_leaf(leaf, path, m, copies, scaling, budget) +} + /// Replace `leaf` (a path or compound path with geometry `path`) by a group of it and `copies` -/// more, each mapped once more by `m` than the last, as a Transform effect copies an object. Each -/// copy is an object of its own, so its gradients fit it (a placed gradient moves with it) rather -/// than spanning every copy. The copies stop where [`crate::distort::transform_within`]'s would. -fn copy_with_gradients(leaf: &mut Node, path: &PathData, m: Affine, copies: usize) { - let each = path.anchor_count(); - let mut anchors = each; +/// more, each mapped once more by `m` than the last (with `scaling`), as a Transform effect copies +/// an object. Each copy is an object of its own, so its gradients fit it (a placed gradient 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`, 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 { + let mut made = Budget::of(path); let mut placements: Vec> = vec![Arc::new(leaf.clone())]; let mut xf = Affine::IDENTITY; for _ in 0..copies { - anchors = anchors.saturating_add(each); - if anchors > crate::distort::MAX_COPY_ANCHORS { + xf *= m; + // A copy scaled up is drawn with more lines. + let cost = Budget::of(&path.transformed(xf)); + if !budget.fits(made.plus(cost)) { + break; + } + if scaling.strokes && vectorcraft_doc::Scaling::factor(xf).is_some_and(|k| !(k.is_finite() && k <= MAX_STROKE_SCALE)) { break; } - xf *= m; let mut copy = leaf.clone(); - copy.transform(xf, vectorcraft_doc::Scaling::default()); + copy.transform(xf, scaling); if !copy.geometric_bounds().is_some_and(crate::distort::within_reach) { break; } placements.push(Arc::new(copy)); + made = made.plus(cost); } // The copies become nodes of their own under a group with the object's id and name. let mut g = Node::group(leaf.id, placements); g.name = leaf.name.clone(); *leaf = g; + made } /// The bounds of each group of type's outlines under `n` ([`outline_text`]), `n` included, in @@ -577,9 +705,8 @@ fn placed_count(n: &Node) -> usize { /// `n` with type anywhere inside it outlined and live objects evaluated, so geometry effects on /// it reach every member. -pub(crate) fn outlined_members(n: &Node) -> Node { - let hook: &dyn Fn(&Node) -> Option = &outline_text; - let mut art = vectorcraft_doc::live::expand_deep(n, Some(hook)); +pub(crate) fn outlined_members(doc: Option<&Document>, n: &Node) -> Node { + let mut art = evaluated(doc, n); outline_nested_text(&mut art, false); art } @@ -597,6 +724,18 @@ fn for_each_leaf(n: &mut Node, f: &mut dyn FnMut(&mut Node)) { } } +/// What the paths under `n` that [`for_each_leaf`] visits cost together, as [`leaf_geometry`] +/// gives them. +fn art_cost(n: &Node) -> Budget { + let none = Budget { anchors: 0, lines: 0 }; + match &n.kind { + NodeKind::Path { guide: false, path, .. } => Budget::of(path), + NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).map(Budget::of).fold(none, Budget::plus), + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().map(|c| art_cost(c)).fold(none, Budget::plus), + _ => none, + } +} + pub(crate) fn leaf_geometry(n: &Node) -> Option<(PathData, FillRule)> { match &n.kind { NodeKind::Path { path, rule, .. } => Some((path.clone(), *rule)), diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 1f17010e37..b2528818bc 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -12,6 +12,24 @@ use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params}; pub const REVOLVE: &str = "threeD.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; + +/// About the bytes one copy of `paint` takes. +fn paint_bytes(paint: &Paint) -> usize { + use std::mem::size_of; + use vectorcraft_doc::color::{FreeformPoint, GradientStop}; + let own = size_of::(); + let Paint::Gradient(g) = paint else { return own }; + let freeform = g + .freeform + .as_ref() + .map_or(0, |f| f.points.len() * size_of::() + f.lines.iter().map(|l| l.len() * size_of::()).sum::()); + own + size_of::() + g.gradient.stops.len() * size_of::() + freeform +} + fn visible(fx: &[Effect]) -> bool { fx.iter().any(|e| e.visible && e.id == REVOLVE) } @@ -93,6 +111,10 @@ fn surface( let options = revolve_options(&merged_params(REVOLVE, &fx.params)); let colored = options.light_color != [1.0; 3] || options.lights.is_some(); let faces = vectorcraft_three_d::revolve(path, b, options).ok()?; + // A face's fill, its shadow and their seam strokes: up to four copies of the paint. + if faces.len().saturating_mul(4).saturating_mul(paint_bytes(&paint)) > MAX_PAINT_COPIES { + return None; + } // 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. @@ -181,7 +203,7 @@ fn shading_paint(g: vectorcraft_three_d::ShadeGradient, color: impl Fn(f64) -> C use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; let stops = g.brightness.into_iter().enumerate().map(|(i, s)| GradientStop { opacity: opacity(s), ..GradientStop::new(i as f32, color(s)) }).collect(); - let mut paint = GradientPaint::new(Gradient { kind: GradientKind::Linear, stops }); + let mut paint = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); paint.geom = Some(GradientGeom { start: g.start, end: g.end, aspect: 1.0, focal: None }); Paint::Gradient(Box::new(paint)) } diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index d4c461f073..a68b7f579d 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -143,6 +143,13 @@ pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> { facets(id, &path, rule, b, p).map(|_| ()) } +/// Can 3D effect `id` (Revolve included, [`is_three_d`]) with parameters `p` draw `n`? Checked +/// before a command changes the document: Revolve by [`crate::validate_revolve`], the others by +/// [`validate_solid`]. +pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> { + if id == crate::REVOLVE { crate::validate_revolve(n, p) } else { validate_solid(n, id, p) } +} + /// One surface: each facet a path shaded from `paint`, as a group with the paint's opacity and /// blend mode (so overlapping facets don't add up their transparency). fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool) -> Node { @@ -351,5 +358,4 @@ pub fn solid_art(n: &Node) -> Option { } #[cfg(test)] -#[path = "tests_solids.rs"] mod tests; diff --git a/crates/effects/src/tests_solids.rs b/crates/effects/src/solids/tests.rs similarity index 99% rename from crates/effects/src/tests_solids.rs rename to crates/effects/src/solids/tests.rs index 61b5a7f575..9dd72d4b14 100644 --- a/crates/effects/src/tests_solids.rs +++ b/crates/effects/src/solids/tests.rs @@ -286,7 +286,7 @@ fn a_masked_surface_under_a_colored_light_stays_whole() { use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; let mut half = GradientStop::new(1.0, RED); half.opacity = 0.5; - let gradient = GradientPaint::new(Gradient { kind: GradientKind::Linear, stops: vec![GradientStop::new(0.0, RED), half] }); + 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)] { let mut n = stroked_rect(100.0); if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) { diff --git a/crates/effects/src/stroke/gradient.rs b/crates/effects/src/stroke/gradient.rs index 62d1d536fb..d274bdc2aa 100644 --- a/crates/effects/src/stroke/gradient.rs +++ b/crates/effects/src/stroke/gradient.rs @@ -15,7 +15,7 @@ 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, lerp_color}; +use vectorcraft_doc::live::{H_DOWN, H_LEFT, H_RIGHT, H_UP}; use vectorcraft_doc::{GradientMesh, LineJoin, MeshPoint, StrokeAlign, StrokeGradientMode, StrokeLayer}; use vectorcraft_geom::FillRule; @@ -375,7 +375,7 @@ pub fn written_slices(bp: &BezPath, rule: FillRule, st: &StrokeLayer, outlines: /// stroke's outline), coloured as [`gradient_slices`] paint it. pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradient) -> Vec { let across = st.gradient_mode == StrokeGradientMode::Across; - let color = |t: f64| g.sample_with(t.clamp(0.0, 1.0) as f32, lerp_color); + 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 = if across { vec![] } else { g.expanded_stops().iter().map(|s| s.0 as f64).collect() }; let max_dt = match (across, st.profile.is_some()) { diff --git a/crates/effects/src/stroke/tests.rs b/crates/effects/src/stroke/tests.rs index a7d8b40316..067064950a 100644 --- a/crates/effects/src/stroke/tests.rs +++ b/crates/effects/src/stroke/tests.rs @@ -127,6 +127,25 @@ fn dot_outlines_take_the_cap_shape_and_wind_like_stroked_dashes() { assert!(o.contains(Point::new(10.5, 0.0)), "the dot overlapping the dash end is painted"); } +#[test] +fn expand_stroke_region_of_a_round_line_stays_compact() { + use std::f64::consts::PI; + use vectorcraft_geom::{FillRule, PathData, Point, SubPath}; + let path = PathData::single(SubPath::polyline(&[Point::new(0.0, 50.0), Point::new(100.0, 50.0)], false)); + let st = stroke(10.0, |s| s.cap = vectorcraft_doc::LineCap::Round); + let region = crate::stroke::outline::outline_region(&path, FillRule::NonZero, &st); + let anchors = region.subpaths.iter().map(|s| s.anchors.len()).sum::(); + assert!(anchors <= 8, "expand stroke should use few anchors for a round line, got {anchors}"); + let area = region.subpaths.iter().map(|s| s.area()).sum::().abs(); + assert!(near(area, 100.0 * 10.0 + PI * 5.0 * 5.0, 1.0), "{area}"); + // Extra colinear anchors along the spine must not multiply outline anchors (#3446). + let dense: Vec = (0..=20).map(|i| Point::new(i as f64 * 5.0, 50.0)).collect(); + let dense_path = PathData::single(SubPath::polyline(&dense, false)); + let dense_region = crate::stroke::outline::outline_region(&dense_path, FillRule::NonZero, &st); + let dense_anchors = dense_region.subpaths.iter().map(|s| s.anchors.len()).sum::(); + assert_eq!(dense_anchors, anchors, "colinear spine points should not add outline anchors"); +} + #[test] fn line_outline_uses_the_profile_dashes_or_a_plain_stroke() { let l = line(0.0, 100.0); diff --git a/crates/effects/src/stroke/width.rs b/crates/effects/src/stroke/width.rs index 44d24343b4..87eca97d78 100644 --- a/crates/effects/src/stroke/width.rs +++ b/crates/effects/src/stroke/width.rs @@ -58,7 +58,9 @@ pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> (Vec, }; match seg { PathSeg::Line(l) => push(l.p1), - _ => kurbo::flatten([PathEl::MoveTo(seg.start()), seg.as_path_el()], tol, |el| { + // Bounded per curve: a projection can blow a small curve up enough that kurbo sizes + // an enormous buffer from it. + _ => vectorcraft_geom::flatten([PathEl::MoveTo(seg.start()), seg.as_path_el()], tol, |el| { if let PathEl::LineTo(p) = el { push(p); } diff --git a/crates/effects/src/stylize.rs b/crates/effects/src/stylize.rs index 2db14d10f2..98bf2dd67e 100644 --- a/crates/effects/src/stylize.rs +++ b/crates/effects/src/stylize.rs @@ -1,6 +1,6 @@ //! Convert to Shape, Round Corners and Scribble. -use serde_json::Value; +use serde_json::{Value, json}; use vectorcraft_geom::kurbo; use vectorcraft_geom::shapes::{self, KAPPA}; use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, SubPath, corners}; @@ -144,6 +144,54 @@ fn crosses_outline(p: Point, q: Point, polys: &[Vec]) -> bool { }) } +/// One named Settings entry in Effect › Stylize › Scribble (public feature names; parameter sets +/// are chosen for VectorCraft). +pub struct ScribbleSetting { + pub id: &'static str, + pub label: &'static str, + pub params: Value, +} + +/// The Scribble dialog's Settings presets, in menu order. +pub fn scribble_settings() -> &'static [ScribbleSetting] { + static PRESETS: std::sync::OnceLock> = std::sync::OnceLock::new(); + PRESETS.get_or_init(|| { + [ + ("default", "Default", json!({"angle": 30.0, "overlap": 0.0, "overlapVariation": 0.5, "strokeWidth": 3.0, "curviness": 5.0, "curvinessVariation": 0.0, "spacing": 5.0, "spacingVariation": 0.5})), + ("childlike", "Childlike", json!({"angle": 45.0, "overlap": 2.0, "overlapVariation": 2.0, "strokeWidth": 2.0, "curviness": 15.0, "curvinessVariation": 30.0, "spacing": 4.0, "spacingVariation": 1.5})), + ("dense", "Dense", json!({"angle": 30.0, "overlap": 0.0, "overlapVariation": 0.0, "strokeWidth": 3.0, "curviness": 0.0, "curvinessVariation": 0.0, "spacing": 2.0, "spacingVariation": 0.0})), + ("loose", "Loose", json!({"angle": 30.0, "overlap": 0.0, "overlapVariation": 1.0, "strokeWidth": 2.0, "curviness": 20.0, "curvinessVariation": 40.0, "spacing": 12.0, "spacingVariation": 3.0})), + ("moire", "Moire", json!({"angle": 0.0, "overlap": 0.0, "overlapVariation": 0.0, "strokeWidth": 1.0, "curviness": 80.0, "curvinessVariation": 10.0, "spacing": 3.0, "spacingVariation": 0.5})), + ("sharp", "Sharp", json!({"angle": 30.0, "overlap": 0.0, "overlapVariation": 0.0, "strokeWidth": 2.0, "curviness": 0.0, "curvinessVariation": 0.0, "spacing": 3.0, "spacingVariation": 0.0})), + ("sketch", "Sketch", json!({"angle": 30.0, "overlap": -1.0, "overlapVariation": 0.5, "strokeWidth": 2.0, "curviness": 10.0, "curvinessVariation": 15.0, "spacing": 6.0, "spacingVariation": 1.0})), + ("snarl", "Snarl", json!({"angle": 15.0, "overlap": 3.0, "overlapVariation": 3.0, "strokeWidth": 4.0, "curviness": 40.0, "curvinessVariation": 50.0, "spacing": 8.0, "spacingVariation": 4.0})), + ("swash", "Swash", json!({"angle": 60.0, "overlap": 5.0, "overlapVariation": 2.0, "strokeWidth": 5.0, "curviness": 30.0, "curvinessVariation": 20.0, "spacing": 10.0, "spacingVariation": 2.0})), + ("tight", "Tight", json!({"angle": 30.0, "overlap": 0.0, "overlapVariation": 0.0, "strokeWidth": 3.0, "curviness": 5.0, "curvinessVariation": 0.0, "spacing": 2.0, "spacingVariation": 0.2})), + ("zigzag", "Zigzag", json!({"angle": 90.0, "overlap": 0.0, "overlapVariation": 0.0, "strokeWidth": 3.0, "curviness": 0.0, "curvinessVariation": 0.0, "spacing": 8.0, "spacingVariation": 0.0})), + ] + .into_iter() + .map(|(id, label, params)| ScribbleSetting { id, label, params }) + .collect() + }) +} + +/// Which Settings preset matches `params` (seed ignored), if any. +pub fn scribble_setting_id(params: &Value) -> Option<&'static str> { + let obj = params.as_object()?; + scribble_settings().iter().find(|p| p.params.as_object().is_some_and(|want| scribble_params_match(obj, want))).map(|p| p.id) +} + +fn scribble_params_match(have: &serde_json::Map, want: &serde_json::Map) -> bool { + want.iter().all(|(k, v)| have.get(k).is_some_and(|a| scribble_param_eq(a, v))) +} + +fn scribble_param_eq(a: &Value, b: &Value) -> bool { + match (a.as_f64(), b.as_f64()) { + (Some(x), Some(y)) => (x - y).abs() < 1e-6, + _ => a == b, + } +} + /// Scribble (simplified): a zig-zag hatching across the filled area at `angle`, one per region /// of the shape, outlined to `strokeWidth` so the fill paints it. `overlapVariation` moves each /// line's ends along it by up to that many points, `spacingVariation` moves them across it, and @@ -184,9 +232,14 @@ pub fn scribble(path: &PathData, b: Rect, p: &Value) -> PathData { row: u64, } let mut chains: Vec = vec![]; - let mut y = y0 + step / 2.0; let mut row = 0u64; - while y < y1 { + // Rows are counted, not summed: adding a step that is below the spacing of the numbers at `y` + // would never move it. + while row <= 2001 { + let y = y0 + step / 2.0 + row as f64 * step; + if y.partial_cmp(&y1) != Some(std::cmp::Ordering::Less) { + break; + } let mut xs: Vec = vec![]; for pl in &polys { for w in pl.windows(2) { @@ -225,7 +278,6 @@ pub fn scribble(path: &PathData, b: Rect, p: &Value) -> PathData { } } row += 1; - y += step; } let lines: Vec = chains .into_iter() diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 34047cc05a..3996794ace 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 scale; +mod transformfx; + fn fx(id: &str, params: Value) -> Effect { Effect { id: id.into(), params, visible: true } } @@ -262,6 +265,7 @@ fn stacked_transform_copies_stay_within_the_image_budget() { xf: Affine::translate((10.0, 0.0)), link: None, placement: Default::default(), + pixels: None, })), ) }; @@ -284,7 +288,154 @@ fn stacked_transform_copies_stay_within_the_image_budget() { assert_eq!(count(&art), 25); let mut g = Node::group(id, vec![Arc::new(image())]); g.appearance.effects.push(fx("distort.transform", json!({"moveH": 70, "copies": 1000}))); - assert_eq!(count(&evaluate_container(&g).unwrap()), 1001); + assert_eq!(count(&evaluate_container(None, &g).unwrap()), 1001); +} + +/// 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) +} + +/// What `effects` make of `path` within a budget of `max` anchors (and any number of lines). +fn anchors_within(effects: &[Effect], path: &PathData, max: usize) -> PathData { + within(effects, path, Budget { anchors: max, lines: usize::MAX }) +} + +/// #3578: stacked Roughens multiply their points (up to 2000 a segment); the anchors they make +/// stay within the budget, each Roughen spacing its points further apart where it must. +#[test] +fn stacked_roughens_stay_within_the_anchor_budget() { + let rough = fx("distort.roughen", json!({"size": 10000, "relative": false, "detail": 100})); + let outs: Vec = (1..=3).map(|n| anchors_within(&vec![rough.clone(); n], &square(), 10_000)).collect(); + let counts: Vec = outs.iter().map(PathData::anchor_count).collect(); + // 100 pt sides at 100 points per inch: 139 points each, within the budget. + assert_eq!(counts[0], 4 * 139); + assert_eq!(outs[0], run("distort.roughen", rough.params.clone(), &square())); + assert!(counts[1..].iter().all(|&c| c > 5_000 && c <= 10_000), "{counts:?}"); + // The third Roughen still roughens, with its points spaced to fit. + assert_ne!(outs[2], outs[1]); + assert!(outs.iter().all(all_finite)); +} + +/// #3578: stacked Zig Zags multiply their points (up to 101 a segment); each segment gets as many +/// ridges as fit the budget. +#[test] +fn stacked_zig_zags_stay_within_the_anchor_budget() { + let zig = fx("distort.zigZag", json!({"ridges": 100, "points": "corner"})); + let counts: Vec = (1..=3).map(|n| anchors_within(&vec![zig.clone(); n], &square(), 10_000).anchor_count()).collect(); + // 4 × 101 points; then 23 ridges a segment fit (404 × 24); then none, each point displaced. + assert_eq!(counts, [404, 9_696, 9_696]); + let twice = anchors_within(&vec![zig.clone(); 2], &square(), 10_000); + assert_ne!(anchors_within(&vec![zig.clone(); 3], &square(), 10_000), twice); + // An open path's end point counts as well. + let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0)], false)); + assert_eq!(anchors_within(&[zig], &line, 30).anchor_count(), 30, "the start, 28 ridges and the end"); +} + +/// #3578: every effect that multiplies anchors builds within the budget, stacked or not, and one +/// that doesn't (Round Corners doubles them) is left out where it would pass it. +#[test] +fn stacked_geometry_effects_stay_within_the_anchor_budget() { + let star = shapes::star(Point::new(150.0, 100.0), 70.0, 32.0, 5, 0.0); + for (id, params) in [ + ("distort.roughen", json!({"size": 50, "detail": 100})), + ("distort.zigZag", json!({"ridges": 100, "size": 30})), + ("distort.twist", json!({"angle": 3600})), + ("distort.freeDistort", json!({"corners": [[0.3, -2], [1, 0], [4, 1], [0, 3]]})), + ("warp.twist", json!({"bend": 100})), + ("distort.transform", json!({"copies": 1000, "moveH": 1})), + ] { + for n in 1..=4 { + let out = anchors_within(&vec![fx(id, params.clone()); n], &star, 2_000); + assert!(out.anchor_count() <= 2_000 && all_finite(&out), "{id} × {n}: {}", out.anchor_count()); + } + } + let zig = fx("distort.zigZag", json!({"ridges": 100, "points": "corner"})); + let full = anchors_within(&[zig.clone(), zig.clone()], &square(), 10_000); + let round = fx("stylize.roundCorners", json!({"radius": 1})); + assert_eq!(anchors_within(&[zig.clone(), zig.clone(), round.clone()], &square(), 10_000), full); + assert_ne!(anchors_within(&[zig, round], &square(), 10_000), run("distort.zigZag", json!({"ridges": 100, "points": "corner"}), &square())); +} + +/// #3578: a path with more anchors than the budget keeps its count as its budget: effects that +/// add none apply, and the others add none. +#[test] +fn a_path_past_the_anchor_budget_still_takes_effects() { + let star = shapes::star(Point::new(150.0, 100.0), 70.0, 32.0, 25, 0.0); + let n = star.anchor_count(); + for (id, params) in [ + ("distort.tweak", json!({})), + ("distort.roughen", json!({"detail": 100})), + ("distort.zigZag", json!({"ridges": 100})), + ("distort.twist", json!({"angle": 90})), + ] { + let out = anchors_within(&[fx(id, params)], &star, 10); + assert_eq!(out.anchor_count(), n, "{id}"); + assert_ne!(out, star, "{id}"); + } +} + +/// #3578: the effects on type, symbols and images reshape all their paths within one budget. +#[test] +fn stacked_effects_on_art_stay_within_the_anchor_budget() { + use std::sync::Arc; + + use vectorcraft_doc::NodeId; + let id = NodeId(9); + let leaf = |x: f64| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0)), Appearance::default())); + let mut art = Node::group(id, (0..10).map(|k| leaf(k as f64 * 120.0)).collect()); + let rough = fx("distort.roughen", json!({"size": 50, "detail": 100})); + crate::reshape::reshape_leaves_within(&mut art, &[&rough, &rough, &rough], Budget { anchors: 5_000, lines: usize::MAX }); + let mut total = 0; + let mut reshaped = 0; + for c in art.children().into_iter().flatten() { + let path = c.path_data().unwrap(); + total += path.anchor_count(); + reshaped += usize::from(path.anchor_count() > 4); + } + // One Roughen alone makes 10 × 556: the budget binds, and goes to the paths in turn. + assert!(total > 4_000 && total <= 5_000, "{total}"); + assert_eq!(reshaped, 10); +} + +/// #3578: a large Roughen draws each of its points as many lines; they stay within the budget, +/// the Roughen built again with fewer points where they wouldn't. +#[test] +fn large_roughens_stay_within_the_line_budget() { + let rough = fx("distort.roughen", json!({"size": 10000, "relative": false, "detail": 100})); + let budget = Budget { anchors: 100_000, lines: 200_000 }; + let once = within(std::slice::from_ref(&rough), &square(), budget); + assert_eq!(once, run("distort.roughen", rough.params.clone(), &square()), "within both budgets"); + let twice = within(&[rough.clone(), rough], &square(), budget); + let cost = Budget::of(&twice); + assert!(budget.fits(cost) && cost.lines > 100_000, "{cost:?}"); + assert!(cost.anchors < 10_000 && twice != once, "the second Roughen with fewer points: {cost:?}"); + // Art of small curves draws its anchors as a few lines each: the anchors bind first. + let zig = fx("distort.zigZag", json!({"ridges": 100, "size": 2})); + let out = within(&[zig.clone(), zig], &square(), Budget { anchors: 10_000, lines: 100_000 }); + assert!(out.anchor_count() > 9_000 && util::line_estimate(&out) < 50_000, "{}", util::line_estimate(&out)); +} + +/// Straight segments are one line each, and a curve as many as Wang's formula takes at 0.25 px. +#[test] +fn line_estimate_counts_the_lines_a_path_is_drawn_with() { + assert_eq!(util::line_estimate(&square()), 4); + let circle = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)); + assert_eq!(util::line_estimate(&circle), 4 * 9, "a quarter circle of 50 pt in 9 lines"); + let big = shapes::ellipse(Rect::new(0.0, 0.0, 10_000.0, 10_000.0)); + assert_eq!(util::line_estimate(&big), 4 * 84, "100 times as large: about 10 times the lines"); +} + +/// #3578: the issue's input, a large rectangle with three max-detail Roughens of the largest +/// size, at the real budgets: two million anchors of it were 141 million lines to draw. +#[test] +fn three_max_detail_roughens_stay_within_the_effect_budget() { + let rough = fx("distort.roughen", json!({"size": 10000, "relative": false, "detail": 100})); + let rect = shapes::rectangle(Rect::new(0.0, 0.0, 1000.0, 1000.0)); + let out = apply_geometry(&vec![rough.clone(); 3], &rect, rect.bounds().unwrap()); + let cost = Budget::of(&out); + assert!(Budget::EFFECTS.fits(cost) && cost.lines > MAX_EFFECT_LINES / 2, "{cost:?}"); + assert_ne!(out, apply_geometry(&[rough], &rect, rect.bounds().unwrap()), "more than one Roughen applies"); } #[test] @@ -311,11 +462,12 @@ fn transform_on_a_group_moves_and_copies_its_images() { xf: Affine::translate((10.0, 0.0)), link: None, placement: Default::default(), + pixels: None, })), ); let mut g = Node::group(id, vec![Arc::new(sq), Arc::new(image)]); g.appearance.effects.push(fx("distort.transform", json!({"moveH": 70, "copies": 2}))); - let art = evaluate_container(&g).unwrap(); + let art = evaluate_container(None, &g).unwrap(); let mut xs = vec![]; image_xs(&art, &mut xs); xs.sort_by(f64::total_cmp); @@ -332,11 +484,12 @@ fn transform_on_a_group_moves_and_copies_its_images() { xf: Affine::translate((10.0, 0.0)), link: None, placement: Default::default(), + pixels: None, })), ))], ); g.appearance.effects.push(fx("distort.transform", json!({"scaleH": 50, "scaleV": 50, "reference": 8}))); - let art = evaluate_container(&g).unwrap(); + let art = evaluate_container(None, &g).unwrap(); let mut xs = vec![]; image_xs(&art, &mut xs); // The bounds are the image itself, so the bottom-right reference is its own: it halves in place. @@ -361,11 +514,11 @@ fn transform_on_a_group_moves_and_copies_its_symbol_instances() { }; let mut g = Node::group(id, vec![Arc::new(Node::path(id, square(), Appearance::default())), Arc::new(instance())]); g.appearance.effects.push(fx("distort.transform", json!({"moveH": 70, "copies": 2}))); - assert_eq!(xs(&evaluate_container(&g).unwrap()), [5.0, 75.0, 145.0], "the instance and its two copies, 70 pt apart"); + assert_eq!(xs(&evaluate_container(None, &g).unwrap()), [5.0, 75.0, 145.0], "the instance and its two copies, 70 pt apart"); // Without copies the instance itself takes the transform, as a path does. let mut g = Node::group(id, vec![Arc::new(instance())]); g.appearance.effects.push(fx("distort.transform", json!({"moveH": 70}))); - assert_eq!(xs(&evaluate_container(&g).unwrap()), [75.0]); + assert_eq!(xs(&evaluate_container(None, &g).unwrap()), [75.0]); } /// Images and symbol instances share the copy budget: copies of one leave less room for the other. @@ -384,6 +537,7 @@ fn images_and_symbol_instances_share_the_copy_budget() { xf: Affine::translate((10.0, 0.0)), link: None, placement: Default::default(), + pixels: None, })), ); let instance = Node::new(id, NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY }); @@ -413,13 +567,14 @@ fn transform_copies_of_images_stop_at_the_reach_limit() { xf: Affine::translate((10.0, 0.0)), link: None, placement: Default::default(), + pixels: None, })), ); let mut g = Node::group(id, vec![Arc::new(image)]); // The largest move: every copy is 1e7 pt further right, so the 100th would end past 1e9. g.appearance.effects.push(fx("distort.transform", json!({"moveH": 1.0e7, "copies": 1000}))); let mut xs = vec![]; - image_xs(&evaluate_container(&g).unwrap(), &mut xs); + image_xs(&evaluate_container(None, &g).unwrap(), &mut xs); assert_eq!(xs.len(), 100, "the image and the 99 copies that stay within reach"); assert!(xs.iter().all(|x| x + 40.0 <= 1.0e9)); } @@ -770,6 +925,17 @@ fn scribble_reads_its_earlier_single_variation() { assert!(default_params("stylize.scribble").unwrap().get("variation").is_none()); } +#[test] +fn scribble_settings_presets_are_distinct_and_recognized() { + let presets = crate::scribble_settings(); + assert_eq!(presets.len(), 11); + assert_eq!(presets[0].id, "default"); + assert_eq!(crate::scribble_setting_id(&presets[0].params), Some("default")); + assert_eq!(crate::scribble_setting_id(&presets[9].params), Some("tight")); + let custom = json!({"angle": 30.0, "overlap": 0.0, "overlapVariation": 0.5, "strokeWidth": 3.0, "curviness": 5.0, "curvinessVariation": 0.0, "spacing": 4.0, "spacingVariation": 0.5}); + assert_eq!(crate::scribble_setting_id(&custom), None); +} + #[test] fn scribble_angle_is_stored_above_minus_180_and_up_to_180() { for (given, stored) in [(270.0, -90.0), (-180.0, 180.0), (180.0, 180.0), (540.0, 180.0), (-270.0, 90.0), (-200.0, 160.0)] { @@ -914,3 +1080,43 @@ fn bench_catalog_lookup() { } eprintln!("10k lookups: {:?} ({n})", t.elapsed()); } + +#[test] +fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() { + use std::sync::Arc; + use vectorcraft_doc::{Document, NodeId, RepeatKind, RepeatSpec, Symbol}; + let unit = || { + Arc::new(Node::path( + NodeId(0), + PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(1.0, 0.0), Point::new(1.0, 1.0)], true)), + Appearance::default(), + )) + }; + let grid = |source: Arc, n: u32| { + let mut g = RepeatSpec::grid(vec![source], 0.0, 0.0); + if let RepeatKind::Grid { rows, cols, .. } = &mut g.kind { + *rows = n; + *cols = n; + } + g + }; + let repeat = |r: RepeatSpec| Arc::new(Node::new(NodeId(0), NodeKind::Repeat(r))); + let instance = |name: &str| Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })); + let mut d = Document::new(100.0, 100.0); + // A 500 × 500 grid as a symbol's art, directly and inside a group; a symbol holding itself. + d.symbols.push(Symbol { name: "Grid".into(), art: repeat(grid(unit(), 500)) }); + d.symbols.push(Symbol { name: "Grouped".into(), art: Arc::new(Node::group(NodeId(0), vec![repeat(grid(unit(), 500))])) }); + d.symbols.push(Symbol { name: "Loop".into(), art: Arc::new(Node::group(NodeId(0), vec![unit(), instance("Loop")])) }); + d.symbols.push(Symbol { name: "Small".into(), art: repeat(grid(unit(), 3)) }); + // A 3 × 3 grid of an instance of each: each copy draws 250,000 instances, so one copy fits. + for name in ["Grid", "Grouped"] { + let outer = Node::new(NodeId(0), NodeKind::Repeat(grid(instance(name), 3))); + let kept = expand_live(Some(&d), &outer).len(); + assert!(kept <= 1, "{name}: {kept} copies of 250,000 instances"); + } + // A symbol holding itself counts no Repeats, and small nests keep every instance. + let looped = Node::new(NodeId(0), NodeKind::Repeat(grid(instance("Loop"), 3))); + assert_eq!(expand_live(Some(&d), &looped).len(), 9); + let small = Node::new(NodeId(0), NodeKind::Repeat(RepeatSpec::mirror(vec![instance("Small")], 90.0, 5.0))); + assert_eq!(expand_live(Some(&d), &small).len(), 2); +} diff --git a/crates/effects/src/tests_scale.rs b/crates/effects/src/tests/scale.rs similarity index 99% rename from crates/effects/src/tests_scale.rs rename to crates/effects/src/tests/scale.rs index 6e2c716890..061695e731 100644 --- a/crates/effects/src/tests_scale.rs +++ b/crates/effects/src/tests/scale.rs @@ -3,7 +3,7 @@ use serde_json::json; use vectorcraft_doc::Effect; -use super::*; +use crate::*; #[test] fn every_distance_parameter_is_a_parameter() { diff --git a/crates/effects/src/tests/transformfx.rs b/crates/effects/src/tests/transformfx.rs new file mode 100644 index 0000000000..a5fdd674cc --- /dev/null +++ b/crates/effects/src/tests/transformfx.rs @@ -0,0 +1,159 @@ +//! The Transform effect's Transform Objects, Transform Patterns and Scale Strokes & Effects +//! options (#885). + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Dash, Effect, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, Rect, shapes}; + +use crate::distort::{TransformOptions, transform_map, transform_move}; +use crate::{has_transform_art, has_transform_options, reshape}; + +fn transform(params: Value) -> Effect { + Effect { id: "distort.transform".into(), params, visible: true } +} + +/// A 100 pt square at the origin with a 2 pt black stroke (dashed 4/2) and the Transform effect +/// `params`. +fn stroked(params: Value) -> Node { + 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::BLACK), 2.0)); + if let Some(s) = n.appearance.stroke_mut() { + s.dash = Some(Dash { pattern: vec![4.0, 2.0], offset: 0.0, align_corners: false }); + } + n.appearance.effects.push(transform(params)); + n +} + +/// A 100 pt square at the origin filled with pattern "p" placed at the identity, with the +/// Transform effect `params`. +fn patterned(params: Value) -> Node { + let paint = Paint::Pattern { pattern: "p".into(), xf: Affine::IDENTITY }; + let mut n = Node::path(NodeId(8), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(paint, Paint::None, 0.0)); + n.appearance.effects.push(transform(params)); + n +} + +/// The paths under `n`, in document order. +fn leaves(n: &Node) -> Vec<&Node> { + let mut out = vec![]; + fn walk<'a>(n: &'a Node, out: &mut Vec<&'a Node>) { + match n.children() { + Some(ch) if !matches!(n.kind, NodeKind::Compound { .. }) => ch.iter().for_each(|c| walk(c, out)), + _ => out.push(n), + } + } + walk(n, &mut out); + out +} + +fn stroke_of(n: &Node) -> (f64, Vec) { + let s = n.appearance.stroke().unwrap(); + (s.width, s.dash.as_ref().map(|d| d.pattern.clone()).unwrap_or_default()) +} + +fn pattern_xf(n: &Node) -> Affine { + match n.appearance.fill_paint() { + Paint::Pattern { xf, .. } => xf, + p => panic!("not a pattern: {p:?}"), + } +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +#[test] +fn the_options_default_to_what_the_effect_did_before() { + let o = TransformOptions::of(&crate::merged_params("distort.transform", &json!({}))); + assert_eq!(o, TransformOptions { objects: true, patterns: false, strokes: false }); + assert!(!o.reach_appearance()); + // An old effect, with no options stored, still draws as geometry alone. + let n = stroked(json!({"scaleH": 50, "scaleV": 50, "copies": 2})); + assert!(!has_transform_options(&n)); + assert!(!has_transform_art(&n)); +} + +#[test] +fn transform_objects_off_maps_nothing_and_makes_no_copies() { + let b = Rect::new(0.0, 0.0, 100.0, 100.0); + let (m, copies) = transform_map(b, &json!({"scaleH": 50, "moveH": 30, "copies": 3, "objects": false}), 0); + assert_eq!((m, copies), (Affine::IDENTITY, 0)); + // A plain move with Transform Patterns on isn't a plain move any more: the pattern moves too. + assert!(transform_move(&json!({"moveH": 30})).is_some()); + assert!(transform_move(&json!({"moveH": 30, "patterns": true})).is_none()); + assert!(transform_move(&json!({"moveH": 30, "strokes": true})).is_some(), "a move scales nothing"); + assert!(transform_move(&json!({"scaleH": 50, "objects": false, "strokes": true})).is_none()); +} + +#[test] +fn scale_strokes_and_effects_scales_the_stroke_and_dash_with_the_object() { + let n = stroked(json!({"scaleH": 50, "scaleV": 50, "strokes": true})); + assert!(has_transform_art(&n)); + let art = reshape(None, &n, None).unwrap(); + let paths = leaves(&art); + assert_eq!(paths.len(), 1); + let (w, dash) = stroke_of(paths[0]); + assert!(close(w, 1.0), "{w}"); + assert_eq!(dash, vec![2.0, 1.0]); + let b = paths[0].geometric_bounds().unwrap(); + assert!(close(b.width(), 50.0), "{b:?}"); +} + +#[test] +fn each_copy_scales_its_stroke_once_more() { + let n = stroked(json!({"scaleH": 200, "scaleV": 200, "copies": 2, "strokes": true})); + let art = reshape(None, &n, None).unwrap(); + let widths: Vec = leaves(&art).iter().map(|p| stroke_of(p).0).collect(); + assert_eq!(widths, vec![2.0, 4.0, 8.0]); + // Without the option the copies keep the original's weight. + let plain = stroked(json!({"scaleH": 200, "scaleV": 200, "copies": 2})); + assert!(!has_transform_art(&plain)); +} + +#[test] +fn transform_objects_off_keeps_the_geometry_and_scales_the_stroke_once() { + let n = stroked(json!({"scaleH": 50, "scaleV": 50, "moveH": 40, "copies": 3, "objects": false, "strokes": true})); + let art = reshape(None, &n, None).unwrap(); + let paths = leaves(&art); + assert_eq!(paths.len(), 1, "no copies"); + assert_eq!(paths[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)); + assert!(close(stroke_of(paths[0]).0, 1.0)); +} + +#[test] +fn transform_patterns_moves_each_copys_pattern() { + let n = patterned(json!({"moveH": 30, "copies": 2, "patterns": true})); + assert!(has_transform_options(&n)); + let art = reshape(None, &n, None).unwrap(); + let xs: Vec = leaves(&art).iter().map(|p| pattern_xf(p).as_coeffs()[4]).collect(); + assert_eq!(xs, vec![0.0, 30.0, 60.0]); + // Without it, every copy's pattern stays put (the tiles don't follow the copies). + let n = patterned(json!({"moveH": 30, "patterns": false, "strokes": false, "objects": true})); + assert!(!has_transform_art(&n)); +} + +#[test] +fn transform_patterns_with_objects_off_moves_only_the_pattern() { + let n = patterned(json!({"rotate": 45, "objects": false, "patterns": true})); + let art = reshape(None, &n, None).unwrap(); + let paths = leaves(&art); + assert_eq!(paths.len(), 1); + assert_eq!(paths[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)); + assert_ne!(pattern_xf(paths[0]), Affine::IDENTITY); +} + +#[test] +fn stroke_scaling_across_copies_stays_finite() { + // A horizontal line stretched vertically barely grows, but its stroke would: the copies stop + // before a stroke weight runs away. + let mut n = + Node::path(NodeId(9), shapes::line((0.0, 0.0).into(), (100.0, 0.0).into()), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + n.appearance.effects.push(transform(json!({"scaleH": 4000, "scaleV": 4000, "copies": 1000, "strokes": true}))); + if let Some(art) = reshape(None, &n, None) { + for p in leaves(&art) { + let w = stroke_of(p).0; + assert!(w.is_finite() && w <= 1.0e6, "{w}"); + } + } +} diff --git a/crates/effects/src/trap.rs b/crates/effects/src/trap.rs new file mode 100644 index 0000000000..f60232bedd --- /dev/null +++ b/crates/effects/src/trap.rs @@ -0,0 +1,469 @@ +//! Pathfinder › Trap, shared by the Pathfinder panel's Trap command (`object.pathfinder.trap`) and +//! the live effect Effect › Pathfinder › Trap ([`TRAP`]). +//! +//! Where two colours printed from separate plates meet, a press that registers the plates slightly +//! off leaves a sliver of paper showing between them. A trap closes that gap: a thin extra shape +//! along the edge where the colours meet, lying over the darker colour, painted with the lighter +//! colour and set to overprint, so the lighter colour seems to spread into the darker one (a +//! lighter object on a darker background) or to choke it (a lighter background around a darker +//! object). The options: +//! +//! - **Thickness** (0.01–5000 pt): how far the lighter colour reaches into the darker one across +//! vertical edges. +//! - **Height/Width** (%): the reach across horizontal edges as a percentage of the vertical one +//! (100%: the same everywhere), for paper that stretches more one way on press. +//! - **Tint Reduction** (%): the trap paints the lighter colour at this percentage of its tint +//! (100: at full strength), so two light colours don't print a dark border where they overlap. +//! - **Traps with Process Color**: a trap of a swatch colour (a spot colour) is painted with the +//! equivalent CMYK process colour instead of the swatch. +//! - **Reverse Traps**: the darker colour spreads into the lighter one instead; not when the +//! darker colour is a rich black (100% K with other inks), which stays where it is. +//! - **Precision** and **Remove Redundant Points** (the effect only): the tolerance in points the +//! trap's outline is refitted to, and whether anchors that don't change its shape are dropped. +//! +//! Only objects filled with a solid colour take part; each object's visible part (what the objects +//! above leave of it) is what traps, so a trap follows the edges that actually show. Two objects +//! filled with the same colour need no trap. The lighter colour is the one with the higher CIE +//! lightness (L*); between colours of equal lightness, the one with less ink. +//! +//! Behaviour from the public descriptions only: +//! and +//! (feature names and +//! option ranges; the defaults of 0.25 pt, 100% and 40% are VectorCraft's own choices, the pages +//! give none). + +use serde_json::{Value, json}; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, NodeId}; +use vectorcraft_geom::{FillRule, PathData, Rect}; +use vectorcraft_pathops as po; + +use crate::util::{flag, num}; + +/// Effect id of Effect › Pathfinder › Trap. +pub const TRAP: &str = "pathfinder.trap"; + +/// Undo label and name of the Pathfinder panel's Trap. +pub const TRAP_LABEL: &str = "Trap"; + +/// Parameter documentation of the effect (the panel command `object.pathfinder.trap` documents the +/// same keys but precision and removeRedundantPoints). +pub const EFFECT_PARAMS_DOC: &str = "{thickness?: pt 0.01..5000 (0.25; how far the lighter colour reaches into the darker one across vertical edges), heightWidth?: % 1..1000 (100; the reach across horizontal edges as a percentage of the vertical one), tintReduction?: % 0..100 (40; the trap paints the lighter colour at this percentage of its tint), trapsWithProcessColor?: bool (false; a swatch (spot) colour's trap is painted with its CMYK process equivalent), reverseTraps?: bool (false; the darker colour spreads into the lighter one, except a rich black), precision?: pt 0.001..10 (0.01; the tolerance the trap's outline is refitted to), removeRedundantPoints?: bool (true)} adds overprinting traps where the members' visible areas of different solid colours meet (groups and layers: live Pathfinder over the members)"; + +/// The options of a trap; [`TrapOptions::from_params`] reads and bounds them. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TrapOptions { + /// Reach across vertical edges, in points (0.01..=5000). + pub thickness: f64, + /// Reach across horizontal edges as a fraction of `thickness` (0.01..=10). + pub height_width: f64, + /// The fraction of the lighter colour's tint the trap paints with (0..=1). + pub tint: f32, + /// Paint traps of swatch colours with their CMYK equivalent. + pub process: bool, + /// Spread the darker colour into the lighter one. + pub reverse: bool, + /// Refit tolerance of the trap outline, in points (0.001..=10). + pub precision: f64, + /// Drop anchors that don't change the trap's shape. + pub remove_redundant: bool, +} + +impl Default for TrapOptions { + fn default() -> Self { + TrapOptions { + thickness: 0.25, + height_width: 1.0, + tint: 0.4, + process: false, + reverse: false, + precision: po::DEFAULT_PRECISION, + remove_redundant: true, + } + } +} + +impl TrapOptions { + /// The options in `p` (keys of [`EFFECT_PARAMS_DOC`]): a missing or non-numeric value takes its + /// default and a value out of range its nearest bound, so a live effect always evaluates. + pub fn from_params(p: &Value) -> Self { + let d = TrapOptions::default(); + let (hw_min, hw_max) = po::TRAP_HEIGHT_WIDTH_RANGE; + TrapOptions { + thickness: num(p, "thickness", d.thickness).clamp(po::TRAP_MIN_WIDTH, po::TRAP_MAX_WIDTH), + height_width: (num(p, "heightWidth", d.height_width * 100.0) / 100.0).clamp(hw_min, hw_max), + tint: (num(p, "tintReduction", f64::from(d.tint) * 100.0) / 100.0).clamp(0.0, 1.0) as f32, + process: flag(p, "trapsWithProcessColor", d.process), + reverse: flag(p, "reverseTraps", d.reverse), + precision: num(p, "precision", d.precision).clamp(0.001, 10.0), + remove_redundant: flag(p, "removeRedundantPoints", d.remove_redundant), + } + } +} + +/// The Pathfinder panel Trap dialog's fields, at their defaults. +pub fn command_defaults() -> Value { + let d = TrapOptions::default(); + json!({ + "thickness": d.thickness, + "heightWidth": d.height_width * 100.0, + "tintReduction": (f64::from(d.tint) * 100.0).round(), + "trapsWithProcessColor": d.process, + "reverseTraps": d.reverse, + }) +} + +/// The Effect › Pathfinder › Trap dialog's fields, at their defaults. +pub fn effect_defaults() -> Value { + let d = TrapOptions::default(); + let mut v = command_defaults(); + if let Some(o) = v.as_object_mut() { + o.insert("precision".into(), json!(d.precision)); + o.insert("removeRedundantPoints".into(), json!(d.remove_redundant)); + } + v +} + +/// One object taking part in a trap, back to front: its outline and its fill. +#[derive(Clone, Debug)] +pub struct TrapSource { + pub path: PathData, + pub rule: FillRule, + pub fill: Paint, +} + +/// One trap: its outline, its paint (the spreading colour, tinted) and the sources it spreads +/// from and into (indices into the sources given to [`traps`]). +#[derive(Clone, Debug)] +pub struct TrapPiece { + pub path: PathData, + pub paint: Paint, + pub from: usize, + pub into: usize, +} + +/// The solid colour a source traps with: none for no fill, gradients, patterns and Registration. +fn trap_color(p: &Paint) -> Option { + if p.is_registration() { None } else { p.color() } +} + +fn finite(p: &PathData) -> bool { + p.subpaths.iter().flat_map(|sp| sp.anchors.iter()).all(|a| a.p.x.is_finite() && a.p.y.is_finite()) +} + +/// Is `a` lighter than `b`? Higher L*; at equal lightness, less ink. +fn lighter(a: Color, b: Color) -> bool { + let (la, lb) = (a.to_lab().l, b.to_lab().l); + if (la - lb).abs() > 1e-3 { + return la > lb; + } + let ink = |c: Color| c.to_cmyk().iter().sum::(); + ink(a) < ink(b) +} + +/// 100% black with other inks under it. +fn rich_black(c: Color) -> bool { + matches!(c, Color::Cmyk { c, m, y, k } if k >= 0.995 && c + m + y > 0.005) +} + +/// Do `a` and `b` print the same (no trap needed)? +fn same_color(a: &Paint, b: &Paint, ca: Color, cb: Color) -> bool { + let link = |p: &Paint| match p { + Paint::Solid { swatch, .. } => swatch.clone(), + _ => None, + }; + link(a) == link(b) && ca.to_cmyk().iter().zip(cb.to_cmyk()).all(|(x, y)| (x - y).abs() < 1e-4) +} + +/// The paint of a trap spreading `p` at tint `t`. +fn trap_paint(p: &Paint, color: Color, o: &TrapOptions) -> Paint { + // A solid colour shows its swatch at `tint` already, so tinting it again gives the swatch at + // `tint × t` ([`Color::tinted`] multiplies in every model). + let shown = color.tinted(o.tint); + match p { + Paint::Solid { swatch: Some(_), .. } if o.process => { + let [c, m, y, k] = shown.to_cmyk(); + Paint::solid(Color::cmyk(c, m, y, k)) + } + Paint::Solid { swatch: Some(s), tint, .. } => Paint::Solid { color: shown, swatch: Some(s.clone()), tint: tint * o.tint }, + _ => Paint::solid(shown), + } +} + +/// The visible part of each source: the faces of their arrangement that it is the top one of. +/// Sources that paint no fill hide nothing and have none. +fn visible(sources: &[TrapSource]) -> Vec { + let mut shapes = vec![]; + for (i, s) in sources.iter().enumerate() { + if !s.fill.is_none() && !s.path.is_empty() && finite(&s.path) { + shapes.push(po::Shape::new(s.path.clone(), s.rule, i as u64)); + } + } + let mut faces: Vec> = vec![vec![]; sources.len()]; + for r in po::regions(&shapes) { + if let Some(face) = r.sources.last().and_then(|&si| shapes.get(si)).and_then(|s| faces.get_mut(s.key as usize)) { + face.push(r.path); + } + } + faces + .into_iter() + .map(|mut f| match f.len() { + 0 => PathData::default(), + 1 => f.pop().unwrap_or_default(), + _ => po::unite_all(&f.iter().map(|p| (p, FillRule::NonZero)).collect::>()), + }) + .collect() +} + +/// The pairs `(i, j)`, `i < j`, in ascending order, of `rects` (`None`: left out) that come within +/// `reach_x` of each other across x and `reach_y` across y. A sweep over the rects sorted by their +/// left edge, so shapes spread over the page cost about one check each rather than one per pair. +fn near_pairs(rects: &[Option], reach_x: f64, reach_y: f64) -> Vec<(usize, usize)> { + let mut order: Vec<(usize, Rect)> = rects.iter().enumerate().filter_map(|(i, r)| r.map(|r| (i, r))).collect(); + order.sort_unstable_by(|a, b| a.1.x0.total_cmp(&b.1.x0).then(a.0.cmp(&b.0))); + let mut pairs = vec![]; + for (k, &(i, a)) in order.iter().enumerate() { + // Later rects start at or right of `a`, so only how far right they start can rule them out. + for &(j, b) in order[k + 1..].iter().take_while(|(_, b)| b.x0 <= a.x1 + reach_x) { + if b.y0 <= a.y1 + reach_y && a.y0 <= b.y1 + reach_y { + pairs.push((i.min(j), i.max(j))); + } + } + } + pairs.sort_unstable(); + pairs +} + +/// The traps between `sources` (back to front) with options `o`: for each two sources of +/// different solid colours whose visible parts meet, the strip of the darker one's visible part +/// next to the lighter one's (the other way round with [`TrapOptions::reverse`]), painted per +/// [`trap_paint`]. Empty when no visible edges of different colours meet. +pub fn traps(sources: &[TrapSource], o: &TrapOptions) -> Vec { + let colors: Vec> = sources.iter().map(|s| trap_color(&s.fill)).collect(); + if colors.iter().flatten().count() < 2 { + return vec![]; + } + let (w, r) = (o.thickness, o.height_width); + if !(w.is_finite() && w > 0.0 && r.is_finite() && r > 0.0) { + return vec![]; // `trap_band` cuts nothing with these. + } + let vis = visible(sources); + // Only pairs whose visible parts come within the trap's reach can trap (`trap_band` rejects + // the rest by the same bounds), so find those first instead of trying every pair. The hair + // keeps rounding from rejecting a pair `trap_band` would keep. + let rects: Vec> = + vis.iter().zip(&colors).map(|(p, c)| c.and(p.bounds()).filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))).collect(); + let (w, r) = (w.clamp(po::TRAP_MIN_WIDTH, po::TRAP_MAX_WIDTH), r.clamp(po::TRAP_HEIGHT_WIDTH_RANGE.0, po::TRAP_HEIGHT_WIDTH_RANGE.1)); + let extent = rects.iter().flatten().flat_map(|b| [b.x0, b.y0, b.x1, b.y1]).fold(0.0_f64, |m, v| m.max(v.abs())); + let hair = 1e-9 * (1.0 + extent + w * r.max(1.0)); + let mut out = vec![]; + for (i, j) in near_pairs(&rects, w + hair, w * r + hair) { + let (Some(ci), Some(cj)) = (colors[i], colors[j]) else { continue }; + if vis[i].is_empty() || vis[j].is_empty() || same_color(&sources[i].fill, &sources[j].fill, ci, cj) { + continue; + } + let (mut from, mut into) = if lighter(ci, cj) { (i, j) } else { (j, i) }; + if o.reverse && colors[into].is_some_and(|c| !rich_black(c)) { + (from, into) = (into, from); + } + let mut band = po::trap_band(&vis[from], FillRule::NonZero, &vis[into], FillRule::NonZero, o.thickness, o.height_width, o.precision); + if o.remove_redundant { + band = po::remove_redundant_points(&band, o.precision); + } + if band.is_empty() || po::area(&band, FillRule::NonZero) <= 1e-9 { + continue; + } + let Some(color) = colors[from] else { continue }; + out.push(TrapPiece { path: band, paint: trap_paint(&sources[from].fill, color, o), from, into }); + } + out +} + +/// A trap's appearance: one overprinting fill of `paint`, no stroke. +pub fn trap_appearance(paint: Paint) -> Appearance { + Appearance { items: vec![AppearanceItem::Fill(FillLayer { overprint: true, ..FillLayer::new(paint) })], ..Default::default() } +} + +/// A trap as a path object with id `id`. +pub fn trap_node(id: NodeId, piece: TrapPiece) -> Node { + Node::path(id, piece.path, trap_appearance(piece.paint)) +} + +#[cfg(test)] +mod tests { + use vectorcraft_geom::Rect; + use vectorcraft_geom::shapes::rectangle; + + use super::*; + + fn src(r: Rect, c: Color) -> TrapSource { + TrapSource { path: rectangle(r), rule: FillRule::NonZero, fill: Paint::solid(c) } + } + + fn yellow() -> Color { + Color::cmyk(0.0, 0.0, 1.0, 0.0) + } + + fn blue() -> Color { + Color::cmyk(1.0, 0.6, 0.0, 0.0) + } + + fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 0.02 + } + + fn abutting() -> Vec { + vec![src(Rect::new(0.0, 0.0, 50.0, 40.0), yellow()), src(Rect::new(50.0, 0.0, 100.0, 40.0), blue())] + } + + #[test] + fn the_lighter_colour_spreads_into_the_darker_along_the_shared_edge() { + let o = TrapOptions { thickness: 3.0, tint: 1.0, ..Default::default() }; + let t = traps(&abutting(), &o); + assert_eq!(t.len(), 1); + let b = t[0].path.bounds().unwrap(); + assert!(near(b.x0, 50.0) && near(b.x1, 53.0) && near(b.y0, 0.0) && near(b.y1, 40.0), "inside the blue, 3 pt wide: {b:?}"); + assert_eq!((t[0].from, t[0].into), (0, 1)); + assert_eq!(t[0].paint.color(), Some(yellow())); + let n = trap_node(NodeId(7), t[0].clone()); + assert!(n.appearance.fill().is_some_and(|f| f.overprint), "the trap overprints"); + assert!(n.appearance.stroke_paint().is_none()); + } + + #[test] + fn reverse_traps_spread_the_darker_colour() { + let o = TrapOptions { thickness: 2.0, reverse: true, tint: 1.0, ..Default::default() }; + let t = traps(&abutting(), &o); + assert_eq!(t.len(), 1); + let b = t[0].path.bounds().unwrap(); + assert!(near(b.x0, 48.0) && near(b.x1, 50.0), "inside the yellow: {b:?}"); + assert_eq!(t[0].paint.color(), Some(blue())); + } + + #[test] + fn reverse_traps_leave_rich_black_alone() { + let rich = Color::cmyk(0.6, 0.4, 0.4, 1.0); + let s = vec![src(Rect::new(0.0, 0.0, 50.0, 40.0), yellow()), src(Rect::new(50.0, 0.0, 100.0, 40.0), rich)]; + let t = traps(&s, &TrapOptions { reverse: true, ..Default::default() }); + assert_eq!(t[0].from, 0, "the yellow still spreads into the rich black"); + } + + #[test] + fn tint_reduction_tints_the_trap_and_keeps_a_swatch_unless_process_colour() { + let mut s = abutting(); + s[0].fill = Paint::Solid { color: yellow(), swatch: Some("PANTONE Yellow".into()), tint: 1.0 }; + let t = traps(&s, &TrapOptions { tint: 0.5, ..Default::default() }); + match &t[0].paint { + Paint::Solid { color, swatch, tint } => { + assert_eq!(swatch.as_deref(), Some("PANTONE Yellow")); + assert!((tint - 0.5).abs() < 1e-6); + assert!((color.to_cmyk()[2] - 0.5).abs() < 1e-4, "{color:?}"); + } + p => panic!("{p:?}"), + } + let t = traps(&s, &TrapOptions { tint: 0.5, process: true, ..Default::default() }); + match &t[0].paint { + Paint::Solid { color, swatch: None, .. } => assert!(matches!(color, Color::Cmyk { .. })), + p => panic!("{p:?}"), + } + } + + #[test] + fn a_lighter_object_on_a_darker_background_spreads_all_round() { + // Yellow square on top of a blue background: a ring around the yellow, inside the blue. + let s = vec![src(Rect::new(0.0, 0.0, 100.0, 100.0), blue()), src(Rect::new(40.0, 40.0, 60.0, 60.0), yellow())]; + let t = traps(&s, &TrapOptions { thickness: 1.0, ..Default::default() }); + assert_eq!(t.len(), 1); + let b = t[0].path.bounds().unwrap(); + assert!(near(b.x0, 39.0) && near(b.x1, 61.0) && near(b.y0, 39.0) && near(b.y1, 61.0), "{b:?}"); + assert!(near(po::area(&t[0].path, FillRule::NonZero), 22.0 * 22.0 - 400.0)); + } + + #[test] + fn no_trap_without_adjoining_edges_of_different_colours() { + let apart = vec![src(Rect::new(0.0, 0.0, 10.0, 10.0), yellow()), src(Rect::new(30.0, 0.0, 40.0, 10.0), blue())]; + assert!(traps(&apart, &TrapOptions::default()).is_empty()); + let same = vec![src(Rect::new(0.0, 0.0, 10.0, 10.0), blue()), src(Rect::new(10.0, 0.0, 20.0, 10.0), blue())]; + assert!(traps(&same, &TrapOptions::default()).is_empty()); + let mut unfilled = abutting(); + unfilled[1].fill = Paint::None; + assert!(traps(&unfilled, &TrapOptions::default()).is_empty()); + } + + #[test] + fn options_are_bounded_and_bad_numbers_take_defaults() { + let o = TrapOptions::from_params(&json!({"thickness": 1e300, "heightWidth": -5, "tintReduction": 400, "precision": "x"})); + assert_eq!(o.thickness, po::TRAP_MAX_WIDTH); + assert_eq!(o.height_width, po::TRAP_HEIGHT_WIDTH_RANGE.0); + assert_eq!(o.tint, 1.0); + assert_eq!(o.precision, po::DEFAULT_PRECISION); + let o = TrapOptions::from_params(&json!({"thickness": "NaN"})); + assert_eq!(o.thickness, TrapOptions::default().thickness); + // The widest trap still stays inside the darker shape. + let t = traps(&abutting(), &TrapOptions { thickness: f64::NAN, ..Default::default() }); + assert!(t.is_empty(), "a NaN thickness traps nothing"); + let t = traps(&abutting(), &TrapOptions { thickness: po::TRAP_MAX_WIDTH, ..Default::default() }); + let b = t[0].path.bounds().unwrap(); + assert!(near(b.x0, 50.0) && near(b.x1, 100.0), "{b:?}"); + } + + #[test] + fn nan_coordinates_are_left_out() { + let mut s = abutting(); + s[1].path.subpaths[0].anchors[0].p.x = f64::NAN; + assert!(traps(&s, &TrapOptions::default()).is_empty()); + } + + /// 2,000 separated 10 pt squares in alternating colours on a 20 pt grid, then a yellow square + /// abutting the first (blue) one's right edge. + fn many_apart_and_one_abutting() -> Vec { + let mut s: Vec = (0..2000) + .map(|k| { + let (x, y) = (f64::from(k % 50) * 20.0, f64::from(k / 50) * 20.0); + src(Rect::new(x, y, x + 10.0, y + 10.0), if (k + k / 50) % 2 == 0 { blue() } else { yellow() }) + }) + .collect(); + s.push(src(Rect::new(10.0, 0.0, 15.0, 10.0), yellow())); + s + } + + #[test] + fn only_shapes_within_reach_are_paired() { + let s = many_apart_and_one_abutting(); + let rects: Vec> = s.iter().map(|t| t.path.bounds()).collect(); + assert_eq!(near_pairs(&rects, 1.0, 1.0), vec![(0, 2000)], "the squares 10 pt apart are never paired"); + // Reaching 10 pt, neighbours in a row pair, in ascending order; left-out rects never do. + let row: Vec> = [3, 1, 0, 2].iter().map(|&k| s[k].path.bounds()).chain([None]).collect(); + assert_eq!(near_pairs(&row, 10.0, 10.0), vec![(0, 3), (1, 2), (1, 3)]); + let t = traps(&s, &TrapOptions { thickness: 1.0, ..Default::default() }); + assert_eq!(t.len(), 1, "only the abutting pair traps"); + assert_eq!((t[0].from, t[0].into), (2000, 0)); + let b = t[0].path.bounds().unwrap(); + assert!(near(b.x0, 9.0) && near(b.x1, 10.0) && near(b.y0, 0.0) && near(b.y1, 10.0), "{b:?}"); + } + + #[test] + fn pairing_by_bounds_keeps_every_trap_in_order() { + // Shapes abutting across x and y, overlapping, and half a point apart (within a 1 pt trap), + // none of them hiding another's edges: the traps are those of each pair alone. + let s = vec![ + src(Rect::new(0.0, 0.0, 100.0, 100.0), blue()), + src(Rect::new(40.0, 40.0, 60.0, 60.0), yellow()), + src(Rect::new(100.0, 0.0, 120.0, 50.0), yellow()), + src(Rect::new(0.0, 100.5, 50.0, 120.0), yellow()), + src(Rect::new(55.0, 100.0, 80.0, 130.0), Color::cmyk(0.0, 1.0, 0.0, 0.0)), + ]; + let o = TrapOptions { thickness: 1.0, ..Default::default() }; + let got: Vec<(usize, usize)> = traps(&s, &o).iter().map(|t| (t.from, t.into)).collect(); + let mut want = vec![]; + for i in 0..s.len() { + for j in i + 1..s.len() { + if let Some(t) = traps(&[s[i].clone(), s[j].clone()], &o).first() { + want.push(if t.from == 0 { (i, j) } else { (j, i) }); + } + } + } + assert_eq!(want.len(), 4, "{want:?}"); + assert_eq!(got, want); + } +} diff --git a/crates/effects/src/util.rs b/crates/effects/src/util.rs index 336d65199c..ec8cb4cba8 100644 --- a/crates/effects/src/util.rs +++ b/crates/effects/src/util.rs @@ -1,7 +1,7 @@ //! Parameter parsing, deterministic noise and path-mapping helpers. use serde_json::Value; -use vectorcraft_geom::{Anchor, CubicBez, ParamCurve, Point, Rect, SubPath, Vec2}; +use vectorcraft_geom::{Anchor, CubicBez, ParamCurve, PathData, Point, Rect, SubPath, Vec2}; /// Number param (also accepts numeric strings such as `"10 pt"`); non-finite → default. pub fn num(p: &Value, key: &str, default: f64) -> f64 { @@ -69,8 +69,25 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez { if sp.segment_is_line(i) { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c } } -/// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`). -pub use vectorcraft_doc::live::map_nonlinear; +/// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of +/// segments into pieces within an anchor budget. +pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, pieces}; + +/// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight +/// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px, +/// `sqrt(0.75 × d / 0.25)` for the largest second difference `d` of its control points. +pub fn line_estimate(path: &PathData) -> usize { + let curve = |c: CubicBez| { + let d = + (c.p0.to_vec2() - c.p1.to_vec2() * 2.0 + c.p2.to_vec2()).hypot().max((c.p1.to_vec2() - c.p2.to_vec2() * 2.0 + c.p3.to_vec2()).hypot()); + // A NaN casts to 0 and an infinity to the largest count. + ((3.0 * d).sqrt().ceil() as usize).max(1) + }; + path.subpaths + .iter() + .flat_map(|sp| (0..sp.segment_count()).map(move |i| if sp.segment_is_line(i) { 1 } else { curve(sp.segment(i)) })) + .fold(0, usize::saturating_add) +} /// Smooth subpath through `pts` (Catmull-Rom tangents, see [`turn_tangent`] for sharp turns). pub fn catmull_rom(pts: &[Point], closed: bool, tension: f64) -> SubPath { diff --git a/crates/effects/src/warp.rs b/crates/effects/src/warp.rs index 35a67ba237..f3b7efea91 100644 --- a/crates/effects/src/warp.rs +++ b/crates/effects/src/warp.rs @@ -10,8 +10,8 @@ use crate::util::*; pub use vectorcraft_doc::live::{WarpStyle, warp_point}; -/// Apply a warp to `path` using box `b`. -pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value) -> PathData { +/// 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 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; @@ -30,5 +30,5 @@ pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value) -> PathData { Point::new(c.x + x2 * hw, c.y + y2 * hh) }; let piece = b.width().hypot(b.height()) / 24.0; - map_nonlinear(path, piece, f) + map_nonlinear_within(path, piece, max, f) } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b83b990324..f495697ceb 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -45,6 +45,11 @@ serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } +# Whether a recovery area folder is this account's own (`FolderStore::own_area`). Already in +# Cargo.lock (tempfile, ui-egui), so this adds no new crate. +[target.'cfg(unix)'.dependencies] +rustix = { workspace = true, features = ["std", "process"] } + [dev-dependencies] vectorcraft-affinity = { workspace = true, features = ["synth"] } crc32fast = { workspace = true } diff --git a/crates/engine/examples/export_bench.rs b/crates/engine/examples/export_bench.rs new file mode 100644 index 0000000000..62438b2be9 --- /dev/null +++ b/crates/engine/examples/export_bench.rs @@ -0,0 +1,47 @@ +//! `cargo run --release -p vectorcraft-engine --example export_bench -- [FORMAT] [FILE…]` — wall +//! time of `document.export` (default SVG) for each file (default: the documents in `examples/`). +//! `ITERS` sets the runs per file (default 7); prints the median and the fastest run. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::PathBuf; +use std::time::Instant; + +use serde_json::json; +use vectorcraft_engine::Session; + +fn main() { + let mut args = std::env::args().skip(1); + let format = args.next().unwrap_or_else(|| "svg".into()); + let mut files: Vec = args.map(PathBuf::from).collect(); + if files.is_empty() { + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples"); + files = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| p.extension().is_some_and(|e| e == "vectorcraft")).collect(); + files.sort(); + } + let iters: usize = std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1); + let out_dir = std::env::temp_dir().join(format!("vectorcraft-export-bench-{}", std::process::id())); + std::fs::create_dir_all(&out_dir).unwrap(); + let mut total = 0.0; + for file in &files { + let mut s = Session::new(); + s.execute("document.open", &json!({ "path": file.to_string_lossy() })).unwrap(); + let name = file.file_stem().unwrap().to_string_lossy().into_owned(); + let out = out_dir.join(format!("{name}.{format}")); + let p = json!({ "path": out.to_string_lossy(), "format": format }); + let mut ms: Vec = (0..iters) + .map(|_| { + let t = Instant::now(); + s.execute("document.export", &p).unwrap(); + t.elapsed().as_secs_f64() * 1000.0 + }) + .collect(); + ms.sort_by(f64::total_cmp); + let median = ms[ms.len() / 2]; + total += median; + let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0); + println!("{name}.{format}: median {median:.1} ms, min {:.1} ms ({bytes} bytes)", ms[0]); + } + println!("total of medians: {total:.1} ms"); + std::fs::remove_dir_all(&out_dir).ok(); +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd.rs similarity index 85% rename from crates/engine/src/cmd/mod.rs rename to crates/engine/src/cmd.rs index 5ec103e898..411f2004af 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd.rs @@ -3,13 +3,14 @@ pub(crate) mod appearance; mod assets; mod attributes; +pub mod brushlib; mod brushsym; mod buildcmds; pub mod clipboard; mod colorcmds; pub mod colormgmt; pub mod colortheme; -mod create; +pub(crate) mod create; mod css; mod cut; pub(crate) mod dimension; @@ -28,6 +29,7 @@ pub mod flatten; pub mod fontfiles; mod fonts; pub(crate) mod freeform; +pub mod globaledit; pub(crate) mod gradient; pub(crate) mod graph; mod halftone; @@ -50,16 +52,16 @@ mod object; pub(crate) mod objects_on_path; mod opacitymask; mod overprint; -mod package; +pub mod package; mod paint; mod panelcmds; pub mod params; mod path; -mod pathops; +pub(crate) mod pathops; mod patterncmds; pub mod pdfcmds; pub mod perspgrid; -pub(crate) mod place; +pub mod place; pub mod plugin; pub mod prefscmds; pub mod print; @@ -79,6 +81,7 @@ mod style; pub mod stylelib; mod swatch; pub mod swatchlib; +pub mod symbollib; pub(crate) mod tabs; mod textedit; pub mod textstyles; @@ -214,6 +217,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(object::specs()); v.extend(path::specs()); v.extend(select::specs()); + v.extend(globaledit::specs()); v.extend(wand::specs()); v.extend(paint::specs()); // Split out of `paint` (M3.8); kept next to it so lists in registry order (the command @@ -267,6 +271,8 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(freeform::specs()); v.extend(flatten::specs()); v.extend(stylelib::specs()); + v.extend(symbollib::specs()); + v.extend(brushlib::specs()); v.extend(library::specs()); v.extend(expand::specs()); v.extend(attributes::specs()); @@ -318,20 +324,42 @@ pub(crate) fn f64_or(p: &Value, key: &str, default: f64) -> f64 { pub(crate) fn f64_req(p: &Value, key: &str, cmd: &str) -> Result { p.get(key).and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("missing number `{key}`"))) } -/// Error unless each of `keys` that `p` gives is a number (or null): an optional number read with -/// [`f64_or`] would otherwise fall back to its default for a string such as `"60 mm"` (#1952). +/// 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}". +pub(crate) fn number_or(p: &Value, key: &str, default: f64, cmd: &str) -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(default), + Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))), + } +} +/// Error unless each of `keys` that `p` gives is a number (or null), as [`number_or`] reads them: an +/// optional number read with [`f64_or`] would otherwise fall back to its default for a string such as +/// `"60 mm"` (#1952). pub(crate) fn check_numbers(p: &Value, keys: &[&str], cmd: &str) -> Result<()> { for key in keys { - match p.get(*key) { - None | Some(Value::Null) | Some(Value::Number(_)) => {} - Some(v) => return Err(bad(cmd, format!("`{key}` must be a number, not {v}"))), - } + number_or(p, key, 0.0, cmd)?; } Ok(()) } pub(crate) fn bool_or(p: &Value, key: &str, default: bool) -> bool { p.get(key).and_then(Value::as_bool).unwrap_or(default) } +/// The true or false `p` gives for `key`, or `default` when `p` leaves it out or gives null. Any +/// other value, such as `"false"`, is an error: "`{key}` must be true or false". +pub(crate) fn switch_or(p: &Value, key: &str, default: bool, cmd: &str) -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(default), + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, format!("`{key}` must be true or false"))), + } +} +/// Error unless each of `keys` that `p` gives is true or false (or null), as [`switch_or`] reads +/// them. +pub(crate) fn check_switches(p: &Value, keys: &[&str], cmd: &str) -> Result<()> { + for key in keys { + switch_or(p, key, false, cmd)?; + } + Ok(()) +} pub(crate) fn str_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> { p.get(key).and_then(Value::as_str) } @@ -341,6 +369,26 @@ pub(crate) fn id_param(p: &Value, key: &str) -> Option { pub(crate) fn ids_param(p: &Value, key: &str) -> Option> { p.get(key).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(NodeId).collect()) } +/// The objects `p` gives `command`: its `ids`, else its `id` as `ids` of one (as [`targets`] reads +/// 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>> { + if p.get("ids").is_some_and(|v| !v.is_null()) { + return checked_ids_param(s, p, "ids", command).map(Some); + } + match p.get("id").filter(|v| !v.is_null()) { + None => Ok(None), + // A step reference a batch couldn't resolve, as `targets` reports it, under the command. + 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)?])), + } +} +/// `v` as an index, a count or a byte offset: past `usize::MAX` reads as `usize::MAX`, past the end of any list. +pub(crate) fn index(v: u64) -> usize { + usize::try_from(v).unwrap_or(usize::MAX) +} /// 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> { let values = @@ -451,10 +499,12 @@ pub(crate) fn ok() -> Result { } /// Leaves whose appearance a paint command changes: groups and layers expand to their contents, -/// and compound paths own their children's appearance. +/// and compound paths own their children's appearance, so a member stands for its compound path +/// (#3692), which is listed once. pub(crate) fn leaf_targets(s: &Session, ids: &[NodeId]) -> Result> { use vectorcraft_doc::NodeKind; let d = &s.doc()?.doc; + let compound = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); let mut out = vec![]; for id in ids { let Some(n) = d.node(*id) else { continue }; @@ -464,11 +514,13 @@ pub(crate) fn leaf_targets(s: &Session, ids: &[NodeId]) -> Result> { out.push(c.id) } }), - _ => out.push(*id), + _ => out.push(compound(*id).unwrap_or(*id)), } } let comp: Vec = out.iter().filter(|id| matches!(d.node(**id).map(|n| &n.kind), Some(NodeKind::Compound { .. }))).copied().collect(); out.retain(|id| !comp.iter().any(|c| d.parent_of(*id) == Some(*c))); + let mut seen = std::collections::HashSet::new(); + out.retain(|id| seen.insert(*id)); Ok(out) } @@ -486,6 +538,7 @@ pub(crate) fn unique_name(base: &str, taken: impl Fn(&str) -> bool) -> String { } pub(crate) use edit::{settle_interaction, typing_in_progress}; +pub(crate) use object::bounds_rewrite; pub(crate) use vectorcraft_doc::range::parse_range; /// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see @@ -513,6 +566,9 @@ pub use opacitymask::TransparencyInfo; /// Eyedropper Options (`Prefs::eyedropper`). pub use xform::{AppearanceAttrs, EyedropperAttrs, EyedropperOptions, FillAttrs, StrokeAttrs}; +/// Pathfinder Options (`Prefs::pathfinder`). +pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions}; + /// The Attributes panel's state ([`Session::attributes_info`]). pub use overprint::AttributesInfo; @@ -525,6 +581,9 @@ pub use flatten::FlattenerPreset; /// The shapes a group selected alone gives the Pathfinder panel. pub use pathops::shape_count; +/// The gaps View › Show Live Paint Gaps shows on a Live Paint group. +pub use buildcmds::live_paint_gaps; + /// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`. /// They run as before but the command palette leaves them out (it lists the command once). pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")]; diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 84dc1f3c04..3e1173d8ba 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -21,6 +21,7 @@ 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_geom::Rect; @@ -37,7 +38,7 @@ pub fn specs() -> Vec { "appearance.addFill", "Add New Fill", ["Window", "Appearance"], - None, + Some("Cmd+/"), "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row (a copy of its top fill; type without one: its characters' fill; else the default fill)", has_doc, |s, p| add_item(s, p, true) @@ -46,7 +47,7 @@ pub fn specs() -> Vec { "appearance.addStroke", "Add New Stroke", ["Window", "Appearance"], - None, + 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 (a copy of its top stroke, else the default stroke)", has_doc, |s, p| add_item(s, p, false) @@ -74,7 +75,7 @@ pub fn specs() -> Vec { "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)} edit one fill/stroke of each target object's own appearance stack", + "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack", has_doc, set_item ), @@ -83,7 +84,7 @@ pub fn specs() -> Vec { "Remove Item", [], None, - "{index | indices: [..] (paint-order item indices), ids?|id?, target?} remove those fills/strokes from each target object's own stack", + "{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack", has_doc, remove_item ), @@ -101,7 +102,7 @@ pub fn specs() -> Vec { "Duplicate Item", ["Window", "Appearance"], None, - "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (one `index` only; default: right above it, as Alt-dragging a row places it), ids?|id?, target?} copy fills/strokes with their effects", + "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (one `index` only; default: right above it, as Alt-dragging a row places it; not with aligned rows of a mixed selection), 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", has_doc, duplicate_item ), @@ -110,7 +111,7 @@ pub fn specs() -> Vec { "Reorder Appearance Item", [], None, - "{from: paint-order item index | \"contents\", to, contents?: count, ids?|id?, target?} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above → {index: where the item landed | contents: the row's slot}", + "{from: paint-order item index | \"contents\", to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above → {index: where the item landed | contents: the row's slot}", has_doc, move_item ), @@ -119,7 +120,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: the selection), the fill, stroke and weight also to the paint defaults; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead; `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art) → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead; `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art) → {ids}", has_doc, copy_from ), @@ -203,8 +204,11 @@ pub(crate) enum ItemTarget { /// The topmost fill or stroke (for effects: the object-level effects). Top, /// Item `index`. `explicit`: named by the `item` param, so it must exist and be of the edited - /// kind; otherwise it is the panel's active item, which applies only where it fits. - Item { index: usize, explicit: bool }, + /// kind; otherwise it is the panel's active item, which applies only where it fits. `aligned`: + /// `index` is a row of the first target's stack, and each other target edits the item equal to + /// it there ([`ItemTarget::per_target`]): the active item always is (it is a row of the first + /// selected object's stack), an explicit one with `aligned: true`. + Item { index: usize, explicit: bool, aligned: bool }, } /// Parse the `item` param of `cmd` (see the module docs). @@ -218,11 +222,11 @@ pub(crate) fn item_target_at(s: &Session, p: &Value, key: &str, cmd: &str) -> Re Some(Value::Null) => Ok(ItemTarget::Top), Some(v) => v .as_u64() - .map(|i| ItemTarget::Item { index: i as usize, explicit: true }) + .map(|i| ItemTarget::Item { index: index(i), explicit: true, aligned: aligned(p) }) .ok_or_else(|| bad(cmd, format!("`{key}` must be an appearance item index (paint order) or null"))), // The active item is a row of the first selected object's own stack. None if p.get("ids").is_some() || p.get("id").is_some() || targets_contents(p)? => Ok(ItemTarget::Top), - None => Ok(s.appearance_item().map_or(ItemTarget::Top, |index| ItemTarget::Item { index, explicit: false })), + None => Ok(s.appearance_item().map_or(ItemTarget::Top, |index| ItemTarget::Item { index, explicit: false, aligned: true })), } } @@ -240,17 +244,30 @@ impl ItemTarget { /// of its own kind, so a fill row leaves stroke edits on the topmost stroke of the painted /// leaves (as without an active item) and vice versa. Explicit items are kept (and checked). pub(crate) fn of_kind(self, s: &Session, fill: bool) -> Self { - let ItemTarget::Item { index, explicit: false } = self else { return self }; + let ItemTarget::Item { index, explicit: false, .. } = self else { return self }; let fits = s.active().and_then(|st| st.doc.node(*st.selection.subjects().first()?)?.appearance.items.get(index).map(|it| it.is_fill() == fill)); if fits == Some(true) { self } else { ItemTarget::Top } } + /// This target for each of `ids` in `d` (in their order): an aligned item (a row of the first + /// target's stack) is, in each other target, the item equal to it there (see + /// [`SharedStack`]); `None` for a target that has none, which the edit leaves alone. A row the + /// targets don't share, and any other target, stands for itself in every target. + pub(crate) fn per_target(self, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec> { + let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] }; + let Some(shared) = shared_stack(d, ids) else { return vec![Some(self); ids.len()] }; + if !shared.has_item(index) { + return vec![Some(self); ids.len()]; + } + (0..ids.len()).map(|k| shared.item_in(index, k).map(|index| ItemTarget::Item { index, explicit, aligned: true })).collect() + } + /// The item of `ap` a fill (`fill`) or stroke edit changes; `None` = the topmost one. pub(crate) fn resolve(self, ap: &Appearance, fill: bool, cmd: &str) -> Result> { match self { ItemTarget::Top => Ok(None), - ItemTarget::Item { index, explicit } => match ap.item_of_kind(Some(index), fill) { + ItemTarget::Item { index, explicit, .. } => match ap.item_of_kind(Some(index), fill) { None if explicit => Err(bad( cmd, match ap.items.get(index) { @@ -268,12 +285,45 @@ impl ItemTarget { match self { ItemTarget::Top => Ok(None), ItemTarget::Item { index, .. } if index < ap.items.len() => Ok(Some(index)), - ItemTarget::Item { index, explicit: true } => Err(bad(cmd, format!("no appearance item {index}"))), + ItemTarget::Item { index, explicit: true, .. } => Err(bad(cmd, format!("no appearance item {index}"))), ItemTarget::Item { explicit: false, .. } => Ok(None), } } } +/// Does `p` say its item and effect indices are rows of the first target's stack (`aligned`), +/// which each other target edits where it has them (see [`ItemTarget::per_target`])? +pub(crate) fn aligned(p: &Value) -> bool { + p.get("aligned").and_then(Value::as_bool).unwrap_or(false) +} + +/// What the appearances of `ids` share, when there are several of them and they all exist. +pub(crate) fn shared_stack(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Option { + if ids.len() < 2 { + return None; + } + let aps: Vec<&Appearance> = ids.iter().map(|id| d.node(*id).map(|n| &*n.appearance)).collect::>()?; + Some(SharedStack::of(&aps)) +} + +/// Do the appearances of `ids` differ (several objects whose stacks aren't all equal)? +pub(crate) fn appearances_differ(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> bool { + let mut aps = ids.iter().filter_map(|id| d.node(*id)).map(|n| &n.appearance); + let Some(first) = aps.next() else { return false }; + aps.any(|a| a != first) +} + +/// Indices `idx` of the first target's items (aligned with `aligned`) in each of `ids`: the first +/// target's own, and in each other one the items equal to them there (see [`SharedStack`]), each +/// index on its own: one the targets don't share is left out of the others (never taken as the +/// same index there). Not aligned, or one target: the same indices in each. +pub(crate) fn items_per_target(d: &vectorcraft_doc::Document, ids: &[NodeId], idx: &[usize], aligned: bool) -> Vec> { + match shared_stack(d, ids).filter(|_| aligned) { + Some(sh) => (0..ids.len()).map(|k| if k == 0 { idx.to_vec() } else { idx.iter().filter_map(|i| sh.item_in(*i, k)).collect() }).collect(), + None => vec![idx.to_vec(); ids.len()], + } +} + /// Whether the `target` param asks for the contents of groups and layers (see the module docs). fn targets_contents(p: &Value) -> Result { match p.get("target") { @@ -352,9 +402,11 @@ pub(crate) fn edit_items_then( return Ok(()); } let before = s.doc()?.doc.clone(); + let per = item.per_target(&before, ids); super::overprint::edit_counted(s, label, |d| { let mut edited = Vec::new(); - for id in ids { + for (id, item) in ids.iter().zip(&per) { + let Some(item) = item else { continue }; let Some(n) = d.node_mut(*id) else { continue }; let index = item.resolve(&n.appearance, fill, cmd)?; f(n, index)?; @@ -372,8 +424,10 @@ pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_ } /// Whether an edit aimed at `item` changes a stroke: the `stroke` param, else the kind of the -/// targeted item (on the first target object), else `default`. -pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool) -> Result { +/// targeted item (on the first target object), else `default`. A `stroke` other than true, false or +/// null is an error of command `cmd`. +pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool, cmd: &str) -> Result { + check_switches(p, &["stroke"], cmd)?; if let Some(b) = p.get("stroke").and_then(Value::as_bool) { return Ok(b); } @@ -383,8 +437,9 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo Ok(ids.first().and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill())) } +/// The whole number of 0 or more that `key` holds, read with [`index`]. pub(crate) fn index_param(p: &Value, key: &str, cmd: &str) -> Result { - p.get(key).and_then(Value::as_u64).map(|i| i as usize).ok_or_else(|| bad(cmd, format!("missing integer `{key}`"))) + p.get(key).and_then(Value::as_u64).map(index).ok_or_else(|| bad(cmd, format!("missing integer `{key}`"))) } fn set_active_item(s: &mut Session, p: &Value) -> Result { @@ -485,7 +540,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result { if source == target { return Err(bad(C, "`source` and `target` are the same object")); } - let copy = bool_or(p, "copy", false); + let copy = switch_or(p, "copy", false, C)?; // 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| { @@ -547,6 +602,9 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result { fn set_item(s: &mut Session, p: &Value) -> Result { let idx = index_param(p, "index", "appearance.setItem")?; + super::paint::check_keep_model(p, "appearance.setItem")?; + 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)?; if ids.is_empty() { @@ -556,8 +614,10 @@ fn set_item(s: &mut Session, p: &Value) -> Result { // When every object comes out as it was (for example, when none has item `index`), the document // and its undo history stay as they are. let before = s.doc()?.doc.clone(); + let per = items_per_target(&before, &ids, &[idx], aligned(p)); super::overprint::edit_counted(s, "Appearance", |d| { - for id in &ids { + for (id, at) in ids.iter().zip(&per) { + let Some(&idx) = at.first() else { continue }; let Some(n) = d.node_mut(*id) else { continue }; if p.get("weight").is_none() && let Some(pa) = &paint @@ -603,7 +663,7 @@ fn item_indices(p: &Value, cmd: &str) -> Result> { let mut v = match p.get("indices") { Some(a) => a .as_array() - .and_then(|a| a.iter().map(|x| x.as_u64().map(|i| i as usize)).collect::>>()) + .and_then(|a| a.iter().map(|x| x.as_u64().map(index)).collect::>>()) .filter(|v| !v.is_empty()) .ok_or_else(|| bad(cmd, "`indices` must be a non-empty array of item indices"))?, None => vec![index_param(p, "index", cmd)?], @@ -619,9 +679,12 @@ fn remove_item(s: &mut Session, p: &Value) -> Result { // When no object has an item at any of the indices, the document and its undo history stay as // they are. let before = s.doc()?.doc.clone(); + let per = items_per_target(&before, &ids, &idx, aligned(p)); super::overprint::edit_counted(s, "Remove Item", |d| { - for id in &ids { + for (id, idx) in ids.iter().zip(&per) { if let Some(n) = d.node_mut(*id) { + let mut idx = idx.clone(); + idx.sort_unstable(); // From the top down, so the lower indices stay valid. for &i in idx.iter().rev() { n.appearance.remove_item(i); @@ -644,11 +707,18 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { let ids = require_targets(s, p, C)?; // Where the first object's copy landed (the active item lives in the first object's stack). let mut first_at = None; + // Aligned rows of a mixed selection are copied right above themselves in each object. + if aligned(p) && to.is_some() && shared_stack(&s.doc()?.doc, &ids).is_some() { + return Err(bad(C, "`to` takes the rows of one object's stack, not aligned rows")); + } + let per = items_per_target(&s.doc()?.doc, &ids, &idx, aligned(p)); s.edit("Duplicate Item", |d, _| { let mut any = false; - for id in &ids { + for (id, idx) in ids.iter().zip(&per) { let Some(n) = d.node_mut(*id) else { continue }; let ap = &mut n.appearance; + let mut idx = idx.clone(); + idx.sort_unstable(); // From the top down, so the lower indices stay valid. for &i in idx.iter().rev() { if let Some(item) = ap.items.get(i).cloned() { @@ -691,6 +761,10 @@ fn move_item(s: &mut Session, p: &Value) -> Result { return move_contents(s, &ids, to); } let from = index_param(p, "from", C)?; + // Where an aligned row would go in each of several different stacks isn't one place. + if aligned(p) && appearances_differ(&s.doc()?.doc, &ids) { + return Err(bad(C, "rows of objects whose appearances differ can't be reordered together")); + } let contents = p.get("contents").map(|_| index_param(p, "contents", C)).transpose()?; let mut landed = to; // When every object's stack comes out as it was, the document and its undo history stay as they @@ -756,11 +830,13 @@ fn target_contents(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) } +/// Sample enabled attributes, refusing object transparency that a text range cannot store. fn copy_from(s: &mut Session, p: &Value) -> Result { const C: &str = "appearance.copyFrom"; let clicked = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?; - let (reverse, append) = (bool_or(p, "reverse", false), bool_or(p, "append", false)); + let (reverse, append) = (switch_or(p, "reverse", false, C)?, switch_or(p, "append", false, C)?); let attrs = s.prefs.eyedropper.attrs(p).map_err(|e| bad(C, e))?; + let range = if !reverse && !append && p.get("ids").is_none() { super::textedit::editing_range(s)?.filter(|(_, a, b)| a != b) } else { None }; let selected = match ids_param(p, "ids") { Some(v) => outermost(&s.doc()?.doc, v), None => selected_roots(s)?, @@ -774,12 +850,38 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { }; targets.retain(|id| *id != src_id); let picked = Picked::of(s.doc()?.doc.node(src_id).ok_or(EngineError::NoNode(src_id))?); + let range = range.filter(|(id, _, _)| targets.contains(id)); + // Character styles cannot represent object transparency. Refuse before even changing + // paint defaults; applying it to the object would also alter the unselected characters. + if let Some((id, _, _)) = range.filter(|_| attrs.appearance.transparency) { + let target = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?; + if picked.opacity != 1.0 || picked.blend != BlendMode::Normal || target.opacity != 1.0 || target.blend != BlendMode::Normal { + return Err(bad( + C, + "object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object", + )); + } + } if !reverse { picked.to_defaults(s, &attrs.appearance); } if targets.is_empty() || attrs.is_empty() { return Ok(json!({ "ids": [] })); } + if let Some((id, start, end)) = range { + let before = s.doc()?.doc.clone(); + super::overprint::edit_counted(s, "Eyedropper", |d| { + let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; + let placed = picked.placed(Some(t.local_bounds())); + vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| picked.run(st, &placed, &attrs)); + 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); + Ok(count_changed(d, &before, &[id])) + })?; + return Ok(json!({ "ids": [id.0] })); + } // 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| { @@ -841,6 +943,22 @@ 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) { + *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, + ..cs.clone() + }; + } + run_attrs(st, placed, &a.appearance); + } + /// 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. @@ -860,19 +978,7 @@ impl Picked { let placed = self.placed(Some(t.local_bounds())); let text = self.text.as_ref(); for r in &mut t.runs { - if let Some((cs, _)) = text.filter(|_| a.character) { - // The character attributes; the paints follow the appearance attributes. - let st = &mut r.style; - *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, - ..cs.clone() - }; - } - run_attrs(&mut r.style, &placed, ap); + self.run(&mut r.style, &placed, a); } 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/assets.rs b/crates/engine/src/cmd/assets.rs index a137271c59..c560a35c86 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -65,7 +65,7 @@ pub fn specs() -> Vec { } /// `e` as an error of command `cmd` (for errors of the export underneath). -fn of_cmd(cmd: &str, e: EngineError) -> EngineError { +pub(crate) fn of_cmd(cmd: &str, e: EngineError) -> EngineError { match e { EngineError::BadParams { msg, .. } => bad(cmd, msg), e => e, diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs new file mode 100644 index 0000000000..1c7de99787 --- /dev/null +++ b/crates/engine/src/cmd/brushlib.rs @@ -0,0 +1,502 @@ +//! Brush libraries (Window → Brush Libraries, the Brushes panel's library button): read-only sets +//! of brushes the library panel shows. A library is a document holding the brushes with the +//! resources their art uses (patterns, symbols, swatches, graphic styles, images); saved, it is a +//! native `.vectorcraft` file, which File › Open also opens. The built-in libraries are generated +//! here ([`BUILTIN`]); User Defined ones are the `.vectorcraft` files in the user library folder +//! ([`Libraries`]), and Other Library… loads the brushes of any document VectorCraft opens. +//! `brush.addFromLibrary` copies brushes into the document; `brush.saveLibrary` writes the +//! document's. + +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_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}; + +use super::brushsym::{apply_brush, brush_targets, roots, stroke_paint}; +use super::clipboard::Clipboard; +use super::clipboard::resources::SwatchChoices; +use super::patterncmds::add_pattern; +use super::swatch::str_list; +use super::swatchlib::{FileData, LibraryFile, LibraryInfo, stem}; +use super::*; + +/// The extension of saved brush libraries: native documents. +pub const BRUSHES_EXT: &str = vectorcraft_format::EXTENSION; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "brush.libraries", + "Brush Libraries", + [], + None, + "{} → {libraries: [{id, name, category: \"builtIn\"|\"user\" (User Defined: the .vectorcraft files in the user library folder, rescanned now)|\"loaded\" (brush.loadLibrary), count, path?}], userFolder} every brush library the library panel opens, in menu order", + always, + list + ), + cmd!( + query "brush.library", + "Brush Library", + [], + None, + "{library: id or name} → {id, name, category, brushes: [{name, type}] (as brush.list)}", + always, + get + ), + cmd!( + "brush.addFromLibrary", + "Add to Brushes", + ["Window", "Brush Libraries"], + None, + "{library: id or name, name? | names?: [brush names in the library] (default: all of it), apply?: false (also apply the first one to paths, as brush.apply does), ids?|id? (the paths apply takes; default the selected ones), swatchConflict? (as edit.paste)} copy library brushes into the document's Brushes as one undo step (with the apply; named Apply Brush when no brush is added and it only applies one), with the resources their art uses (patterns, symbols, swatches, graphic styles, images). A brush the document already has (same name and definition) isn't added again; a name another brush has gets a number (\"Ribbon 2\"). The first one becomes the current brush → {library, names: [each brush's name in the document], added: [names added], existing: [names already there], applied: [ids of the paths it was applied to]}", + has_doc, + add + ), + cmd!( + "brush.saveLibrary", + "Save Brush Library…", + ["Window", "Brushes"], + None, + "{path?, names?: [brush names] (default: all), name?: library name (default: the document's), user?: false (save into the user library folder, listed under User Defined)} save the document's brushes, with the resources their art uses, as a brush library: a .vectorcraft document holding only them → {path, count, library?: id when saved to the user folder}; without path or user → {dataBase64: the file's bytes, count}", + has_doc, + save + ), + cmd!( + "brush.loadLibrary", + "Other Library…", + ["Window", "Brush Libraries"], + None, + "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load the brushes of any document VectorCraft opens (see document.formats; one without brushes of its own has the default ones), a saved brush library included, for the library panel (Window → Brush Libraries lists it until the app quits; a file of the user library folder, or a file with the same bytes as one there, opens as that User Defined library) → {library: id, name, count}", + always, + load + ), + ] +} + +/// A brush library: its name, its brushes (in panel order) and a document holding them with the +/// resources their art uses; the document has no art of its own. +#[derive(Clone, Debug)] +pub struct BrushLibrary { + pub name: String, + pub brushes: Vec, + pub doc: Document, +} + +impl Default for BrushLibrary { + fn default() -> Self { + Self { name: String::new(), brushes: vec![], doc: Document::new(100.0, 100.0) } + } +} + +impl BrushLibrary { + pub fn len(&self) -> usize { + self.brushes.len() + } + pub fn is_empty(&self) -> bool { + self.brushes.is_empty() + } + pub fn brush(&self, name: &str) -> Option<&Brush> { + self.brushes.iter().find(|b| b.name == name) + } + + /// Document `src`'s brushes `names` (empty: all of them, in panel order) as a library named + /// `name`: the brushes and every resource their art uses. + pub fn from_document(src: &Document, names: &[String], name: String) -> std::result::Result { + let all = brush::library(src); + if let Some(n) = names.iter().find(|n| !all.iter().any(|b| b.name == **n)) { + return Err(format!("no brush `{n}`")); + } + let picked = all.iter().filter(|b| names.is_empty() || names.contains(&b.name)); + let clip = Clipboard::gather(src, picked.map(|b| stroke(&b.name)).collect()); + let mut doc = clip.to_document(); + for l in &mut doc.layers { + if let Some(ch) = Arc::make_mut(l).children_mut() { + ch.clear(); + } + } + // The brushes picked and those their art paints with, in the panel order of the document + // they came from. + let brushes: Vec = all.into_iter().filter(|b| clip.brushes.iter().any(|c| c.name == b.name)).collect(); + brush::store(&mut doc, &brushes); + doc.title = name.clone(); + Ok(Self { name, brushes, doc }) + } +} + +impl LibraryFile for BrushLibrary { + const EXTS: &'static [&'static str] = &[BRUSHES_EXT]; + fn read(bytes: &[u8], stem: &str) -> std::result::Result { + let doc = vectorcraft_format::load(bytes).map_err(|e| e.to_string())?; + BrushLibrary::from_document(&doc, &[], stem.to_string()) + } + fn name(&self) -> &str { + &self.name + } +} + +/// User Defined and loaded brush libraries. +pub type Libraries = super::swatchlib::Libraries; + +/// A path stroked with brush `name` (what the resource gathering follows). +fn stroke(name: &str) -> Node { + let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + if let Some(st) = ap.stroke_mut() { + st.brush = Some(name.into()); + } + let line = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0)], false); + Node::path(NodeId(0), PathData::single(line), ap) +} + +// ---------- built-in libraries ---------- + +/// A library generated in code. +pub struct BuiltinBrushLibrary { + pub id: &'static str, + pub name: &'static str, + make: fn() -> BrushLibrary, +} + +/// The built-in brush libraries, in menu order: original brushes generated in code, one library +/// per kind of brush. +pub const BUILTIN: &[BuiltinBrushLibrary] = &[ + BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons }, + BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs }, + BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders }, + BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes }, +]; + +/// Built-in library `id`, made once. +fn builtin_library(id: &str) -> Option> { + static MADE: LazyLock>> = LazyLock::new(|| BUILTIN.iter().map(|b| Arc::new((b.make)())).collect()); + BUILTIN.iter().position(|b| b.id == id).and_then(|i| MADE.get(i).cloned()) +} + +/// Library `name` of `brushes`, `doc` holding the resources their art uses. +fn built(name: &str, mut doc: Document, brushes: Vec) -> BrushLibrary { + brush::store(&mut doc, &brushes); + doc.title = name.into(); + BrushLibrary { name: name.into(), brushes, doc } +} + +fn filled(p: PathData, paint: Paint) -> Node { + Node::path(NodeId(0), p, Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(paint))], ..Default::default() }) +} + +fn black(p: PathData) -> Node { + filled(p, Paint::solid(Color::BLACK)) +} + +fn group(children: Vec) -> Node { + Node::group(NodeId(0), children.into_iter().map(Arc::new).collect()) +} + +fn polygon(pts: &[(f64, f64)]) -> PathData { + let pts: Vec = pts.iter().map(|&(x, y)| Point::new(x, y)).collect(); + PathData::single(SubPath::polyline(&pts, true)) +} + +/// A band along y = `f(x)` for x in 0..`len`, `thick` pt thick, in `n` steps. +fn band(len: f64, thick: f64, n: usize, f: impl Fn(f64) -> f64) -> PathData { + let xs: Vec = (0..=n).map(|i| len * i as f64 / n as f64).collect(); + let mut pts: Vec = xs.iter().map(|&x| Point::new(x, f(x) - thick / 2.0)).collect(); + pts.extend(xs.iter().rev().map(|&x| Point::new(x, f(x) + thick / 2.0))); + PathData::single(SubPath::polyline(&pts, true)) +} + +/// An even-odd ring of radii `outer` and `inner` around `c`. +fn ring(c: Point, outer: f64, inner: f64) -> Node { + let disc = |r: f64| shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)); + let children = [disc(outer), disc(inner)].into_iter().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::BLACK)))], ..Default::default() }.into(); + n +} + +fn art(name: &str, art: Node, colorization: Colorization) -> Brush { + Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) } +} + +/// Art Ribbons: art brushes, 100 pt long, drawn here; Striped Ribbon is filled with the library's +/// own pattern, Pinstripes. +fn art_ribbons() -> BrushLibrary { + let mut doc = Document::new(100.0, 100.0); + let stripe = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 1.5)), { + let mut a = Appearance::default(); + a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::from_hex("#2f80c9").unwrap_or(Color::BLACK))))); + a + }); + add_pattern(&mut doc, PatternDef { tile: Rect::new(0.0, 0.0, 6.0, 3.0), ..PatternDef::new("Pinstripes", vec![Arc::new(stripe)]) }); + let notched = polygon(&[(0.0, -3.0), (100.0, -3.0), (95.0, 0.0), (100.0, 3.0), (0.0, 3.0), (5.0, 0.0)]); + let double = group(vec![black(shapes::rectangle(Rect::new(0.0, -2.5, 100.0, -1.5))), black(shapes::rectangle(Rect::new(0.0, 1.5, 100.0, 2.5)))]); + let wave = band(100.0, 1.6, 64, |x| 2.5 * (x / 100.0 * 4.0 * std::f64::consts::TAU).sin()); + // Round and thick at the start, tapering to a point. + let teardrop = { + let n = 48; + let half = |x: f64| 3.5 * (1.0 - x / 100.0).powf(0.8) * (x / 4.0).min(1.0).sqrt(); + let xs = |i: usize| 100.0 * i as f64 / n as f64; + let mut pts: Vec = (0..=n).map(xs).map(|x| Point::new(x, -half(x))).collect(); + pts.extend((0..n).rev().map(xs).map(|x| Point::new(x, half(x)))); + PathData::single(SubPath::polyline(&pts, true)) + }; + let striped = { + let mut n = + filled(shapes::rectangle(Rect::new(0.0, -4.0, 100.0, 4.0)), Paint::Pattern { pattern: "Pinstripes".into(), xf: Default::default() }); + n.appearance.set_stroke(Paint::solid(Color::from_hex("#1d4f7c").unwrap_or(Color::BLACK))); + n + }; + let brushes = vec![ + art("Notched Ribbon", black(notched), Colorization::Tints), + art("Double Line", double, Colorization::Tints), + art("Wave", black(wave), Colorization::Tints), + art("Teardrop", black(teardrop), Colorization::Tints), + art("Striped Ribbon", striped, Colorization::None), + ]; + built("Art Ribbons", doc, 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() }) } +} + +/// Calligraphic Nibs: pen nibs of several shapes; Pressure Pen's size follows the pen pressure. +fn calligraphic_nibs() -> BrushLibrary { + let pressure = Brush { + name: "Pressure Pen".into(), + kind: BrushKind::Calligraphic(Calligraphic { + angle: 30.0, + roundness: 60.0, + size: 5.0, + variation: [0.0, 0.0, 4.0], + modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]), + }), + }; + let brushes = vec![ + nib("Fine Nib", 45.0, 25.0, 2.0), + nib("Broad Nib", 45.0, 15.0, 9.0), + nib("Chisel", 0.0, 8.0, 6.0), + nib("Round Pen", 0.0, 100.0, 4.0), + pressure, + ]; + built("Calligraphic Nibs", Document::new(100.0, 100.0), brushes) +} + +fn border(name: &str, side: Node, corner: Option, fit: PatternFit) -> Brush { + let kind = BrushKind::Pattern(PatternBrush { side, outer_corner: corner.clone(), inner_corner: corner, fit, ..Default::default() }); + Brush { name: name.into(), kind } +} + +/// An invisible rectangle that fixes a tile's width. +fn spacer(r: Rect) -> Node { + Node::path(NodeId(0), shapes::rectangle(r), Appearance::default()) +} + +/// Pattern Borders: pattern brushes of tiles drawn here; Beads has corner tiles. +fn pattern_borders() -> BrushLibrary { + let zigzag = black(polygon(&[(0.0, 1.4), (5.0, -2.6), (10.0, 1.4), (10.0, 2.6), (5.0, -1.4), (0.0, 2.6)])); + let beads = group(vec![black(shapes::rectangle(Rect::new(0.0, -0.3, 8.0, 0.3))), black(shapes::ellipse(Rect::new(1.5, -2.5, 6.5, 2.5)))]); + let dash_dot = group(vec![ + spacer(Rect::new(0.0, -1.0, 12.0, 1.0)), + black(shapes::rounded_rectangle(Rect::new(0.5, -0.75, 6.5, 0.75), 0.75)), + black(shapes::ellipse(Rect::new(8.5, -1.0, 10.5, 1.0))), + ]); + let scallops = black(band(10.0, 1.0, 20, |x| -3.0 * (x / 10.0 * std::f64::consts::PI).sin())); + let brushes = vec![ + border("Zigzag", zigzag, None, PatternFit::Stretch), + border("Beads", beads, Some(ring(Point::ZERO, 3.5, 1.5)), PatternFit::Stretch), + border("Dash Dot", dash_dot, None, PatternFit::AddSpace), + border("Scallops", scallops, None, PatternFit::Stretch), + ]; + built("Pattern Borders", Document::new(100.0, 100.0), brushes) +} + +fn scatter(name: &str, art: Node, s: Scatter) -> Brush { + Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) } +} + +/// Scatter Shapes: scatter brushes of shapes drawn here; Sparkles scatters the library's own +/// symbol, Sparkle. +fn scatter_shapes() -> BrushLibrary { + let mut doc = Document::new(100.0, 100.0); + // A four-pointed gold sparkle in the ±10 pt box symbol instances assume. + let points: Vec = (0..8) + .map(|i| { + let r = if i % 2 == 0 { 10.0 } else { 2.5 }; + let a = std::f64::consts::FRAC_PI_4 * i as f64; + Point::new(r * a.cos(), r * a.sin()) + }) + .collect(); + let gold = Color::from_hex("#e0a526").unwrap_or(Color::BLACK); + let sparkle = Node::path(doc.alloc_id(), PathData::single(SubPath::polyline(&points, true)), { + let mut a = Appearance::default(); + a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(gold)))); + a + }); + doc.symbols.push(Symbol { name: "Sparkle".into(), art: Arc::new(sparkle) }); + let instance = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Sparkle".into(), xf: Affine::scale(0.3) }); + let random = |a: f64, b: f64| (a, b); + let base = Scatter { colorization: Colorization::Tints, ..Default::default() }; + let brushes = vec![ + scatter( + "Stars", + black(shapes::star(Point::ZERO, 4.0, 1.7, 5, 0.0)), + Scatter { + size: random(70.0, 130.0), + spacing: random(150.0, 220.0), + scatter: random(-80.0, 80.0), + rotation: random(-180.0, 180.0), + ..base.clone() + }, + ), + scatter("Rings", ring(Point::ZERO, 2.5, 1.5), Scatter { spacing: (140.0, 140.0), ..base.clone() }), + scatter( + "Triangles", + black(shapes::polygon(Point::ZERO, 3.0, 3, 0.0)), + Scatter { spacing: (120.0, 120.0), rotation: (90.0, 90.0), rotation_relative_to_path: true, ..base.clone() }, + ), + scatter( + "Sparkles", + instance, + Scatter { + size: random(60.0, 140.0), + spacing: random(110.0, 180.0), + scatter: random(-60.0, 60.0), + rotation: random(-45.0, 45.0), + colorization: Colorization::None, + ..base + }, + ), + ]; + built("Scatter Shapes", doc, brushes) +} + +// ---------- commands ---------- + +fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo { + LibraryInfo { id: b.id.into(), name: b.name.into(), category: "builtIn" } +} + +/// Every brush library, in menu order: built-in, User Defined, loaded. +pub fn libraries(s: &Session) -> Vec { + BUILTIN.iter().map(builtin_info).chain(s.brush_libraries.infos().cloned()).collect() +} + +/// Library `key` (an id, or a name in any case) with its info. +pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc)> { + if let Some(found) = s.brush_libraries.get(key) { + return Some(found); + } + if let Some(b) = BUILTIN.iter().find(|b| b.id == key) { + return Some((builtin_info(b), builtin_library(key)?)); + } + let id = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key))?.id; + library(s, &id) +} + +fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc)> { + let key = str_param(p, "library").ok_or_else(|| bad(cmd, "missing `library` (see brush.libraries)"))?; + library(s, key).ok_or_else(|| bad(cmd, format!("no brush library `{key}` (see brush.libraries)"))) +} + +fn list(s: &mut Session, _: &Value) -> Result { + s.brush_libraries.rescan(); + let libs: Vec = libraries(s) + .into_iter() + .map(|l| { + let count = library(s, &l.id).map_or(0, |(_, lib)| lib.len()); + json!({"id": l.id, "name": l.name, "category": l.category, "count": count, "path": s.brush_libraries.path(&l.id)}) + }) + .collect(); + Ok(json!({ "libraries": libs, "userFolder": s.brush_libraries.user_dir() })) +} + +fn get(s: &mut Session, p: &Value) -> Result { + let (info, lib) = library_param(s, p, "brush.library")?; + let brushes: Vec = lib.brushes.iter().map(|b| json!({"name": b.name, "type": b.kind.type_id()})).collect(); + Ok(json!({"id": info.id, "name": info.name, "category": info.category, "brushes": brushes})) +} + +fn add(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.addFromLibrary"; + let (info, lib) = library_param(s, p, C)?; + let mut names = str_list(p, "names"); + names.extend(str_param(p, "name").map(str::to_string)); + if let Some(n) = names.iter().find(|n| lib.brush(n).is_none()) { + return Err(bad(C, format!("no brush `{n}` in `{}`", lib.name))); + } + let mut picked: Vec = if names.is_empty() { lib.brushes.iter().map(|b| b.name.clone()).collect() } else { names }; + // Each once, in the order asked for. + let mut seen = HashSet::new(); + picked.retain(|n| seen.insert(n.clone())); + let apply = bool_or(p, "apply", false); + if apply && picked.is_empty() { + return Err(bad(C, format!("`{}` has no brushes to apply", lib.name))); + } + let choices = SwatchChoices::parse(C, p)?; + let clip = Clipboard::gather(&lib.doc, picked.iter().map(|n| stroke(n)).collect()); + // The typing `s.edit` would settle first is settled before the probe below, so the document + // the edit installs is the one it starts from. + if !s.previewing && super::typing_in_progress(s) { + super::settle_interaction(s)?; + } + let st = s.doc()?; + let before: HashSet = brush::library(&st.doc).into_iter().map(|b| b.name).collect(); + // A library brush's name in the document: its own, or the one the import gave it. + let target = |renamed: &[Value], n: &str| -> String { + let to = renamed.iter().find(|r| r["kind"] == "brush" && r["from"] == n).and_then(|r| r["to"].as_str()); + to.unwrap_or(n).to_string() + }; + // Where the brushes land, worked out on a copy that the edit then installs: nothing to add and + // nothing to apply is no edit, and a click that only applies brushes the document has is + // named for that. + let mut probe = (*st.doc).clone(); + let imported = clip.import_into(&mut probe, &choices, false); + let doc_names: Vec = picked.iter().map(|n| target(&imported.renamed, n)).collect(); + let paths = if apply { brush_targets(&st.doc, &roots(s, p)?) } else { vec![] }; + let paint = stroke_paint(s); + if imported.added > 0 || !paths.is_empty() { + let label = if imported.added > 0 { "Add to Brushes" } else { "Apply Brush" }; + s.edit(label, |d, _| { + *d = probe; + if let Some(first) = doc_names.first() { + d.unknown.insert(brush::CURRENT_KEY.into(), json!(first)); + apply_brush(d, &paths, first, &paint); + } + Ok(()) + })?; + } else if let Some(first) = doc_names.first() { + s.execute("brush.setCurrent", &json!({ "name": first }))?; + } + let (added, existing): (Vec<&String>, Vec<&String>) = doc_names.iter().partition(|n| !before.contains(*n)); + let applied: Vec = paths.iter().map(|id| id.0).collect(); + Ok(json!({"library": info.id, "names": doc_names, "added": added, "existing": existing, "applied": applied})) +} + +fn save(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.saveLibrary"; + let st = s.doc()?; + let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string); + let lib = BrushLibrary::from_document(&st.doc, &str_list(p, "names"), name).map_err(|e| bad(C, e))?; + if lib.is_empty() { + return Err(bad(C, "the document has no brushes to save")); + } + let mut out = json!({ "count": lib.len() }); + let bytes = vectorcraft_format::save_file(&lib.doc); + s.brush_libraries.write(p, &lib.name, BRUSHES_EXT, FileData::Binary(bytes), &mut out, C)?; + Ok(out) +} + +fn load(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.loadLibrary"; + let (info, lib) = s.brush_libraries.load(p, C, |bytes, file| { + let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?; + if loaded.preview_only { + return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning")); + } + BrushLibrary::from_document(&loaded.doc, &[], stem(file).to_string()).map_err(|e| bad(C, e)) + })?; + Ok(json!({"library": info.id, "name": info.name, "count": lib.len()})) +} diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 61e9949935..b677b30036 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -6,22 +6,37 @@ //! `Node::geometric_bounds` assumes for instances, and each instance's `xf` scales it back. The //! natural size is kept in `Document::unknown["symbolSizes"]` so new instances come out right. +use std::collections::BTreeSet; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_brush::{self as brush, Brush}; +use vectorcraft_brush::{self as brush, Bristle, Brush, BrushKind}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration}; use vectorcraft_geom::{Affine, Point, Vec2}; use super::edit::{outermost, selected_roots}; use super::pathops::{remove_each, separate}; -use super::swatch::names_param; +use super::swatch::{anchor, names_param}; use super::*; use crate::EngineError; +mod brushes; +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, +}; +pub(crate) use symbols::{natural_size, normalize, place_xf, set_natural_size}; +use symbols::{ + symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_edit, symbol_list, symbol_new, symbol_options, symbol_place, + symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_update, +}; + const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES; -const CURRENT_SYMBOL: &str = "currentSymbol"; +pub(crate) const CURRENT_SYMBOL: &str = "currentSymbol"; /// Half the instance box `Node::geometric_bounds` uses for symbol instances. const HALF: f64 = vectorcraft_doc::SYMBOL_HALF; @@ -30,6 +45,15 @@ pub fn specs() -> Vec { // ----- brushes ----- cmd!(query "brush.list", "Brushes", [], None, "{} → {brushes: [{name, type}], current}", has_doc, brush_list), cmd!(query "brush.get", "Brush Definition", [], None, "{name} → the brush definition (JSON)", has_doc, brush_get), + cmd!( + query "brush.selectionArt", + "Brush Art", + [], + None, + "{ids?|id?} → {art: the object brush.new takes as a new scatter or art brush's art and as a new pattern brush's side tile (several objects become one group), or null when nothing is selected or ids name no object}", + has_doc, + brush_selection_art + ), cmd!( "brush.apply", "Apply Brush", @@ -62,7 +86,7 @@ pub fn specs() -> Vec { "New Brush…", [], None, - "{type: calligraphic|scatter|art|pattern|bristle, name? (trimmed; blank: New Brush), params?: {…definition fields}, ids?|id?} new brush; art/scatter/pattern brushes take the selected art (pattern: side tile) unless params give it → {name}", + "{type: calligraphic|scatter|art|pattern|bristle, name? (trimmed; blank: New Brush; a bristle brush name, with the number a taken name gets, has at most 31 characters), params?: {…definition fields}, ids?|id?} new brush; art/scatter/pattern brushes take the selected art (pattern: side tile) unless params give it → {name}", has_doc, brush_new ), @@ -75,6 +99,15 @@ pub fn specs() -> Vec { has_doc, brush_delete ), + cmd!( + "brush.move", + "Move Brush", + [], + None, + "{name? | names?: [brush names of one type, in order], to?: index among the brushes of that type in brush.list order (they go before the brush of that type now there that isn't moving; default: after the last one), type?: calligraphic|scatter|art|pattern|bristle (the type they go into; default: theirs)} reorder brushes within their type, as one undo step (none when the order stays as it was); brushes of different types, or a type that isn't theirs, are refused (brushes move only within their type) → {moved}", + has_doc, + brush_move + ), cmd!( "brush.duplicate", "Duplicate Brush", @@ -84,12 +117,21 @@ pub fn specs() -> Vec { has_doc, brush_duplicate ), + cmd!( + query "brush.unused", + "Select All Unused", + [], + None, + "{} → {names: [the brushes no stroke paints with, in library order]} (the Brushes panel selects them): strokes in the art (opacity masks included), symbols, graph designs, pattern tiles and graphic styles count, and so do strokes in the art of a brush that is used", + has_doc, + brush_unused + ), cmd!( "brush.options", "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour)}}, newName? (trimmed; blank: the name is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across. 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 ), @@ -118,7 +160,7 @@ pub fn specs() -> Vec { "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array} make a symbol from the selection and replace it with an instance; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a third each) → {name, id, registration, exportType, nineSlice}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a third each) → {name, id, registration, exportType, nineSlice}", has_selection, symbol_new ), @@ -163,7 +205,7 @@ pub fn specs() -> Vec { "Redefine Symbol", [], None, - "{name, ids?|id?} replace the symbol's art with the selection (instances update; the selection becomes an instance) → {name, id}", + "{name, ids?|id?} replace the symbol's art with the selection (instances update; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}", has_selection, symbol_update ), @@ -221,7 +263,7 @@ fn ids_json(ids: &[NodeId]) -> Value { Value::Array(ids.iter().map(|i| Value::from(i.0)).collect()) } -fn roots(s: &Session, p: &Value) -> Result> { +pub(crate) fn roots(s: &Session, p: &Value) -> Result> { match ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])) { Some(mut v) => { // Explicit ids: only existing, non-layer objects, none inside another of them. @@ -238,80 +280,6 @@ fn name_param<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> { str_param(p, "name").filter(|n| !n.trim().is_empty()).ok_or_else(|| bad(cmd, "missing `name`")) } -// ---------- brushes ---------- - -/// Brushable nodes (paths and compound paths) under `ids`. -fn brush_targets(d: &Document, ids: &[NodeId]) -> Vec { - let mut out = vec![]; - for id in ids { - let Some(n) = d.node(*id) else { continue }; - n.walk(&mut |c| { - let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }); - let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); - if own && !in_compound && !out.contains(&c.id) { - out.push(c.id); - } - }); - } - out -} - -fn brush_list(s: &mut Session, _: &Value) -> Result { - let d = &s.doc()?.doc; - let list: Vec = brush::library(d).iter().map(|b| json!({"name": b.name, "type": b.kind.type_id()})).collect(); - Ok(json!({ "brushes": list, "current": brush::current(d) })) -} - -fn brush_get(s: &mut Session, p: &Value) -> Result { - let name = name_param(p, "brush.get")?; - let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?; - Ok(serde_json::to_value(b).unwrap_or_default()) -} - -fn brush_apply(s: &mut Session, p: &Value) -> Result { - const C: &str = "brush.apply"; - let name = name_param(p, C)?.to_string(); - if brush::find(&s.doc()?.doc, &name).is_none() { - return Err(bad(C, format!("no brush named `{name}`"))); - } - let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?); - let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() }; - s.edit("Apply Brush", |d, _| { - d.unknown.insert(brush::CURRENT_KEY.into(), json!(name)); - for id in &ids { - let Some(n) = d.node_mut(*id) else { continue }; - if n.appearance.stroke().is_none_or(|st| st.paint.is_none()) { - n.appearance.set_stroke(stroke.clone()); - } - if let Some(st) = n.appearance.stroke_mut() { - if st.width <= 0.0 { - st.width = 1.0; - } - st.brush = Some(name.clone()); - } - } - Ok(()) - })?; - Ok(json!({ "ids": ids_json(&ids) })) -} - -fn brush_remove(s: &mut Session, p: &Value) -> Result { - let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?); - s.edit("Remove Brush Stroke", |d, _| { - for id in &ids { - if let Some(n) = d.node_mut(*id) { - for it in &mut n.appearance.items { - if let AppearanceItem::Stroke(st) = it { - st.brush = None; - } - } - } - } - Ok(()) - })?; - Ok(json!({ "ids": ids_json(&ids) })) -} - /// Set a document preference outside the undo history. fn set_unknown(s: &mut Session, key: &str, v: Option) -> Result<()> { let st = s.doc_mut()?; @@ -323,19 +291,6 @@ fn set_unknown(s: &mut Session, key: &str, v: Option) -> Result<()> { Ok(()) } -fn brush_set_current(s: &mut Session, p: &Value) -> Result { - match str_param(p, "name") { - Some(n) => { - if brush::find(&s.doc()?.doc, n).is_none() { - return Err(bad("brush.setCurrent", format!("no brush named `{n}`"))); - } - set_unknown(s, brush::CURRENT_KEY, Some(json!(n)))?; - } - None => set_unknown(s, brush::CURRENT_KEY, None)?, - } - ok() -} - /// The selection as one art node (a group for several objects), ids kept. pub(crate) fn selection_art(s: &Session, p: &Value) -> Result> { let d = &s.doc()?.doc; @@ -347,860 +302,3 @@ pub(crate) fn selection_art(s: &Session, p: &Value) -> Result> { _ => Some(Node::group(NodeId(0), nodes.into_iter().map(Arc::new).collect())), }) } - -fn merge(base: &mut Value, patch: &Value) { - if let (Some(b), Some(pt)) = (base.as_object_mut(), patch.as_object()) { - for (k, v) in pt { - b.insert(k.clone(), v.clone()); - } - } -} - -fn save_library(s: &mut Session, label: &str, lib: Vec, renames: &[(String, Option)]) -> Result<()> { - s.edit(label, |d, _| { - brush::store(d, &lib); - for (from, to) in renames { - let ids: Vec = { - let mut v = vec![]; - d.walk(|n| { - if n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if st.brush.as_deref() == Some(from.as_str()))) { - v.push(n.id); - } - }); - v - }; - for id in ids { - if let Some(n) = d.node_mut(id) { - for it in &mut n.appearance.items { - if let AppearanceItem::Stroke(st) = it - && st.brush.as_deref() == Some(from.as_str()) - { - st.brush = to.clone(); - } - } - } - } - if brush::current(d).as_deref() == Some(from.as_str()) { - match to { - Some(t) => d.unknown.insert(brush::CURRENT_KEY.into(), json!(t)), - None => d.unknown.remove(brush::CURRENT_KEY), - }; - } - } - Ok(()) - }) -} - -fn brush_new(s: &mut Session, p: &Value) -> Result { - const C: &str = "brush.new"; - let ty = str_param(p, "type").ok_or_else(|| bad(C, "missing `type`"))?; - let art_key = match ty { - "calligraphic" | "bristle" => None, - "scatter" | "art" => Some("art"), - "pattern" => Some("side"), - o => return Err(bad(C, format!("unknown brush type `{o}`"))), - }; - let mut lib = brush::library(&s.doc()?.doc); - let given = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()); - let base_name = given.map_or_else(|| format!("New {} Brush", ty[..1].to_uppercase() + &ty[1..]), str::to_string); - let name = brush::unique_name(&lib, &base_name); - let mut v = json!({"name": name, "type": ty}); - if let Some(params) = p.get("params") { - merge(&mut v, params); - v["name"] = json!(name); - v["type"] = json!(ty); - } - if let Some(k) = art_key - && 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) { - return Err(bad(C, "the selected art has no width")); - } - v[k] = serde_json::to_value(&art).unwrap_or_default(); - } - lib.push(parse_brush(C, v)?); - save_library(s, "New Brush", lib, &[])?; - Ok(json!({ "name": name })) -} - -/// A brush definition from command params, its values kept within their ranges. -fn parse_brush(cmd: &str, v: Value) -> Result { - let mut b: Brush = serde_json::from_value(v).map_err(|e| bad(cmd, format!("invalid brush: {e}")))?; - b.sanitize(); - Ok(b) -} - -fn brush_delete(s: &mut Session, p: &Value) -> Result { - const C: &str = "brush.delete"; - let names = names_param(p, C)?; - let mut lib = brush::library(&s.doc()?.doc); - if let Some(name) = names.iter().find(|n| !lib.iter().any(|b| &b.name == *n)) { - return Err(bad(C, format!("no brush named `{name}`"))); - } - lib.retain(|b| !names.contains(&b.name)); - let renames: Vec<(String, Option)> = names.into_iter().map(|n| (n, None)).collect(); - save_library(s, "Delete Brush", lib, &renames)?; - ok() -} - -/// Adds a copy of each brush in `name` or `names` at the end of the library. `newName`, given -/// without `names`, names the copy. -fn brush_duplicate(s: &mut Session, p: &Value) -> Result { - const C: &str = "brush.duplicate"; - let names = names_param(p, C)?; - let before = brush::library(&s.doc()?.doc); - let mut lib = before.clone(); - let mut out = vec![]; - for name in &names { - let mut b = before.iter().find(|b| &b.name == name).cloned().ok_or_else(|| bad(C, format!("no brush named `{name}`")))?; - let given = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty() && p.get("names").is_none()); - let new_name = given.map_or_else(|| format!("{} copy", name.trim()), str::to_string); - b.name = brush::unique_name(&lib, &new_name); - out.push(b.name.clone()); - lib.push(b); - } - save_library(s, "Duplicate Brush", lib, &[])?; - Ok(if p.get("names").is_some() { json!({ "names": out }) } else { json!({ "name": out.first() }) }) -} - -fn brush_options(s: &mut Session, p: &Value) -> Result { - const C: &str = "brush.options"; - let name = name_param(p, C)?.to_string(); - 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}`")))?; - let mut v = serde_json::to_value(&lib[i]).unwrap_or_default(); - if let Some(params) = p.get("params") { - merge(&mut v, params); - } - let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty() && *n != name).map(str::to_string); - if let Some(nn) = &new_name { - if lib.iter().any(|b| &b.name == nn) { - return Err(bad(C, format!("a brush named `{nn}` exists"))); - } - v["name"] = json!(nn); - } else { - v["name"] = json!(name); - } - v["type"] = json!(lib[i].kind.type_id()); - lib[i] = parse_brush(C, v)?; - let out = lib[i].name.clone(); - let rename = new_name.map(|nn| (name, Some(nn))); - save_library(s, "Brush Options", lib, rename.as_slice())?; - Ok(json!({ "name": out })) -} - -fn expand_brush(s: &mut Session, p: &Value) -> Result { - let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?); - let ids: Vec = ids.into_iter().filter(|id| s.doc().ok().and_then(|st| st.doc.node(*id)).is_some_and(brush::has_brush)).collect(); - if ids.is_empty() { - return Err(EngineError::Other("Expand: no brush strokes selected".into())); - } - let out = s.edit("Expand", |d, sel| { - let mut out = vec![]; - for id in &ids { - let Some(n) = d.node(*id).cloned() else { continue }; - let Some(g) = brush::expand(d, &n) else { continue }; - let g = d.reid(&g); - let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?; - let gid = g.id; - d.remove(*id)?; - d.insert(par, idx, g)?; - out.push(gid); - } - sel.set(out.iter().copied()); - Ok(out) - })?; - Ok(json!({ "ids": ids_json(&out) })) -} - -fn brush_freehand(s: &mut Session, p: &Value) -> Result { - let name = str_param(p, "brush").map(str::to_string).filter(|n| s.doc().is_ok_and(|st| brush::find(&st.doc, n).is_some())); - let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?; - let r = (spec.run)(s, p)?; - let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) }; - s.edit("Paintbrush", |d, _| { - if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { - st.brush = Some(name.clone()); - } - Ok(()) - })?; - Ok(r) -} - -// ---------- symbols ---------- - -fn natural_size(d: &Document, name: &str) -> (f64, f64) { - d.unknown - .get(SIZES_KEY) - .and_then(|m| m.get(name)) - .and_then(|v| Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?))) - .unwrap_or((2.0 * HALF, 2.0 * HALF)) -} - -fn set_natural_size(d: &mut Document, name: &str, size: Option<(f64, f64)>) { - let m = d.unknown.entry(SIZES_KEY.to_string()).or_insert_with(|| json!({})); - if let Some(o) = m.as_object_mut() { - match size { - Some((w, h)) => o.insert(name.into(), json!([w, h])), - None => o.remove(name), - }; - } -} - -/// Instance transform for a symbol of natural size `(w, h)` whose registration point is at `at`. -fn place_xf(at: Point, (w, h): (f64, f64), reg: SymbolRegistration) -> Affine { - let c = at - reg.offset_from_center(w, h); - Affine::translate(c.to_vec2()) * Affine::scale_non_uniform(w / (2.0 * HALF), h / (2.0 * HALF)) -} - -fn registration_param(p: &Value, cmd: &str) -> Result> { - match p.get("registration") { - None => Ok(None), - Some(v) => v.as_u64().and_then(SymbolRegistration::from_u64).map(Some).ok_or_else(|| bad(cmd, "registration must be 0..8")), - } -} - -fn export_type_param(p: &Value, cmd: &str) -> Result> { - match str_param(p, "exportType") { - None => Ok(None), - Some(s) => SymbolExportType::from_id(s).map(Some).ok_or_else(|| bad(cmd, format!("exportType must be movieClip or graphic, not `{s}`"))), - } -} - -/// `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 the centre third, when none are given). -fn nine_slice_param(p: &Value, cmd: &str, current: Option) -> Result>> { - 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") - })?), - }; - Ok(match (on, guides) { - (Some(false), _) => Some(None), - (None, None) => None, - (_, Some(g)) => Some(Some(g)), - (Some(true), None) => Some(Some(current.unwrap_or_default())), - }) -} - -fn nine_slice_json(d: &Document, name: &str) -> Value { - d.symbol_nine_slice(name).map_or(Value::Null, SymbolNineSlice::to_value) -} - -fn rename_natural_size(d: &mut Document, from: &str, to: &str) { - if from == to { - return; - } - let size = d.unknown.get(SIZES_KEY).and_then(|m| m.get(from)).cloned(); - set_natural_size(d, from, None); - if let Some(v) = size - && let (Some(w), Some(h)) = (v.get(0).and_then(Value::as_f64), v.get(1).and_then(Value::as_f64)) - { - set_natural_size(d, to, Some((w, h))); - } -} - -/// Normalise art for a symbol definition: returns (art, natural size, centre in the document). -fn normalize(mut art: Node) -> Result<(Node, (f64, f64), Point)> { - let b = art.geometric_bounds().ok_or_else(|| EngineError::Other("the art has no bounds".into()))?; - let (w, h) = (b.width().max(1.0), b.height().max(1.0)); - let c = b.center(); - let n = Affine::scale_non_uniform(2.0 * HALF / w, 2.0 * HALF / h) * Affine::translate(-c.to_vec2()); - art.transform(n, false); - Ok((art, (w, h), c)) -} - -fn instances_of(d: &Document, name: Option<&str>) -> Vec { - let mut v = vec![]; - d.walk(|n| { - if let NodeKind::SymbolInstance { symbol, .. } = &n.kind - && name.is_none_or(|x| x == symbol) - { - v.push(n.id); - } - }); - v -} - -fn symbol_names(d: &Document) -> Vec { - d.symbols.iter().map(|s| s.name.clone()).collect() -} - -fn current_symbol(d: &Document) -> Option { - d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string) -} - -fn symbol_list(s: &mut Session, _: &Value) -> Result { - let d = &s.doc()?.doc; - let list: Vec = d - .symbols - .iter() - .map(|sym| { - let (w, h) = natural_size(d, &sym.name); - json!({ - "name": sym.name, - "instances": instances_of(d, Some(&sym.name)).len(), - "size": [w, h], - "registration": d.symbol_registration(&sym.name).0, - "exportType": d.symbol_export_type(&sym.name).id(), - "nineSlice": nine_slice_json(d, &sym.name), - }) - }) - .collect(); - Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) })) -} - -/// Replace the root nodes `ids` with one instance of `name` (art already stored). Returns the id. -fn replace_with_instance(d: &mut Document, ids: &[NodeId], name: &str, xf: Affine) -> Result { - let top = *ids.last().ok_or_else(|| EngineError::Other("nothing selected".into()))?; - if separate(d, ids) { - let id = d.alloc_id(); - return Ok(d.wrap(ids, |_| Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf }))?); - } - let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?; - let id = d.alloc_id(); - d.insert(par, idx + 1, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf }))?; - for r in ids { - d.remove(*r)?; - } - Ok(id) -} - -fn symbol_new(s: &mut Session, p: &Value) -> Result { - const C: &str = "symbol.new"; - let ids = roots(s, p)?; - let art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?; - let (art, size, c) = normalize(art)?; - let name = s.doc()?.doc.unique_symbol_name(str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("New Symbol")); - let reg = registration_param(p, C)?.unwrap_or(SymbolRegistration::CENTER); - let export = export_type_param(p, C)?.unwrap_or_default(); - let nine = nine_slice_param(p, C, None)?.flatten(); - // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. - let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); - let id = s.edit("New Symbol", |d, sel| { - let art = d.reid(&art); - d.symbols.push(Symbol { name: name.clone(), art: Arc::new(art) }); - set_natural_size(d, &name, Some(size)); - d.set_symbol_registration(&name, reg); - d.set_symbol_export_type(&name, export); - d.set_symbol_nine_slice(&name, nine); - d.unknown.insert(CURRENT_SYMBOL.into(), json!(name)); - let id = replace_with_instance(d, &ids, &name, place)?; - sel.set([id]); - Ok(id) - })?; - Ok( - json!({ "name": name, "id": id.0, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }), - ) -} - -fn symbol_options(s: &mut Session, p: &Value) -> Result { - const C: &str = "symbol.options"; - let name = resolve_symbol(&s.doc()?.doc, p, C)?; - let export = export_type_param(p, C)?; - let reg = registration_param(p, C)?; - let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?; - let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); - if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() { - return Err(bad(C, "pass newName, registration, exportType and/or nineSlice")); - } - if let Some(ref n) = new_name - && n != &name - && s.doc()?.doc.symbols.iter().any(|x| x.name == *n) - { - return Err(bad(C, format!("a symbol named `{n}` already exists"))); - } - let final_name = new_name.clone().unwrap_or_else(|| name.clone()); - s.edit("Symbol Options", |d, _| { - if let Some(ref n) = new_name - && n != &name - { - if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) { - sym.name = n.clone(); - } - for id in instances_of(d, Some(&name)) { - if let Some(NodeKind::SymbolInstance { symbol, .. }) = d.node_mut(id).map(|node| &mut node.kind) { - *symbol = n.clone(); - } - } - rename_natural_size(d, &name, n); - d.rename_symbol_registration(&name, n); - d.rename_symbol_export_type(&name, n); - d.rename_symbol_nine_slice(&name, n); - if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { - d.unknown.insert(CURRENT_SYMBOL.into(), json!(n)); - } - } - if let Some(r) = reg { - d.set_symbol_registration(&final_name, r); - } - if let Some(kind) = export { - d.set_symbol_export_type(&final_name, kind); - } - if let Some(g) = nine { - d.set_symbol_nine_slice(&final_name, g); - } - Ok(()) - })?; - let d = &s.doc()?.doc; - Ok(json!({ - "name": final_name, - "registration": d.symbol_registration(&final_name).0, - "exportType": d.symbol_export_type(&final_name).id(), - "nineSlice": nine_slice_json(d, &final_name), - })) -} - -fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result { - match str_param(p, "name") { - Some(n) if d.symbols.iter().any(|s| s.name == n) => Ok(n.to_string()), - Some(n) => Err(bad(cmd, format!("no symbol named `{n}`"))), - None => { - current_symbol(d).or_else(|| symbol_names(d).into_iter().next()).ok_or_else(|| EngineError::Other("the document has no symbols".into())) - } - } -} - -fn symbol_place(s: &mut Session, p: &Value) -> Result { - let d = &s.doc()?.doc; - let name = resolve_symbol(d, p, "symbol.place")?; - let centre = d.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); - let at = Point::new(f64_or(p, "x", centre.x), f64_or(p, "y", centre.y)); - let size = natural_size(d, &name); - let reg = d.symbol_registration(&name); - let parent = s.doc()?.target_parent()?; - let id = s.edit("Place Symbol Instance", |d, sel| { - let id = d.alloc_id(); - d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?; - sel.set([id]); - Ok(id) - })?; - Ok(json!({ "id": id.0 })) -} - -/// The plain art of instance `inst` in document space (fresh ids). -fn expanded_instance(d: &mut Document, inst: &Node) -> Option { - let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None }; - let sym = d.symbols.iter().find(|s| &s.name == symbol)?; - let mut art = (*sym.art).clone(); - if let Some(f) = inst.appearance.fill() - && let Some(c) = f.paint.color() - { - brush::tint_node(&mut art, &c, f.opacity); - } - art.transform(*xf, false); - let mut art = d.reid(&art); - if inst.opacity < 1.0 || inst.blend != vectorcraft_color::BlendMode::Normal { - if !matches!(art.kind, NodeKind::Group { .. }) { - let id = d.alloc_id(); - art = Node::group(id, vec![Arc::new(art)]); - } - art.opacity *= inst.opacity; - art.blend = inst.blend; - } - Some(art) -} - -fn break_links(d: &mut Document, ids: &[NodeId]) -> Result> { - let mut out = vec![]; - for id in ids { - let Some(inst) = d.node(*id).cloned() else { continue }; - let Some(art) = expanded_instance(d, &inst) else { continue }; - let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?; - let aid = art.id; - d.remove(*id)?; - d.insert(par, idx, art)?; - out.push(aid); - } - Ok(out) -} - -fn selected_instances(s: &Session, p: &Value) -> Result> { - let d = &s.doc()?.doc; - let mut out = vec![]; - for id in roots(s, p)? { - if let Some(n) = d.node(id) { - n.walk(&mut |c| { - if matches!(c.kind, NodeKind::SymbolInstance { .. }) { - out.push(c.id); - } - }); - } - } - Ok(out) -} - -fn symbol_break_link(s: &mut Session, p: &Value) -> Result { - let ids = selected_instances(s, p)?; - if ids.is_empty() { - return Err(EngineError::Other("no symbol instances selected".into())); - } - let out = s.edit("Break Link to Symbol", |d, sel| { - let out = break_links(d, &ids)?; - sel.set(out.iter().copied()); - Ok(out) - })?; - Ok(json!({ "ids": ids_json(&out) })) -} - -fn symbol_edit(s: &mut Session, p: &Value) -> Result { - let ids = selected_instances(s, p)?; - let first = *ids.first().ok_or_else(|| EngineError::Other("select a symbol instance".into()))?; - let name = match &s.doc()?.doc.node(first).map(|n| n.kind.clone()) { - Some(NodeKind::SymbolInstance { symbol, .. }) => symbol.clone(), - _ => return Err(EngineError::Other("select a symbol instance".into())), - }; - let out = s.edit("Edit Symbol", |d, sel| { - let out = break_links(d, &[first])?; - sel.set(out.iter().copied()); - Ok(out) - })?; - Ok(json!({ "name": name, "ids": ids_json(&out) })) -} - -fn symbol_update(s: &mut Session, p: &Value) -> Result { - const C: &str = "symbol.update"; - let name = name_param(p, C)?.to_string(); - if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) { - return Err(bad(C, format!("no symbol named `{name}`"))); - } - let ids = roots(s, p)?; - let art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?; - let (art, size, c) = normalize(art)?; - let old = natural_size(&s.doc()?.doc, &name); - let id = s.edit("Redefine Symbol", |d, sel| { - let art = d.reid(&art); - if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) { - sym.art = Arc::new(art); - } - set_natural_size(d, &name, Some(size)); - let fix = Affine::scale_non_uniform(size.0 / old.0, size.1 / old.1); - for i in instances_of(d, Some(&name)) { - if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(i).map(|n| &mut n.kind) { - *xf *= fix; - } - } - let reg = d.symbol_registration(&name); - let id = replace_with_instance(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?; - sel.set([id]); - Ok(id) - })?; - Ok(json!({ "name": name, "id": id.0 })) -} - -fn symbol_delete(s: &mut Session, p: &Value) -> Result { - const C: &str = "symbol.delete"; - let name = name_param(p, C)?.to_string(); - if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) { - return Err(bad(C, format!("no symbol named `{name}`"))); - } - let expand = bool_or(p, "expandInstances", true); - s.edit("Delete Symbol", |d, _| { - let inst = instances_of(d, Some(&name)); - if expand { - break_links(d, &inst)?; - } else { - remove_each(d, &inst)?; - } - d.symbols.retain(|x| x.name != name); - set_natural_size(d, &name, None); - d.set_symbol_registration(&name, SymbolRegistration::CENTER); - d.clear_symbol_export_type(&name); - d.set_symbol_nine_slice(&name, None); - if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { - d.unknown.remove(CURRENT_SYMBOL); - } - Ok(()) - })?; - ok() -} - -fn symbol_duplicate(s: &mut Session, p: &Value) -> Result { - const C: &str = "symbol.duplicate"; - let name = name_param(p, C)?.to_string(); - let d = &s.doc()?.doc; - let sym = d.symbols.iter().find(|x| x.name == name).cloned().ok_or_else(|| bad(C, format!("no symbol named `{name}`")))?; - let given = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()); - let new = d.unique_symbol_name(&given.map_or_else(|| format!("{} copy", name.trim()), str::to_string)); - let size = natural_size(d, &name); - let reg = d.symbol_registration(&name); - let export = d.symbol_export_type(&name); - let nine = d.symbol_nine_slice(&name); - s.edit("Duplicate Symbol", |d, _| { - let art = d.reid(&sym.art); - d.symbols.push(Symbol { name: new.clone(), art: Arc::new(art) }); - set_natural_size(d, &new, Some(size)); - d.set_symbol_registration(&new, reg); - d.set_symbol_export_type(&new, export); - d.set_symbol_nine_slice(&new, nine); - Ok(()) - })?; - Ok(json!({ "name": new, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) })) -} - -fn symbol_replace(s: &mut Session, p: &Value) -> Result { - const C: &str = "symbol.replace"; - let name = name_param(p, C)?.to_string(); - if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) { - return Err(bad(C, format!("no symbol named `{name}`"))); - } - let ids = selected_instances(s, p)?; - if ids.is_empty() { - return Err(EngineError::Other("no symbol instances selected".into())); - } - s.edit("Replace Symbol", |d, _| { - let new = natural_size(d, &name); - for id in &ids { - let old = match d.node(*id).map(|n| &n.kind) { - Some(NodeKind::SymbolInstance { symbol, .. }) => natural_size(d, symbol), - _ => continue, - }; - if let Some(NodeKind::SymbolInstance { symbol, xf }) = d.node_mut(*id).map(|n| &mut n.kind) { - *symbol = name.clone(); - *xf *= Affine::scale_non_uniform(new.0 / old.0, new.1 / old.1); - } - } - Ok(()) - })?; - Ok(json!({ "ids": ids_json(&ids) })) -} - -fn symbol_set_current(s: &mut Session, p: &Value) -> Result { - let name = resolve_symbol(&s.doc()?.doc, p, "symbol.setCurrent")?; - set_unknown(s, CURRENT_SYMBOL, Some(json!(name)))?; - ok() -} - -fn symbol_select_instances(s: &mut Session, p: &Value) -> Result { - let name = resolve_symbol(&s.doc()?.doc, p, "symbol.selectInstances")?; - let ids = instances_of(&s.doc()?.doc, Some(&name)); - let n = ids.len(); - s.select(|_, sel| sel.set(ids))?; - Ok(json!({ "count": n })) -} - -// ---------- symbolism tools ---------- - -fn points(p: &Value, cmd: &str) -> Result> { - let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?; - let v: Vec = a.iter().filter_map(|q| Some(Point::new(q.get(0)?.as_f64()?, q.get(1)?.as_f64()?))).collect(); - if v.is_empty() || v.iter().any(|q| !q.x.is_finite() || !q.y.is_finite()) { - return Err(bad(cmd, "points must be finite [x,y] pairs")); - } - Ok(v) -} - -/// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree). -fn jitter(i: usize, q: Point) -> (f64, f64, f64) { - let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ i as u64; - for v in [(q.x * 16.0).round() as i64 as u64, (q.y * 16.0).round() as i64 as u64] { - h ^= v; - h = h.wrapping_mul(0x0000_0100_0000_01b3); - h ^= h >> 29; - } - let f = |k: u32| ((h.rotate_left(k * 21) & 0xffff) as f64 / 65535.0) * 2.0 - 1.0; - (f(0), f(1), f(2)) -} - -fn is_symbol_set(n: &Node) -> bool { - matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.name.as_deref() == Some("Symbol Set") -} - -fn symbol_spray(s: &mut Session, p: &Value) -> Result { - const C: &str = "symbol.spray"; - let pts = points(p, C)?; - let st = s.doc()?; - let name = resolve_symbol(&st.doc, p, C)?; - let radius = f64_or(p, "radius", 40.0).clamp(1.0, 2000.0); - let density = f64_or(p, "density", 5.0).clamp(1.0, 10.0); - let scale = f64_or(p, "scale", 1.0).clamp(0.01, 100.0); - let alt = bool_or(p, "alt", false); - let size = natural_size(&st.doc, &name); - let set = st.selection.objects.first().copied().filter(|id| st.selection.len() == 1 && st.doc.node(*id).is_some_and(is_symbol_set)); - // Only a new Symbol Set needs a layer that takes new art. - let parent = if alt || set.is_some() { st.insertion_parent() } else { st.target_parent()? }; - if alt { - // Remove instances of this symbol under the brush (within the set, or anywhere). - let d = &st.doc; - let scope: Vec = match set { - Some(g) => d.node(g).and_then(|n| n.children()).map(|c| c.iter().map(|c| c.id).collect()).unwrap_or_default(), - None => instances_of(d, Some(&name)), - }; - let doomed: Vec = scope - .into_iter() - .filter(|id| { - d.node(*id).is_some_and(|n| { - matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if *symbol == name) - && n.geometric_bounds().is_some_and(|b| pts.iter().any(|q| q.distance(b.center()) <= radius)) - }) - }) - .collect(); - let n = doomed.len(); - if n > 0 { - s.edit("Symbol Sprayer", |d, _| remove_each(d, &doomed))?; - } - return Ok(json!({ "count": n })); - } - // Keep instances at least this far apart along the stroke (denser = closer). - let min_gap = size.0.max(size.1) * scale * (1.15 - density * 0.1).max(0.1); - let mut placed: Vec = vec![]; - for (i, q) in pts.iter().enumerate() { - let (jx, jy, _) = jitter(i, *q); - let c = Point::new(q.x + jx * radius * 0.5, q.y + jy * radius * 0.5); - if placed.last().is_some_and(|l| l.distance(c) < min_gap) && i > 0 { - continue; - } - placed.push(c); - } - let count = placed.len(); - let reg = s.doc()?.doc.symbol_registration(&name); - let id = s.edit("Symbol Sprayer", |d, sel| { - let mut nodes = vec![]; - for (i, c) in placed.iter().enumerate() { - let (_, _, js) = jitter(i + 7, *c); - let k = scale * (1.0 + js * 0.1); - let id = d.alloc_id(); - nodes.push(Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(*c, size, reg) * Affine::scale(k) })); - } - let gid = match set { - Some(g) => { - for n in nodes { - d.insert(Some(g), usize::MAX, n)?; - } - g - } - None => { - let gid = d.alloc_id(); - let mut g = Node::group(gid, nodes.into_iter().map(Arc::new).collect()); - g.name = Some("Symbol Set".into()); - d.insert(parent, usize::MAX, g)?; - gid - } - }; - sel.set([gid]); - Ok(gid) - })?; - Ok(json!({ "id": id.0, "count": count })) -} - -fn instance_center(n: &Node) -> Option { - match &n.kind { - NodeKind::SymbolInstance { xf, .. } => Some(*xf * Point::ZERO), - _ => None, - } -} - -fn symbol_adjust(s: &mut Session, p: &Value) -> Result { - const C: &str = "symbol.adjust"; - let tool = str_param(p, "tool").ok_or_else(|| bad(C, "missing `tool`"))?.to_string(); - if !["shift", "scrunch", "size", "spin", "stain", "screen", "style"].contains(&tool.as_str()) { - return Err(bad(C, format!("unknown tool `{tool}`"))); - } - let pts = points(p, C)?; - let radius = f64_or(p, "radius", 40.0).clamp(1.0, 2000.0); - let intensity = f64_or(p, "intensity", 5.0).clamp(1.0, 10.0) / 10.0; - let alt = bool_or(p, "alt", false); - let st = s.doc()?; - let color = match p.get("color").and_then(color_value) { - Some(c) => super::paint::new_color(s, p, c), - None => s.paint.fill.color().unwrap_or(Color::BLACK), - }; - let style_paint = match str_param(p, "style") { - Some(n) => st.doc.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()), - None => st.doc.graphic_styles.get(1).or(st.doc.graphic_styles.first()).map(|g| g.appearance.fill_paint()), - }; - let candidates: Vec = { - let d = &st.doc; - let mut v = vec![]; - if st.selection.is_empty() { - v = instances_of(d, None); - } else { - for id in &st.selection.objects { - if let Some(n) = d.node(*id) { - n.walk(&mut |c| { - if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !v.contains(&c.id) { - v.push(c.id); - } - }); - } - } - } - v.retain(|id| d.is_editable(*id)); - v - }; - let label = match tool.as_str() { - "shift" => "Symbol Shifter", - "scrunch" => "Symbol Scruncher", - "size" => "Symbol Sizer", - "spin" => "Symbol Spinner", - "stain" => "Symbol Stainer", - "screen" => "Symbol Screener", - _ => "Symbol Styler", - }; - let count = s.edit(label, |d, _| { - let mut touched = std::collections::BTreeSet::new(); - for (j, q) in pts.iter().enumerate() { - let delta = if j > 0 { *q - pts[j - 1] } else { Vec2::ZERO }; - for id in &candidates { - let Some(n) = d.node_mut(*id) else { continue }; - let Some(c) = instance_center(n) else { continue }; - let dist = c.distance(*q); - if dist > radius { - continue; - } - let w = intensity * (1.0 - dist / radius).max(0.0); - if w <= 0.0 { - continue; - } - touched.insert(*id); - let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2()); - match tool.as_str() { - "shift" => n.transform(Affine::translate(delta * w.min(1.0)), false), - "scrunch" => { - let v = (*q - c) * (0.15 * w) * if alt { -1.0 } else { 1.0 }; - n.transform(Affine::translate(v), false); - } - "size" => { - let k = 1.0 + 0.08 * w; - n.transform(about(Affine::scale(if alt { 1.0 / k } else { k })), false); - } - "spin" => { - // Turn towards the drag direction; a click spins a little. - let a = if delta.hypot() > 1e-9 { (c - *q).cross(delta).signum() * 0.1 * w } else { 0.05 * w }; - n.transform(about(Affine::rotate(if alt { -a } else { a })), false); - } - "stain" | "style" => { - let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) }; - if tool == "style" && alt { - n.appearance.items.clear(); - continue; - } - let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); - let step = if tool == "style" { 1.0 } else { 0.15 * w as f32 }; - let o = if alt { (cur - step).max(0.0) } else { (cur + step).min(1.0) }; - n.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); - if o > 0.0 { - let mut f = FillLayer::new(paint); - f.opacity = o; - n.appearance.items.insert(0, AppearanceItem::Fill(f)); - } - } - _ => { - let step = (0.1 * w) as f32; - n.opacity = if alt { (n.opacity + step).min(1.0) } else { (n.opacity - step).max(0.05) }; - } - } - } - } - Ok(touched.len()) - })?; - Ok(json!({ "count": count })) -} diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs new file mode 100644 index 0000000000..18f744b1d5 --- /dev/null +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -0,0 +1,447 @@ +use super::*; + +// ---------- brushes ---------- + +/// Brushable nodes (paths and compound paths) under `ids`. +pub(crate) fn brush_targets(d: &Document, ids: &[NodeId]) -> Vec { + let mut out = vec![]; + for id in ids { + let Some(n) = d.node(*id) else { continue }; + n.walk(&mut |c| { + let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }); + let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); + if own && !in_compound && !out.contains(&c.id) { + out.push(c.id); + } + }); + } + out +} + +pub(super) fn brush_list(s: &mut Session, _: &Value) -> Result { + let d = &s.doc()?.doc; + let list: Vec = brush::library(d).iter().map(|b| json!({"name": b.name, "type": b.kind.type_id()})).collect(); + Ok(json!({ "brushes": list, "current": brush::current(d) })) +} + +pub(super) fn brush_get(s: &mut Session, p: &Value) -> Result { + let name = name_param(p, "brush.get")?; + let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?; + Ok(serde_json::to_value(b).unwrap_or_default()) +} + +/// The art `brush.new` takes from `ids` or `id`, else from the selection ([`selection_art`]). +pub(super) fn brush_selection_art(s: &mut Session, p: &Value) -> Result { + let art = selection_art(s, p)?; + Ok(json!({ "art": art.map(|n| serde_json::to_value(&n).unwrap_or_default()) })) +} + +/// The stroke paint a brush gives paths without one: the current stroke colour, else black. +pub(crate) fn stroke_paint(s: &Session) -> Paint { + if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() } +} + +/// Paint paths `ids` of `d` with brush `name` (a path without a stroke takes `stroke`). +pub(crate) fn apply_brush(d: &mut Document, ids: &[NodeId], name: &str, stroke: &Paint) { + for id in ids { + let Some(n) = d.node_mut(*id) else { continue }; + if n.appearance.stroke().is_none_or(|st| st.paint.is_none()) { + n.appearance.set_stroke(stroke.clone()); + } + if let Some(st) = n.appearance.stroke_mut() { + if st.width <= 0.0 { + st.width = 1.0; + } + st.brush = Some(name.to_string()); + } + } +} + +pub(super) fn brush_apply(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.apply"; + let name = name_param(p, C)?.to_string(); + if brush::find(&s.doc()?.doc, &name).is_none() { + return Err(bad(C, format!("no brush named `{name}`"))); + } + let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?); + let stroke = stroke_paint(s); + s.edit("Apply Brush", |d, _| { + d.unknown.insert(brush::CURRENT_KEY.into(), json!(name)); + apply_brush(d, &ids, &name, &stroke); + Ok(()) + })?; + Ok(json!({ "ids": ids_json(&ids) })) +} + +pub(super) fn brush_remove(s: &mut Session, p: &Value) -> Result { + let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?); + s.edit("Remove Brush Stroke", |d, _| { + for id in &ids { + if let Some(n) = d.node_mut(*id) { + for it in &mut n.appearance.items { + if let AppearanceItem::Stroke(st) = it { + st.brush = None; + } + } + } + } + Ok(()) + })?; + Ok(json!({ "ids": ids_json(&ids) })) +} + +pub(super) fn brush_set_current(s: &mut Session, p: &Value) -> Result { + match str_param(p, "name") { + Some(n) => { + if brush::find(&s.doc()?.doc, n).is_none() { + return Err(bad("brush.setCurrent", format!("no brush named `{n}`"))); + } + set_unknown(s, brush::CURRENT_KEY, Some(json!(n)))?; + } + None => set_unknown(s, brush::CURRENT_KEY, None)?, + } + ok() +} + +/// The definition fields that `params` change field by field when the brush has them as objects: +/// `{colorization: {method: "hueShift"}}` keeps the key color, and an art brush's `scale` with only +/// `start` keeps `end`. +const MERGED_FIELDS: [&str; 2] = ["colorization", "scale"]; + +fn merge(base: &mut Value, patch: &Value) { + if let (Some(b), Some(pt)) = (base.as_object_mut(), patch.as_object()) { + for (k, v) in pt { + match (b.get_mut(k).and_then(Value::as_object_mut), v.as_object()) { + (Some(inner), Some(fields)) if MERGED_FIELDS.contains(&k.as_str()) => { + for (f, fv) in fields { + inner.insert(f.clone(), fv.clone()); + } + } + _ => { + b.insert(k.clone(), v.clone()); + } + } + } + } +} + +/// Sets brush `to` on the strokes in `items` that paint with brush `from`. +fn set_stroke_brush(items: &mut [AppearanceItem], from: &str, to: Option<&str>) { + for it in items { + if let AppearanceItem::Stroke(st) = it + && st.brush.as_deref() == Some(from) + { + st.brush = to.map(str::to_string); + } + } +} + +/// Whether a stroke in `n` (its opacity masks included) paints with brush `name`. +fn paints_with(n: &Node, name: &str) -> bool { + let mut hit = false; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + hit |= m.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if st.brush.as_deref() == Some(name))); + }); + hit +} + +/// Applies [`set_stroke_brush`] to every stroke in `n` and its opacity masks. Only the objects that +/// hold such a stroke, and those that hold them, are copied. +fn set_brush_in(n: &mut Node, from: &str, to: Option<&str>) { + set_stroke_brush(&mut n.appearance.items, from, to); + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && paints_with(&mask.art, from) + { + set_brush_in(Arc::make_mut(&mut mask.art), from, to); + } + for c in n.children_mut().into_iter().flatten() { + if paints_with(c, from) { + set_brush_in(Arc::make_mut(c), from, to); + } + } +} + +/// Returns the art a brush is made of ([`Brush::art`]) for editing. +fn brush_art_mut(b: &mut Brush) -> Vec<&mut Node> { + use vectorcraft_brush::BrushKind; + match &mut b.kind { + BrushKind::Scatter(s) => vec![&mut s.art], + BrushKind::Art(a) => vec![&mut a.art], + BrushKind::Pattern(p) => { + std::iter::once(&mut p.side).chain([&mut p.outer_corner, &mut p.inner_corner, &mut p.start, &mut p.end].into_iter().flatten()).collect() + } + BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => vec![], + } +} + +/// Sets brush `to` (`None`: no brush) on every stroke that paints with brush `from`: in the art +/// (opacity masks included), symbols, graph designs, pattern tiles and the tiles that pattern +/// editing's Cancel puts back, graphic styles and the art of the brushes in `lib`. +fn rename_brush_strokes(d: &mut Document, lib: &mut [Brush], from: &str, to: Option<&str>) { + let trees = d.layers.iter_mut().chain(d.symbols.iter_mut().map(|s| &mut s.art)).chain(d.graph_designs.iter_mut().map(|g| &mut g.art)); + let patterns = d.patterns.iter_mut().chain(d.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())); + for n in trees.chain(patterns.flat_map(|p| &mut p.art)) { + if paints_with(n, from) { + set_brush_in(Arc::make_mut(n), from, to); + } + } + for g in &mut d.graphic_styles { + set_stroke_brush(&mut g.appearance.items, from, to); + } + for n in lib.iter_mut().flat_map(brush_art_mut) { + set_brush_in(n, from, to); + } +} + +fn save_library(s: &mut Session, label: &str, mut lib: Vec, renames: &[(String, Option)]) -> Result<()> { + s.edit(label, |d, _| { + for (from, to) in renames { + rename_brush_strokes(d, &mut lib, from, to.as_deref()); + if brush::current(d).as_deref() == Some(from.as_str()) { + match to { + Some(t) => d.unknown.insert(brush::CURRENT_KEY.into(), json!(t)), + None => d.unknown.remove(brush::CURRENT_KEY), + }; + } + } + brush::store(d, &lib); + Ok(()) + }) +} + +pub(super) fn brush_new(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.new"; + let ty = str_param(p, "type").ok_or_else(|| bad(C, "missing `type`"))?; + let art_key = match ty { + "calligraphic" | "bristle" => None, + "scatter" | "art" => Some("art"), + "pattern" => Some("side"), + o => return Err(bad(C, format!("unknown brush type `{o}`"))), + }; + let mut lib = brush::library(&s.doc()?.doc); + let given = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()); + let base_name = given.map_or_else(|| format!("New {} Brush", ty[..1].to_uppercase() + &ty[1..]), str::to_string); + let name = brush::unique_name(&lib, &base_name); + if ty == "bristle" { + bristle_name_fits(C, &name)?; + } + let mut v = json!({"name": name, "type": ty}); + if let Some(params) = p.get("params") { + merge(&mut v, params); + v["name"] = json!(name); + v["type"] = json!(ty); + } + if let Some(k) = art_key + && 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) { + return Err(bad(C, "the selected art has no width")); + } + v[k] = serde_json::to_value(&art).unwrap_or_default(); + } + lib.push(parse_brush(C, v)?); + save_library(s, "New Brush", lib, &[])?; + Ok(json!({ "name": name })) +} + +/// 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); + if count > max { + return Err(bad(cmd, format!("a bristle brush name can have at most {max} characters: `{name}` has {count}"))); + } + Ok(()) +} + +/// A brush definition from command params, its values kept within their ranges ([`Brush::from_json`]). +fn parse_brush(cmd: &str, v: Value) -> Result { + Brush::from_json(v).map_err(|e| bad(cmd, format!("invalid brush: {e}"))) +} + +pub(super) fn brush_delete(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.delete"; + let names = names_param(p, C)?; + let mut lib = brush::library(&s.doc()?.doc); + if let Some(name) = names.iter().find(|n| !lib.iter().any(|b| &b.name == *n)) { + return Err(bad(C, format!("no brush named `{name}`"))); + } + lib.retain(|b| !names.contains(&b.name)); + let renames: Vec<(String, Option)> = names.into_iter().map(|n| (n, None)).collect(); + save_library(s, "Delete Brush", lib, &renames)?; + ok() +} + +/// Moves the brushes in `name` or `names`, in that order, to index `to` among the brushes of their +/// type in library order: before the first brush of that type at or after `to` that isn't moving, +/// else after the last brush of that type that isn't moving. Brushes of different types, or a `type` +/// that isn't theirs, are an error. A move that leaves the order as it was records no undo step. +pub(super) fn brush_move(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.move"; + const WITHIN: &str = "brushes move only within their type"; + let names = names_param(p, C)?; + check_numbers(p, &["to"], C)?; + let to = match p.get("to").filter(|v| !v.is_null()) { + Some(v) => Some(v.as_u64().map(|i| usize::try_from(i).unwrap_or(usize::MAX)).ok_or_else(|| bad(C, "`to` must be a whole number"))?), + None => None, + }; + let old = brush::library(&s.doc()?.doc); + let mut lib = old.clone(); + // `names_param` refuses an empty list, so the loop sets `kind`. + let mut kind = ""; + for name in &names { + let b = lib.iter().find(|b| &b.name == name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?; + if !kind.is_empty() && kind != b.kind.type_id() { + return Err(bad(C, WITHIN)); + } + kind = b.kind.type_id(); + } + if p.get("type").filter(|v| !v.is_null()).is_some_and(|t| t.as_str() != Some(kind)) { + return Err(bad(C, WITHIN)); + } + let same: Vec<&Brush> = lib.iter().filter(|b| b.kind.type_id() == kind).collect(); + let before = anchor(&same, to, &names, |b| &b.name); + let first = lib.iter().position(|b| names.contains(&b.name)).unwrap_or(lib.len()); + let mut items = vec![]; + for name in &names { + if let Some(i) = lib.iter().position(|b| &b.name == name) { + items.push(lib.remove(i)); + } + } + let at = match before { + Some(a) => lib.iter().position(|b| b.name == a), + None => lib.iter().rposition(|b| b.kind.type_id() == kind).map(|i| i + 1), + }; + let at = at.unwrap_or(first).min(lib.len()); + lib.splice(at..at, items); + if lib != old { + save_library(s, "Move Brush", lib, &[])?; + } + Ok(json!({ "moved": names.len() })) +} + +/// Adds a copy of each brush in `name` or `names` at the end of the library. `newName`, given +/// without `names`, names the copy. +pub(super) fn brush_duplicate(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.duplicate"; + let names = names_param(p, C)?; + let before = brush::library(&s.doc()?.doc); + let mut lib = before.clone(); + let mut out = vec![]; + for name in &names { + let mut b = before.iter().find(|b| &b.name == name).cloned().ok_or_else(|| bad(C, format!("no brush named `{name}`")))?; + let given = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty() && p.get("names").is_none()); + let new_name = given.map_or_else(|| format!("{} copy", name.trim()), str::to_string); + b.name = brush::unique_name(&lib, &new_name); + out.push(b.name.clone()); + lib.push(b); + } + save_library(s, "Duplicate Brush", lib, &[])?; + Ok(if p.get("names").is_some() { json!({ "names": out }) } else { json!({ "name": out.first() }) }) +} + +/// Adds the names of the brushes the strokes of `items` paint with to `out`. +fn stroke_brushes(items: &[AppearanceItem], out: &mut Vec) { + for it in items { + if let AppearanceItem::Stroke(st) = it + && let Some(b) = &st.brush + { + out.push(b.clone()); + } + } +} + +/// Adds the names of the brushes the strokes in `n` (its opacity masks included) paint with to +/// `out`. +fn art_brushes(n: &Node, out: &mut Vec) { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| stroke_brushes(&m.appearance.items, out)); +} + +/// The brushes no stroke paints with. Strokes in the art (opacity masks included), symbols, graph +/// designs, pattern tiles and graphic styles count, and so do the strokes in the art of every brush +/// that a counted stroke paints with. +pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result { + let d = &s.doc()?.doc; + let lib = brush::library(d); + let mut todo = vec![]; + let trees = d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)).chain(d.graph_designs.iter().map(|g| &g.art)); + trees.chain(d.patterns.iter().flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo)); + d.graphic_styles.iter().for_each(|g| stroke_brushes(&g.appearance.items, &mut todo)); + let mut used = BTreeSet::new(); + while let Some(name) = todo.pop() { + if !used.contains(&name) { + lib.iter().filter(|b| b.name == name).flat_map(Brush::art).for_each(|n| art_brushes(n, &mut todo)); + 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 })) +} + +pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.options"; + let name = name_param(p, C)?.to_string(); + 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}`")))?; + let mut v = serde_json::to_value(&lib[i]).unwrap_or_default(); + if let Some(params) = p.get("params") { + merge(&mut v, params); + } + let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty() && *n != name).map(str::to_string); + if let Some(nn) = &new_name { + if lib.iter().any(|b| &b.name == nn) { + return Err(bad(C, format!("a brush named `{nn}` exists"))); + } + // A `newName` that only trims the white space around the saved name is taken at any length. + if matches!(lib[i].kind, BrushKind::Bristle(_)) && nn != name.trim() { + bristle_name_fits(C, nn)?; + } + v["name"] = json!(nn); + } else { + v["name"] = json!(name); + } + v["type"] = json!(lib[i].kind.type_id()); + lib[i] = parse_brush(C, v)?; + let out = lib[i].name.clone(); + let rename = new_name.map(|nn| (name, Some(nn))); + save_library(s, "Brush Options", lib, rename.as_slice())?; + Ok(json!({ "name": out })) +} + +pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result { + let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?); + let ids: Vec = ids.into_iter().filter(|id| s.doc().ok().and_then(|st| st.doc.node(*id)).is_some_and(brush::has_brush)).collect(); + if ids.is_empty() { + return Err(EngineError::Other("Expand: no brush strokes selected".into())); + } + let out = s.edit("Expand", |d, sel| { + let mut out = vec![]; + for id in &ids { + let Some(n) = d.node(*id).cloned() else { continue }; + let Some(g) = brush::expand(d, &n) else { continue }; + let g = d.reid(&g); + let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?; + let gid = g.id; + d.remove(*id)?; + d.insert(par, idx, g)?; + out.push(gid); + } + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "ids": ids_json(&out) })) +} + +pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result { + let name = str_param(p, "brush").map(str::to_string).filter(|n| s.doc().is_ok_and(|st| brush::find(&st.doc, n).is_some())); + let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?; + let r = (spec.run)(s, p)?; + let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) }; + s.edit("Paintbrush", |d, _| { + if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { + st.brush = Some(name.clone()); + } + Ok(()) + })?; + Ok(r) +} diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs new file mode 100644 index 0000000000..63eeed6b5d --- /dev/null +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -0,0 +1,688 @@ +use super::*; + +// ---------- symbols ---------- + +pub(crate) fn natural_size(d: &Document, name: &str) -> (f64, f64) { + d.unknown + .get(SIZES_KEY) + .and_then(|m| m.get(name)) + .and_then(|v| Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?))) + .unwrap_or((2.0 * HALF, 2.0 * HALF)) +} + +pub(crate) fn set_natural_size(d: &mut Document, name: &str, size: Option<(f64, f64)>) { + let m = d.unknown.entry(SIZES_KEY.to_string()).or_insert_with(|| json!({})); + if let Some(o) = m.as_object_mut() { + match size { + Some((w, h)) => o.insert(name.into(), json!([w, h])), + None => o.remove(name), + }; + } +} + +/// Instance transform for a symbol of natural size `(w, h)` whose registration point is at `at`. +pub(crate) fn place_xf(at: Point, (w, h): (f64, f64), reg: SymbolRegistration) -> Affine { + let c = at - reg.offset_from_center(w, h); + Affine::translate(c.to_vec2()) * Affine::scale_non_uniform(w / (2.0 * HALF), h / (2.0 * HALF)) +} + +fn registration_param(p: &Value, cmd: &str) -> Result> { + match p.get("registration") { + None => Ok(None), + Some(v) => v.as_u64().and_then(SymbolRegistration::from_u64).map(Some).ok_or_else(|| bad(cmd, "registration must be 0..8")), + } +} + +fn export_type_param(p: &Value, cmd: &str) -> Result> { + match str_param(p, "exportType") { + None => Ok(None), + Some(s) => SymbolExportType::from_id(s).map(Some).ok_or_else(|| bad(cmd, format!("exportType must be movieClip or graphic, not `{s}`"))), + } +} + +/// `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 the centre third, when none are given). +fn nine_slice_param(p: &Value, cmd: &str, current: Option) -> Result>> { + 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") + })?), + }; + Ok(match (on, guides) { + (Some(false), _) => Some(None), + (None, None) => None, + (_, Some(g)) => Some(Some(g)), + (Some(true), None) => Some(Some(current.unwrap_or_default())), + }) +} + +fn nine_slice_json(d: &Document, name: &str) -> Value { + d.symbol_nine_slice(name).map_or(Value::Null, SymbolNineSlice::to_value) +} + +fn rename_natural_size(d: &mut Document, from: &str, to: &str) { + if from == to { + return; + } + let size = d.unknown.get(SIZES_KEY).and_then(|m| m.get(from)).cloned(); + set_natural_size(d, from, None); + if let Some(v) = size + && let (Some(w), Some(h)) = (v.get(0).and_then(Value::as_f64), v.get(1).and_then(Value::as_f64)) + { + set_natural_size(d, to, Some((w, h))); + } +} + +/// Normalise art for a symbol definition: returns (art, natural size, centre in the document). +pub(crate) fn normalize(mut art: Node) -> Result<(Node, (f64, f64), Point)> { + let b = art.geometric_bounds().ok_or_else(|| EngineError::Other("the art has no bounds".into()))?; + let (w, h) = (b.width().max(1.0), b.height().max(1.0)); + let c = b.center(); + let n = Affine::scale_non_uniform(2.0 * HALF / w, 2.0 * HALF / h) * Affine::translate(-c.to_vec2()); + art.transform(n, false); + Ok((art, (w, h), c)) +} + +fn instances_of(d: &Document, name: Option<&str>) -> Vec { + let mut v = vec![]; + d.walk(|n| { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && name.is_none_or(|x| x == symbol) + { + v.push(n.id); + } + }); + v +} + +fn symbol_names(d: &Document) -> Vec { + d.symbols.iter().map(|s| s.name.clone()).collect() +} + +fn current_symbol(d: &Document) -> Option { + d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str).filter(|n| d.symbols.iter().any(|s| s.name == *n)).map(str::to_string) +} + +pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result { + let d = &s.doc()?.doc; + let list: Vec = d + .symbols + .iter() + .map(|sym| { + let (w, h) = natural_size(d, &sym.name); + json!({ + "name": sym.name, + "instances": instances_of(d, Some(&sym.name)).len(), + "size": [w, h], + "registration": d.symbol_registration(&sym.name).0, + "exportType": d.symbol_export_type(&sym.name).id(), + "nineSlice": nine_slice_json(d, &sym.name), + }) + }) + .collect(); + Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) })) +} + +/// Replace the root nodes `ids` with one instance of `name` (art already stored). Returns the id. +fn replace_with_instance(d: &mut Document, ids: &[NodeId], name: &str, xf: Affine) -> Result { + let top = *ids.last().ok_or_else(|| EngineError::Other("nothing selected".into()))?; + if separate(d, ids) { + let id = d.alloc_id(); + return Ok(d.wrap(ids, |_| Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf }))?); + } + let (par, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?; + let id = d.alloc_id(); + d.insert(par, idx + 1, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf }))?; + for r in ids { + d.remove(*r)?; + } + Ok(id) +} + +pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.new"; + let ids = roots(s, p)?; + let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?; + crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art); + let (art, size, c) = normalize(art)?; + let name = s.doc()?.doc.unique_symbol_name(str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("New Symbol")); + let reg = registration_param(p, C)?.unwrap_or(SymbolRegistration::CENTER); + let export = export_type_param(p, C)?.unwrap_or_default(); + let nine = nine_slice_param(p, C, None)?.flatten(); + // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. + let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); + let id = s.edit("New Symbol", |d, sel| { + let art = d.reid(&art); + d.symbols.push(Symbol { name: name.clone(), art: Arc::new(art) }); + set_natural_size(d, &name, Some(size)); + d.set_symbol_registration(&name, reg); + d.set_symbol_export_type(&name, export); + d.set_symbol_nine_slice(&name, nine); + d.unknown.insert(CURRENT_SYMBOL.into(), json!(name)); + let threaded = crate::cmd::threads::frames(d); + let id = replace_with_instance(d, &ids, &name, place)?; + // Frames of threaded text in the symbol leave their threads with the text they show. + crate::cmd::threads::leave_threads(d, &threaded); + sel.set([id]); + Ok(id) + })?; + Ok( + json!({ "name": name, "id": id.0, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }), + ) +} + +pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.options"; + let name = resolve_symbol(&s.doc()?.doc, p, C)?; + let export = export_type_param(p, C)?; + let reg = registration_param(p, C)?; + let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?; + let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); + if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() { + return Err(bad(C, "pass newName, registration, exportType and/or nineSlice")); + } + if let Some(ref n) = new_name + && n != &name + && s.doc()?.doc.symbols.iter().any(|x| x.name == *n) + { + return Err(bad(C, format!("a symbol named `{n}` already exists"))); + } + let final_name = new_name.clone().unwrap_or_else(|| name.clone()); + s.edit("Symbol Options", |d, _| { + if let Some(ref n) = new_name + && n != &name + { + if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) { + sym.name = n.clone(); + } + for id in instances_of(d, Some(&name)) { + if let Some(NodeKind::SymbolInstance { symbol, .. }) = d.node_mut(id).map(|node| &mut node.kind) { + *symbol = n.clone(); + } + } + rename_natural_size(d, &name, n); + d.rename_symbol_registration(&name, n); + d.rename_symbol_export_type(&name, n); + d.rename_symbol_nine_slice(&name, n); + if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { + d.unknown.insert(CURRENT_SYMBOL.into(), json!(n)); + } + } + if let Some(r) = reg { + d.set_symbol_registration(&final_name, r); + } + if let Some(kind) = export { + d.set_symbol_export_type(&final_name, kind); + } + if let Some(g) = nine { + d.set_symbol_nine_slice(&final_name, g); + } + Ok(()) + })?; + let d = &s.doc()?.doc; + Ok(json!({ + "name": final_name, + "registration": d.symbol_registration(&final_name).0, + "exportType": d.symbol_export_type(&final_name).id(), + "nineSlice": nine_slice_json(d, &final_name), + })) +} + +fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result { + match str_param(p, "name") { + Some(n) if d.symbols.iter().any(|s| s.name == n) => Ok(n.to_string()), + Some(n) => Err(bad(cmd, format!("no symbol named `{n}`"))), + None => { + current_symbol(d).or_else(|| symbol_names(d).into_iter().next()).ok_or_else(|| EngineError::Other("the document has no symbols".into())) + } + } +} + +pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result { + let d = &s.doc()?.doc; + let name = resolve_symbol(d, p, "symbol.place")?; + let centre = d.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); + let at = Point::new(number_or(p, "x", centre.x, "symbol.place")?, number_or(p, "y", centre.y, "symbol.place")?); + let size = natural_size(d, &name); + let reg = d.symbol_registration(&name); + let parent = s.doc()?.target_parent()?; + let id = s.edit("Place Symbol Instance", |d, sel| { + let id = d.alloc_id(); + d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + +/// The plain art of instance `inst` in document space (fresh ids). +fn expanded_instance(d: &mut Document, inst: &Node) -> Option { + let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None }; + let sym = d.symbols.iter().find(|s| &s.name == symbol)?; + let mut art = (*sym.art).clone(); + if let Some(f) = inst.appearance.fill() + && let Some(c) = f.paint.color() + { + brush::tint_node(&mut art, &c, f.opacity); + } + art.transform(*xf, false); + let mut art = d.reid(&art); + if inst.opacity < 1.0 || inst.blend != vectorcraft_color::BlendMode::Normal { + if !matches!(art.kind, NodeKind::Group { .. }) { + let id = d.alloc_id(); + art = Node::group(id, vec![Arc::new(art)]); + } + art.opacity *= inst.opacity; + art.blend = inst.blend; + } + Some(art) +} + +fn break_links(d: &mut Document, ids: &[NodeId]) -> Result> { + let mut out = vec![]; + for id in ids { + let Some(inst) = d.node(*id).cloned() else { continue }; + let Some(art) = expanded_instance(d, &inst) else { continue }; + let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?; + let aid = art.id; + d.remove(*id)?; + d.insert(par, idx, art)?; + out.push(aid); + } + Ok(out) +} + +fn selected_instances(s: &Session, p: &Value) -> Result> { + let d = &s.doc()?.doc; + let mut out = vec![]; + for id in roots(s, p)? { + if let Some(n) = d.node(id) { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::SymbolInstance { .. }) { + out.push(c.id); + } + }); + } + } + Ok(out) +} + +pub(super) fn symbol_break_link(s: &mut Session, p: &Value) -> Result { + let ids = selected_instances(s, p)?; + if ids.is_empty() { + return Err(EngineError::Other("no symbol instances selected".into())); + } + let out = s.edit("Break Link to Symbol", |d, sel| { + let out = break_links(d, &ids)?; + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "ids": ids_json(&out) })) +} + +pub(super) fn symbol_edit(s: &mut Session, p: &Value) -> Result { + let ids = selected_instances(s, p)?; + let first = *ids.first().ok_or_else(|| EngineError::Other("select a symbol instance".into()))?; + let name = match &s.doc()?.doc.node(first).map(|n| n.kind.clone()) { + Some(NodeKind::SymbolInstance { symbol, .. }) => symbol.clone(), + _ => return Err(EngineError::Other("select a symbol instance".into())), + }; + let out = s.edit("Edit Symbol", |d, sel| { + let out = break_links(d, &[first])?; + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "name": name, "ids": ids_json(&out) })) +} + +pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.update"; + let name = name_param(p, C)?.to_string(); + if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) { + return Err(bad(C, format!("no symbol named `{name}`"))); + } + let ids = roots(s, p)?; + let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?; + crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art); + let (art, size, c) = normalize(art)?; + let old = natural_size(&s.doc()?.doc, &name); + let id = s.edit("Redefine Symbol", |d, sel| { + let art = d.reid(&art); + if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) { + sym.art = Arc::new(art); + } + set_natural_size(d, &name, Some(size)); + let fix = Affine::scale_non_uniform(size.0 / old.0, size.1 / old.1); + for i in instances_of(d, Some(&name)) { + if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(i).map(|n| &mut n.kind) { + *xf *= fix; + } + } + let reg = d.symbol_registration(&name); + let threaded = crate::cmd::threads::frames(d); + let id = replace_with_instance(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?; + // Frames of threaded text in the symbol leave their threads with the text they show. + crate::cmd::threads::leave_threads(d, &threaded); + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "name": name, "id": id.0 })) +} + +pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.delete"; + let name = name_param(p, C)?.to_string(); + if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) { + return Err(bad(C, format!("no symbol named `{name}`"))); + } + let expand = switch_or(p, "expandInstances", true, C)?; + s.edit("Delete Symbol", |d, _| { + let inst = instances_of(d, Some(&name)); + if expand { + break_links(d, &inst)?; + } else { + remove_each(d, &inst)?; + } + d.symbols.retain(|x| x.name != name); + set_natural_size(d, &name, None); + d.set_symbol_registration(&name, SymbolRegistration::CENTER); + d.clear_symbol_export_type(&name); + d.set_symbol_nine_slice(&name, None); + if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { + d.unknown.remove(CURRENT_SYMBOL); + } + Ok(()) + })?; + ok() +} + +pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.duplicate"; + let name = name_param(p, C)?.to_string(); + let d = &s.doc()?.doc; + let sym = d.symbols.iter().find(|x| x.name == name).cloned().ok_or_else(|| bad(C, format!("no symbol named `{name}`")))?; + let given = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()); + let new = d.unique_symbol_name(&given.map_or_else(|| format!("{} copy", name.trim()), str::to_string)); + let size = natural_size(d, &name); + let reg = d.symbol_registration(&name); + let export = d.symbol_export_type(&name); + let nine = d.symbol_nine_slice(&name); + s.edit("Duplicate Symbol", |d, _| { + let art = d.reid(&sym.art); + d.symbols.push(Symbol { name: new.clone(), art: Arc::new(art) }); + set_natural_size(d, &new, Some(size)); + d.set_symbol_registration(&new, reg); + d.set_symbol_export_type(&new, export); + d.set_symbol_nine_slice(&new, nine); + Ok(()) + })?; + Ok(json!({ "name": new, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) })) +} + +pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.replace"; + let name = name_param(p, C)?.to_string(); + if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) { + return Err(bad(C, format!("no symbol named `{name}`"))); + } + let ids = selected_instances(s, p)?; + if ids.is_empty() { + return Err(EngineError::Other("no symbol instances selected".into())); + } + s.edit("Replace Symbol", |d, _| { + let new = natural_size(d, &name); + for id in &ids { + let old = match d.node(*id).map(|n| &n.kind) { + Some(NodeKind::SymbolInstance { symbol, .. }) => natural_size(d, symbol), + _ => continue, + }; + if let Some(NodeKind::SymbolInstance { symbol, xf }) = d.node_mut(*id).map(|n| &mut n.kind) { + *symbol = name.clone(); + *xf *= Affine::scale_non_uniform(new.0 / old.0, new.1 / old.1); + } + } + Ok(()) + })?; + Ok(json!({ "ids": ids_json(&ids) })) +} + +pub(super) fn symbol_set_current(s: &mut Session, p: &Value) -> Result { + let name = resolve_symbol(&s.doc()?.doc, p, "symbol.setCurrent")?; + set_unknown(s, CURRENT_SYMBOL, Some(json!(name)))?; + ok() +} + +pub(super) fn symbol_select_instances(s: &mut Session, p: &Value) -> Result { + let name = resolve_symbol(&s.doc()?.doc, p, "symbol.selectInstances")?; + let ids = instances_of(&s.doc()?.doc, Some(&name)); + let n = ids.len(); + s.select(|_, sel| sel.set(ids))?; + Ok(json!({ "count": n })) +} + +// ---------- symbolism tools ---------- + +fn points(p: &Value, cmd: &str) -> Result> { + let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?; + let v: Vec = a.iter().filter_map(|q| Some(Point::new(q.get(0)?.as_f64()?, q.get(1)?.as_f64()?))).collect(); + if v.is_empty() || v.iter().any(|q| !q.x.is_finite() || !q.y.is_finite()) { + return Err(bad(cmd, "points must be finite [x,y] pairs")); + } + Ok(v) +} + +/// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree). +fn jitter(i: usize, q: Point) -> (f64, f64, f64) { + let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ i as u64; + for v in [(q.x * 16.0).round() as i64 as u64, (q.y * 16.0).round() as i64 as u64] { + h ^= v; + h = h.wrapping_mul(0x0000_0100_0000_01b3); + h ^= h >> 29; + } + let f = |k: u32| ((h.rotate_left(k * 21) & 0xffff) as f64 / 65535.0) * 2.0 - 1.0; + (f(0), f(1), f(2)) +} + +fn is_symbol_set(n: &Node) -> bool { + matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.name.as_deref() == Some("Symbol Set") +} + +pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.spray"; + let pts = points(p, C)?; + let st = s.doc()?; + let name = resolve_symbol(&st.doc, p, C)?; + let radius = number_or(p, "radius", 40.0, C)?.clamp(1.0, 2000.0); + let density = number_or(p, "density", 5.0, C)?.clamp(1.0, 10.0); + let scale = number_or(p, "scale", 1.0, C)?.clamp(0.01, 100.0); + let alt = switch_or(p, "alt", false, C)?; + let size = natural_size(&st.doc, &name); + let set = st.selection.objects.first().copied().filter(|id| st.selection.len() == 1 && st.doc.node(*id).is_some_and(is_symbol_set)); + // Only a new Symbol Set needs a layer that takes new art. + let parent = if alt || set.is_some() { st.insertion_parent() } else { st.target_parent()? }; + if alt { + // Remove instances of this symbol under the brush (within the set, or anywhere). + let d = &st.doc; + let scope: Vec = match set { + Some(g) => d.node(g).and_then(|n| n.children()).map(|c| c.iter().map(|c| c.id).collect()).unwrap_or_default(), + None => instances_of(d, Some(&name)), + }; + let doomed: Vec = scope + .into_iter() + .filter(|id| { + d.node(*id).is_some_and(|n| { + matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if *symbol == name) + && n.geometric_bounds().is_some_and(|b| pts.iter().any(|q| q.distance(b.center()) <= radius)) + }) + }) + .collect(); + let n = doomed.len(); + if n > 0 { + s.edit("Symbol Sprayer", |d, _| remove_each(d, &doomed))?; + } + return Ok(json!({ "count": n })); + } + // Keep instances at least this far apart along the stroke (denser = closer). + let min_gap = size.0.max(size.1) * scale * (1.15 - density * 0.1).max(0.1); + let mut placed: Vec = vec![]; + for (i, q) in pts.iter().enumerate() { + let (jx, jy, _) = jitter(i, *q); + let c = Point::new(q.x + jx * radius * 0.5, q.y + jy * radius * 0.5); + if placed.last().is_some_and(|l| l.distance(c) < min_gap) && i > 0 { + continue; + } + placed.push(c); + } + let count = placed.len(); + let reg = s.doc()?.doc.symbol_registration(&name); + let id = s.edit("Symbol Sprayer", |d, sel| { + let mut nodes = vec![]; + for (i, c) in placed.iter().enumerate() { + let (_, _, js) = jitter(i + 7, *c); + let k = scale * (1.0 + js * 0.1); + let id = d.alloc_id(); + nodes.push(Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(*c, size, reg) * Affine::scale(k) })); + } + let gid = match set { + Some(g) => { + for n in nodes { + d.insert(Some(g), usize::MAX, n)?; + } + g + } + None => { + let gid = d.alloc_id(); + let mut g = Node::group(gid, nodes.into_iter().map(Arc::new).collect()); + g.name = Some("Symbol Set".into()); + d.insert(parent, usize::MAX, g)?; + gid + } + }; + sel.set([gid]); + Ok(gid) + })?; + Ok(json!({ "id": id.0, "count": count })) +} + +fn instance_center(n: &Node) -> Option { + match &n.kind { + NodeKind::SymbolInstance { xf, .. } => Some(*xf * Point::ZERO), + _ => None, + } +} + +pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.adjust"; + let tool = str_param(p, "tool").ok_or_else(|| bad(C, "missing `tool`"))?.to_string(); + if !["shift", "scrunch", "size", "spin", "stain", "screen", "style"].contains(&tool.as_str()) { + return Err(bad(C, format!("unknown tool `{tool}`"))); + } + crate::cmd::paint::check_keep_model(p, C)?; + let pts = points(p, C)?; + let radius = number_or(p, "radius", 40.0, C)?.clamp(1.0, 2000.0); + let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0; + let alt = switch_or(p, "alt", false, C)?; + let st = s.doc()?; + let color = match p.get("color").and_then(color_value) { + Some(c) => crate::cmd::paint::new_color(s, p, c), + None => s.paint.fill.color().unwrap_or(Color::BLACK), + }; + let style_paint = match str_param(p, "style") { + Some(n) => st.doc.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()), + None => st.doc.graphic_styles.get(1).or(st.doc.graphic_styles.first()).map(|g| g.appearance.fill_paint()), + }; + let candidates: Vec = { + let d = &st.doc; + let mut v = vec![]; + if st.selection.is_empty() { + v = instances_of(d, None); + } else { + for id in &st.selection.objects { + if let Some(n) = d.node(*id) { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !v.contains(&c.id) { + v.push(c.id); + } + }); + } + } + } + let editable = d.editable(); + v.retain(|id| editable(*id)); + v + }; + let label = match tool.as_str() { + "shift" => "Symbol Shifter", + "scrunch" => "Symbol Scruncher", + "size" => "Symbol Sizer", + "spin" => "Symbol Spinner", + "stain" => "Symbol Stainer", + "screen" => "Symbol Screener", + _ => "Symbol Styler", + }; + let count = s.edit(label, |d, _| { + let mut touched = std::collections::BTreeSet::new(); + for (j, q) in pts.iter().enumerate() { + let delta = if j > 0 { *q - pts[j - 1] } else { Vec2::ZERO }; + for id in &candidates { + let Some(n) = d.node_mut(*id) else { continue }; + let Some(c) = instance_center(n) else { continue }; + let dist = c.distance(*q); + if dist > radius { + continue; + } + let w = intensity * (1.0 - dist / radius).max(0.0); + if w <= 0.0 { + continue; + } + touched.insert(*id); + let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2()); + match tool.as_str() { + "shift" => n.transform(Affine::translate(delta * w.min(1.0)), false), + "scrunch" => { + let v = (*q - c) * (0.15 * w) * if alt { -1.0 } else { 1.0 }; + n.transform(Affine::translate(v), false); + } + "size" => { + let k = 1.0 + 0.08 * w; + n.transform(about(Affine::scale(if alt { 1.0 / k } else { k })), false); + } + "spin" => { + // Turn towards the drag direction; a click spins a little. + let a = if delta.hypot() > 1e-9 { (c - *q).cross(delta).signum() * 0.1 * w } else { 0.05 * w }; + n.transform(about(Affine::rotate(if alt { -a } else { a })), false); + } + "stain" | "style" => { + let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) }; + if tool == "style" && alt { + n.appearance.items.clear(); + continue; + } + let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); + let step = if tool == "style" { 1.0 } else { 0.15 * w as f32 }; + let o = if alt { (cur - step).max(0.0) } else { (cur + step).min(1.0) }; + n.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); + if o > 0.0 { + let mut f = FillLayer::new(paint); + f.opacity = o; + n.appearance.items.insert(0, AppearanceItem::Fill(f)); + } + } + _ => { + let step = (0.1 * w) as f32; + n.opacity = if alt { (n.opacity + step).min(1.0) } else { (n.opacity - step).max(0.05) }; + } + } + } + } + Ok(touched.len()) + })?; + Ok(json!({ "count": count })) +} diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 92d0012441..8d72ce3359 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -1,10 +1,10 @@ //! Shape Builder (`shapeBuilder.*`), Live Paint (`livePaint.*`) and Image Trace (`imageTrace.*`). //! //! **Live Paint groups** need no special node kind: a Live Paint group is a plain group whose name -//! starts with "Live Paint". Its first child is a hidden group named "Live Paint Sources" holding -//! the original paths (the planar map's inputs, used by Release, Merge and re-computation); then -//! come the faces (paths named "Face", fill only) and the edges (open paths named "Edge", stroke -//! only). See `vectorcraft_tools::builder` for the shared helpers. +//! starts with "Live Paint" and that holds a group named "Live Paint Sources". That group is its +//! first child, hidden, and holds the original paths (the planar map's inputs, used by Release, +//! Merge and re-computation); then come the faces (paths named "Face", fill only) and the edges +//! (open paths named "Edge", stroke only). See `vectorcraft_tools::builder` for the shared helpers. //! //! **Image Trace** makes a group named "Image Trace" holding the source image (hidden, bottom) //! and the traced filled paths above it, mapped with the image's transform. Expand drops the @@ -19,16 +19,25 @@ use vectorcraft_doc::{Appearance, Document, GapOptions, GapSize, LiveShape, Node use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath}; use vectorcraft_pathops as po; use vectorcraft_tools::builder::{ - self as b, BuilderMap, EDGE_NAME, FACE_NAME, LIVE_PAINT_NAME, SOURCES_NAME, Touched, edge_near, face_at, is_live_paint, sample_polyline, - sorted_roots, + self as b, BuilderMap, EDGE_NAME, FACE_NAME, LIVE_PAINT_NAME, SOURCES_NAME, Touched, edge_near, face_at, is_live_paint, sorted_roots, }; use vectorcraft_trace as tr; +use super::draw2::replace_with_pieces; use super::edit::{outermost, selected_roots}; use super::paint::paint_from; use super::pathops::{Beside, shape_node}; use super::*; +mod live_paint; +mod shape_builder; +mod trace; + +pub use live_paint::live_paint_gaps; +use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge}; +use shape_builder::{sb_merge, sb_regions}; +use trace::{trace_expand, trace_make, trace_release, trace_set_view}; + /// Name of an Image Trace group. pub const TRACE_NAME: &str = "Image Trace"; @@ -39,7 +48,7 @@ pub fn specs() -> Vec { "Shape Builder", [], None, - "{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of unfilled open paths and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance; a deleted edge opens its path there, and edges bounding a deleted region go with it), tolerance?: pt (2, erase only), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the fill of the object under the first point; the current fill for an area only lines enclose)} → {ids, merged, regions, lines, edges} (counts deleted or merged)", + "{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} → {ids, merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one", has_selection_or_ids, sb_merge ), @@ -48,7 +57,7 @@ pub fn specs() -> Vec { "Shape Builder Regions", [], None, - "{ids?|id?} → {regions: [{bounds: [x0,y0,x1,y1], area, sources: [id…]}], lines: [{bounds, source: id}], edges: [{bounds, source: id}]} faces of the planar arrangement (unfilled open paths cut them; sources is empty for an area only they enclose), the pieces of those open paths and the edges (the other paths' outlines cut where paths meet; source: the front-most path along it), which erasing deletes", + "{ids?|id?, gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (as shapeBuilder.merge)} → {regions: [{bounds: [x0,y0,x1,y1], area, sources: [id…]}], lines: [{bounds, source: id}], edges: [{bounds, source: id}]} faces of the planar arrangement (unfilled open paths cut them, and filled ones too with openFilledAsClosed false; sources is empty for an area only they enclose), the pieces of those open paths and the edges (the other paths' outlines cut where paths meet; source: the front-most path along it), which erasing deletes", has_selection_or_ids, sb_regions ), @@ -57,7 +66,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Live Paint"], Some("Cmd+Alt+X"), - "{ids?|id?} build a Live Paint group from the selected paths → {id, faces, edges}", + "{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); with a Live Paint group among them, add the others to it as livePaint.merge does → {id, faces, edges}", has_selection_or_ids, lp_make ), @@ -66,7 +75,7 @@ pub fn specs() -> Vec { "Merge", ["Object", "Live Paint"], None, - "{ids?|id?} add the other selected paths (and Live Paint groups) to the first Live Paint group, keeping its paint → {id, faces, edges}", + "{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link) → {id, faces, edges}", has_multi_or_ids, lp_merge ), @@ -102,7 +111,7 @@ pub fn specs() -> Vec { "Live Paint Bucket", [], None, - "{group?: id | ids?|id?: [id…] (paths to make live first), point: [x,y], color?|swatch?|gradient?|none? (default: current fill), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point → {group, face}", + "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}", has_doc, lp_fill ), @@ -129,7 +138,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), 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), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, white is always its own colour, at most ten; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white unless ignoreWhite makes them holes; fills/strokes are ignored; gradients and photos are refused)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, white is always its own colour, at most ten; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white unless ignoreWhite makes them holes; fills/strokes are ignored; gradients and photos are refused)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), @@ -236,115 +245,21 @@ fn fill_param(s: &Session, p: &Value, cmd: &str) -> Result> { } } -fn sb_merge(s: &mut Session, p: &Value) -> Result { - const C: &str = "shapeBuilder.merge"; - let pts = points_param(p, "points").ok_or_else(|| bad(C, "missing points [[x,y]…]"))?; - if pts.is_empty() || !pts.iter().all(|q| finite(*q)) { - return Err(bad(C, "points must be a non-empty list of finite [x,y]")); +/// Gap Detection length in points, bounded like Live Paint's custom gap size. +fn gap_param(p: &Value) -> f64 { + let gap = f64_or(p, "gap", 0.0); + if gap.is_finite() { gap.clamp(0.0, po::SHAPE_BUILDER_MAX_GAP) } else { 0.0 } +} + +/// The Shift-drag marquee `rect: [x, y, width, height]`, as the point where the drag started +/// (`x`, `y`) and the opposite corner; the width and height may be negative. +fn marquee_param(p: &Value, cmd: &str) -> Result> { + let Some(v) = p.get("rect").filter(|v| !v.is_null()) else { return Ok(None) }; + let corners = finite_numbers(v).map(|[x, y, w, h]| (Point::new(x, y), Point::new(x + w, y + h))); + match corners { + Some((a, b)) if finite(a) && finite(b) => Ok(Some((a, b))), + _ => Err(bad(cmd, "rect must be [x, y, width, height]")), } - let erase = bool_or(p, "erase", false); - // Line pieces and edges are only deleted (erase mode), never merged. - let piece_tol = erase.then(|| f64_or(p, "tolerance", 2.0).clamp(0.0, 1000.0)); - let fill = fill_param(s, p, C)?; - let current_fill = s.paint.fill.clone(); - let roots = root_ids(s, p)?; - let label = if erase { "Shape Builder Delete" } else { "Shape Builder" }; - let (ids, merged, touched) = s.edit(label, |d, sel| { - let (map, leaves) = BuilderMap::new(d, &roots, erase); - let leaves: Vec = leaves.into_iter().cloned().collect(); - if map.shapes.is_empty() { - return Err(EngineError::Other("Shape Builder: select paths or compound paths".into())); - } - let step = (d.bounds_of(&roots, false).map(|r| r.width().max(r.height())).unwrap_or(100.0) / 2000.0).max(0.25); - let mut touched = Touched::default(); - for q in sample_polyline(&pts, step) { - touched.add(map.hit(q, piece_tol)); - } - touched.edges = map.erased_edges(&touched); - if touched.is_empty() { - return Err(EngineError::Other("Shape Builder: no region under the pointer".into())); - } - let cuts: Vec<&SubPath> = touched.edges.iter().filter_map(|&k| map.edges.get(k)?.0.path.subpaths.first()).collect(); - // Edges come back from the planar map within a few hundredths of the outlines they follow. - let cut_tol = step * 0.2; - let picked: Vec<&po::Region> = touched.regions.iter().filter_map(|&i| map.regions.get(i).map(|r| &r.0)).collect(); - let faces = po::FaceMerger::new(&map.shapes); - let union = if picked.is_empty() { PathData::default() } else { faces.merge(&picked) }; - // The merged shape takes the look of the front-most object over the first region, or (for an - // area only lines enclose) of the front-most object and the current fill. - let covered = picked.iter().find_map(|r| r.top()); - let style_src = covered.or(map.shapes.len().checked_sub(1)); - let merged_fill = fill.or_else(|| covered.is_none().then_some(current_fill)); - let mut new_nodes: Vec = vec![]; - let mut merged_id = None; - for (i, (sh, leaf)) in map.shapes.iter().zip(&leaves).enumerate() { - let pieces: Vec = map.lines.iter().enumerate().filter(|(_, (l, _))| l.key == i as u64).map(|(k, _)| k).collect(); - if !pieces.is_empty() { - // An open path loses the pieces deleted and those between merged (or deleted) regions. - let keep: Vec = - pieces.iter().copied().filter(|k| !touched.lines.contains(k) && !map.line_between(*k, &touched.regions)).collect(); - if keep.len() == pieces.len() { - new_nodes.push(d.reid(leaf)); - } else { - for k in keep { - if let Some((l, _)) = map.lines.get(k) { - new_nodes.push(shape_node(d, l.path.clone(), Some(leaf))); - } - } - } - } else { - // A shape loses the regions deleted or merged, then the edges deleted (each one on - // its outline, shared edges from every shape along them). - let in_union = picked.iter().any(|r| r.sources.contains(&i)); - let mut rest = if in_union { - // What is left of it: its faces not merged or deleted, united. They share their - // edges with the merged faces exactly, where subtracting the merged shape left - // slivers of the outline along them (#569). - let kept: Vec<&po::Region> = map - .regions - .iter() - .enumerate() - .filter(|(k, (r, ..))| r.sources.contains(&i) && !touched.regions.contains(k)) - .map(|(_, (r, ..))| r) - .collect(); - if kept.is_empty() { PathData::default() } else { faces.merge(&kept) } - } else { - b::node_outline(leaf).map_or_else(|| sh.path.clone(), |o| o.0) - }; - let fill_closes = !leaf.appearance.fill_paint().is_none(); - let mut cut = false; - for piece in &cuts { - if let Some(r) = po::cut_out(&rest, piece, fill_closes, cut_tol) { - rest = r; - cut = true; - } - } - if !in_union && !cut { - new_nodes.push(d.reid(leaf)); - } else if !rest.is_empty() { - new_nodes.push(shape_node(d, rest, Some(leaf))); - } - } - if !erase && !union.is_empty() && Some(i) == style_src { - let mut m = shape_node(d, union.clone(), Some(leaf)); - if let Some(f) = &merged_fill { - m.appearance.set_fill(f.clone()); - } - merged_id = Some(m.id); - new_nodes.push(m); - } - } - let new_ids = replace_roots(d, &roots, new_nodes)?; - sel.set(new_ids.iter().copied()); - Ok((new_ids, merged_id, touched)) - })?; - Ok(json!({ - "ids": ids_json(&ids), - "merged": merged.map(|m| m.0), - "regions": touched.regions.len(), - "lines": touched.lines.len(), - "edges": touched.edges.len(), - })) } /// Remove the roots and insert `nodes` where the front-most root was. Returns the new ids. @@ -363,26 +278,24 @@ fn replace_roots(d: &mut Document, roots: &[NodeId], nodes: Vec) -> Result Ok(ids) } -fn sb_regions(s: &mut Session, p: &Value) -> Result { - let roots = root_ids(s, p)?; - let d = &s.doc()?.doc; - let (map, leaves) = BuilderMap::new(d, &roots, true); - let id_of = |i: usize| leaves.get(i).map(|n| n.id.0); - let regions: Vec = map - .regions - .iter() - .map(|(r, _, bb)| { - json!({ - "bounds": [bb.x0, bb.y0, bb.x1, bb.y1], - "area": po::area(&r.path, FillRule::NonZero), - "sources": r.sources.iter().filter_map(|&i| id_of(i)).collect::>(), - }) - }) - .collect(); - let pieces = |list: &[(po::Shape, Rect)]| -> Vec { - list.iter().map(|(l, bb)| json!({ "bounds": [bb.x0, bb.y0, bb.x1, bb.y1], "source": id_of(l.key as usize) })).collect() +/// What is left of path or compound path `src`: a copy of it with a fresh id and the geometry `path` +/// (a path for one subpath, else a compound path, as [`shape_node`] makes them). It keeps the rest +/// of `src`: its look, with gradients fitted to its bounds kept where they were on it, its name, +/// opacity mask and attributes, and its fill rule unless `rule` is given. +fn remnant(d: &mut Document, src: &Node, path: PathData, rule: Option) -> Node { + let own = match &src.kind { + NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. } => *rule, + _ => FillRule::NonZero, }; - Ok(json!({ "regions": regions, "lines": pieces(&map.lines), "edges": pieces(&map.edges) })) + let shaped = shape_node(d, path, None); + let mut n = src.clone(); + n.pin_gradients(); + n.id = shaped.id; + n.kind = shaped.kind; + if let NodeKind::Path { rule: r, .. } | NodeKind::Compound { rule: r, .. } = &mut n.kind { + *r = rule.unwrap_or(own); + } + n } // ---------- Live Paint ---------- @@ -487,682 +400,3 @@ fn repaint_from(g: &mut Node, old: &Node) { } } } - -/// `options` as stored on a Live Paint group: none for the defaults. -fn stored_gap_options(options: GapOptions) -> Option> { - (options != GapOptions::default()).then(|| Box::new(options)) -} - -/// The Gap Options of Live Paint groups merged into one, given bottom-most first: the bottom-most -/// group's when its Gap Detection is on; else Gap Detection on with Small Gaps when another -/// group's is on; else the bottom-most group's. -fn merged_gap_options(groups: &[GapOptions]) -> GapOptions { - let Some(&bottom) = groups.first() else { return GapOptions::default() }; - if !bottom.detect && groups.iter().any(|g| g.detect) { GapOptions { detect: true, size: GapSize::Small, ..bottom } } else { bottom } -} - -/// Make a Live Paint group from `roots`; returns (group, faces, edges). -fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<(NodeId, usize, usize)> { - let mut sources = vec![]; - for r in roots { - let n = d.node(*r).ok_or(EngineError::NoNode(*r))?; - sources.extend(source_nodes(n)); - } - let (children, nf, ne) = build_children(d, sources, None)?; - let gid = d.alloc_id(); - let mut g = Node::group(gid, children); - g.name = Some(LIVE_PAINT_NAME.into()); - replace_roots(d, roots, vec![g])?; - sel.set([gid]); - Ok((gid, nf, ne)) -} - -fn lp_make(s: &mut Session, p: &Value) -> Result { - let roots = root_ids(s, p)?; - let (id, faces, edges) = s.edit("Make Live Paint", |d, sel| make_live(d, sel, &roots))?; - Ok(json!({ "id": id.0, "faces": faces, "edges": edges })) -} - -fn lp_merge(s: &mut Session, p: &Value) -> Result { - let roots = root_ids(s, p)?; - let (id, faces, edges) = s.edit("Merge Live Paint", |d, sel| { - let target = roots - .iter() - .copied() - .find(|r| d.node(*r).is_some_and(is_live_paint)) - .ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?; - let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?; - // Paint to carry over: (point inside face, fill) and (point on edge, stroke). - let keep_faces: Vec<(Point, Paint)> = b::faces(&old) - .iter() - .filter(|f| !f.appearance.fill_paint().is_none()) - .filter_map(|f| Some((po::interior_point(f.path_data()?)?, f.appearance.fill_paint()))) - .collect(); - let keep_edges: Vec<(Point, Appearance)> = b::edges(&old) - .iter() - .filter_map(|e| { - let pd = e.path_data()?; - let sp = pd.subpaths.first().filter(|sp| sp.segment_count() > 0)?; - Some((kurbo::ParamCurve::eval(&sp.segment(0), 0.5), (*e.appearance).clone())) - }) - .collect(); - let mut sources = source_nodes(&old); - for r in &roots { - if *r != target { - sources.extend(source_nodes(d.node(*r).ok_or(EngineError::NoNode(*r))?)); - } - } - // Merge applies the Gap Options' merge rules to the groups' options, bottom-most first. - let groups: Vec = roots.iter().filter_map(|r| d.node(*r)).filter(|n| is_live_paint(n)).map(Node::gap_options).collect(); - let options = merged_gap_options(&groups); - let (children, nf, ne) = build_children(d, sources, options.max_gap())?; - let mut g = Node::group(target, children); - g.name = old.name.clone(); - g.opacity = old.opacity; - g.blend = old.blend; - g.extras_mut().live_paint_gaps = stored_gap_options(options); - for (pt, paint) in keep_faces { - if let Some(fid) = face_at(&g, pt).map(|f| f.id) - && let Some(ch) = g.children_mut() - && let Some(f) = ch.iter_mut().find(|c| c.id == fid) - { - Arc::make_mut(f).appearance.set_fill(paint); - } - } - for (pt, app) in keep_edges { - if let Some(eid) = edge_near(&g, pt, 0.5).map(|e| e.id) - && let Some(ch) = g.children_mut() - && let Some(e) = ch.iter_mut().find(|c| c.id == eid) - { - Arc::make_mut(e).appearance = app.into(); - } - } - let mut merged = Beside::replacing(d, &roots); - for r in roots.iter().filter(|r| **r != target) { - if d.node(*r).is_some() { - merged.put(d, *r, vec![])?; - } - } - merged.put(d, target, vec![g])?; - merged.finish(d)?; - sel.set([target]); - Ok((target, nf, ne)) - })?; - Ok(json!({ "id": id.0, "faces": faces, "edges": edges })) -} - -fn live_targets(s: &Session, p: &Value) -> Result> { - let d = &s.doc()?.doc; - let ids = root_ids(s, p)?; - let v: Vec = ids.into_iter().filter(|i| d.node(*i).is_some_and(is_live_paint)).collect(); - if v.is_empty() { - return Err(EngineError::Other("select a Live Paint group".into())); - } - Ok(v) -} - -fn lp_release(s: &mut Session, p: &Value) -> Result { - let targets = live_targets(s, p)?; - let ids = s.edit("Release Live Paint", |d, sel| { - let mut out = vec![]; - let mut released = Beside::replacing(d, &targets); - for g in &targets { - let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?; - let srcs: Vec = source_nodes(&n).iter().map(|c| (**c).clone()).collect(); - out.extend(srcs.iter().map(|c| c.id)); - released.put(d, *g, srcs)?; - } - released.finish(d)?; - sel.set(out.iter().copied()); - Ok(out) - })?; - Ok(json!({ "ids": ids_json(&ids) })) -} - -fn lp_expand(s: &mut Session, p: &Value) -> Result { - let targets = live_targets(s, p)?; - s.edit("Expand Live Paint", |d, sel| { - for g in &targets { - let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?; - n.name = None; - { - let mut e = n.extras_mut(); - e.trace = None; - e.live_paint_gaps = None; - } - if let Some(ch) = n.children_mut() { - ch.retain(|c| match c.name.as_deref() { - Some(SOURCES_NAME) => false, - Some(FACE_NAME) => !c.appearance.fill_paint().is_none(), - Some(EDGE_NAME) => !c.appearance.stroke_paint().is_none() && c.appearance.stroke_width() > 0.0, - _ => true, - }); - } - } - sel.set(targets.iter().copied()); - Ok(()) - })?; - Ok(json!({ "ids": ids_json(&targets) })) -} - -/// Gaps as `[x0, y0, x1, y1]` (the loose end, then where it closes to). -fn gaps_json(gaps: &[[Point; 2]]) -> Value { - json!(gaps.iter().map(|[a, b]| [a.x, a.y, b.x, b.y]).collect::>()) -} - -/// A group's Gap Options as `livePaint.info` gives them. -fn gap_options_json(o: GapOptions) -> Value { - let [r, g, b] = o.color; - let size = o.size.id().map_or_else(|| json!(o.size.points()), |id| json!(id)); - json!({ "detect": o.detect, "size": size, "points": o.size.points(), "color": format!("#{r:02x}{g:02x}{b:02x}") }) -} - -/// The gaps up to `options`' size wide among a Live Paint group's sources. -fn open_gaps(group: &Node, options: GapOptions) -> Vec<[Point; 2]> { - po::find_gaps(&source_shapes(&source_nodes(group)).0, options.size.points()) -} - -fn lp_gap_options(s: &mut Session, p: &Value) -> Result { - const C: &str = "livePaint.gapOptions"; - let detect = match p.get("detect").filter(|v| !v.is_null()) { - Some(v) => Some(v.as_bool().ok_or_else(|| bad(C, "detect must be true or false"))?), - None => None, - }; - let size = - match p.get("size").filter(|v| !v.is_null()) { - Some(v) => Some(GapSize::parse(v).ok_or_else(|| { - bad(C, format!("size must be \"small\", \"medium\", \"large\" or a number of points over 0 up to {}", GapSize::MAX)) - })?), - None => None, - }; - let color = match p.get("color").filter(|v| !v.is_null()) { - Some(v) => Some(super::layer::layer_color_param(v).map_err(|e| bad(C, e))?.rgb()), - None => None, - }; - let close = bool_or(p, "closeGaps", false); - let targets = live_targets(s, p)?; - let (faces, gaps, closed) = s.edit("Gap Options", |d, sel| { - let (mut faces, mut gaps, mut closed) = (0, vec![], 0); - let mut changed = Beside::replacing(d, &targets); - for g in &targets { - let old = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?; - let mut options = old.gap_options(); - options.detect = detect.unwrap_or(options.detect); - options.size = size.unwrap_or(options.size); - options.color = color.unwrap_or(options.color); - let mut sources = source_nodes(&old); - if close { - // Close Gaps With Paths adds an unpainted line across each gap to the group's paths. - for gap in po::find_gaps(&source_shapes(&sources).0, options.size.points()) { - let line = PathData::single(SubPath::polyline(&gap, false)); - sources.push(Arc::new(Node::path(d.alloc_id(), line, Appearance::default()))); - closed += 1; - } - } - let mut n = old.clone(); - // The faces change only with what paint stops at, or with new paths. - if close || options.max_gap() != old.gap_options().max_gap() { - let (children, _, _) = build_children(d, sources, options.max_gap())?; - if let Some(ch) = n.children_mut() { - *ch = children; - } - repaint_from(&mut n, &old); - } - n.extras_mut().live_paint_gaps = stored_gap_options(options); - faces += b::faces(&n).len(); - gaps.extend(open_gaps(&n, options)); - changed.put(d, *g, vec![n])?; - } - changed.finish(d)?; - sel.set(targets.iter().copied()); - Ok((faces, gaps, closed)) - })?; - Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": closed })) -} - -fn lp_fill(s: &mut Session, p: &Value) -> Result { - 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 paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone()); - let group = id_param(p, "group"); - 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 { - Some(g) => { - if !d.node(g).is_some_and(is_live_paint) { - return Err(bad(C, format!("{g} is not a Live Paint group"))); - } - g - } - None => match roots.iter().copied().find(|r| d.node(*r).is_some_and(|n| is_live_paint(n) && face_at(n, pt).is_some())) { - Some(g) => g, - None => make_live(d, sel, &roots)?.0, - }, - }; - let fid = - d.node(gid).and_then(|n| 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()); - Ok((gid, fid)) - })?; - s.remember_paint(&paint); - Ok(json!({ "group": g.0, "face": face.0 })) -} - -fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result { - 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 paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.stroke.clone()); - let width = p.get("width").and_then(Value::as_f64).unwrap_or(s.paint.stroke_width.max(0.0)); - if !(0.0..=1000.0).contains(&width) { - return Err(bad(C, "width out of range")); - } - let tol = f64_or(p, "tolerance", 4.0).clamp(0.0, 1000.0); - let edge = s.edit("Live Paint Bucket", |d, _| { - let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?; - let eid = edge_near(n, pt, tol).map(|e| e.id).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?; - let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?; - e.appearance.set_stroke(paint.clone()); - if let Some(st) = e.appearance.stroke_mut() { - st.width = width; - } - Ok(eid) - })?; - s.remember_paint(&paint); - Ok(json!({ "group": g.0, "edge": edge.0 })) -} - -fn lp_info(s: &mut Session, p: &Value) -> Result { - let g = id_param(p, "group").or_else(|| id_param(p, "id")).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 = b::faces(n) - .iter() - .map(|f| { - let bb = f.geometric_bounds().unwrap_or(Rect::ZERO); - json!({ "id": f.id.0, "fill": f.appearance.fill_paint().label(), "bounds": [bb.x0, bb.y0, bb.x1, bb.y1] }) - }) - .collect(); - let edges: Vec = b::edges(n) - .iter() - .map(|e| json!({ "id": e.id.0, "stroke": e.appearance.stroke_paint().label(), "width": e.appearance.stroke_width() })) - .collect(); - let sources = b::sources(n).and_then(|g| g.children()).map(|c| c.len()).unwrap_or(0); - let options = n.gap_options(); - Ok(json!({ - "faces": faces, - "edges": edges, - "sources": sources, - "gapOptions": gap_options_json(options), - "gaps": gaps_json(&open_gaps(n, options)), - })) -} - -// ---------- Image Trace ---------- - -fn is_trace_group(n: &Node) -> bool { - matches!(n.kind, NodeKind::Group { clip: false, .. }) - && n.name.as_deref() == Some(TRACE_NAME) - && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) -} - -/// The `view` param ([`TraceView`] id), if given. -fn view_param(cmd: &str, p: &Value) -> Result> { - let Some(v) = p.get("view").filter(|v| !v.is_null()) else { return Ok(None) }; - let ids = || TraceView::ALL.map(TraceView::id).join(", "); - v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids()))) -} - -fn trace_params(p: &Value) -> Result { - let name = str_param(p, "preset").unwrap_or("Default"); - let enhanced = p.get("enhanced").and_then(Value::as_bool).unwrap_or(false); - // (A preset without an enhanced version is traced as it is.) - let base = enhanced.then(|| tr::enhanced_preset(name)).flatten().or_else(|| tr::preset(name)); - let base = base.ok_or_else(|| bad("imageTrace.make", format!("unknown preset `{name}` (see imageTrace.presets)")))?; - let Some(over) = p.get("params").filter(|v| !v.is_null()) else { return Ok(base) }; - let mut v = serde_json::to_value(&base).map_err(|e| EngineError::Other(e.to_string()))?; - let (Some(o), Some(src)) = (v.as_object_mut(), over.as_object()) else { return Err(bad("imageTrace.make", "params must be an object")) }; - for (k, val) in src { - o.insert(k.clone(), val.clone()); - } - let params: tr::TraceParams = serde_json::from_value(v).map_err(|e| bad("imageTrace.make", e.to_string()))?; - if !params.fills && !params.strokes { - return Err(bad("imageTrace.make", "Create needs fills, strokes or both")); - } - if !(params.stroke_width.is_finite() && params.stroke_width > 0.0) { - return Err(bad("imageTrace.make", "strokeWidth must be a positive number of pixels")); - } - Ok(params) -} - -/// Document Library in Color mode: look the library's colours up into `params.swatches` → each -/// one as traced (sRGB) with the colour to fill with. -fn trace_library(s: &Session, params: &mut tr::TraceParams) -> Result> { - const C: &str = "imageTrace.make"; - if params.mode != tr::Mode::Color || params.palette != tr::Palette::DocumentLibrary { - return Ok(vec![]); - } - let key = params.library.as_str(); - let colors = super::swatchlib::library_colors(s, key) - .ok_or_else(|| bad(C, format!("no swatch library `{key}` (see swatch.library.list; \"document\": the document's swatches)")))?; - if colors.is_empty() { - return Err(bad(C, format!("`{key}` has no colours"))); - } - let library: Vec<([u8; 3], Color)> = colors - .into_iter() - .map(|c| { - let [r, g, b, _] = c.to_rgba8(1.0); - ([r, g, b], c) - }) - .collect(); - params.swatches = library.iter().map(|l| l.0).collect(); - Ok(library) -} - -/// The most anchor points an Image Trace may make, a guard for memory: a trace past it is refused -/// with advice instead (#525). A trace keeps about 90 bytes an anchor in the document (measured on -/// code-drawn photos of 2000 × 2000 to 6000 × 4000 pixels), so 8,000,000 anchors are about -/// 0.7 GB, with a peak of about 1 GB while tracing: a 4000 × 3000 photo at High Fidelity Photo -/// makes about 1.9 million, and even at Paths 100, Noise 1 and every tone about 7.9 million. On the -/// web, where a page has at most 4 GB of memory, the limit stays at 2,000,000. -#[cfg(not(target_arch = "wasm32"))] -pub const MAX_TRACE_ANCHORS: usize = 8_000_000; -/// The most anchor points an Image Trace may make on the web (see the native limit). -#[cfg(target_arch = "wasm32")] -pub const MAX_TRACE_ANCHORS: usize = 2_000_000; - -/// The live shape for a shape the tracer found (in the image's pixels), placed in the document by `xf`. -fn traced_shape(shape: tr::TracedShape, xf: vectorcraft_geom::Affine) -> LiveShape { - use vectorcraft_geom::Affine; - let about = |c: Point, deg: f64| Affine::translate(c.to_vec2()) * Affine::rotate(deg.to_radians()); - let mut live = match shape { - tr::TracedShape::Rectangle { center, width, height, radius, rotation } => LiveShape::Rectangle { - w: width, - h: height, - radii: [radius; 4], - kinds: Default::default(), - xf: about(center, rotation) * Affine::translate((-width / 2.0, -height / 2.0)), - }, - tr::TracedShape::Ellipse { center, rx, ry, rotation } => { - LiveShape::Ellipse { w: 2.0 * rx, h: 2.0 * ry, pie: (0.0, 360.0), xf: about(center, rotation) * Affine::translate((-rx, -ry)) } - } - tr::TracedShape::Polygon { center, radius, sides, rotation } => { - LiveShape::Polygon { radius, sides, xf: about(center, rotation), radii: vec![], kinds: vec![] } - } - }; - // (Whether the move changed the shape's own numbers does not matter: its path is made from them next.) - let _ = live.transform(xf); - live -} - -/// The gradient fill for a linear gradient the tracer found (in the image's pixels), placed in the -/// document by `xf`. -fn traced_gradient(g: &tr::TracedGradient, xf: vectorcraft_geom::Affine) -> Paint { - use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; - let stops = g.stops.iter().map(|&(at, c)| GradientStop::new(at as f32, Color::rgb8(c[0], c[1], c[2]))).collect(); - let mut paint = GradientPaint::new(Gradient { kind: GradientKind::Linear, stops }); - paint.geom = Some(GradientGeom { start: xf * g.start, end: xf * g.end, aspect: 1.0, focal: None }); - Paint::Gradient(Box::new(paint)) -} - -/// Auto Grouping: `nodes` (one per traced path, bottom-most first) with each path that has others -/// inside it (`parents`, as the tracer gives them) in a group with them, in the order they had: -/// abutting paths painted in another order would show a seam where they meet. Without parents, -/// the nodes as they are. -fn grouped(d: &mut Document, nodes: Vec, parents: &[Option]) -> Vec> { - let n = nodes.len(); - let mut inside: Vec> = vec![vec![]; n]; - let mut roots = vec![]; - for i in 0..n { - match parents.get(i).copied().flatten().and_then(|p| inside.get_mut(p).filter(|_| p != i)) { - Some(of) => of.push(i), - None => roots.push(i), - } - } - // Outermost first, so that backwards each path comes after those inside it. - let mut order = roots.clone(); - let mut at = 0; - while let Some(&i) = order.get(at) { - order.extend(inside.get(i).into_iter().flatten()); - at += 1; - } - let mut nodes: Vec> = nodes.into_iter().map(Some).collect(); - let mut built: Vec>> = vec![None; n]; - for &i in order.iter().rev() { - let Some(node) = nodes.get_mut(i).and_then(Option::take) else { continue }; - let mut within: Vec<(usize, Arc)> = inside.get(i).into_iter().flatten().filter_map(|&c| Some((c, built.get_mut(c)?.take()?))).collect(); - let made = if within.is_empty() { - node - } else { - within.push((i, Arc::new(node))); - within.sort_by_key(|m| m.0); - Node::group(d.alloc_id(), within.into_iter().map(|m| m.1).collect()) - }; - if let Some(slot) = built.get_mut(i) { - *slot = Some(Arc::new(made)); - } - } - // (Paths that are inside each other in a ring are reached from no root: the tracer makes none, - // and they are kept all the same.) - let ring = nodes.into_iter().flatten().map(Arc::new).collect::>(); - roots.iter().filter_map(|&r| built.get_mut(r)?.take()).chain(ring).collect() -} - -fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result { - const C: &str = "imageTrace.make"; - let mut params = trace_params(p)?; - let view = view_param(C, p)?; - let params_json = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?; - // The preset's name if the parameters are exactly that preset's or its enhanced version's, - // else "Custom". - let named = str_param(p, "preset").unwrap_or("Default"); - let is = |b: Option| b.and_then(|b| serde_json::to_value(&b).ok()).as_ref() == Some(¶ms_json); - let preset_label = if is(tr::preset(named)) || is(tr::enhanced_preset(named)) { named.to_string() } else { "Custom".to_string() }; - let roots = root_ids(s, p)?; - // The image (inside a trace group, or selected directly). - let (target, img) = { - let d = &s.doc()?.doc; - roots - .iter() - .find_map(|r| { - let n = d.node(*r)?; - match &n.kind { - NodeKind::Image(i) => Some((*r, i.clone())), - _ if is_trace_group(n) => match &n.children()?.first()?.kind { - NodeKind::Image(i) => Some((*r, i.clone())), - _ => None, - }, - _ => None, - } - }) - .ok_or_else(|| bad(C, "select an image (or an Image Trace group)"))? - }; - let blob = s.doc()?.doc.images.get(&img.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", img.key)))?; - // An image over the tracer's size is traced scaled down (the paths are scaled back below). - let raster = tr::Raster::decode_to_fit(&blob.bytes).map_err(|e| EngineError::Other(e.to_string()))?; - let library = trace_library(s, &mut params)?; - let res = tr::trace_within(&raster, ¶ms, MAX_TRACE_ANCHORS).map_err(|e| EngineError::Other(e.to_string()))?; - let warnings = trace_warnings((img.width, img.height), (raster.width, raster.height)); - // Pixel space of the decoded raster → the image object's pixel space → document. - let sx = img.width.max(1) as f64 / raster.width.max(1) as f64; - let sy = img.height.max(1) as f64 / raster.height.max(1) as f64; - let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy); - // Document units per raster pixel (stroke widths). - let unit = xf.determinant().abs().sqrt(); - let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len()); - let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" }; - let id = s.edit(label, |d, sel| { - let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?; - let mut image = if is_trace_group(&src) { - src.children() - .and_then(|c| c.first()) - .map(|c| (**c).clone()) - .ok_or_else(|| EngineError::Other("Image Trace: the traced image is missing".into()))? - } else { - src.clone() - }; - image.visible = true; - let mut children: Vec> = vec![]; - if !expand { - let mut hidden = image.clone(); - hidden.visible = false; - children.push(Arc::new(hidden)); - } - let mut traced = Vec::with_capacity(res.paths.len()); - for tp in res.paths { - let path = tp.path.transformed(xf); - let mut n = shape_node(d, path, None); - // Shapes: a path the tracer found to be a shape is that live shape. - if let (Some(shape), NodeKind::Path { path, live, .. }) = (tp.shape, &mut n.kind) { - let shape = traced_shape(shape, xf); - *path = shape.to_path(); - *live = Some(Box::new(shape)); - } - // A library colour fills with the swatch's own colour (its model kept). - let color = library.iter().find(|(rgb, _)| *rgb == tp.color).map_or_else(|| Color::rgb8(tp.color[0], tp.color[1], tp.color[2]), |l| l.1); - // Gradients: a path the tracer found to be a linear gradient is filled with it. - let paint = tp.gradient.as_ref().map_or_else(|| Paint::solid(color), |g| traced_gradient(g, xf)); - n.appearance = match tp.stroke { - // Traced lines: round corners, and ends round or square as the tracer found them. - Some(width) => Appearance { - items: vec![AppearanceItem::Stroke(StrokeLayer { - cap: if tp.square_caps { LineCap::Square } else { LineCap::Round }, - join: LineJoin::Round, - ..StrokeLayer::new(paint, width * unit) - })], - ..Default::default() - } - .into(), - None => fill_only(paint).into(), - }; - traced.push(n); - } - children.extend(grouped(d, traced, &res.parents)); - let gid = d.alloc_id(); - let mut g = Node::group(gid, children); - g.name = if expand { None } else { Some(TRACE_NAME.into()) }; - if !expand { - // Tracing again keeps the object's view unless another is asked for. - let view = view.unwrap_or_else(|| src.trace_view()); - g.extras_mut().trace = Some(Box::new(json!({ "preset": preset_label, "params": params_json, "view": view.id() }))); - } - let (par, idx, _) = d.position(target).ok_or(EngineError::NoNode(target))?; - d.remove(target)?; - d.insert(par, idx, g)?; - sel.set([gid]); - Ok(gid) - })?; - Ok(json!({ "id": id.0, "paths": npaths, "anchors": anchors, "colors": colors, "warnings": warnings })) -} - -/// Images larger than this on a side are traced, but more slowly: the trace says so. -pub const LARGE_TRACE_SIDE: u32 = 1500; - -/// What a trace of an image of `size` pixels, traced at `traced` pixels, tells the user: that a -/// large image takes longer (the public documentation's warning for images over 1500 px), and that -/// one over the tracer's [`tr::MAX_PIXELS`] was traced scaled down. -pub(crate) fn trace_warnings(size: (u32, u32), traced: (u32, u32)) -> Vec { - let mut out = vec![]; - if size.0.max(size.1) > LARGE_TRACE_SIDE { - out.push(format!( - "The image is {} × {} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster.", - size.0, size.1 - )); - } - if u64::from(traced.0) * u64::from(traced.1) < u64::from(size.0) * u64::from(size.1) { - out.push(format!( - "The image was traced at {} × {} pixels, scaled down from {} × {} ({} megapixels at most).", - traced.0, - traced.1, - size.0, - size.1, - tr::MAX_PIXELS >> 20 - )); - } - out -} - -fn trace_targets(s: &Session, p: &Value) -> Result> { - let d = &s.doc()?.doc; - let v: Vec = root_ids(s, p)?.into_iter().filter(|i| d.node(*i).is_some_and(is_trace_group)).collect(); - if v.is_empty() { - return Err(EngineError::Other("select an Image Trace object".into())); - } - Ok(v) -} - -fn trace_set_view(s: &mut Session, p: &Value) -> Result { - const C: &str = "imageTrace.setView"; - let view = view_param(C, p)?.ok_or_else(|| bad(C, "view is required"))?; - let targets = trace_targets(s, p)?; - let d = &s.doc()?.doc; - if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view)) { - return Ok(json!({ "ids": ids_json(&targets), "view": view.id() })); - } - s.edit("Image Trace View", |d, _| { - for g in &targets { - let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?; - if let Some(t) = n.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(Value::as_object_mut) { - t.insert("view".into(), json!(view.id())); - } else { - n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom", "view": view.id() }))); - } - } - Ok(()) - })?; - Ok(json!({ "ids": ids_json(&targets), "view": view.id() })) -} - -fn trace_release(s: &mut Session, p: &Value) -> Result { - let targets = trace_targets(s, p)?; - let ids = s.edit("Release Image Trace", |d, sel| { - let mut out = vec![]; - let mut released = Beside::replacing(d, &targets); - for g in &targets { - let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?; - let mut img = (**n.children().and_then(|c| c.first()).ok_or(EngineError::NoNode(*g))?).clone(); - img.visible = true; - out.push(img.id); - released.put(d, *g, vec![img])?; - } - released.finish(d)?; - sel.set(out.iter().copied()); - Ok(out) - })?; - Ok(json!({ "ids": ids_json(&ids) })) -} - -fn trace_expand(s: &mut Session, p: &Value) -> Result { - let targets = trace_targets(s, p)?; - s.edit("Expand Image Trace", |d, sel| { - for g in &targets { - let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?; - n.name = None; - n.extras_mut().trace = None; - if let Some(ch) = n.children_mut() { - ch.retain(|c| !matches!(c.kind, NodeKind::Image(_))); - } - } - sel.set(targets.iter().copied()); - Ok(()) - })?; - Ok(json!({ "ids": ids_json(&targets) })) -} - -#[cfg(test)] -mod trace_limit_tests { - use super::{MAX_TRACE_ANCHORS, trace_warnings}; - - #[test] - fn trace_warnings_name_a_large_or_scaled_down_image() { - assert!(trace_warnings((1500, 1500), (1500, 1500)).is_empty()); - assert_eq!(trace_warnings((1501, 10), (1501, 10)).len(), 1); - let w = trace_warnings((16000, 12000), (9459, 7094)); - assert_eq!(w.len(), 2, "{w:?}"); - assert!(w[0].contains("16000 × 12000") && w[1].contains("9459 × 7094") && w[1].contains("64 megapixels"), "{w:?}"); - } - - // A 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million anchors, which must fit; - // the limit still guards memory (about 90 bytes an anchor). Checked when the tests build. - const _: () = assert!(MAX_TRACE_ANCHORS >= 2_000_000 && MAX_TRACE_ANCHORS <= 16_000_000); -} diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs new file mode 100644 index 0000000000..f9b224ce8c --- /dev/null +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -0,0 +1,357 @@ +use super::*; + +/// `options` as stored on a Live Paint group: none for the defaults. +fn stored_gap_options(options: GapOptions) -> Option> { + (options != GapOptions::default()).then(|| Box::new(options)) +} + +/// The Gap Options of Live Paint groups merged into one, given bottom-most first: the bottom-most +/// group's when its Gap Detection is on; else Gap Detection on with Small Gaps when another +/// group's is on; else the bottom-most group's. +fn merged_gap_options(groups: &[GapOptions]) -> GapOptions { + let Some(&bottom) = groups.first() else { return GapOptions::default() }; + if !bottom.detect && groups.iter().any(|g| g.detect) { GapOptions { detect: true, size: GapSize::Small, ..bottom } } else { bottom } +} + +/// Refuse `roots` when one of them is something Live Paint can't take ([`b::live_paint_takes`]): +/// its faces and edges come from path outlines alone, so type or an image would vanish among the +/// group's hidden sources. Checked before anything changes. +fn check_live_paint_takes(d: &Document, roots: &[NodeId]) -> Result<()> { + for r in roots { + if !b::live_paint_takes(d.node(*r).ok_or(EngineError::NoNode(*r))?) { + return Err(EngineError::Other( + "Live Paint takes paths and compound paths: convert type, images and other objects to paths first".into(), + )); + } + } + Ok(()) +} + +/// Make a Live Paint group from `roots`, or add them to the first Live Paint group among them +/// as Merge does; returns (group, faces, edges). +fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<(NodeId, usize, usize)> { + check_live_paint_takes(d, roots)?; + if roots.iter().any(|r| d.node(*r).is_some_and(is_live_paint)) { + return merge_live(d, sel, roots); + } + let mut sources = vec![]; + for r in roots { + let n = d.node(*r).ok_or(EngineError::NoNode(*r))?; + sources.extend(source_nodes(n)); + } + let (children, nf, ne) = build_children(d, sources, None)?; + let gid = d.alloc_id(); + let mut g = Node::group(gid, children); + g.name = Some(LIVE_PAINT_NAME.into()); + replace_roots(d, roots, vec![g])?; + sel.set([gid]); + Ok((gid, nf, ne)) +} + +pub(super) fn lp_make(s: &mut Session, p: &Value) -> Result { + let roots = root_ids(s, p)?; + let (id, faces, edges) = s.edit("Make Live Paint", |d, sel| make_live(d, sel, &roots))?; + Ok(json!({ "id": id.0, "faces": faces, "edges": edges })) +} + +/// Add the other `roots` (back → front) to the first Live Paint group among them, which keeps its +/// id, the paint of its faces and edges, and its own properties apart from the Gap Options, which +/// are merged; returns (group, faces, edges). +fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<(NodeId, usize, usize)> { + let target = roots + .iter() + .copied() + .find(|r| d.node(*r).is_some_and(is_live_paint)) + .ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?; + check_live_paint_takes(d, roots)?; + let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?; + // Paint to carry over: (point inside face, fill) and (point on edge, stroke). + let keep_faces: Vec<(Point, Paint)> = b::faces(&old) + .iter() + .filter(|f| !f.appearance.fill_paint().is_none()) + .filter_map(|f| Some((po::interior_point(f.path_data()?)?, f.appearance.fill_paint()))) + .collect(); + let keep_edges: Vec<(Point, Appearance)> = b::edges(&old) + .iter() + .filter_map(|e| { + let pd = e.path_data()?; + let sp = pd.subpaths.first().filter(|sp| sp.segment_count() > 0)?; + Some((kurbo::ParamCurve::eval(&sp.segment(0), 0.5), (*e.appearance).clone())) + }) + .collect(); + let mut sources = source_nodes(&old); + for r in roots { + if *r != target { + sources.extend(source_nodes(d.node(*r).ok_or(EngineError::NoNode(*r))?)); + } + } + // Merge applies the Gap Options' merge rules to the groups' options, bottom-most first. + let groups: Vec = roots.iter().filter_map(|r| d.node(*r)).filter(|n| is_live_paint(n)).map(Node::gap_options).collect(); + let options = merged_gap_options(&groups); + let (children, nf, ne) = build_children(d, sources, options.max_gap())?; + // The group keeps its name, lock, visibility, transparency, appearance, opacity mask, graphic + // style link and the rest; its children are made again and its Gap Options set to the merged ones. + let mut g = old; + if let Some(ch) = g.children_mut() { + *ch = children; + } + g.extras_mut().live_paint_gaps = stored_gap_options(options); + for (pt, paint) in keep_faces { + if let Some(fid) = face_at(&g, pt).map(|f| f.id) + && let Some(ch) = g.children_mut() + && let Some(f) = ch.iter_mut().find(|c| c.id == fid) + { + Arc::make_mut(f).appearance.set_fill(paint); + } + } + for (pt, app) in keep_edges { + if let Some(eid) = edge_near(&g, pt, 0.5).map(|e| e.id) + && let Some(ch) = g.children_mut() + && let Some(e) = ch.iter_mut().find(|c| c.id == eid) + { + Arc::make_mut(e).appearance = app.into(); + } + } + let mut merged = Beside::replacing(d, roots); + for r in roots.iter().filter(|r| **r != target) { + if d.node(*r).is_some() { + merged.put(d, *r, vec![])?; + } + } + merged.put(d, target, vec![g])?; + merged.finish(d)?; + sel.set([target]); + Ok((target, nf, ne)) +} + +pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result { + let roots = root_ids(s, p)?; + let (id, faces, edges) = s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?; + Ok(json!({ "id": id.0, "faces": faces, "edges": edges })) +} + +fn live_targets(s: &Session, p: &Value) -> Result> { + let d = &s.doc()?.doc; + let ids = root_ids(s, p)?; + let v: Vec = ids.into_iter().filter(|i| d.node(*i).is_some_and(is_live_paint)).collect(); + if v.is_empty() { + return Err(EngineError::Other("select a Live Paint group".into())); + } + Ok(v) +} + +pub(super) fn lp_release(s: &mut Session, p: &Value) -> Result { + let targets = live_targets(s, p)?; + let ids = s.edit("Release Live Paint", |d, sel| { + let mut out = vec![]; + let mut released = Beside::replacing(d, &targets); + for g in &targets { + let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?; + let srcs: Vec = source_nodes(&n).iter().map(|c| (**c).clone()).collect(); + out.extend(srcs.iter().map(|c| c.id)); + released.put(d, *g, srcs)?; + } + released.finish(d)?; + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "ids": ids_json(&ids) })) +} + +pub(super) fn lp_expand(s: &mut Session, p: &Value) -> Result { + let targets = live_targets(s, p)?; + s.edit("Expand Live Paint", |d, sel| { + for g in &targets { + let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?; + n.name = None; + { + let mut e = n.extras_mut(); + e.trace = None; + e.live_paint_gaps = None; + } + if let Some(ch) = n.children_mut() { + ch.retain(|c| match c.name.as_deref() { + Some(SOURCES_NAME) => false, + Some(FACE_NAME) => !c.appearance.fill_paint().is_none(), + Some(EDGE_NAME) => !c.appearance.stroke_paint().is_none() && c.appearance.stroke_width() > 0.0, + _ => true, + }); + } + } + sel.set(targets.iter().copied()); + Ok(()) + })?; + Ok(json!({ "ids": ids_json(&targets) })) +} + +/// Gaps as `[x0, y0, x1, y1]` (the loose end, then where it closes to). +fn gaps_json(gaps: &[[Point; 2]]) -> Value { + json!(gaps.iter().map(|[a, b]| [a.x, a.y, b.x, b.y]).collect::>()) +} + +/// A group's Gap Options as `livePaint.info` gives them. +fn gap_options_json(o: GapOptions) -> Value { + let [r, g, b] = o.color; + let size = o.size.id().map_or_else(|| json!(o.size.points()), |id| json!(id)); + json!({ "detect": o.detect, "size": size, "points": o.size.points(), "color": format!("#{r:02x}{g:02x}{b:02x}") }) +} + +/// The gaps up to `options`' size wide among a Live Paint group's sources. +fn open_gaps(group: &Node, options: GapOptions) -> Vec<[Point; 2]> { + po::find_gaps(&source_shapes(&source_nodes(group)).0, options.size.points()) +} + +/// The gaps View › Show Live Paint Gaps shows on `group`: those up to its Gap Options' size wide, +/// as `livePaint.info` lists them. None when `group` is not a Live Paint group. +pub fn live_paint_gaps(group: &Node) -> Vec<[Point; 2]> { + if is_live_paint(group) { open_gaps(group, group.gap_options()) } else { vec![] } +} + +pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result { + const C: &str = "livePaint.gapOptions"; + let detect = match p.get("detect").filter(|v| !v.is_null()) { + Some(v) => Some(v.as_bool().ok_or_else(|| bad(C, "detect must be true or false"))?), + None => None, + }; + let size = + match p.get("size").filter(|v| !v.is_null()) { + Some(v) => Some(GapSize::parse(v).ok_or_else(|| { + bad(C, format!("size must be \"small\", \"medium\", \"large\" or a number of points over 0 up to {}", GapSize::MAX)) + })?), + None => None, + }; + let color = match p.get("color").filter(|v| !v.is_null()) { + Some(v) => Some(crate::cmd::layer::layer_color_param(v).map_err(|e| bad(C, e))?.rgb()), + None => None, + }; + let close = switch_or(p, "closeGaps", false, C)?; + let targets = live_targets(s, p)?; + let (faces, gaps, closed) = s.edit("Gap Options", |d, sel| { + let (mut faces, mut gaps, mut closed) = (0, vec![], 0); + let mut changed = Beside::replacing(d, &targets); + for g in &targets { + let old = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?; + let mut options = old.gap_options(); + options.detect = detect.unwrap_or(options.detect); + options.size = size.unwrap_or(options.size); + options.color = color.unwrap_or(options.color); + let mut sources = source_nodes(&old); + if close { + // Close Gaps With Paths adds an unpainted line across each gap to the group's paths. + for gap in po::find_gaps(&source_shapes(&sources).0, options.size.points()) { + let line = PathData::single(SubPath::polyline(&gap, false)); + sources.push(Arc::new(Node::path(d.alloc_id(), line, Appearance::default()))); + closed += 1; + } + } + let mut n = old.clone(); + // The faces change only with what paint stops at, or with new paths. + if close || options.max_gap() != old.gap_options().max_gap() { + let (children, _, _) = build_children(d, sources, options.max_gap())?; + if let Some(ch) = n.children_mut() { + *ch = children; + } + repaint_from(&mut n, &old); + } + n.extras_mut().live_paint_gaps = stored_gap_options(options); + faces += b::faces(&n).len(); + gaps.extend(open_gaps(&n, options)); + changed.put(d, *g, vec![n])?; + } + changed.finish(d)?; + sel.set(targets.iter().copied()); + Ok((faces, gaps, closed)) + })?; + Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": closed })) +} + +pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { + const C: &str = "livePaint.fill"; + let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?; + 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 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 { + Some(g) => { + if !d.node(g).is_some_and(is_live_paint) { + return Err(bad(C, format!("{g} is not a Live Paint group"))); + } + g + } + None => { + let live_at = |face: fn(&Node, Point) -> Option<&Arc>| { + roots.iter().copied().find(|r| d.node(*r).is_some_and(|n| is_live_paint(n) && face(n, pt).is_some())) + }; + match (live_at(b::visible_face_at), live_at(face_at)) { + (Some(g), _) => g, + // At a point on a hidden face of a Live Paint group among the objects, the command returns an error + // and does not merge the objects. + (None, Some(_)) => return Err(EngineError::Other("no Live Paint face at that point".into())), + (None, None) => make_live(d, sel, &roots)?.0, + } + } + }; + let fid = d + .node(gid) + .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()); + Ok((gid, fid)) + })?; + s.remember_paint(&paint); + Ok(json!({ "group": g.0, "face": face.0 })) +} + +pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result { + 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"))?; + 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)?; + if !(0.0..=1000.0).contains(&width) { + return Err(bad(C, "width out of range")); + } + let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0); + let edge = s.edit("Live Paint Bucket", |d, _| { + let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?; + let eid = b::visible_edge_near(n, pt, tol).map(|e| e.id).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?; + let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?; + e.appearance.set_stroke(paint.clone()); + if let Some(st) = e.appearance.stroke_mut() { + st.width = width; + } + Ok(eid) + })?; + s.remember_paint(&paint); + Ok(json!({ "group": g.0, "edge": edge.0 })) +} + +pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result { + let g = id_param(p, "group").or_else(|| id_param(p, "id")).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 = b::faces(n) + .iter() + .map(|f| { + let bb = f.geometric_bounds().unwrap_or(Rect::ZERO); + json!({ "id": f.id.0, "fill": f.appearance.fill_paint().label(), "bounds": [bb.x0, bb.y0, bb.x1, bb.y1] }) + }) + .collect(); + let edges: Vec = b::edges(n) + .iter() + .map(|e| json!({ "id": e.id.0, "stroke": e.appearance.stroke_paint().label(), "width": e.appearance.stroke_width() })) + .collect(); + let sources = b::sources(n).and_then(|g| g.children()).map(|c| c.len()).unwrap_or(0); + let options = n.gap_options(); + Ok(json!({ + "faces": faces, + "edges": edges, + "sources": sources, + "gapOptions": gap_options_json(options), + "gaps": gaps_json(&open_gaps(n, options)), + })) +} diff --git a/crates/engine/src/cmd/buildcmds/shape_builder.rs b/crates/engine/src/cmd/buildcmds/shape_builder.rs new file mode 100644 index 0000000000..07d4949a0f --- /dev/null +++ b/crates/engine/src/cmd/buildcmds/shape_builder.rs @@ -0,0 +1,214 @@ +use super::*; + +pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result { + const C: &str = "shapeBuilder.merge"; + let marquee = marquee_param(p, C)?; + let pts = match points_param(p, "points") { + Some(pts) => pts, + // A marquee needs no drag path. + None if marquee.is_some() && p.get("points").is_none_or(Value::is_null) => vec![], + None => return Err(bad(C, "missing points [[x,y]…]")), + }; + if (pts.is_empty() && marquee.is_none()) || !pts.iter().all(|q| finite(*q)) { + return Err(bad(C, "points must be a non-empty list of finite [x,y]")); + } + let erase = switch_or(p, "erase", false, C)?; + check_numbers(p, &["tolerance", "gap"], C)?; + // Line pieces and edges are only deleted (erase mode), never merged. + let piece_tol = erase.then(|| f64_or(p, "tolerance", 2.0).clamp(0.0, 1000.0)); + // In Merge Mode, Clicking Stroke Splits the Path: a click (one point) on a stroke splits it; a + // marquee does not. + let split_tol = (switch_or(p, "splitStroke", false, C)? && !erase && pts.len() == 1 && marquee.is_none()) + .then(|| f64_or(p, "tolerance", 2.0).clamp(0.0, 1000.0)); + let open_filled_as_closed = switch_or(p, "openFilledAsClosed", true, C)?; + let swatches = match p.get("pickColorFrom") { + None | Some(Value::Null) => false, + Some(v) => match v.as_str() { + Some("artwork") => false, + Some("swatches") => true, + _ => return Err(bad(C, format!("pickColorFrom is \"artwork\" or \"swatches\", not {v}"))), + }, + }; + let fill = match fill_param(s, p, C)? { + None if swatches => Some(s.paint.fill.clone()), + f => f, + }; + let roots = root_ids(s, p)?; + let gap = gap_param(p); + // The map the Shape Builder tool already has, which a click or drag of it is made over. + let shared = s.tool.shape_builder_map().filter(|(_, g)| *g == gap); + let label = if erase { "Shape Builder Delete" } else { "Shape Builder" }; + let (ids, merged, touched, split) = s.edit(label, |d, sel| { + let (shapes, leaves) = b::shape_builder_shapes(d, &roots, open_filled_as_closed); + let built; + let map = match &shared { + // The tool's map has the outline edges, which erasing and splitting need. + Some((m, _)) if m.shapes == shapes => m.as_ref(), + _ => { + built = BuilderMap::of_shapes(shapes, erase || split_tol.is_some(), gap); + &built + } + }; + let outlines = b::drawn_outlines(d, &leaves); + let leaves: Vec = leaves.into_iter().cloned().collect(); + if map.shapes.is_empty() { + return Err(EngineError::Other("Shape Builder: select paths or compound paths".into())); + } + if let Some(tol) = split_tol + && let Some(&q) = pts.first() + && let Some((i, run)) = map.stroke_at(&outlines, q, tol) + && let (Some(leaf), Some(drawn)) = (leaves.get(i), outlines.get(i)) + && let Some(rest) = po::cut_out(drawn, &run, open_filled_as_closed && !leaf.appearance.fill_paint().is_none(), b::outline_snap(drawn)) + && rest.length() > b::outline_snap(drawn) + { + // The path keeps the rest of it, and a copy of it with the run under the click goes + // directly above it; the other objects stay as they are. Gradients fitted to the + // path's bounds keep that fit on both. + if let Some(n) = d.node_mut(leaf.id) { + n.pin_gradients(); + } + let pieces = [rest, PathData::single(run)].into_iter().filter(|pd| !pd.is_empty()).collect(); + let mut replaced = Beside::replacing(d, &[leaf.id]); + let new_ids = replace_with_pieces(d, &mut replaced, leaf.id, pieces)?; + replaced.finish(d)?; + let split = *new_ids.last().ok_or(EngineError::NoNode(leaf.id))?; + // Pick Color From Color Swatches (or `fill`): the stroke takes that paint. + if let Some(f) = &fill + && let Some(n) = d.node_mut(split) + { + n.appearance.set_stroke(f.clone()); + } + // The roots stay selected, with the two paths in place of the path when it was one. + let ids: Vec = roots.iter().flat_map(|r| if *r == leaf.id { new_ids.clone() } else { vec![*r] }).collect(); + sel.set(ids.iter().copied()); + let mut touched = Touched::default(); + touched.add(map.hit(q, Some(tol))); + return Ok((ids, None, touched, Some(split))); + } + let mut touched = Touched { regions: marquee.map(|(a, b)| map.regions_in_marquee(a, b)).unwrap_or_default(), ..Default::default() }; + touched.extend(&map.builder_hits_along(&pts, piece_tol)); + touched.edges = map.erased_edges(&touched); + if touched.is_empty() { + return Err(EngineError::Other("Shape Builder: no region under the pointer".into())); + } + let cuts: Vec<&SubPath> = touched.edges.iter().filter_map(|&k| map.edges.get(k)?.0.path.subpaths.first()).collect(); + let picked: Vec<&po::Region> = touched.regions.iter().filter_map(|&i| map.regions.get(i).map(|r| &r.0)).collect(); + let faces = po::FaceMerger::with_gap(&map.shapes, gap_param(p)); + let union = if picked.is_empty() { PathData::default() } else { faces.merge(&picked) }; + // Pick Color From Artwork: the merged shape takes the look of the front-most object under the + // drag's first point, else under its last point, else of the front-most object. Color + // Swatches: the current fill, with the rest of the look of the front-most object over the + // first region the drag touched that an object covers, else of the front-most object. A + // marquee's drag starts at its first corner and ends at the opposite one. + let top_at = |q: &Point| map.region_at(*q).and_then(|k| map.regions.get(k)).and_then(|(r, ..)| r.top()); + let (first, last) = match marquee { + Some((a, b)) => (Some(a), Some(b)), + None => (pts.first().copied(), pts.last().copied()), + }; + let covered = + if swatches { picked.iter().find_map(|r| r.top()) } else { first.as_ref().and_then(top_at).or_else(|| last.as_ref().and_then(top_at)) }; + let style_src = covered.or(map.shapes.len().checked_sub(1)); + let mut new_nodes: Vec = vec![]; + let mut merged_id = None; + for (i, (sh, leaf)) in map.shapes.iter().zip(&leaves).enumerate() { + let pieces: Vec = map.lines.iter().enumerate().filter(|(_, (l, _))| l.key == i as u64).map(|(k, _)| k).collect(); + if !pieces.is_empty() { + // An open path loses the pieces deleted and those between two merged (or deleted) regions. + let keep: Vec = + pieces.iter().copied().filter(|k| !touched.lines.contains(k) && !map.line_between(*k, &touched.regions)).collect(); + if keep.len() == pieces.len() { + new_nodes.push(d.reid(leaf)); + } else { + for k in keep { + if let Some((l, _)) = map.lines.get(k) { + new_nodes.push(remnant(d, leaf, l.path.clone(), None)); + } + } + } + } else { + // A shape loses the regions deleted or merged, then the edges deleted (each one on + // its outline, shared edges from every shape along them). + let in_union = picked.iter().any(|r| r.sources.contains(&i)); + let mut rest = if in_union { + // What is left of it: its faces not merged or deleted, united. They share their + // edges with the merged faces exactly, where subtracting the merged shape left + // slivers of the outline along them (#569). A sliver goes in only where the + // shape covers it and the merged shape does not take it in. + let kept: Vec<&po::Region> = map + .regions + .iter() + .enumerate() + .filter(|(k, (r, ..))| r.sources.contains(&i) && !touched.regions.contains(k)) + .map(|(_, (r, ..))| r) + .collect(); + if kept.is_empty() { PathData::default() } else { faces.merge_rest(i, &kept, &picked) } + } else { + b::node_outline(leaf).map_or_else(|| sh.path.clone(), |o| o.0) + }; + let fill_closes = open_filled_as_closed && !leaf.appearance.fill_paint().is_none(); + // Edges come back from the planar map within a few hundredths of the outlines they + // follow, whatever else is selected. + let cut_tol = b::outline_snap(&sh.path); + let mut cut = false; + for piece in &cuts { + if let Some(r) = po::cut_out(&rest, piece, fill_closes, cut_tol) { + rest = r; + cut = true; + } + } + if !in_union && !cut { + new_nodes.push(d.reid(leaf)); + } else if !rest.is_empty() { + // What is left of its own outline keeps its fill rule; united faces fill with non-zero. + new_nodes.push(remnant(d, leaf, rest, in_union.then_some(FillRule::NonZero))); + } + } + if !erase && !union.is_empty() && Some(i) == style_src { + let mut m = shape_node(d, union.clone(), Some(leaf)); + if let Some(f) = &fill { + m.appearance.set_fill(f.clone()); + } + merged_id = Some(m.id); + new_nodes.push(m); + } + } + let new_ids = replace_roots(d, &roots, new_nodes)?; + sel.set(new_ids.iter().copied()); + Ok((new_ids, merged_id, touched, None)) + })?; + let mut out = json!({ + "ids": ids_json(&ids), + "merged": merged.map(|m| m.0), + "regions": touched.regions.len(), + "lines": touched.lines.len(), + "edges": touched.edges.len(), + }); + if let Some(e) = split { + out["split"] = json!(e.0); + } + Ok(out) +} + +pub(super) fn sb_regions(s: &mut Session, p: &Value) -> Result { + let open_filled_as_closed = switch_or(p, "openFilledAsClosed", true, "shapeBuilder.regions")?; + check_numbers(p, &["gap"], "shapeBuilder.regions")?; + let roots = root_ids(s, p)?; + let d = &s.doc()?.doc; + let (map, leaves) = BuilderMap::with_gap(d, &roots, true, open_filled_as_closed, gap_param(p)); + let id_of = |i: usize| leaves.get(i).map(|n| n.id.0); + let regions: Vec = map + .regions + .iter() + .map(|(r, _, bb)| { + json!({ + "bounds": [bb.x0, bb.y0, bb.x1, bb.y1], + "area": po::area(&r.path, FillRule::NonZero), + "sources": r.sources.iter().filter_map(|&i| id_of(i)).collect::>(), + }) + }) + .collect(); + let pieces = |list: &[(po::Shape, Rect)]| -> Vec { + list.iter().map(|(l, bb)| json!({ "bounds": [bb.x0, bb.y0, bb.x1, bb.y1], "source": id_of(l.key as usize) })).collect() + }; + Ok(json!({ "regions": regions, "lines": pieces(&map.lines), "edges": pieces(&map.edges) })) +} diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs new file mode 100644 index 0000000000..2eb4bcfcc3 --- /dev/null +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -0,0 +1,418 @@ +use super::*; + +// ---------- Image Trace ---------- + +fn is_trace_group(n: &Node) -> bool { + matches!(n.kind, NodeKind::Group { clip: false, .. }) + && n.name.as_deref() == Some(TRACE_NAME) + && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) +} + +/// The `view` param ([`TraceView`] id), if given. +fn view_param(cmd: &str, p: &Value) -> Result> { + let Some(v) = p.get("view").filter(|v| !v.is_null()) else { return Ok(None) }; + let ids = || TraceView::ALL.map(TraceView::id).join(", "); + v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids()))) +} + +/// The parameters command `c` traces with: the preset's, with `params` over them. +fn trace_params(c: &str, p: &Value) -> Result { + let name = str_param(p, "preset").unwrap_or("Default"); + let enhanced = switch_or(p, "enhanced", false, c)?; + // (A preset without an enhanced version is traced as it is.) + let base = enhanced.then(|| tr::enhanced_preset(name)).flatten().or_else(|| tr::preset(name)); + let base = base.ok_or_else(|| bad(c, format!("unknown preset `{name}` (see imageTrace.presets)")))?; + let Some(over) = p.get("params").filter(|v| !v.is_null()) else { return Ok(base) }; + let mut v = serde_json::to_value(&base).map_err(|e| EngineError::Other(e.to_string()))?; + let (Some(o), Some(src)) = (v.as_object_mut(), over.as_object()) else { return Err(bad(c, "params must be an object")) }; + // A key that isn't one of the settings is an error, with the nearest setting. + if let Some(key) = src.keys().find(|k| !o.contains_key(k.as_str())) { + return Err(crate::cmd::params::unknown(c, key, &o.keys().map(String::as_str).collect::>())); + } + for (k, val) in src { + o.insert(k.clone(), val.clone()); + } + let params: tr::TraceParams = serde_json::from_value(v).map_err(|e| bad(c, e.to_string()))?; + if !params.fills && !params.strokes { + return Err(bad(c, "Create needs fills, strokes or both")); + } + if !(params.stroke_width.is_finite() && params.stroke_width > 0.0) { + return Err(bad(c, "strokeWidth must be a positive number of pixels")); + } + // A color group is refused unless the trace uses it: Color mode with Document Library and the + // document's swatches. + if params.color_group.as_deref().is_some_and(|g| !g.is_empty()) { + if params.palette != tr::Palette::DocumentLibrary { + return Err(bad(c, "`colorGroup` needs `palette: \"documentLibrary\"`")); + } + if params.library != crate::cmd::swatchlib::DOCUMENT_SWATCHES { + return Err(bad(c, "`colorGroup` needs `library: \"document\"`")); + } + if params.mode != tr::Mode::Color { + return Err(bad(c, "`colorGroup` needs `mode: \"color\"`")); + } + } + Ok(params) +} + +/// Document Library with `colorGroup`: the solid colors of the active document's color group +/// `name` (so named exactly, else ignoring case). Errors name command `c`. +/// ([`trace_params`] has checked that the library is the document's swatches.) +fn trace_group_colors(c: &str, s: &Session, name: &str) -> Result> { + let groups = &s.doc()?.doc.swatch_groups; + let lower = name.to_lowercase(); + let group = groups + .iter() + .find(|g| g.name == name) + .or_else(|| groups.iter().find(|g| g.name.to_lowercase() == lower)) + .ok_or_else(|| bad(c, format!("no color group `{name}` in the document (see swatch.list)")))?; + Ok(group.swatches.iter().filter_map(|w| w.paint.color()).collect()) +} + +/// Document Library in Color mode: look the library's colors (or its color group's) up into +/// `params.swatches` → each one as traced (sRGB) with the color to fill with. Errors name command `c`. +fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result> { + if params.mode != tr::Mode::Color || params.palette != tr::Palette::DocumentLibrary { + return Ok(vec![]); + } + let group = params.color_group.as_deref().filter(|g| !g.is_empty()); + let key = group.unwrap_or(params.library.as_str()); + let colors = match group { + Some(name) => trace_group_colors(c, s, name)?, + None => crate::cmd::swatchlib::library_colors(s, key) + .ok_or_else(|| bad(c, format!("no swatch library `{key}` (see swatch.library.list; \"document\": the document's swatches)")))?, + }; + if colors.is_empty() { + return Err(bad(c, format!("`{key}` has no colours"))); + } + let library: Vec<([u8; 3], Color)> = colors + .into_iter() + .map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + ([r, g, b], c) + }) + .collect(); + params.swatches = library.iter().map(|l| l.0).collect(); + Ok(library) +} + +/// The most anchor points an Image Trace may make, a guard for memory: a trace past it is refused +/// with advice instead (#525). A trace keeps about 90 bytes an anchor in the document (measured on +/// code-drawn photos of 2000 × 2000 to 6000 × 4000 pixels), so 8,000,000 anchors are about +/// 0.7 GB, with a peak of about 1 GB while tracing: a 4000 × 3000 photo at High Fidelity Photo +/// makes about 1.9 million, and even at Paths 100, Noise 1 and every tone about 7.9 million. On the +/// web, where a page has at most 4 GB of memory, the limit stays at 2,000,000. +#[cfg(not(target_arch = "wasm32"))] +pub const MAX_TRACE_ANCHORS: usize = 8_000_000; + +/// The most anchor points an Image Trace may make on the web (see the native limit). +#[cfg(target_arch = "wasm32")] +pub const MAX_TRACE_ANCHORS: usize = 2_000_000; + +/// The live shape for a shape the tracer found (in the image's pixels), placed in the document by `xf`. +fn traced_shape(shape: tr::TracedShape, xf: vectorcraft_geom::Affine) -> LiveShape { + use vectorcraft_geom::Affine; + let about = |c: Point, deg: f64| Affine::translate(c.to_vec2()) * Affine::rotate(deg.to_radians()); + let mut live = match shape { + tr::TracedShape::Rectangle { center, width, height, radius, rotation } => LiveShape::Rectangle { + w: width, + h: height, + radii: [radius; 4], + kinds: Default::default(), + radii_relative: false, + xf: about(center, rotation) * Affine::translate((-width / 2.0, -height / 2.0)), + }, + tr::TracedShape::Ellipse { center, rx, ry, rotation } => { + LiveShape::Ellipse { w: 2.0 * rx, h: 2.0 * ry, pie: (0.0, 360.0), xf: about(center, rotation) * Affine::translate((-rx, -ry)) } + } + tr::TracedShape::Polygon { center, radius, sides, rotation } => { + LiveShape::Polygon { radius, sides, xf: about(center, rotation), radii: vec![], kinds: vec![], radii_relative: false } + } + }; + // (Whether the move changed the shape's own numbers does not matter: its path is made from them next.) + let _ = live.transform(xf); + live +} + +/// The gradient fill for a linear gradient the tracer found (in the image's pixels), placed in the +/// document by `xf`. +fn traced_gradient(g: &tr::TracedGradient, xf: vectorcraft_geom::Affine) -> Paint { + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + let stops = g.stops.iter().map(|&(at, c)| GradientStop::new(at as f32, Color::rgb8(c[0], c[1], c[2]))).collect(); + let mut paint = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); + paint.geom = Some(GradientGeom { start: xf * g.start, end: xf * g.end, aspect: 1.0, focal: None }); + Paint::Gradient(Box::new(paint)) +} + +/// Auto Grouping: `nodes` (one per traced path, bottom-most first) with each path that has others +/// inside it (`parents`, as the tracer gives them) in a group with them, in the order they had: +/// abutting paths painted in another order would show a seam where they meet. Without parents, +/// the nodes as they are. +fn grouped(d: &mut Document, nodes: Vec, parents: &[Option]) -> Vec> { + let n = nodes.len(); + let mut inside: Vec> = vec![vec![]; n]; + let mut roots = vec![]; + for i in 0..n { + match parents.get(i).copied().flatten().and_then(|p| inside.get_mut(p).filter(|_| p != i)) { + Some(of) => of.push(i), + None => roots.push(i), + } + } + // Outermost first, so that backwards each path comes after those inside it. + let mut order = roots.clone(); + let mut at = 0; + while let Some(&i) = order.get(at) { + order.extend(inside.get(i).into_iter().flatten()); + at += 1; + } + let mut nodes: Vec> = nodes.into_iter().map(Some).collect(); + let mut built: Vec>> = vec![None; n]; + for &i in order.iter().rev() { + let Some(node) = nodes.get_mut(i).and_then(Option::take) else { continue }; + let mut within: Vec<(usize, Arc)> = inside.get(i).into_iter().flatten().filter_map(|&c| Some((c, built.get_mut(c)?.take()?))).collect(); + let made = if within.is_empty() { + node + } else { + within.push((i, Arc::new(node))); + within.sort_by_key(|m| m.0); + Node::group(d.alloc_id(), within.into_iter().map(|m| m.1).collect()) + }; + if let Some(slot) = built.get_mut(i) { + *slot = Some(Arc::new(made)); + } + } + // (Paths that are inside each other in a ring are reached from no root: the tracer makes none, + // and they are kept all the same.) + let ring = nodes.into_iter().flatten().map(Arc::new).collect::>(); + roots.iter().filter_map(|&r| built.get_mut(r)?.take()).chain(ring).collect() +} + +pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result { + let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; + let mut params = trace_params(c, p)?; + let view = view_param(c, p)?; + let params_json = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?; + // The preset's name if the parameters are exactly that preset's or its enhanced version's, + // else "Custom". + let named = str_param(p, "preset").unwrap_or("Default"); + let is = |b: Option| b.and_then(|b| serde_json::to_value(&b).ok()).as_ref() == Some(¶ms_json); + let preset_label = if is(tr::preset(named)) || is(tr::enhanced_preset(named)) { named.to_string() } else { "Custom".to_string() }; + let roots = root_ids(s, p)?; + // The image (inside a trace group, or selected directly). + let (target, img) = { + let d = &s.doc()?.doc; + roots + .iter() + .find_map(|r| { + let n = d.node(*r)?; + match &n.kind { + NodeKind::Image(i) => Some((*r, i.clone())), + _ if is_trace_group(n) => match &n.children()?.first()?.kind { + NodeKind::Image(i) => Some((*r, i.clone())), + _ => None, + }, + _ => None, + } + }) + .ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))? + }; + let blob = s.doc()?.doc.images.get(&img.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", img.key)))?; + // An image over the tracer's size is traced scaled down (the paths are scaled back below). + let raster = tr::Raster::decode_to_fit(&blob.bytes).map_err(|e| EngineError::Other(e.to_string()))?; + let library = trace_library(c, s, &mut params)?; + let res = tr::trace_within(&raster, ¶ms, MAX_TRACE_ANCHORS).map_err(|e| EngineError::Other(e.to_string()))?; + let warnings = trace_warnings((img.width, img.height), (raster.width, raster.height), res.worked_at); + // Pixel space of the decoded raster → the image object's pixel space → document. + let sx = img.width.max(1) as f64 / raster.width.max(1) as f64; + let sy = img.height.max(1) as f64 / raster.height.max(1) as f64; + let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy); + // Document units per raster pixel (stroke widths). + let unit = xf.determinant().abs().sqrt(); + let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len()); + let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" }; + let id = s.edit(label, |d, sel| { + let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?; + let mut image = if is_trace_group(&src) { + src.children() + .and_then(|c| c.first()) + .map(|c| (**c).clone()) + .ok_or_else(|| EngineError::Other("Image Trace: the traced image is missing".into()))? + } else { + src.clone() + }; + image.visible = true; + let mut children: Vec> = vec![]; + if !expand { + let mut hidden = image.clone(); + hidden.visible = false; + children.push(Arc::new(hidden)); + } + let mut traced = Vec::with_capacity(res.paths.len()); + for tp in res.paths { + let path = tp.path.transformed(xf); + let mut n = shape_node(d, path, None); + // Shapes: a path the tracer found to be a shape is that live shape. + if let (Some(shape), NodeKind::Path { path, live, .. }) = (tp.shape, &mut n.kind) { + let shape = traced_shape(shape, xf); + *path = shape.to_path(); + *live = Some(Box::new(shape)); + } + // A library colour fills with the swatch's own colour (its model kept). + let color = library.iter().find(|(rgb, _)| *rgb == tp.color).map_or_else(|| Color::rgb8(tp.color[0], tp.color[1], tp.color[2]), |l| l.1); + // Gradients: a path the tracer found to be a linear gradient is filled with it. + let paint = tp.gradient.as_ref().map_or_else(|| Paint::solid(color), |g| traced_gradient(g, xf)); + n.appearance = match tp.stroke { + // Traced lines: round corners, and ends round or square as the tracer found them. + Some(width) => Appearance { + items: vec![AppearanceItem::Stroke(StrokeLayer { + cap: if tp.square_caps { LineCap::Square } else { LineCap::Round }, + join: LineJoin::Round, + ..StrokeLayer::new(paint, width * unit) + })], + ..Default::default() + } + .into(), + None => fill_only(paint).into(), + }; + traced.push(n); + } + children.extend(grouped(d, traced, &res.parents)); + let gid = d.alloc_id(); + let mut g = Node::group(gid, children); + g.name = if expand { None } else { Some(TRACE_NAME.into()) }; + if !expand { + // Tracing again keeps the object's view unless another is asked for. + let view = view.unwrap_or_else(|| src.trace_view()); + g.extras_mut().trace = Some(Box::new(json!({ "preset": preset_label, "params": params_json, "view": view.id() }))); + } + let (par, idx, _) = d.position(target).ok_or(EngineError::NoNode(target))?; + d.remove(target)?; + d.insert(par, idx, g)?; + sel.set([gid]); + Ok(gid) + })?; + Ok(json!({ "id": id.0, "paths": npaths, "anchors": anchors, "colors": colors, "warnings": warnings })) +} + +/// Images larger than this on a side are traced, but more slowly: the trace says so. +pub const LARGE_TRACE_SIDE: u32 = 1500; + +/// What a trace of an image of `size` pixels, traced at `traced` pixels, tells the user: that +/// Flat Logo averaged it down to `worked` pixels first, or else that a large image takes longer +/// (the public documentation's warning for images over 1500 px) and that one over the tracer's +/// [`tr::MAX_PIXELS`] was traced scaled down. +pub(crate) fn trace_warnings(size: (u32, u32), traced: (u32, u32), worked: Option<(u32, u32)>) -> Vec { + let mut out = vec![]; + if worked.is_none() && size.0.max(size.1) > LARGE_TRACE_SIDE { + out.push(format!( + "The image is {} × {} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster.", + size.0, size.1 + )); + } + if let Some(worked) = worked { + out.push(format!("Flat Logo traced the image at {} × {} pixels, averaged down from {} × {}.", worked.0, worked.1, size.0, size.1)); + } else if u64::from(traced.0) * u64::from(traced.1) < u64::from(size.0) * u64::from(size.1) { + out.push(format!( + "The image was traced at {} × {} pixels, scaled down from {} × {} ({} megapixels at most).", + traced.0, + traced.1, + size.0, + size.1, + tr::MAX_PIXELS >> 20 + )); + } + out +} + +fn trace_targets(s: &Session, p: &Value) -> Result> { + let d = &s.doc()?.doc; + let v: Vec = root_ids(s, p)?.into_iter().filter(|i| d.node(*i).is_some_and(is_trace_group)).collect(); + if v.is_empty() { + return Err(EngineError::Other("select an Image Trace object".into())); + } + Ok(v) +} + +pub(super) fn trace_set_view(s: &mut Session, p: &Value) -> Result { + const C: &str = "imageTrace.setView"; + let view = view_param(C, p)?.ok_or_else(|| bad(C, "view is required"))?; + let targets = trace_targets(s, p)?; + let d = &s.doc()?.doc; + if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view)) { + return Ok(json!({ "ids": ids_json(&targets), "view": view.id() })); + } + s.edit("Image Trace View", |d, _| { + for g in &targets { + let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?; + if let Some(t) = n.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(Value::as_object_mut) { + t.insert("view".into(), json!(view.id())); + } else { + n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom", "view": view.id() }))); + } + } + Ok(()) + })?; + Ok(json!({ "ids": ids_json(&targets), "view": view.id() })) +} + +pub(super) fn trace_release(s: &mut Session, p: &Value) -> Result { + let targets = trace_targets(s, p)?; + let ids = s.edit("Release Image Trace", |d, sel| { + let mut out = vec![]; + let mut released = Beside::replacing(d, &targets); + for g in &targets { + let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?; + let mut img = (**n.children().and_then(|c| c.first()).ok_or(EngineError::NoNode(*g))?).clone(); + img.visible = true; + out.push(img.id); + released.put(d, *g, vec![img])?; + } + released.finish(d)?; + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "ids": ids_json(&ids) })) +} + +pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result { + let targets = trace_targets(s, p)?; + s.edit("Expand Image Trace", |d, sel| { + for g in &targets { + let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?; + n.name = None; + n.extras_mut().trace = None; + if let Some(ch) = n.children_mut() { + ch.retain(|c| !matches!(c.kind, NodeKind::Image(_))); + } + } + sel.set(targets.iter().copied()); + Ok(()) + })?; + Ok(json!({ "ids": ids_json(&targets) })) +} + +#[cfg(test)] +mod trace_limit_tests { + use super::{MAX_TRACE_ANCHORS, trace_warnings}; + + #[test] + fn trace_warnings_name_a_large_or_scaled_down_image() { + assert!(trace_warnings((1500, 1500), (1500, 1500), None).is_empty()); + assert_eq!(trace_warnings((1501, 10), (1501, 10), None).len(), 1); + let w = trace_warnings((16000, 12000), (9459, 7094), None); + assert_eq!(w.len(), 2, "{w:?}"); + assert!(w[0].contains("16000 × 12000") && w[1].contains("9459 × 7094") && w[1].contains("64 megapixels"), "{w:?}"); + // Flat Logo's own working size is named instead of the megapixel limit. + let w = trace_warnings((1025, 1025), (1025, 1025), Some((513, 513))); + assert_eq!(w, ["Flat Logo traced the image at 513 × 513 pixels, averaged down from 1025 × 1025."]); + // Flat Logo traces a large image at its reduced size, so it gives no slow-trace warning. + let w = trace_warnings((1600, 1600), (1600, 1600), Some((800, 800))); + assert_eq!(w, ["Flat Logo traced the image at 800 × 800 pixels, averaged down from 1600 × 1600."]); + let w = trace_warnings((16000, 12000), (9459, 7094), Some((946, 710))); + assert_eq!(w, ["Flat Logo traced the image at 946 × 710 pixels, averaged down from 16000 × 12000."]); + } + + // A 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million anchors, which must fit; + // the limit still guards memory (about 90 bytes an anchor). Checked when the tests build. + const _: () = assert!(MAX_TRACE_ANCHORS >= 2_000_000 && MAX_TRACE_ANCHORS <= 16_000_000); +} diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 23a6b9dfad..a01f095fcd 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -10,7 +10,7 @@ //! text besides it (see `flavours`). mod flavours; -mod resources; +pub(crate) mod resources; use std::collections::BTreeMap; use std::sync::Arc; @@ -23,6 +23,7 @@ use vectorcraft_geom::Rect; pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture}; pub(crate) use resources::SwatchChoices; +pub use resources::{ArtResources, art_resources}; use super::*; use crate::DocState; diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index 1a56501990..08098705f9 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -196,7 +196,7 @@ pub fn specs() -> Vec { "Load PDF into Clipboard", [], None, - "{dataBase64, page?: 1, password? (an encrypted PDF), editingData?: false (true: the data is a .ai or .ait file, read as document.open reads it; when document.open would use its editing data, every object of that data comes in, each layer's objects in stacking order and a hidden layer's objects hidden; else page `page`), center?: [x, y]} replace the clipboard with the objects of one PDF page, or of a .ai file's editing data (with the images, patterns and swatches they use), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste", + "{dataBase64, page?: 1, password? (an encrypted PDF), editingData?: false (true: the data is a .ai or .ait file, read as document.open reads it; when document.open would use its editing data, every object of that data comes in, each layer's objects in stacking order and a hidden layer's objects hidden; else page `page`), center?: [x, y]} replace the clipboard with the objects of one PDF page, or of a .ai file's editing data (with the images, patterns and swatches they use; a .ai saved without PDF compatibility: every object of its editing data, as document.open reads it, with or without editingData), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste", has_doc, import_pdf ), @@ -421,8 +421,15 @@ fn import_image(s: &mut Session, p: &Value) -> Result { let img = fileio::raster_image(&data_param(p, C)?).map_err(|e| bad(C, e.to_string()))?; let (sx, sy) = pt_per_px(img.ppi); let (w, h) = (img.width, img.height); - let image = - ImageObject { key: img.key.clone(), width: w, height: h, xf: Affine::scale_non_uniform(sx, sy), link: None, placement: Default::default() }; + let image = ImageObject { + key: img.key.clone(), + width: w, + height: h, + xf: Affine::scale_non_uniform(sx, sy), + link: None, + placement: Default::default(), + pixels: None, + }; let mut clip = Clipboard { nodes: vec![Node::new(NodeId(1), NodeKind::Image(Box::new(image)))], ..Default::default() }; clip.images.insert(img.key, img.blob); let count = s.load_clipboard(clip, p)?; @@ -441,6 +448,7 @@ fn import_text(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "the text is empty")); } let mut t = TextObject::point(Point::ZERO, text, super::super::create::new_type_style(s, &Value::Null)); + t.system_layout = s.doc()?.doc.setup.system_layout; crate::cmd::typecmd::refresh_bounds(&mut t); let n = Node::new(NodeId(1), NodeKind::Text(Box::new(t))); let count = s.load_clipboard(Clipboard { nodes: vec![n], ..Default::default() }, p)?; @@ -510,7 +518,15 @@ fn import_pdf(s: &mut Session, p: &Value) -> Result { { return import_loaded(s, p, C, loaded); } - let (mut doc, warnings) = fileio::page_document(&bytes, page - 1, &opts).map_err(|e| bad(C, e.to_string()))?; + let (mut doc, warnings) = match fileio::page_document(&bytes, page - 1, &opts) { + // For a .ai saved without PDF compatibility, the clipboard takes every object of its + // editing data, as document.open reads it. + Err(e) if fileio::is_placeholder(&e) => { + let loaded = fileio::load_with("Clipboard.ai", &bytes, &opts).map_err(|e| bad(C, e.to_string()))?; + return import_loaded(s, p, C, loaded); + } + read => read.map_err(|e| bad(C, e.to_string()))?, + }; doc.drop_edit_modes(); let clip = Clipboard::from_document(&doc); if clip.is_empty() { diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 032ee02ffc..e6bd96371b 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -2,7 +2,7 @@ //! //! Objects refer to resources by name (image blobs, symbols, patterns, swatches, character and //! paragraph styles, brushes) and to graphic styles by id. Copy follows those references, also -//! through the symbols, patterns and styles it finds, and keeps what they lead to. +//! through the symbols, patterns, styles and brush art it finds, and keeps what they lead to. //! //! Pasting matches each resource by name: an identical one in the document is used, a missing one //! is added, and a different one of the same name is added under a free name, which the pasted @@ -13,6 +13,7 @@ //! the document's Spot Colors option says. Pasting back into the document the objects came from //! uses its resources as they are now. +use std::cell::OnceCell; use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; @@ -147,10 +148,28 @@ struct Defs<'a> { styles: &'a [GraphicStyle], char_styles: &'a [TextStyleDef], para_styles: &'a [TextStyleDef], + brushes: Brushes<'a>, +} + +/// The brushes references lead to: a document's library, read the first time a brush is used +/// (`vectorcraft_brush::library` parses it), or the clipboard's own. +enum Brushes<'a> { + Lazy(&'a Document, &'a OnceCell>), + Ready(&'a [Brush]), +} + +impl<'a> Brushes<'a> { + fn get(&self) -> &'a [Brush] { + match *self { + Brushes::Lazy(d, cell) => cell.get_or_init(|| vectorcraft_brush::library(d)), + Brushes::Ready(list) => list, + } + } } impl<'a> Defs<'a> { - fn of(d: &'a Document) -> Self { + /// `d`'s definitions; `brushes` holds its brush library once a brush is used. + fn of(d: &'a Document, brushes: &'a OnceCell>) -> Self { Self { swatches: d.swatches_iter().collect(), symbols: &d.symbols, @@ -158,6 +177,7 @@ impl<'a> Defs<'a> { styles: &d.graphic_styles, char_styles: &d.char_styles, para_styles: &d.para_styles, + brushes: Brushes::Lazy(d, brushes), } } } @@ -180,9 +200,9 @@ pub(super) struct Used { } impl Used { - fn of<'a>(defs: &Defs<'a>, nodes: &'a [Node]) -> Self { + fn of<'a>(defs: &Defs<'a>, nodes: impl IntoIterator) -> Self { let mut used = Used::default(); - let mut todo: Vec> = nodes.iter().map(Source::Node).collect(); + let mut todo: Vec> = nodes.into_iter().map(Source::Node).collect(); while let Some(src) = todo.pop() { let mut found = |r: Ref<'_>| used.note(defs, r, &mut todo); match src { @@ -224,6 +244,8 @@ impl Used { Res::Pattern => todo.extend(defs.patterns.iter().filter(|p| p.name == name).flat_map(|p| p.art.iter().map(|a| Source::Node(a)))), Res::CharStyle => todo.extend(defs.char_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))), Res::ParaStyle => todo.extend(defs.para_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))), + // A scatter or art brush's art, a pattern brush's tiles. + Res::Brush => todo.extend(defs.brushes.get().iter().filter(|b| b.name == name).flat_map(|b| b.art().into_iter().map(Source::Node))), _ => {} } } @@ -242,6 +264,80 @@ impl Used { } } +/// What a preview of some art shows besides the art itself ([`art_resources`]). +pub struct ArtResources { + /// Changes when any resource the art uses changes, and only then. + pub key: u64, + /// The art and image bytes counted in `key` by their address, held weakly: their allocations + /// stay theirs (no other art can take an address) for as long as the key is kept. + _kept: (Vec>, Vec>>), +} + +/// The resources `art` uses in `doc`, through the definitions they lead to as Copy follows them +/// ([`Used`]): images, symbols, patterns (tile type, overlap and spacing too), swatches (linked +/// colours, tints, gradient swatches; colour groups' included), character and paragraph styles, +/// brushes and graphic styles, and the document's Spot Colors option. Art and image bytes count +/// by identity, the other definitions by their saved form: working the key out walks `art` and +/// the definitions it leads to, and never reads an image's bytes. +pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator) -> ArtResources { + use std::hash::{Hash, Hasher}; + let library = OnceCell::new(); + let defs = Defs::of(doc, &library); + // The art's references shortened to the brush library's life. + let mut nodes: Vec<&Node> = vec![]; + for n in art { + nodes.push(n); + } + let used = Used::of(&defs, nodes); + let mut h = std::collections::hash_map::DefaultHasher::new(); + let mut kept = (vec![], vec![]); + fn saved(h: &mut impl Hasher, v: &impl serde::Serialize) { + serde_json::to_vec(v).unwrap_or_default().hash(h); + } + fn node(h: &mut impl Hasher, kept: &mut Vec>, a: &Arc) { + (Arc::as_ptr(a) as usize).hash(h); + kept.push(Arc::downgrade(a)); + } + for (res, names) in &used.names { + for name in names { + (*res as u8, name).hash(&mut h); + match res { + Res::Image => { + if let Some(b) = doc.images.get(name) { + b.mime.hash(&mut h); + for bytes in std::iter::once(&b.bytes).chain(&b.proxy) { + (Arc::as_ptr(bytes) as usize).hash(&mut h); + kept.1.push(Arc::downgrade(bytes)); + } + } + } + Res::Symbol => doc.symbols.iter().filter(|s| s.name == *name).for_each(|s| node(&mut h, &mut kept.0, &s.art)), + Res::Pattern => { + for p in doc.patterns.iter().filter(|p| p.name == *name) { + saved(&mut h, &PatternDef { art: vec![], ..p.clone() }); + p.art.iter().for_each(|a| node(&mut h, &mut kept.0, a)); + } + } + Res::CharStyle => doc.char_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)), + Res::ParaStyle => doc.para_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)), + Res::Brush => defs.brushes.get().iter().filter(|b| b.name == *name).for_each(|b| saved(&mut h, b)), + // Swatches below (tints count too); graphic styles go by id. + Res::Swatch | Res::GraphicStyle => {} + } + } + } + for w in doc.swatches_iter().filter(|w| used.carries(w) || used.has(Res::Swatch, &w.name)) { + saved(&mut h, w); + } + for g in doc.graphic_styles.iter().filter(|g| g.id != 0 && used.styles.contains(&g.id)) { + saved(&mut h, g); + } + if used.names.contains_key(&Res::Swatch) { + doc.spot_use_lab.hash(&mut h); + } + ArtResources { key: h.finish(), _kept: kept } +} + /// A resource list entry known by its name. trait Named: Clone { fn name(&self) -> &str; @@ -469,6 +565,26 @@ fn same_art(r: &Relink, ours: &[Arc], theirs: &[Arc]) -> bool { ours.len() == theirs.len() && ours.iter().zip(theirs).all(|(a, b)| relinked(&unlinked, a) == relinked(r, b)) } +/// Is `ours` (a document brush) brush `theirs` (a pasted one) once the art of that is relinked by +/// `r`? Graphic style links don't count, as in [`same_art`]. +fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool { + let relinked = |r: &Relink, b: &Brush| { + let mut b = b.clone(); + b.art_mut().into_iter().for_each(|a| r.node(a)); + b + }; + 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 +} + /// What pasting did to the document's resources (part of the paste result). #[derive(Debug, Default)] pub(crate) struct Imported { @@ -500,12 +616,14 @@ impl Imported { impl Clipboard { /// `nodes` (from `src`) and the resources of `src` they use. - pub(super) fn gather(src: &Document, nodes: Vec) -> Self { - let used = Used::of(&Defs::of(src), &nodes); + pub(crate) fn gather(src: &Document, nodes: Vec) -> Self { + let library = OnceCell::new(); + let used = Used::of(&Defs::of(src, &library), &nodes); let pick = |r: Res, list: &[TextStyleDef]| list.iter().filter(|s| used.has(r, &s.name)).cloned().collect::>(); - let brushes = match used.names.get(&Res::Brush) { - Some(names) => vectorcraft_brush::library(src).into_iter().filter(|b| names.contains(&b.name)).collect(), - None => vec![], + // Read when a brush was used. + let brushes = match (used.names.get(&Res::Brush), library.get()) { + (Some(names), Some(library)) => library.iter().filter(|b| names.contains(&b.name)).cloned().collect(), + _ => vec![], }; Self { images: src.images.iter().filter(|(k, _)| used.has(Res::Image, k)).map(|(k, b)| (k.clone(), b.clone())).collect(), @@ -530,6 +648,7 @@ impl Clipboard { styles: &self.graphic_styles, char_styles: &self.char_styles, para_styles: &self.para_styles, + brushes: Brushes::Ready(&self.brushes), }; Used::of(&defs, &self.nodes) } @@ -549,8 +668,10 @@ impl Clipboard { let used = self.used(); let mut out = Imported::default(); self.import_images(d, &used, same_doc, &mut out); - self.import_brushes(d, &used, same_doc, &mut out); self.import_swatches(d, &used, choices, same_doc, &mut out); + // Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art + // they may brush; the others once those are in. + let mut added_brushes = self.import_brushes(d, &used, same_doc, false, &mut out); // Character and paragraph styles (their colours relinked first). for (r, mine, theirs) in [(Res::CharStyle, &self.char_styles, &mut d.char_styles), (Res::ParaStyle, &self.para_styles, &mut d.para_styles)] { for def in mine.iter().filter(|s| used.has(r, &s.name)) { @@ -583,6 +704,7 @@ impl Clipboard { added_patterns.extend(p.new_name(&def.name)); out.placed(Res::Pattern, &def.name, &p); } + added_brushes.extend(self.import_brushes(d, &used, same_doc, true, &mut out)); self.import_graphic_styles(d, &used, same_doc, &mut out); for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) { out.relink.node(Arc::make_mut(&mut s.art)); @@ -592,6 +714,13 @@ impl Clipboard { out.relink.node(Arc::make_mut(a)); } } + if !added_brushes.is_empty() { + let mut lib = vectorcraft_brush::library(d); + for b in lib.iter_mut().filter(|b| added_brushes.contains(&b.name)) { + b.art_mut().into_iter().for_each(|a| out.relink.node(a)); + } + vectorcraft_brush::store(d, &lib); + } out } @@ -607,20 +736,26 @@ impl Clipboard { } } - fn import_brushes(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) { - let brushes: Vec<&Brush> = self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).collect(); + /// 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 { + 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; + return vec![]; } let mut lib = vectorcraft_brush::library(d); - let before = lib.len(); + let mut added = vec![]; for b in brushes { - let p = place(&mut lib, b, same_doc, PartialEq::eq); + 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 lib.len() != before { + 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 diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 91afee24c9..40144f13e4 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -195,6 +195,12 @@ fn load_profile(s: &mut Session, p: &Value) -> Result { 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 { + cms::set_active(&working).map_err(|e| bad(C, e.to_string()))?; + touch_all(s); + } Ok(json!({"name": info.name, "kind": info.kind, "remembered": remembered})) } diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 5aad773873..d5588ff442 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -30,15 +30,23 @@ pub fn specs() -> Vec { has_doc, flare ), - cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2} → {id}", has_doc, line), + cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line), cmd!("shape.spiral", "Spiral", [], None, "{cx, cy, radius, decay=80 (%), segments=10, clockwise?} → {id}", has_doc, spiral), - cmd!("shape.arc", "Arc", [], None, "{x1, y1, x2, y2, closed?} → {id}", has_doc, arc), + cmd!( + "shape.arc", + "Arc", + [], + None, + "{x1, y1, x2, y2, closed?, slope?} or {x, y, lengthX, lengthY, reference?, baseAlong?: x|y, slope?, closed?, fillArc?} → {id}", + has_doc, + arc + ), cmd!( "shape.rectangularGrid", "Rectangular Grid", [], None, - "{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none)} → {id}", + "{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg (about centre)} → {id}", has_doc, rect_grid ), @@ -47,7 +55,7 @@ pub fn specs() -> Vec { "Polar Grid", [], None, - "{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none)} → {id}", + "{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg (about centre)} → {id}", has_doc, polar_grid ), @@ -65,7 +73,7 @@ pub fn specs() -> Vec { "Drawing Mode", [], Some("Shift+D"), - "{mode?: normal|behind|inside} (no param cycles; inside needs one selected path)", + "{mode?: normal|behind|inside} (inside needs one selected path, compound path or type; no param cycles normal → behind → inside → normal, going from behind back to normal when Draw Inside can't draw into the selection; when the Draw Inside target is isolated, drawing or pasting into it moves isolation to its clip group)", has_doc, draw_mode ), @@ -74,7 +82,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, vertical?: bool = false, size?: pt, font?: family, style?, color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -88,11 +96,6 @@ pub(crate) fn add_art(s: &mut Session, label: &str, kind: NodeKind, name: Option add_look(s, label, kind, look, name) } -/// [`add_look`] with just `appearance`. -pub(crate) fn add_node(s: &mut Session, label: &str, kind: NodeKind, appearance: Appearance, name: Option) -> Result { - add_look(s, label, kind, NewArt::plain(appearance), name) -} - /// Insert a new object looking like `look` (drawing modes apply); select it. pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option) -> Result { insert_look(s, label, kind, look, name, true) @@ -101,35 +104,63 @@ pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewAr /// [`add_look`] that selects the new object only when `select` is set; otherwise the selection /// stays as it was. pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option, select: bool) -> Result { + insert_look_turned(s, label, kind, look, name, select, 0.0) +} + +/// [`add_art`] for an object made turned by a `rotation` param (degrees, clockwise on the page): +/// its bounding box turns with it, as after the Rotate tool. +fn add_art_turned(s: &mut Session, label: &str, kind: NodeKind, rotation: f64) -> Result { + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation)) +} + +/// The bounding-box angle (counter-clockwise, as `Node::bbox_angle` and the Rotate tool keep it) +/// of an object made with the clockwise `rotation` param: 0 exactly for none, a whole turn or a +/// non-finite angle, so such objects are as they were. +fn bbox_turn(rotation: f64) -> f64 { + if !rotation.is_finite() { + return 0.0; + } + let a = vectorcraft_geom::normalize_deg(-rotation); + if a == 0.0 { 0.0 } else { a } +} + +/// A polygon's or star's `rotation` when it is the base orientation turned by General › Constrain +/// Angle (a Shift-drawn or click-made one), so its bounding box turns with it; else 0: a polygon +/// turned by the drag's direction keeps its box on the page's axes, as before. +fn constrained_turn(s: &Session, rotation: f64) -> f64 { + match vectorcraft_geom::constrain_rotation(s.prefs.constrain_angle) { + Some(r) if rotation.is_finite() && vectorcraft_geom::normalize_deg(r - rotation).abs() < 1e-9 => rotation, + _ => 0.0, + } +} + +/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. +fn insert_look_turned( + s: &mut Session, + label: &str, + kind: NodeKind, + look: NewArt, + name: Option, + select: bool, + bbox_angle: f64, +) -> Result { let parent = s.doc()?.target_parent()?; let mode = s.draw_mode; let inside = s.draw_inside; let behind_of = s.doc()?.selection.in_paint_order(&s.doc()?.doc).first().copied(); - let id = s.edit(label, |d, sel| { + let (id, into) = s.edit(label, |d, sel| { let id = d.alloc_id(); let mut n = Node::new(id, kind); look.apply(d, &mut n); n.name = name; + n.bbox_angle = bbox_angle; + let mut into = None; match (mode, inside) { (crate::DrawMode::Inside, Some(target)) if d.node(target).is_some() => { - // Wrap the target once in a clip group [mask copy, target, …new art]. - let group = match d.parent_of(target).and_then(|p| d.node(p).map(|pn| (p, pn.kind.clone()))) { - Some((p, NodeKind::Group { clip: true, children })) if children.get(1).is_some_and(|c| c.id == target) => p, - _ => { - let (par, idx, _) = d.position(target).ok_or(crate::EngineError::NoNode(target))?; - let mut mask = d.node(target).cloned().ok_or(crate::EngineError::NoNode(target))?; - mask.id = d.alloc_id(); - mask.appearance = Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0).into(); - if let NodeKind::Path { clipping, .. } = &mut mask.kind { - *clipping = true; - } - let gid = d.alloc_id(); - d.insert(par, idx + 1, Node::new(gid, NodeKind::Group { children: vec![std::sync::Arc::new(mask)], clip: true }))?; - d.move_node(target, Some(gid), usize::MAX)?; - gid - } - }; + let group = draw_inside_group(d, target)?; d.insert(Some(group), usize::MAX, n)?; + into = Some((target, group)); } (crate::DrawMode::Behind, _) => match behind_of.and_then(|b| d.position(b)) { Some((par, idx, _)) => { @@ -146,32 +177,82 @@ pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: Ne if select { sel.set([id]); } - Ok(id) + Ok((id, into)) })?; + if let Some((target, group)) = into { + isolate_draw_inside_group(s, target, group)?; + } Ok(json!({ "id": id.0 })) } +/// Draw Inside's clip group for `target`, the object new art goes inside: the clip group +/// [mask copy, target, …] `target` already is the clipped object of, else one made where `target` +/// was, holding an unpainted clipping copy of it and then `target`. New art and pastes go on top +/// of its children. +pub(crate) fn draw_inside_group(d: &mut vectorcraft_doc::Document, target: NodeId) -> Result { + if let Some(p) = d.parent_of(target) + && d.node(p).is_some_and(|pn| matches!(&pn.kind, NodeKind::Group { clip: true, children } if children.get(1).is_some_and(|c| c.id == target))) + { + return Ok(p); + } + let (par, idx, _) = d.position(target).ok_or(crate::EngineError::NoNode(target))?; + // The mask is a copy with ids of its own, its subpaths' too (a compound path's). + let original = d.node(target).cloned().ok_or(crate::EngineError::NoNode(target))?; + let mut mask = d.reid(&original); + mask.appearance = Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0).into(); + if let NodeKind::Path { clipping, .. } = &mut mask.kind { + *clipping = true; + } + let gid = d.alloc_id(); + d.insert(par, idx + 1, Node::new(gid, NodeKind::Group { children: vec![std::sync::Arc::new(mask)], clip: true }))?; + d.move_node(target, Some(gid), usize::MAX)?; + // Copied type whose layout caches `reid` dropped has them again. + super::typecmd::refresh_bounds_of(d, &[gid]); + Ok(gid) +} + +/// Draw Inside into the isolated object (#3705): isolation mode moves to the clip group the art +/// went into ([`draw_inside_group`]), so what is drawn or pasted inside the object is in isolation +/// mode with it, shown undimmed and picked by clicks, instead of locked beside it. Art added in +/// isolation mode belongs with what is isolated: it takes the isolated art's place when the mode +/// ends (). +/// A drag's next preview, replayed on the drag's snapshot, makes the group again under the same +/// id, so isolation stays on it; cancelling the drag restores the isolation it began with. +pub(crate) fn isolate_draw_inside_group(s: &mut Session, target: NodeId, group: NodeId) -> Result<()> { + let st = s.doc_mut()?; + if st.isolation == Some(target) { + st.isolation = Some(group); + } + Ok(()) +} + +/// The object Draw Inside would draw into: the one selected object, when it is a path, a compound +/// path or type. +fn inside_target(st: &crate::DocState) -> Option { + let first = st.selection.objects.first().copied()?; + let fits = matches!(st.doc.node(first).map(|n| &n.kind), Some(NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_))); + (fits && st.selection.len() == 1).then_some(first) +} + fn draw_mode(s: &mut Session, p: &Value) -> Result { let mode = match str_param(p, "mode") { Some("behind") => crate::DrawMode::Behind, Some("inside") => crate::DrawMode::Inside, Some("normal") => crate::DrawMode::Normal, + // Cycling (Shift+D): Draw Behind goes on to Draw Inside only when it can draw inside the + // selection, else back to Draw Normal (#3705: with one group selected it stayed in Draw + // Behind). None => match s.draw_mode { crate::DrawMode::Normal => crate::DrawMode::Behind, - crate::DrawMode::Behind if s.doc()?.selection.len() == 1 => crate::DrawMode::Inside, + crate::DrawMode::Behind if inside_target(s.doc()?).is_some() => crate::DrawMode::Inside, _ => crate::DrawMode::Normal, }, Some(o) => return Err(bad("view.drawMode", format!("unknown mode `{o}`"))), }; if mode == crate::DrawMode::Inside { - let st = s.doc()?; - let target = - st.selection.objects.first().copied().filter(|id| { - matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_))) - }); - match target { - Some(t) if st.selection.len() == 1 => s.draw_inside = Some(t), - _ => return Err(bad("view.drawMode", "Draw Inside needs exactly one selected path, compound path or text")), + match inside_target(s.doc()?) { + Some(t) => s.draw_inside = Some(t), + None => return Err(bad("view.drawMode", "Draw Inside needs exactly one selected path, compound path or text")), } } else { s.draw_inside = None; @@ -184,6 +265,35 @@ fn path_kind(path: PathData, live: Option) -> NodeKind { NodeKind::Path { path, rule: FillRule::NonZero, live: live.map(Box::new), clipping: false, guide: false } } +/// A click-to-size shape dialog's command `cmd` with `params` drawn along General › Constrain +/// Angle, as the reference app draws new objects along it +/// (): +/// a box (rectangle, ellipse, grid) runs along the turned axes from `pivot`, the point the dialog +/// placed at the click (its top-left corner `x`, `y`, or a grid's reference point), which stays +/// put; a polygon or star turns its base orientation about its centre. The params as they are at +/// 0° or a whole turn, for other commands and when they already carry a `rotation`. +pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) -> Value { + let base = s.prefs.constrain_angle; + let (Some(rotation), Some(axes)) = (vectorcraft_geom::constrain_rotation(base), vectorcraft_geom::constrain_axes(base)) else { return params }; + let Some(o) = params.as_object_mut().filter(|o| !o.contains_key("rotation")) else { return params }; + match cmd { + "shape.rectangle" | "shape.ellipse" | "shape.rectangularGrid" | "shape.polarGrid" => { + let num = |k: &str| o.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()); + let (Some(x), Some(y), Some(w), Some(h)) = (num("x"), num("y"), num("width"), num("height")) else { return params }; + // The box's centre along the turned axes from the pivot; the command turns it there. + let c = pivot + (axes * Point::new(x + w / 2.0 - pivot.x, y + h / 2.0 - pivot.y)).to_vec2(); + o.insert("x".into(), json!(c.x - w / 2.0)); + o.insert("y".into(), json!(c.y - h / 2.0)); + o.insert("rotation".into(), json!(rotation)); + } + "shape.polygon" | "shape.star" => { + o.insert("rotation".into(), json!(rotation)); + } + _ => {} + } + params +} + fn rect_of(p: &Value, cmd: &str) -> Result { let x = f64_req(p, "x", cmd)?; let y = f64_req(p, "y", cmd)?; @@ -203,10 +313,12 @@ fn rect_transform(r: Rect, p: &Value, cmd: &str) -> Result { if rotation == 0.0 { return Ok(Affine::translate(r.origin().to_vec2())); } - Ok(Affine::translate(r.center().to_vec2()) * Affine::rotate(rotation.to_radians()) * Affine::translate((-r.width() / 2.0, -r.height() / 2.0))) + // Exact at quarter turns (a Constrain Angle of 90°). + Ok(Affine::translate(r.center().to_vec2()) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate((-r.width() / 2.0, -r.height() / 2.0))) } fn rectangle(s: &mut Session, p: &Value) -> Result { + check_numbers(p, &["radius"], "shape.rectangle")?; let r = rect_of(p, "shape.rectangle")?; let radius = f64_or(p, "radius", 0.0).max(0.0); let live = LiveShape::Rectangle { @@ -214,35 +326,56 @@ fn rectangle(s: &mut Session, p: &Value) -> Result { h: r.height(), radii: [radius; 4], kinds: Default::default(), + radii_relative: false, xf: rect_transform(r, p, "shape.rectangle")?, }; let label = if radius > 0.0 { "Rounded Rectangle" } else { "Rectangle" }; - add_art(s, label, path_kind(live.to_path(), Some(live)), None) + add_art_turned(s, label, path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0)) } fn ellipse(s: &mut Session, p: &Value) -> Result { let r = rect_of(p, "shape.ellipse")?; let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: rect_transform(r, p, "shape.ellipse")? }; - add_art(s, "Ellipse", path_kind(live.to_path(), Some(live)), None) + add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0)) +} + +/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or +/// null. A fraction, a negative, a non-finite or a non-number is an error rather than the default. +fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result { + let n = number_or(p, key, default as f64, cmd)?; + if n.is_finite() && n >= 0.0 && n.fract() == 0.0 { + Ok(n as u64) + } else { + Err(bad(cmd, format!("`{key}` must be a whole number of at least 0, not {n}"))) + } } fn polygon(s: &mut Session, p: &Value) -> Result { let c = Point::new(f64_req(p, "cx", "shape.polygon")?, f64_req(p, "cy", "shape.polygon")?); let r = f64_req(p, "radius", "shape.polygon")?.abs(); - let sides = p.get("sides").and_then(Value::as_u64).unwrap_or(6).clamp(3, 1000) as u32; + check_numbers(p, &["rotation"], "shape.polygon")?; + let sides = count_or(p, "sides", 6, "shape.polygon")?.clamp(3, 1000) as u32; let rot = f64_or(p, "rotation", 0.0); - let xf = Affine::translate(c.to_vec2()) * Affine::rotate(rot.to_radians()); - let live = LiveShape::Polygon { radius: r, sides, xf, radii: vec![], kinds: vec![] }; - add_art(s, "Polygon", path_kind(live.to_path(), Some(live)), None) + let xf = Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(rot); + let live = LiveShape::Polygon { radius: r, sides, xf, radii: vec![], kinds: vec![], radii_relative: false }; + add_art_turned(s, "Polygon", path_kind(live.to_path(), Some(live)), constrained_turn(s, rot)) } fn star(s: &mut Session, p: &Value) -> Result { let c = Point::new(f64_req(p, "cx", "shape.star")?, f64_req(p, "cy", "shape.star")?); let r1 = f64_req(p, "radius1", "shape.star")?.abs(); + check_numbers(p, &["radius2", "rotation"], "shape.star")?; let r2 = f64_or(p, "radius2", r1 / 2.0).abs(); - let n = p.get("points").and_then(Value::as_u64).unwrap_or(5).clamp(2, 1000) as u32; - let path = shapes::star(c, r1, r2, n, f64_or(p, "rotation", 0.0)); - add_art(s, "Star", path_kind(path, None), None) + let n = count_or(p, "points", 5, "shape.star")?.clamp(2, 1000) as u32; + let rot = f64_or(p, "rotation", 0.0); + let turn = vectorcraft_geom::rotate_deg(rot); + // A quarter or whole turn (a Constrain Angle of 90°, say) turns the upright star exactly. + let path = if rot != 0.0 && turn.as_coeffs()[..4].iter().all(|c| c.fract() == 0.0) { + shapes::star(Point::ZERO, r1, r2, n, 0.0).transformed(Affine::translate(c.to_vec2()) * turn) + } else { + shapes::star(c, r1, r2, n, rot) + }; + add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot)) } /// Flare tool: a lens flare built from radial-gradient paths in Screen mode — a bright centre, a halo @@ -250,6 +383,24 @@ fn star(s: &mut Session, p: &Value) -> Result { fn flare(s: &mut Session, p: &Value) -> Result { use vectorcraft_color::{BlendMode, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; let c = Point::new(f64_req(p, "cx", "shape.flare")?, f64_req(p, "cy", "shape.flare")?); + let numbers = [ + "diameter", + "opacity", + "brightness", + "growth", + "fuzziness", + "rays", + "longest", + "rayFuzziness", + "rings", + "largest", + "x2", + "y2", + "direction", + "pathLength", + "seed", + ]; + check_numbers(p, &numbers, "shape.flare")?; let pct = |k: &str, d: f64| (f64_or(p, k, d) / 100.0).clamp(0.0, 10.0); let r = (f64_or(p, "diameter", 100.0) / 2.0).max(0.5); let opacity = pct("opacity", 50.0).min(1.0) as f32; @@ -278,7 +429,7 @@ fn flare(s: &mut Session, p: &Value) -> Result { }; let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) }; let radial = |centre: Point, radius: f64, stops: Vec| { - let mut g = GradientPaint::new(Gradient { kind: GradientKind::Radial, stops }); + let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops)); g.geom = Some(GradientGeom { start: centre, end: centre + vectorcraft_geom::Vec2::new(radius, 0.0), aspect: 1.0, focal: None }); Paint::Gradient(Box::new(g)) }; @@ -348,9 +499,10 @@ fn line(s: &mut Session, p: &Value) -> Result { let a = Point::new(f64_req(p, "x1", "shape.line")?, f64_req(p, "y1", "shape.line")?); let b = Point::new(f64_req(p, "x2", "shape.line")?, f64_req(p, "y2", "shape.line")?); let live = LiveShape::Line { a, b }; - // Lines are stroked, never filled (Illustrator ignores the fill for new open lines). + // Lines are stroked and, unless Fill Line asks for the current fill, not filled. + let fill = if switch_or(p, "fill", false, "shape.line")? { s.paint.fill.clone() } else { vectorcraft_color::Paint::None }; let look = s.new_art_look( - vectorcraft_color::Paint::None, + fill, if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() }, s.paint.stroke_width.max(0.1), ); @@ -359,25 +511,52 @@ fn line(s: &mut Session, p: &Value) -> Result { fn spiral(s: &mut Session, p: &Value) -> Result { let c = Point::new(f64_req(p, "cx", "shape.spiral")?, f64_req(p, "cy", "shape.spiral")?); + let segments = count_or(p, "segments", 10, "shape.spiral")?.clamp(2, 1000) as u32; let path = shapes::spiral( c, f64_req(p, "radius", "shape.spiral")?, - f64_or(p, "decay", 80.0), - p.get("segments").and_then(Value::as_u64).unwrap_or(10).clamp(2, 1000) as u32, - bool_or(p, "clockwise", true), + number_or(p, "decay", 80.0, "shape.spiral")?, + segments, + switch_or(p, "clockwise", true, "shape.spiral")?, ); add_art(s, "Spiral", path_kind(path, None), None) } fn arc(s: &mut Session, p: &Value) -> Result { - let a = Point::new(f64_req(p, "x1", "shape.arc")?, f64_req(p, "y1", "shape.arc")?); - let b = Point::new(f64_req(p, "x2", "shape.arc")?, f64_req(p, "y2", "shape.arc")?); - add_art(s, "Arc", path_kind(shapes::arc(a, b, 0.0, bool_or(p, "closed", false)), None), None) + let closed = switch_or(p, "closed", false, "shape.arc")?; + let fill_arc = switch_or(p, "fillArc", false, "shape.arc")?; + let base_x = !matches!(p.get("baseAlong").and_then(Value::as_str), Some("y" | "Y")); + let path = if p.get("lengthX").is_some() || p.get("lengthY").is_some() { + let anchor = Point::new(f64_req(p, "x", "shape.arc")?, f64_req(p, "y", "shape.arc")?); + let reference = p.get("reference").and_then(Value::as_u64).unwrap_or(0) as usize; + shapes::arc_segment( + anchor, + reference, + number_or(p, "lengthX", 100.0, "shape.arc")?, + number_or(p, "lengthY", 100.0, "shape.arc")?, + base_x, + number_or(p, "slope", 50.0, "shape.arc")?, + closed, + ) + } else { + let a = Point::new(f64_req(p, "x1", "shape.arc")?, f64_req(p, "y1", "shape.arc")?); + let b = Point::new(f64_req(p, "x2", "shape.arc")?, f64_req(p, "y2", "shape.arc")?); + let slope = number_or(p, "slope", 100.0, "shape.arc")?; + shapes::arc(a, b, slope, closed, base_x) + }; + let fill = if fill_arc { s.paint.fill.clone() } else { vectorcraft_color::Paint::None }; + let look = s.new_art_look( + fill, + if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() }, + s.paint.stroke_width.max(0.1), + ); + add_look(s, "Arc", path_kind(path, None), look, None) } /// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the -/// current fill when `fill`; a path of several subpaths becomes a compound path of them. -fn grid_group(s: &mut Session, label: &str, paths: Vec, fill: bool) -> Result { +/// current fill when `fill`; a path of several subpaths becomes a compound path of them. The group +/// and its members get the bounding-box angle `bbox_angle` (a grid drawn along a Constrain Angle). +fn grid_group(s: &mut Session, label: &str, (paths, bbox_angle): (Vec, f64), fill: bool) -> Result { let parent = s.doc()?.target_parent()?; let fill = if fill { s.paint.fill.clone() } else { vectorcraft_color::Paint::None }; let look = s.new_art_look(fill, s.paint.stroke.clone(), s.paint.stroke_width); @@ -394,20 +573,25 @@ fn grid_group(s: &mut Session, label: &str, paths: Vec, fill: bool) -> Node::path(d.alloc_id(), pd, Appearance::default()) }; look.apply(d, &mut n); + n.bbox_angle = bbox_angle; std::sync::Arc::new(n) }) .collect(); let gid = d.alloc_id(); - d.insert(parent, usize::MAX, Node::group(gid, children))?; + let mut g = Node::group(gid, children); + g.bbox_angle = bbox_angle; + d.insert(parent, usize::MAX, g)?; sel.set([gid]); Ok(gid) })?; Ok(json!({ "id": id.0 })) } -/// A grid's divider count `count` with its skew `key` in percent (0 when absent, clamped to -/// ±[`shapes::GRID_SKEW_MAX`]). +/// A grid's divider count `count` (an error unless it is a number or null; 5 unless it is a JSON +/// integer of 0 or more, so 4.0 and 2.5 give 5; at most 999) with its skew `key` in percent (0 when +/// absent, clamped to ±[`shapes::GRID_SKEW_MAX`]). fn dividers(p: &Value, count: &str, key: &str, cmd: &str) -> Result<(u32, f64)> { + check_numbers(p, &[count], cmd)?; let n = p.get(count).and_then(Value::as_u64).unwrap_or(5).min(999) as u32; let skew = match p.get(key) { None | Some(Value::Null) => 0.0, @@ -429,7 +613,7 @@ fn rect_grid(s: &mut Session, p: &Value) -> Result { let r = rect_of(p, CMD)?; let paths = shapes::rectangular_grid(r, dividers(p, "rows", "rowSkew", CMD)?, dividers(p, "columns", "columnSkew", CMD)?, switch(p, "frame", true, CMD)?); - grid_group(s, "Rectangular Grid", paths, switch(p, "fill", false, CMD)?) + grid_group(s, "Rectangular Grid", turned_grid(p, r, paths, CMD)?, switch(p, "fill", false, CMD)?) } fn polar_grid(s: &mut Session, p: &Value) -> Result { @@ -441,7 +625,24 @@ fn polar_grid(s: &mut Session, p: &Value) -> Result { dividers(p, "radial", "radialSkew", CMD)?, switch(p, "compound", false, CMD)?, ); - grid_group(s, "Polar Grid", paths, switch(p, "fill", false, CMD)?) + grid_group(s, "Polar Grid", turned_grid(p, r, paths, CMD)?, switch(p, "fill", false, CMD)?) +} + +/// A grid's paths in `r` turned by the `rotation` param about the centre of `r` (a grid drawn +/// along a Constrain Angle), and their bounding-box angle; as they are without it or at 0. +fn turned_grid(p: &Value, r: Rect, mut paths: Vec, cmd: &str) -> Result<(Vec, f64)> { + let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", cmd)? } else { 0.0 }; + if !rotation.is_finite() { + return Err(bad(cmd, "rotation must be finite")); + } + if rotation != 0.0 { + let c = r.center().to_vec2(); + let m = Affine::translate(c) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate(-c); + for path in &mut paths { + path.transform(m); + } + } + Ok((paths, bbox_turn(rotation))) } /// An anchor `{x, y, in?, out?, smooth?}` given to `cmd` (handles `[x, y]`, at the anchor when @@ -465,6 +666,8 @@ pub(crate) fn anchor_from_json(v: &Value, cmd: &str) -> Result { } fn path_create(s: &mut Session, p: &Value) -> Result { + // Checked with `d` too, where the path data alone decides whether the path is closed. + let closed = switch_or(p, "closed", false, "path.create")?; let path = if let Some(d) = str_param(p, "d") { let bp = vectorcraft_geom::BezPath::from_svg(d).map_err(|e| bad("path.create", format!("bad path data: {e}")))?; PathData::from_bezpath(&bp) @@ -479,7 +682,7 @@ fn path_create(s: &mut Session, p: &Value) -> Result { if anchors.is_empty() { return Err(bad("path.create", "need at least one anchor")); } - PathData::single(SubPath::new(anchors, bool_or(p, "closed", false))) + PathData::single(SubPath::new(anchors, closed)) }; let mut look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); // Open paths drawn with a stroke of None would be invisible: mimic Illustrator and keep what the user set. @@ -493,8 +696,23 @@ fn path_create(s: &mut Session, p: &Value) -> Result { fn text_create(s: &mut Session, p: &Value) -> Result { let x = f64_req(p, "x", "text.create")?; let y = f64_req(p, "y", "text.create")?; + super::paint::check_keep_model(p, "text.create")?; + check_numbers(p, &["size"], "text.create")?; + check_switches(p, &["vertical", "placeholder"], "text.create")?; + if let Some(a) = p.get("area") { + 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)); + // 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 }; + if !rotation.is_finite() { + return Err(bad("text.create", "rotation must be finite")); + } + if rotation != 0.0 { + t.xf *= vectorcraft_geom::rotate_deg(rotation); + } t.vertical = p.get("vertical").and_then(Value::as_bool).unwrap_or(false); t.para = new_type_para(); new_type_alignment(s, p, "text.create", &mut t)?; @@ -504,13 +722,14 @@ fn text_create(s: &mut Session, p: &Value) -> Result { t.kind = vectorcraft_doc::TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, h)) }; t.area.fit = new_area_fit(s, a, "text.create")?; } + t.system_layout = s.doc()?.doc.setup.system_layout; if bool_or(p, "placeholder", false) { super::typemenu::fill_with_placeholder(&mut t); } else { // Lays the text out (and sizes an Auto Size frame). super::typecmd::refresh_bounds(&mut t); } - let made = add_node(s, "Type", NodeKind::Text(Box::new(t)), Appearance::default(), None)?; + let made = insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation))?; let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); Ok(super::typecmd::with_overflow(s, id.as_slice(), made)) @@ -586,6 +805,9 @@ pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle { } if let Some(f) = str_param(p, "style") { style.font_style = f.to_string(); + } else if str_param(p, "font").is_some() { + // A family without a Regular (#4128): its closest style, as text.setRangeStyle takes. + super::textedit::fit_font_style(&mut style); } style.fill = match p.get("color").and_then(color_value) { Some(c) => vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)), diff --git a/crates/engine/src/cmd/cut.rs b/crates/engine/src/cmd/cut.rs index 10454562f1..faf9050529 100644 --- a/crates/engine/src/cmd/cut.rs +++ b/crates/engine/src/cmd/cut.rs @@ -130,7 +130,8 @@ fn cut_targets(s: &Session) -> Result> { } } out.dedup(); - out.retain(|id| doc.is_editable(*id)); + let editable = doc.editable(); + out.retain(|id| editable(*id)); Ok(out) } @@ -208,8 +209,8 @@ fn split_by_line(pd: &PathData, rule: FillRule, axis: &Axis) -> Option= 0.0)?; + let a = erase_outline(pd, f64::INFINITY, &|q| axis.side(q) < 0.0)?; + let b = erase_outline(pd, f64::INFINITY, &|q| axis.side(q) >= 0.0)?; Some(if pd.subpaths.len() == 1 { a.into_iter().chain(b).collect() } else { @@ -248,7 +249,9 @@ fn crop(pd: &PathData, rule: FillRule, rect: Rect) -> Option> { return Some(if r.is_empty() { vec![] } else { vec![r] }); } let inside = rect.inflate(1e-9, 1e-9); - let pieces = erase_outline(pd, &|q| !(q.x >= inside.x0 && q.x <= inside.x1 && q.y >= inside.y0 && q.y <= inside.y1))?; + // Sampled at least every half of the rectangle's shorter side, so a line through it is found. + let step = rect.width().min(rect.height()) / 2.0; + let pieces = erase_outline(pd, step, &|q| !(q.x >= inside.x0 && q.x <= inside.x1 && q.y >= inside.y0 && q.y <= inside.y1))?; Some(if pd.subpaths.len() == 1 || pieces.is_empty() { pieces } else { @@ -316,7 +319,7 @@ fn mirror(pd: &PathData, rule: FillRule, axis: &Axis, sign: f64) -> Vec pieces.into_iter().flat_map(|p| p.subpaths).collect(), None => pd.subpaths.clone(), }; diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index efc3e5fc72..ec1f91f20e 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -4,7 +4,7 @@ use serde_json::{Value, json}; use std::sync::Arc; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::dimension::{ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, TextAlignment, TextPosition}; -use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, Dash, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject}; use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2}; pub fn specs() -> Vec { @@ -165,11 +165,13 @@ fn apply_to_all(s: &mut Session, p: &Value) -> Result { }; let o = dimension_of(&st.doc, from)?.options; let mut ids = vec![]; + let editable = st.doc.editable(); st.doc.walk(|n| { - if n.extras().dimension.is_some() && st.doc.is_editable(n.id) { + if n.extras().dimension.is_some() && editable(n.id) { ids.push(n.id); } }); + drop(editable); s.edit("Apply to All", |doc, _| { for id in &ids { let mut dim = dimension_of(doc, *id)?; @@ -225,15 +227,64 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<()> { next.moved = None; } } - if next != old || before.node(id).and_then(|n| n.extras().dimension.as_deref()).is_some_and(|d| d != &next) { + // A new document colour mode (Document Color Mode) redraws every dimension in it. + if next != old + || before.color_mode != doc.color_mode + || before.node(id).and_then(|n| n.extras().dimension.as_deref()).is_some_and(|d| d != &next) + { replace(doc, id, next)?; } } Ok(()) } -fn paint(c: [u8; 3]) -> Paint { - Paint::solid(Color::rgb8(c[0], c[1], c[2])) +/// Redraw the dimensions of an opened document whose art isn't in its colour mode: files saved +/// before dimensions followed the colour mode have RGB dimensions in CMYK documents. A dimension +/// that can't be redrawn keeps the art it has. +pub(crate) fn conform(doc: &mut Document) { + if !doc.dimensions { + return; + } + let mode = doc.color_mode; + let off_mode = |c: &Color| match mode { + ColorMode::Rgb => matches!(c, Color::Cmyk { .. }), + ColorMode::Cmyk => matches!(c, Color::Rgb { .. }), + }; + let mut stale = Vec::new(); + doc.walk(|n| { + if let Some(d) = &n.extras().dimension { + let mut off = false; + n.walk(&mut |c| { + off |= [c.appearance.fill_paint(), c.appearance.stroke_paint()].iter().filter_map(|p| p.color()).any(|c| off_mode(&c)); + // The label's characters carry their own fill. + if let NodeKind::Text(t) = &c.kind { + off |= t.runs.iter().filter_map(|r| r.style.fill.color()).any(|c| off_mode(&c)); + } + }); + if off { + stale.push((n.id, (**d).clone())); + } + } + }); + for (id, d) in stale { + // An error leaves this dimension as it was; the others are still redrawn. + let _ = replace(doc, id, d); + } +} + +/// Option colour `c` as a paint in the document's colour model: in a CMYK document black is K +/// only (a rich four-ink black would print a black dimension in every plate) and other colours +/// convert through the active colour settings. +fn paint(c: [u8; 3], mode: ColorMode) -> Paint { + let rgb = Color::rgb8(c[0], c[1], c[2]); + Paint::solid(match mode { + ColorMode::Rgb => rgb, + ColorMode::Cmyk if c == [0, 0, 0] => Color::cmyk(0.0, 0.0, 0.0, 1.0), + ColorMode::Cmyk => { + let cms = vectorcraft_color::cms::active(); + cms.convert(&rgb, vectorcraft_color::cms::Model::Cmyk, cms.settings().intent) + } + }) } fn line(a: Point, b: Point) -> BezPath { let mut p = BezPath::new(); @@ -242,10 +293,10 @@ fn line(a: Point, b: Point) -> BezPath { p } -fn appearance(o: &DimensionOptions, ext: bool, arrows: bool) -> Appearance { +fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) -> Appearance { let (color, width, kind) = if ext { (o.extension_color, o.extension_weight, o.extension_type) } else { (o.line_color, o.line_weight, o.line_type) }; - let mut a = Appearance::basic(Paint::None, paint(color), width); + let mut a = Appearance::basic(Paint::None, paint(color, mode), width); if let Some(st) = a.stroke_mut() { st.dash = match kind { LineType::Dashed => Some(Dash { pattern: vec![width * 5.0, width * 3.0], ..Default::default() }), @@ -283,6 +334,7 @@ fn along(o: &DimensionOptions) -> f64 { fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result>> { d.validate().map_err(error)?; let o = &d.options; + let mode = doc.color_mode; let label = d.label().map_err(error)?; let mut paths: Vec<(BezPath, Appearance)> = Vec::new(); let mut angle = 0.0; @@ -299,11 +351,11 @@ fn artwork(doc: &mut Document, d: &Dimension, old: &[NodeId]) -> Result Result Result Result Vec { vec![ cmd!( @@ -60,7 +68,7 @@ pub fn specs() -> Vec { "Liquify", [], None, - "{tool: warp|twirl|pucker|bloat|scallop|crystallize|wrinkle, points: [[x,y,pressure?]…] (the brush stroke; pen pressure 0..1, default 1), diameter?|width?, height? (pt, default 100), angle?, intensity? (0..1 or %), usePressure? (each point's pressure is the intensity there), detail? (1..10), simplify?: 0..100, simplifyOn?: bool (default true; both for warp, twirl, pucker, bloat), rate? (twirl °), complexity? (0..15), horizontal?, vertical? (wrinkle, 0..1 or %), affectAnchors?, affectIn?, affectOut? (scallop, crystallize, wrinkle; default true), ids?|id? (default: selection, else every path the brush touches)}", + "{tool: warp|twirl|pucker|bloat|scallop|crystallize|wrinkle, points: [[x,y,pressure?]…] (the brush stroke; pen pressure 0..1, default 1), diameter?|width?, height? (pt, default 100), angle?, intensity? (0..1 or %), usePressure?: bool (each point's pressure is the intensity there), detail? (1..10), simplify?: 0..100, simplifyOn?: bool (default true; both for warp, twirl, pucker, bloat), rate? (twirl °), complexity? (0..15), horizontal?, vertical? (wrinkle, 0..1 or %), affectAnchors?, affectIn?, affectOut?: bool (scallop, crystallize, wrinkle; default true), ids?|id? (default: selection, else every path the brush touches)}", has_doc, liquify ), @@ -300,7 +308,7 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result { if !(left.is_finite() && right.is_finite()) || left < 0.0 || right < 0.0 || left.max(right) > 1.0e5 { return Err(bad(C, "left/right must be non-negative widths")); } - let adjust = bool_or(p, "adjustAdjoining", false); + let adjust = switch_or(p, "adjustAdjoining", false, C)?; // When the profile comes out as it was, within a rounding error (1e-9), the document and its undo // history stay as they are. let mut pos = 0; @@ -405,7 +413,7 @@ fn width_profile_set(s: &mut Session, p: &Value) -> Result { Some(Value::Array(a)) => { let mut pts = vec![]; for q in a { - let v: Vec = q.as_array().map(|x| x.iter().filter_map(Value::as_f64).collect()).unwrap_or_default(); + let v: Vec = q.as_array().and_then(|x| x.iter().map(Value::as_f64).collect()).unwrap_or_default(); if v.len() != 3 || v.iter().any(|x| !x.is_finite()) || v[1] < 0.0 || v[2] < 0.0 { return Err(bad(C, "points must be [t, left, right] with non-negative widths")); } @@ -455,7 +463,8 @@ fn samples_of(p: &Value, key: &str) -> Option> { /// What a liquify stroke may reach: the paths it can edit, each with the box no dab outside /// changes it ([`reach_bounds`]), and the objects it leaves as they are (type, symbols, images, /// graphs, meshes, and envelopes, repeats and blends with their contents), each with its bounds -/// and what it is. Hidden and locked objects, and guides, are neither. +/// and what it is. Hidden and locked objects, the art on a locked artboard, and guides are +/// neither. #[derive(Default)] struct Targets { paths: Vec<(NodeId, Rect)>, @@ -484,19 +493,21 @@ impl Targets { /// The targets under `roots` (the selection), or with none every visible object. fn of(d: &Document, roots: &[NodeId]) -> Self { let mut t = Self::default(); + let locks = d.locked_artboards(); if roots.is_empty() { - d.layers.iter().for_each(|l| t.visit(l)); + d.layers.iter().for_each(|l| t.visit(l, &locks)); return t; } + let editable = |id| d.is_editable_with(&locks, id); for r in roots { let (Some(n), Some(chain)) = (d.node(*r), d.ancestry(*r)) else { continue }; - if !d.is_editable(*r) { + if !editable(*r) { continue; } // Inside a graph, an envelope, a repeat or a blend: that object is what is left alone. match chain.iter().filter_map(|a| d.node(*a)).find_map(|a| Some((a, not_liquified(a)?))) { Some((a, what)) => t.block(a, what), - None => t.visit(n), + None => t.visit(n, &locks), } } t @@ -510,7 +521,7 @@ impl Targets { } } - fn visit(&mut self, n: &Node) { + fn visit(&mut self, n: &Node, locks: &vectorcraft_doc::LockedArtboards) { if !n.visible || n.locked { return; } @@ -525,7 +536,8 @@ impl Targets { self.paths.push((n.id, b)); } } - _ => n.children().into_iter().flatten().for_each(|c| self.visit(c)), + // The objects of a layer on a locked artboard, members and all, are left out. + _ => n.children().into_iter().flatten().filter(|c| !(n.is_layer() && locks.holds(c))).for_each(|c| self.visit(c, locks)), } } } @@ -628,9 +640,17 @@ impl LiquifyStroke { } } +/// The number keys of `object.liquify`. [`LiquifyParams::from_json`] reads a value that is not a +/// number as the key left out. +const LIQUIFY_NUMBERS: &[&str] = + &["diameter", "width", "height", "angle", "intensity", "detail", "simplify", "rate", "complexity", "horizontal", "vertical"]; + fn liquify(s: &mut Session, p: &Value) -> Result { const C: &str = "object.liquify"; + check_numbers(p, LIQUIFY_NUMBERS, C)?; let prm = LiquifyParams::from_json(p).ok_or_else(|| bad(C, "missing or unknown `tool`"))?; + // `LiquifyParams::from_json` uses a key's default for a value that is not true or false. + check_switches(p, &["usePressure", "simplifyOn", "affectAnchors", "affectIn", "affectOut"], C)?; let pts = samples_of(p, "points").filter(|v| !v.is_empty()).ok_or_else(|| bad(C, "points must be a non-empty [[x,y,pressure?]…] list"))?; if pts.iter().any(|(q, f)| !q.x.is_finite() || !q.y.is_finite() || !f.is_finite()) { return Err(bad(C, "points must be finite")); @@ -697,9 +717,10 @@ fn puppet_ids(p: &Value, default: impl FnOnce() -> Result>) -> Resul fn puppet_warp(s: &mut Session, p: &Value) -> Result { const C: &str = "object.puppetWarp"; + check_numbers(p, &["expand"], C)?; let pins = points_of(p, "pins").ok_or_else(|| bad(C, "pins must be [[x,y]…]"))?; let moved = points_of(p, "moved").ok_or_else(|| bad(C, "moved must be [[x,y]…]"))?; - let rest = bool_or(p, "rest", false); + let rest = switch_or(p, "rest", false, C)?; if (pins.is_empty() && !rest) || pins.len() != moved.len() { return Err(bad(C, "pins and moved must be non-empty lists of the same length")); } @@ -711,7 +732,9 @@ fn puppet_warp(s: &mut Session, p: &Value) -> Result { let expand = f64_or(p, "expand", 3.0).clamp(0.0, 1000.0); let angles: Vec> = match p.get("angles") { None | Some(Value::Null) => vec![None; pins.len()], - Some(Value::Array(a)) if a.len() == pins.len() => a.iter().map(|v| v.as_f64().filter(|d| d.is_finite()).map(f64::to_radians)).collect(), + Some(Value::Array(a)) if a.len() == pins.len() && a.iter().all(|v| v.is_null() || v.is_number()) => { + a.iter().map(|v| v.as_f64().filter(|d| d.is_finite()).map(f64::to_radians)).collect() + } Some(_) => return Err(bad(C, "angles must be a list as long as pins (degrees or null)")), }; let ids_json = json!({ "ids": ids.iter().map(|i| i.0).collect::>() }); @@ -752,6 +775,7 @@ pub(crate) fn drop_puppet_pins(st: &mut crate::DocState) { } fn puppet_pins(s: &mut Session, p: &Value) -> Result { + check_numbers(p, &["expand"], "object.puppetWarp.pins")?; let ids = puppet_ids(p, || Ok(s.doc()?.selection.objects.clone()))?; let expand = f64_or(p, "expand", 3.0).clamp(0.0, 1000.0); let set = PinSet::of(&s.doc()?.doc, &ids, expand).ok_or_else(|| EngineError::Other("nothing to warp".into()))?; @@ -759,601 +783,3 @@ fn puppet_pins(s: &mut Session, p: &Value) -> Result { v["auto"] = json!(set.auto); Ok(v) } - -// ---------- perspective grid ---------- - -/// The document's perspective grid (the default preset when none was defined). -pub(crate) fn grid_of(d: &Document) -> PerspectiveGrid { - PerspectiveGrid::effective(d) -} - -/// Write the grid into the document (`Document.unknown["perspectiveGrid"]`). -pub(crate) fn store_grid(d: &mut Document, g: &PerspectiveGrid) { - g.store(d); -} - -/// Whether `d` holds `g` as [`store_grid`] writes it (with `attached` cleared): then storing `g` -/// leaves `d` as it is. -fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool { - let mut g = g.clone(); - g.attached.clear(); - serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v)) -} - -/// Change view state of the grid without an undo step. -pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> Result { - let st = s.doc_mut()?; - let mut g = grid_of(&st.doc); - f(&mut g); - store_grid(Arc::make_mut(&mut st.doc), &g); - if let Some(it) = &mut st.interaction { - store_grid(Arc::make_mut(&mut it.doc), &g); - } - st.revision += 1; - Ok(g) -} - -fn grid_set(s: &mut Session, p: &Value) -> Result { - let old = grid_of(&s.doc()?.doc); - let g = old.merged(p).map_err(|e| bad("perspective.grid.set", e))?; - let reproject = bool_or(p, "reproject", false); - // When the document holds this grid already, no object moves, and the document and its undo - // history stay as they are. - if grid_kept(&s.doc()?.doc, &g) { - return Ok(g.definition_json()); - } - s.edit("Define Perspective Grid", |d, _| { - if reproject { - old.adopt_stored_attachments(d); - for (id, plane, depth) in persp::attached_roots(d) { - let h = old.homography_at(plane, depth).and_then(|h| h.inverse()).zip(g.homography_at(plane, depth)); - let (hi, h) = h.ok_or_else(|| EngineError::Other("an object in perspective would leave the edited grid".into()))?; - let m = h.then_after(&hi); - warp_checked(d, id, &m)?; - } - } - store_grid(d, &g); - Ok(()) - })?; - Ok(g.definition_json()) -} - -fn grid_show(s: &mut Session, p: &Value) -> Result { - let want = p.get("visible").and_then(Value::as_bool); - let g = silent(s, |g| g.visible = want.unwrap_or(!g.visible))?; - Ok(json!({ "visible": g.visible })) -} - -fn plane_set(s: &mut Session, p: &Value) -> Result { - let plane = str_param(p, "plane").and_then(Plane::parse).ok_or_else(|| bad("perspective.plane.set", "plane must be left|right|ground|none"))?; - silent(s, |g| g.plane = plane)?; - Ok(json!({ "plane": plane.id() })) -} - -fn plane_param(g: &PerspectiveGrid, p: &Value, cmd: &str) -> Result { - let plane = match str_param(p, "plane") { - Some(v) => Plane::parse(v).ok_or_else(|| bad(cmd, "plane must be left|right|ground"))?, - None => g.plane, - }; - if plane == Plane::None { - return Err(EngineError::Other("no active perspective plane".into())); - } - Ok(plane) -} - -fn roots(s: &Session, p: &Value) -> Result> { - match ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])) { - Some(v) => Ok(outermost(&s.doc()?.doc, v)), - None => selected_roots(s), - } -} - -/// Map `n` with `f`, failing if any point would leave the plane's visible side. -/// Map `n` with `h` (type and symbols in perspective keep their art and are drawn through it), -/// failing if any point would leave the plane's visible side. -fn warp_checked(d: &mut Document, id: NodeId, h: &Homography) -> Result<()> { - let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; - let mut pts = vec![]; - collect_points(n, &mut pts); - if pts.iter().any(|q| h.apply(*q).is_none()) { - return Err(EngineError::Other("the object would cross the horizon of the perspective plane".into())); - } - project_node(n, h); - Ok(()) -} - -/// Attach `id` to `plane`: projected by `map`, else by the map that keeps its bounds' corners -/// (on the nearest gridlines with `snap`). -fn attach_in(d: &mut Document, g: &mut PerspectiveGrid, id: NodeId, plane: Plane, snap: bool, map: Option) -> Result<()> { - let b = d.node(id).ok_or(EngineError::NoNode(id))?.geometric_bounds().ok_or_else(|| EngineError::Other("the object has no geometry".into()))?; - let m = - map.or_else(|| g.attach_homography(plane, b, snap)).ok_or_else(|| EngineError::Other("the object is beyond the plane's horizon".into()))?; - warp_checked(d, id, &m)?; - persp::set_attachment(d.node_mut(id).ok_or(EngineError::NoNode(id))?, plane, g.offset(plane)); - g.attached.insert(id.0.to_string(), plane); - Ok(()) -} - -fn attach(s: &mut Session, p: &Value) -> Result { - let ids = roots(s, p)?; - let mut g = grid_of(&s.doc()?.doc); - let plane = plane_param(&g, p, "perspective.attach")?; - // With no object to attach, when the document holds the grid already, the document and its undo - // history stay as they are. - if ids.is_empty() && grid_kept(&s.doc()?.doc, &g) { - return Ok(json!({ "ids": [], "plane": plane.id() })); - } - s.edit("Attach to Active Plane", |d, _| { - for id in &ids { - attach_in(d, &mut g, *id, plane, false, None)?; - } - store_grid(d, &g); - Ok(()) - })?; - Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "plane": plane.id() })) -} - -fn release(s: &mut Session, p: &Value) -> Result { - let ids = roots(s, p)?; - let mut g = grid_of(&s.doc()?.doc); - // When releasing leaves every object as it is (none is in perspective) and the document holds - // the grid already, the document and its undo history stay as they are. - let d = &s.doc()?.doc; - let unchanged = |id: &NodeId| { - d.node(*id).is_none_or(|n| { - let mut released = n.clone(); - persp::release(&mut released); - released == *n - }) - }; - if ids.iter().all(unchanged) && grid_kept(d, &g) { - return ok(); - } - s.edit("Release with Perspective", |d, _| { - for id in &ids { - g.attached.remove(&id.0.to_string()); - if let Some(n) = d.node_mut(*id) { - persp::release(n); - } - } - store_grid(d, &g); - Ok(()) - })?; - ok() -} - -/// One object's share of a perspective edit: the page map for an object on `plane` at `depth`, and -/// the depth it ends at. -type PerspStep<'a> = &'a dyn Fn(&PerspectiveGrid, Plane, f64) -> Result<(Homography, f64)>; - -/// Where an object is in perspective: its plane and depth. -type Attached = (Plane, f64); - -fn beyond_horizon() -> EngineError { - EngineError::Other("the pointer is beyond the plane's horizon".into()) -} - -/// Whether the grid stored in `d` lists attachments of its own, as grids stored before attachments -/// were kept on the objects do ([`PerspectiveGrid::adopt_stored_attachments`]). -fn stores_attachments(d: &Document) -> bool { - !PerspectiveGrid::current(d).attached.is_empty() -} - -/// Edit objects in perspective (one undo step `label`): with `copy` their duplicates (which stay -/// attached), each mapped by `step` for its own plane and depth; objects not in perspective attach -/// to `fallback` first. → the edited objects and where the first one was (plane, depth). In an -/// interaction whose document is still its snapshot, the duplicates are the copies the interaction -/// keeps ([`super::object::preview_copies`]), unless the snapshot's grid lists attachments of its -/// own ([`stores_attachments`]). -fn persp_edit( - s: &mut Session, - label: &str, - ids: &[NodeId], - fallback: Option, - copy: bool, - step: PerspStep, -) -> Result<(Vec, Option)> { - if ids.is_empty() { - return Err(EngineError::Other("select the objects to transform in perspective".into())); - } - let mut g = grid_of(&s.doc()?.doc); - let kept = if copy && !stores_attachments(&s.doc()?.doc) { super::object::preview_copies(s, ids, false)? } else { None }; - s.edit(label, |d, sel| { - g.adopt_stored_attachments(d); - let targets = match &kept { - // The document becomes the snapshot with the kept copies, not yet mapped, and the loop - // below maps only the copies. - Some(k) => { - *d = Document::clone(&k.doc); - sel.clone_from(&k.selection); - k.ids.clone() - } - None if copy => duplicate_in(d, sel, ids, Affine::IDENTITY)?, - None => ids.to_vec(), - }; - let mut first = None; - for id in &targets { - let (plane, depth) = match g.attachment_of(d, *id) { - Some(a) => a, - None => { - let pl = fallback.ok_or_else(|| EngineError::Other("the object isn't on a perspective plane".into()))?; - attach_in(d, &mut g, *id, pl, false, None)?; - (pl, g.offset(pl)) - } - }; - first.get_or_insert((plane, depth)); - let (h, depth) = step(&g, plane, depth)?; - warp_checked(d, *id, &h)?; - persp::set_attachment(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, plane, depth); - } - store_grid(d, &g); - Ok((targets, first)) - }) -} - -/// Where the first of `ids` is in perspective (its plane and depth) when `ids` is not empty, every one -/// of them is in perspective already, `still` holds for each one's plane and depth, and the document -/// holds the grid already; None otherwise. -fn unmoved(s: &Session, ids: &[NodeId], still: impl Fn(&PerspectiveGrid, Plane, f64) -> bool) -> Result> { - let d = &s.doc()?.doc; - let g = grid_of(d); - if ids.is_empty() || !grid_kept(d, &g) { - return Ok(None); - } - let at: Option> = ids.iter().map(|id| g.attachment_of(d, *id).filter(|(pl, depth)| still(&g, *pl, *depth))).collect(); - Ok(at.and_then(|at| at.first().copied())) -} - -/// Remember `again` (`perspective.transform` params) for Object › Transform › Transform Again, once -/// the drag that made it is committed. -fn record_again(s: &mut Session, again: Value) -> Result<()> { - let st = s.doc_mut()?; - match &mut st.interaction { - Some(it) => it.perspective_again = Some(again), - None => st.last_perspective = Some(again), - } - Ok(()) -} - -fn ids_json(ids: &[NodeId]) -> Value { - json!({ "ids": ids.iter().map(|i| i.0).collect::>() }) -} - -/// A plane-space affine map as `perspective.transform`'s `matrix` param. -fn matrix_json(m: Affine) -> Value { - json!(m.as_coeffs()) -} - -fn persp_move(s: &mut Session, p: &Value) -> Result { - const C: &str = "perspective.move"; - let ids = roots(s, p)?; - let from = point_param(p, "from").ok_or_else(|| bad(C, "missing from"))?; - let to = point_param(p, "to").ok_or_else(|| bad(C, "missing to"))?; - if ![from.x, from.y, to.x, to.y].iter().all(|v| v.is_finite()) { - return Err(bad(C, "from and to must be finite")); - } - let fallback = plane_param(&grid_of(&s.doc()?.doc), p, C).ok(); - let (perp, copy) = (bool_or(p, "perpendicular", false), bool_or(p, "copy", false)); - // Snap to Grid: a correction for the objects on the first one's plane and depth. - let fix = if perp { None } else { super::perspgrid::snap_fix(&s.doc()?.doc, &ids, p, (from, to)) }; - let snapped = move |pl: Plane, depth: f64, dv: vectorcraft_geom::Vec2| { - dv + fix.filter(|f| f.0 == pl && f.1 == depth).map_or(vectorcraft_geom::Vec2::ZERO, |f| f.2) - }; - // In-plane: the plane-space offset under the pointer; perpendicular: the depth it reaches. - let step = |g: &PerspectiveGrid, pl: Plane, depth: f64| -> Result<(Homography, f64)> { - if perp { - let to_depth = g.depth_at(pl, depth, from, to).ok_or_else(beyond_horizon)?; - Ok((g.transform_map(pl, depth, Affine::IDENTITY, to_depth - depth).ok_or_else(beyond_horizon)?, to_depth)) - } else { - let dv = snapped(pl, depth, g.plane_delta(pl, depth, from, to).ok_or_else(beyond_horizon)?); - Ok((g.transform_map(pl, depth, Affine::translate(dv), 0.0).ok_or_else(beyond_horizon)?, depth)) - } - }; - let label = if copy { "Copy in Perspective" } else { "Move in Perspective" }; - // When no object moves more than 1e-9 pt along its plane's axes or its normal (Snap to Grid - // included) and there is no copy, the document and its undo history stay as they are. - let still = |g: &PerspectiveGrid, pl: Plane, depth: f64| { - if perp { - g.depth_at(pl, depth, from, to).is_some_and(|d| (d - depth).abs() <= 1e-9) - } else { - g.plane_delta(pl, depth, from, to).map(|dv| snapped(pl, depth, dv)).is_some_and(|dv| dv.x.abs() <= 1e-9 && dv.y.abs() <= 1e-9) - } - }; - let first_still = if copy { None } else { unmoved(s, &ids, still)? }; - let (targets, first) = match first_still { - Some(at) => (ids, Some(at)), - None => persp_edit(s, label, &ids, fallback, copy, &step)?, - }; - // Transform Again repeats the first object's move, and the identity when no object moved. - if let Some((pl, depth)) = first { - let g = grid_of(&s.doc()?.doc); - let again = match perp { - _ if first_still.is_some() => Some(json!({"matrix": matrix_json(Affine::IDENTITY), "copy": copy})), - true => g.depth_at(pl, depth, from, to).map(|d| json!({"matrix": matrix_json(Affine::IDENTITY), "depth": d - depth, "copy": copy})), - false => { - g.plane_delta(pl, depth, from, to).map(|dv| json!({"matrix": matrix_json(Affine::translate(snapped(pl, depth, dv))), "copy": copy})) - } - }; - if let Some(a) = again { - record_again(s, a)?; - } - } - Ok(ids_json(&targets)) -} - -fn persp_transform(s: &mut Session, p: &Value) -> Result { - const C: &str = "perspective.transform"; - let m = matrix_param(p, "matrix").ok_or_else(|| bad(C, "missing matrix [a,b,c,d,e,f]"))?; - let dz = f64_or(p, "depth", 0.0); - if !m.as_coeffs().iter().all(|v| v.is_finite()) || m.determinant().abs() < 1e-12 || !dz.is_finite() { - return Err(bad(C, "matrix must be finite and invertible, depth finite")); - } - let ids = roots(s, p)?; - let fallback = plane_param(&grid_of(&s.doc()?.doc), p, C).ok(); - let copy = bool_or(p, "copy", false); - let step = |g: &PerspectiveGrid, pl: Plane, depth: f64| -> Result<(Homography, f64)> { - let to = depth + dz; - if to.abs() > persp::MAX_DEPTH { - return Err(EngineError::Other("the objects would leave the grid".into())); - } - Ok((g.transform_map(pl, depth, m, dz).ok_or_else(beyond_horizon)?, to)) - }; - // An identity without a copy moves no object that is in perspective already: then the document - // and its undo history stay as they are, and Transform Again repeats the identity. - let identity = !copy && m == Affine::IDENTITY && dz == 0.0; - let targets = if identity && unmoved(s, &ids, |g, pl, depth| g.transform_map(pl, depth, m, dz).is_some())?.is_some() { - ids - } else { - persp_edit(s, if copy { "Copy in Perspective" } else { "Transform in Perspective" }, &ids, fallback, copy, &step)?.0 - }; - record_again(s, json!({"matrix": matrix_json(m), "depth": dz, "copy": copy}))?; - Ok(ids_json(&targets)) -} - -/// Object › Transform › Transform Again after a perspective move or scale: the same plane-space -/// transform on the selection. -pub(crate) fn transform_again(s: &mut Session, again: &Value) -> Result { - let mut p = again.clone(); - if let Some(o) = p.as_object_mut() { - o.remove("ids"); - } - persp_transform(s, &p) -} - -fn plane_move(s: &mut Session, p: &Value) -> Result { - const C: &str = "perspective.plane.move"; - let old = grid_of(&s.doc()?.doc); - let plane = plane_param(&old, p, C)?; - let from = old.offset(plane); - let to = match (p.get("offset").and_then(Value::as_f64), p.get("by").and_then(Value::as_f64)) { - (Some(o), _) => o, - (None, Some(b)) => from + b, - (None, None) => return Err(bad(C, "give offset or by")), - }; - let objects = str_param(p, "objects").unwrap_or("none"); - if !matches!(objects, "none" | "move" | "copy") { - return Err(bad(C, "objects must be none, move or copy")); - } - let mut g = old.clone(); - g.set_offset(plane, to); - g.validate().map_err(|e| bad(C, e))?; - let label = match objects { - "copy" => "Move Plane and Copy Objects", - "move" => "Move Plane and Objects", - _ => "Move Plane", - }; - // The objects on the plane where it was (not those moved off it along its normal). - let on_plane = |d: &Document| -> Vec { - persp::attached_roots(d) - .into_iter() - .filter(|(id, pl, depth)| *pl == plane && (depth - from).abs() < 1e-6 && d.is_editable(*id)) - .map(|(id, ..)| id) - .collect() - }; - // A plane moved to where it is, with its objects or without them, moves nothing: when the - // document holds the grid already, the document and its undo history stay as they are. - if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &g) { - let ids = if objects == "move" { on_plane(&s.doc()?.doc) } else { vec![] }; - return Ok(json!({ "plane": plane.id(), "offset": to, "ids": ids.iter().map(|i| i.0).collect::>() })); - } - // In an interaction whose document is still its snapshot, the copies of the objects on the - // plane are the copies the interaction keeps (`preview_copies`), unless the snapshot's grid - // lists attachments of its own (`stores_attachments`). - let kept = if objects == "copy" && s.in_interaction() && !stores_attachments(&s.doc()?.doc) { - let on = on_plane(&s.doc()?.doc); - super::object::preview_copies(s, &on, false)? - } else { - None - }; - let ids = s.edit(label, |d, sel| { - old.adopt_stored_attachments(d); - let mut ids = vec![]; - if objects != "none" { - ids = match &kept { - // The document becomes the snapshot with the kept copies, not yet moved, and the - // loop below moves only the copies. - Some(k) => { - *d = Document::clone(&k.doc); - sel.clone_from(&k.selection); - k.ids.clone() - } - None => { - let on = on_plane(d); - if objects == "copy" { duplicate_in(d, sel, &on, Affine::IDENTITY)? } else { on } - } - }; - let m = old.transform_map(plane, from, Affine::IDENTITY, to - from).ok_or_else(beyond_horizon)?; - for id in &ids { - warp_checked(d, *id, &m)?; - persp::set_attachment(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, plane, to); - } - } - store_grid(d, &g); - Ok(ids) - })?; - Ok(json!({ "plane": plane.id(), "offset": to, "ids": ids.iter().map(|i| i.0).collect::>() })) -} - -fn plane_match(s: &mut Session, p: &Value) -> Result { - let st = s.doc()?; - let id = id_param(p, "id") - .or_else(|| st.selection.objects.first().copied()) - .ok_or_else(|| EngineError::Other("select an object in perspective".into()))?; - let mut g = grid_of(&st.doc); - let (plane, depth) = g.attachment_of(&st.doc, id).ok_or_else(|| EngineError::Other("the object isn't in perspective".into()))?; - g.set_offset(plane, depth); - g.plane = plane; - g.validate().map_err(|e| bad("perspective.plane.matchObject", e))?; - // When the plane is at the object and active already, and the document holds that grid, the - // document and its undo history stay as they are. - if grid_kept(&st.doc, &g) { - return Ok(json!({ "plane": plane.id(), "offset": depth })); - } - s.edit("Move Plane to Match Object", |d, _| { - store_grid(d, &g); - Ok(()) - })?; - Ok(json!({ "plane": plane.id(), "offset": depth })) -} - -fn persp_nudge(s: &mut Session, p: &Value) -> Result { - const C: &str = "perspective.nudge"; - let (dx, dy) = (f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0)); - if !(dx.is_finite() && dy.is_finite()) || (dx == 0.0 && dy == 0.0) { - return Err(bad(C, "dx and dy give the arrow's direction")); - } - let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 }; - let ids = selected_roots(s)?; - // The step is measured on the page at the centre of the selection's perspective box. - let st = s.doc()?; - let g = grid_of(&st.doc); - let (plane, depth, rect) = g.plane_bounds(&st.doc, &ids).ok_or_else(|| EngineError::Other("the selection isn't in perspective".into()))?; - let from = g.homography_at(plane, depth).and_then(|h| h.apply(rect.center())).ok_or_else(beyond_horizon)?; - let to = from + vectorcraft_geom::Vec2::new(dx.clamp(-1.0, 1.0), dy.clamp(-1.0, 1.0)) * k; - persp_move( - s, - &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "from": [from.x, from.y], "to": [to.x, to.y], "copy": bool_or(p, "copy", false)}), - ) -} - -fn persp_draw(s: &mut Session, p: &Value) -> Result { - const C: &str = "perspective.draw"; - let command = str_param(p, "command").filter(|c| c.starts_with("shape.")).ok_or_else(|| bad(C, "command must be a shape.* command"))?.to_string(); - let params = p.get("params").cloned().unwrap_or_else(|| json!({})); - let mut g = grid_of(&s.doc()?.doc); - let plane = plane_param(&g, p, C)?; - let snap = bool_or(p, "snap", g.snap); - // A click-to-size dialog's shape keeps its sizes in plane units from the click. - let map = match point_param(p, "at") { - Some(at) => Some(g.size_homography(plane, at, snap).ok_or_else(beyond_horizon)?), - None => None, - }; - let undo_before = s.doc()?.history.undo.len(); - let r = s.execute(&command, ¶ms)?; - let id = r.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| EngineError::Other(format!("{command} didn't create an object")))?; - let res = s.edit("Draw in Perspective", |d, _| { - attach_in(d, &mut g, id, plane, snap, map)?; - store_grid(d, &g); - Ok(()) - }); - // One undo step for the whole gesture. - let st = s.doc_mut()?; - if st.interaction.is_none() && st.history.undo.len() > undo_before + 1 { - st.history.undo.truncate(undo_before + 1); - if let Some(e) = st.history.undo.last_mut() { - e.label = "Draw in Perspective".into(); - } - st.history.recost_last(&st.doc); - } - res?; - Ok(json!({ "id": id.0, "plane": plane.id() })) -} - -/// Shape tool previews become `perspective.draw` while the grid is shown with an active plane. -pub(crate) fn perspective_rewrite(s: &Session, cmd: &str, params: &Value) -> Option<(String, Value)> { - const SHAPES: &[&str] = &[ - "shape.rectangle", - "shape.ellipse", - "shape.polygon", - "shape.star", - "shape.line", - "shape.rectangularGrid", - "shape.arc", - "shape.flare", - "shape.spiral", - "shape.polarGrid", - ]; - if !SHAPES.contains(&cmd) { - return None; - } - let g = PerspectiveGrid::current(&s.active()?.doc); - (g.visible && g.plane != Plane::None).then(|| ("perspective.draw".to_string(), json!({"command": cmd, "params": params}))) -} - -/// A click-to-size shape dialog's command (`cmd` with `params`, clicked at `at`) as it runs: on the -/// active plane while the grid shows (`perspective.draw` keeping the sizes in plane units from the -/// click), else `None` (run it as it is). -pub fn perspective_click(s: &Session, cmd: &str, params: &Value, at: Point) -> Option<(String, Value)> { - let (c, mut p) = perspective_rewrite(s, cmd, params)?; - p["at"] = json!([at.x, at.y]); - Some((c, p)) -} - -/// Object › Perspective › Edit Text: type in perspective shown flat where it is drawn, in isolation -/// mode, to be edited; exiting isolation projects it again ([`finish_edit_text`]). -fn edit_text(s: &mut Session, p: &Value) -> Result { - let st = s.doc()?; - let id = - id_param(p, "id").or_else(|| st.selection.objects.first().copied()).ok_or_else(|| EngineError::Other("select type in perspective".into()))?; - if !st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)) && n.projection().is_some()) { - return Err(EngineError::Other("select type in perspective".into())); - } - s.edit("Edit Text", |d, _| { - let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; - let h = n.projection().ok_or_else(|| EngineError::Other("select type in perspective".into()))?; - let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::Other("select type in perspective".into())) }; - // Shown flat where it is drawn: the type moves there and the projection moves the other - // way, so the picture stays. - let (Some(flat), Some(drawn)) = (t.bounds(), t.bounds().and_then(|b| h.map_rect_bbox(b))) else { return Ok(()) }; - let shift = vectorcraft_geom::Affine::translate(drawn.center() - flat.center()); - t.transform(shift); - if let Some(rec) = n.extras_if_any().and_then(|e| e.perspective.as_deref_mut()) { - rec.projection = Some(h.then_after(&Homography::from_affine(shift.inverse())).to_array()); - rec.editing = true; - } - Ok(()) - })?; - let st = s.doc_mut()?; - st.isolation = Some(id); - st.selection.set([id]); - st.revision += 1; - Ok(json!({ "id": id.0 })) -} - -/// Edit Text ends (isolation mode on `id` exits): the type is projected again, in the document and -/// in every undo state (the flat view is never an undo step of its own, and never saved: a saved -/// state stays saved, [`crate::DocState::change_unsaved`]). -pub(crate) fn finish_edit_text(st: &mut crate::DocState, id: NodeId) { - let clear = |doc: &mut Arc| { - // Undo steps keep no lookup cache: look without building one, and drop the one an edit - // builds (the document now keeps its own). - if doc.node_uncached(id).and_then(|n| n.extras().perspective.as_deref()).is_some_and(|p| p.editing) - && let Some(p) = Arc::make_mut(doc).node_mut(id).and_then(|n| n.extras_if_any().and_then(|e| e.perspective.as_deref_mut())) - { - p.editing = false; - } - }; - st.change_unsaved(clear); - for e in st.history.undo.iter_mut().chain(st.history.redo.iter_mut()) { - let saved = Arc::ptr_eq(&e.doc, &st.saved_doc); - clear(&mut e.doc); - e.doc.drop_lookup_cache(); - if saved { - st.saved_doc = e.doc.clone(); - } - } - if let Some(it) = &mut st.interaction { - clear(&mut it.doc); - } - st.revision += 1; -} diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs new file mode 100644 index 0000000000..a655e3e3f4 --- /dev/null +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -0,0 +1,610 @@ +use super::*; + +// ---------- perspective grid ---------- + +/// The document's perspective grid (the default preset when none was defined). +pub(crate) fn grid_of(d: &Document) -> PerspectiveGrid { + PerspectiveGrid::effective(d) +} + +/// Write the grid into the document (`Document.unknown["perspectiveGrid"]`). +pub(crate) fn store_grid(d: &mut Document, g: &PerspectiveGrid) { + g.store(d); +} + +/// Whether `d` holds `g` as [`store_grid`] writes it (with `attached` cleared): then storing `g` +/// leaves `d` as it is. +fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool { + let mut g = g.clone(); + g.attached.clear(); + serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v)) +} + +/// Change view state of the grid without an undo step. +pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> Result { + let st = s.doc_mut()?; + let mut g = grid_of(&st.doc); + f(&mut g); + store_grid(Arc::make_mut(&mut st.doc), &g); + if let Some(it) = &mut st.interaction { + store_grid(Arc::make_mut(&mut it.doc), &g); + } + st.revision += 1; + Ok(g) +} + +pub(super) fn grid_set(s: &mut Session, p: &Value) -> Result { + const C: &str = "perspective.grid.set"; + let old = grid_of(&s.doc()?.doc); + let g = old.merged(p).map_err(|e| bad(C, e))?; + let reproject = switch_or(p, "reproject", false, C)?; + // When the document holds this grid already, no object moves, and the document and its undo + // history stay as they are. + if grid_kept(&s.doc()?.doc, &g) { + return Ok(g.definition_json()); + } + s.edit("Define Perspective Grid", |d, _| { + if reproject { + old.adopt_stored_attachments(d); + for (id, plane, depth) in persp::attached_roots(d) { + let h = old.homography_at(plane, depth).and_then(|h| h.inverse()).zip(g.homography_at(plane, depth)); + let (hi, h) = h.ok_or_else(|| EngineError::Other("an object in perspective would leave the edited grid".into()))?; + let m = h.then_after(&hi); + warp_checked(d, id, &m)?; + } + } + store_grid(d, &g); + Ok(()) + })?; + Ok(g.definition_json()) +} + +pub(super) fn grid_show(s: &mut Session, p: &Value) -> Result { + const C: &str = "perspective.grid.show"; + // A missing or null `visible` toggles the grid. + let want = match p.get("visible") { + None | Some(Value::Null) => None, + Some(_) => Some(switch_or(p, "visible", false, C)?), + }; + let g = silent(s, |g| g.visible = want.unwrap_or(!g.visible))?; + Ok(json!({ "visible": g.visible })) +} + +pub(super) fn plane_set(s: &mut Session, p: &Value) -> Result { + let plane = str_param(p, "plane").and_then(Plane::parse).ok_or_else(|| bad("perspective.plane.set", "plane must be left|right|ground|none"))?; + silent(s, |g| g.plane = plane)?; + Ok(json!({ "plane": plane.id() })) +} + +fn plane_param(g: &PerspectiveGrid, p: &Value, cmd: &str) -> Result { + let plane = match str_param(p, "plane") { + Some(v) => Plane::parse(v).ok_or_else(|| bad(cmd, "plane must be left|right|ground"))?, + None => g.plane, + }; + if plane == Plane::None { + return Err(EngineError::Other("no active perspective plane".into())); + } + Ok(plane) +} + +pub(super) fn roots(s: &Session, p: &Value) -> Result> { + match ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])) { + Some(v) => Ok(outermost(&s.doc()?.doc, v)), + None => selected_roots(s), + } +} + +/// Map `n` with `f`, failing if any point would leave the plane's visible side. +/// Map `n` with `h` (type and symbols in perspective keep their art and are drawn through it), +/// failing if any point would leave the plane's visible side. +fn warp_checked(d: &mut Document, id: NodeId, h: &Homography) -> Result<()> { + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + let mut pts = vec![]; + collect_points(n, &mut pts); + if pts.iter().any(|q| h.apply(*q).is_none()) { + return Err(EngineError::Other("the object would cross the horizon of the perspective plane".into())); + } + project_node(n, h); + Ok(()) +} + +/// Attach `id` to `plane`: projected by `map`, else by the map that keeps its bounds' corners +/// (on the nearest gridlines with `snap`). +fn attach_in(d: &mut Document, g: &mut PerspectiveGrid, id: NodeId, plane: Plane, snap: bool, map: Option) -> Result<()> { + let b = d.node(id).ok_or(EngineError::NoNode(id))?.geometric_bounds().ok_or_else(|| EngineError::Other("the object has no geometry".into()))?; + let m = + map.or_else(|| g.attach_homography(plane, b, snap)).ok_or_else(|| EngineError::Other("the object is beyond the plane's horizon".into()))?; + warp_checked(d, id, &m)?; + persp::set_attachment(d.node_mut(id).ok_or(EngineError::NoNode(id))?, plane, g.offset(plane)); + g.attached.insert(id.0.to_string(), plane); + Ok(()) +} + +pub(super) fn attach(s: &mut Session, p: &Value) -> Result { + let ids = roots(s, p)?; + let mut g = grid_of(&s.doc()?.doc); + let plane = plane_param(&g, p, "perspective.attach")?; + // With no object to attach, when the document holds the grid already, the document and its undo + // history stay as they are. + if ids.is_empty() && grid_kept(&s.doc()?.doc, &g) { + return Ok(json!({ "ids": [], "plane": plane.id() })); + } + s.edit("Attach to Active Plane", |d, _| { + for id in &ids { + attach_in(d, &mut g, *id, plane, false, None)?; + } + store_grid(d, &g); + Ok(()) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "plane": plane.id() })) +} + +pub(super) fn release(s: &mut Session, p: &Value) -> Result { + let ids = roots(s, p)?; + let mut g = grid_of(&s.doc()?.doc); + // When releasing leaves every object as it is (none is in perspective) and the document holds + // the grid already, the document and its undo history stay as they are. + let d = &s.doc()?.doc; + let unchanged = |id: &NodeId| { + d.node(*id).is_none_or(|n| { + let mut released = n.clone(); + persp::release(&mut released); + released == *n + }) + }; + if ids.iter().all(unchanged) && grid_kept(d, &g) { + return ok(); + } + s.edit("Release with Perspective", |d, _| { + for id in &ids { + g.attached.remove(&id.0.to_string()); + if let Some(n) = d.node_mut(*id) { + persp::release(n); + } + } + store_grid(d, &g); + Ok(()) + })?; + ok() +} + +/// One object's share of a perspective edit: the page map for an object on `plane` at `depth`, and +/// the depth it ends at. +type PerspStep<'a> = &'a dyn Fn(&PerspectiveGrid, Plane, f64) -> Result<(Homography, f64)>; + +/// Where an object is in perspective: its plane and depth. +type Attached = (Plane, f64); + +fn beyond_horizon() -> EngineError { + EngineError::Other("the pointer is beyond the plane's horizon".into()) +} + +/// Whether the grid stored in `d` lists attachments of its own, as grids stored before attachments +/// were kept on the objects do ([`PerspectiveGrid::adopt_stored_attachments`]). +fn stores_attachments(d: &Document) -> bool { + !PerspectiveGrid::current(d).attached.is_empty() +} + +/// Edit objects in perspective (one undo step `label`): with `copy` their duplicates (which stay +/// attached), each mapped by `step` for its own plane and depth; objects not in perspective attach +/// to `fallback` first. → the edited objects and where the first one was (plane, depth). In an +/// interaction whose document is still its snapshot, the duplicates are the copies the interaction +/// keeps ([`super::object::preview_copies`]), unless the snapshot's grid lists attachments of its +/// own ([`stores_attachments`]). +fn persp_edit( + s: &mut Session, + label: &str, + ids: &[NodeId], + fallback: Option, + copy: bool, + step: PerspStep, +) -> Result<(Vec, Option)> { + if ids.is_empty() { + return Err(EngineError::Other("select the objects to transform in perspective".into())); + } + let mut g = grid_of(&s.doc()?.doc); + let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false)? } else { None }; + s.edit(label, |d, sel| { + g.adopt_stored_attachments(d); + let targets = match &kept { + // The document becomes the snapshot with the kept copies, not yet mapped, and the loop + // below maps only the copies. + Some(k) => { + *d = Document::clone(&k.doc); + sel.clone_from(&k.selection); + k.ids.clone() + } + None if copy => duplicate_in(d, sel, ids, Affine::IDENTITY)?, + None => ids.to_vec(), + }; + let mut first = None; + for id in &targets { + let (plane, depth) = match g.attachment_of(d, *id) { + Some(a) => a, + None => { + let pl = fallback.ok_or_else(|| EngineError::Other("the object isn't on a perspective plane".into()))?; + attach_in(d, &mut g, *id, pl, false, None)?; + (pl, g.offset(pl)) + } + }; + first.get_or_insert((plane, depth)); + let (h, depth) = step(&g, plane, depth)?; + warp_checked(d, *id, &h)?; + persp::set_attachment(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, plane, depth); + } + store_grid(d, &g); + Ok((targets, first)) + }) +} + +/// Where the first of `ids` is in perspective (its plane and depth) when `ids` is not empty, every one +/// of them is in perspective already, `still` holds for each one's plane and depth, and the document +/// holds the grid already; None otherwise. +fn unmoved(s: &Session, ids: &[NodeId], still: impl Fn(&PerspectiveGrid, Plane, f64) -> bool) -> Result> { + let d = &s.doc()?.doc; + let g = grid_of(d); + if ids.is_empty() || !grid_kept(d, &g) { + return Ok(None); + } + let at: Option> = ids.iter().map(|id| g.attachment_of(d, *id).filter(|(pl, depth)| still(&g, *pl, *depth))).collect(); + Ok(at.and_then(|at| at.first().copied())) +} + +/// Remember `again` (`perspective.transform` params) for Object › Transform › Transform Again, once +/// the drag that made it is committed. +fn record_again(s: &mut Session, again: Value) -> Result<()> { + let st = s.doc_mut()?; + match &mut st.interaction { + Some(it) => it.perspective_again = Some(again), + None => st.last_perspective = Some(again), + } + Ok(()) +} + +fn ids_json(ids: &[NodeId]) -> Value { + json!({ "ids": ids.iter().map(|i| i.0).collect::>() }) +} + +/// A plane-space affine map as `perspective.transform`'s `matrix` param. +fn matrix_json(m: Affine) -> Value { + json!(m.as_coeffs()) +} + +pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result { + const C: &str = "perspective.move"; + let ids = roots(s, p)?; + let from = point_param(p, "from").ok_or_else(|| bad(C, "missing from"))?; + let to = point_param(p, "to").ok_or_else(|| bad(C, "missing to"))?; + if ![from.x, from.y, to.x, to.y].iter().all(|v| v.is_finite()) { + return Err(bad(C, "from and to must be finite")); + } + let fallback = plane_param(&grid_of(&s.doc()?.doc), p, C).ok(); + let (perp, copy) = (switch_or(p, "perpendicular", false, C)?, switch_or(p, "copy", false, C)?); + // `snap_fix` uses Snap to Grid's setting for a `snap` that is not true or false. + check_switches(p, &["snap"], C)?; + // Snap to Grid: a correction for the objects on the first one's plane and depth. + let fix = if perp { None } else { crate::cmd::perspgrid::snap_fix(&s.doc()?.doc, &ids, p, (from, to)) }; + let snapped = move |pl: Plane, depth: f64, dv: vectorcraft_geom::Vec2| { + dv + fix.filter(|f| f.0 == pl && f.1 == depth).map_or(vectorcraft_geom::Vec2::ZERO, |f| f.2) + }; + // In-plane: the plane-space offset under the pointer; perpendicular: the depth it reaches. + let step = |g: &PerspectiveGrid, pl: Plane, depth: f64| -> Result<(Homography, f64)> { + if perp { + let to_depth = g.depth_at(pl, depth, from, to).ok_or_else(beyond_horizon)?; + Ok((g.transform_map(pl, depth, Affine::IDENTITY, to_depth - depth).ok_or_else(beyond_horizon)?, to_depth)) + } else { + let dv = snapped(pl, depth, g.plane_delta(pl, depth, from, to).ok_or_else(beyond_horizon)?); + Ok((g.transform_map(pl, depth, Affine::translate(dv), 0.0).ok_or_else(beyond_horizon)?, depth)) + } + }; + let label = if copy { "Copy in Perspective" } else { "Move in Perspective" }; + // When no object moves more than 1e-9 pt along its plane's axes or its normal (Snap to Grid + // included) and there is no copy, the document and its undo history stay as they are. + let still = |g: &PerspectiveGrid, pl: Plane, depth: f64| { + if perp { + g.depth_at(pl, depth, from, to).is_some_and(|d| (d - depth).abs() <= 1e-9) + } else { + g.plane_delta(pl, depth, from, to).map(|dv| snapped(pl, depth, dv)).is_some_and(|dv| dv.x.abs() <= 1e-9 && dv.y.abs() <= 1e-9) + } + }; + let first_still = if copy { None } else { unmoved(s, &ids, still)? }; + let (targets, first) = match first_still { + Some(at) => (ids, Some(at)), + None => persp_edit(s, label, &ids, fallback, copy, &step)?, + }; + // Transform Again repeats the first object's move, and the identity when no object moved. + if let Some((pl, depth)) = first { + let g = grid_of(&s.doc()?.doc); + let again = match perp { + _ if first_still.is_some() => Some(json!({"matrix": matrix_json(Affine::IDENTITY), "copy": copy})), + true => g.depth_at(pl, depth, from, to).map(|d| json!({"matrix": matrix_json(Affine::IDENTITY), "depth": d - depth, "copy": copy})), + false => { + g.plane_delta(pl, depth, from, to).map(|dv| json!({"matrix": matrix_json(Affine::translate(snapped(pl, depth, dv))), "copy": copy})) + } + }; + if let Some(a) = again { + record_again(s, a)?; + } + } + Ok(ids_json(&targets)) +} + +pub(super) fn persp_transform(s: &mut Session, p: &Value) -> Result { + const C: &str = "perspective.transform"; + let m = matrix_param(p, "matrix").ok_or_else(|| bad(C, "missing matrix [a,b,c,d,e,f]"))?; + let dz = number_or(p, "depth", 0.0, C)?; + if !m.as_coeffs().iter().all(|v| v.is_finite()) || m.determinant().abs() < 1e-12 || !dz.is_finite() { + return Err(bad(C, "matrix must be finite and invertible, depth finite")); + } + let ids = roots(s, p)?; + let fallback = plane_param(&grid_of(&s.doc()?.doc), p, C).ok(); + let copy = switch_or(p, "copy", false, C)?; + let step = |g: &PerspectiveGrid, pl: Plane, depth: f64| -> Result<(Homography, f64)> { + let to = depth + dz; + if to.abs() > persp::MAX_DEPTH { + return Err(EngineError::Other("the objects would leave the grid".into())); + } + Ok((g.transform_map(pl, depth, m, dz).ok_or_else(beyond_horizon)?, to)) + }; + // An identity without a copy moves no object that is in perspective already: then the document + // and its undo history stay as they are, and Transform Again repeats the identity. + let identity = !copy && m == Affine::IDENTITY && dz == 0.0; + let targets = if identity && unmoved(s, &ids, |g, pl, depth| g.transform_map(pl, depth, m, dz).is_some())?.is_some() { + ids + } else { + persp_edit(s, if copy { "Copy in Perspective" } else { "Transform in Perspective" }, &ids, fallback, copy, &step)?.0 + }; + record_again(s, json!({"matrix": matrix_json(m), "depth": dz, "copy": copy}))?; + Ok(ids_json(&targets)) +} + +/// Object › Transform › Transform Again after a perspective move or scale: the same plane-space +/// transform on the selection. +pub(crate) fn transform_again(s: &mut Session, again: &Value) -> Result { + let mut p = again.clone(); + if let Some(o) = p.as_object_mut() { + o.remove("ids"); + } + persp_transform(s, &p) +} + +pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result { + const C: &str = "perspective.plane.move"; + check_numbers(p, &["offset", "by"], C)?; + let old = grid_of(&s.doc()?.doc); + let plane = plane_param(&old, p, C)?; + let from = old.offset(plane); + let to = match (p.get("offset").and_then(Value::as_f64), p.get("by").and_then(Value::as_f64)) { + (Some(o), _) => o, + (None, Some(b)) => from + b, + (None, None) => return Err(bad(C, "give offset or by")), + }; + let objects = str_param(p, "objects").unwrap_or("none"); + if !matches!(objects, "none" | "move" | "copy") { + return Err(bad(C, "objects must be none, move or copy")); + } + let mut g = old.clone(); + g.set_offset(plane, to); + g.validate().map_err(|e| bad(C, e))?; + let label = match objects { + "copy" => "Move Plane and Copy Objects", + "move" => "Move Plane and Objects", + _ => "Move Plane", + }; + // The objects on the plane where it was (not those moved off it along its normal). + let on_plane = |d: &Document| -> Vec { + let editable = d.editable(); + persp::attached_roots(d) + .into_iter() + .filter(|(id, pl, depth)| *pl == plane && (depth - from).abs() < 1e-6 && editable(*id)) + .map(|(id, ..)| id) + .collect() + }; + // A plane moved to where it is, with its objects or without them, moves nothing: when the + // document holds the grid already, the document and its undo history stay as they are. + if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &g) { + let ids = if objects == "move" { on_plane(&s.doc()?.doc) } else { vec![] }; + return Ok(json!({ "plane": plane.id(), "offset": to, "ids": ids.iter().map(|i| i.0).collect::>() })); + } + // In an interaction whose document is still its snapshot, the copies of the objects on the + // plane are the copies the interaction keeps (`preview_copies`), unless the snapshot's grid + // lists attachments of its own (`stores_attachments`). + let kept = if objects == "copy" && s.in_interaction() && !stores_attachments(&s.doc()?.doc) { + let on = on_plane(&s.doc()?.doc); + crate::cmd::object::preview_copies(s, &on, false)? + } else { + None + }; + let ids = s.edit(label, |d, sel| { + old.adopt_stored_attachments(d); + let mut ids = vec![]; + if objects != "none" { + ids = match &kept { + // The document becomes the snapshot with the kept copies, not yet moved, and the + // loop below moves only the copies. + Some(k) => { + *d = Document::clone(&k.doc); + sel.clone_from(&k.selection); + k.ids.clone() + } + None => { + let on = on_plane(d); + if objects == "copy" { duplicate_in(d, sel, &on, Affine::IDENTITY)? } else { on } + } + }; + let m = old.transform_map(plane, from, Affine::IDENTITY, to - from).ok_or_else(beyond_horizon)?; + for id in &ids { + warp_checked(d, *id, &m)?; + persp::set_attachment(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, plane, to); + } + } + store_grid(d, &g); + Ok(ids) + })?; + Ok(json!({ "plane": plane.id(), "offset": to, "ids": ids.iter().map(|i| i.0).collect::>() })) +} + +pub(super) fn plane_match(s: &mut Session, p: &Value) -> Result { + let st = s.doc()?; + let id = id_param(p, "id") + .or_else(|| st.selection.objects.first().copied()) + .ok_or_else(|| EngineError::Other("select an object in perspective".into()))?; + let mut g = grid_of(&st.doc); + let (plane, depth) = g.attachment_of(&st.doc, id).ok_or_else(|| EngineError::Other("the object isn't in perspective".into()))?; + g.set_offset(plane, depth); + g.plane = plane; + g.validate().map_err(|e| bad("perspective.plane.matchObject", e))?; + // When the plane is at the object and active already, and the document holds that grid, the + // document and its undo history stay as they are. + if grid_kept(&st.doc, &g) { + return Ok(json!({ "plane": plane.id(), "offset": depth })); + } + s.edit("Move Plane to Match Object", |d, _| { + store_grid(d, &g); + Ok(()) + })?; + Ok(json!({ "plane": plane.id(), "offset": depth })) +} + +pub(super) fn persp_nudge(s: &mut Session, p: &Value) -> Result { + const C: &str = "perspective.nudge"; + let (dx, dy) = (number_or(p, "dx", 0.0, C)?, number_or(p, "dy", 0.0, C)?); + if !(dx.is_finite() && dy.is_finite()) || (dx == 0.0 && dy == 0.0) { + return Err(bad(C, "dx and dy give the arrow's direction")); + } + let k = s.prefs.keyboard_increment * if switch_or(p, "big", false, C)? { 10.0 } else { 1.0 }; + let copy = switch_or(p, "copy", false, C)?; + let ids = selected_roots(s)?; + // The step is measured on the page at the centre of the selection's perspective box. + let st = s.doc()?; + let g = grid_of(&st.doc); + let (plane, depth, rect) = g.plane_bounds(&st.doc, &ids).ok_or_else(|| EngineError::Other("the selection isn't in perspective".into()))?; + let from = g.homography_at(plane, depth).and_then(|h| h.apply(rect.center())).ok_or_else(beyond_horizon)?; + let to = from + vectorcraft_geom::Vec2::new(dx.clamp(-1.0, 1.0), dy.clamp(-1.0, 1.0)) * k; + persp_move(s, &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "from": [from.x, from.y], "to": [to.x, to.y], "copy": copy})) +} + +pub(super) fn persp_draw(s: &mut Session, p: &Value) -> Result { + const C: &str = "perspective.draw"; + let command = str_param(p, "command").filter(|c| c.starts_with("shape.")).ok_or_else(|| bad(C, "command must be a shape.* command"))?.to_string(); + let params = p.get("params").cloned().unwrap_or_else(|| json!({})); + let mut g = grid_of(&s.doc()?.doc); + let plane = plane_param(&g, p, C)?; + let snap = switch_or(p, "snap", g.snap, C)?; + // A click-to-size dialog's shape keeps its sizes in plane units from the click. + let map = match p.get("at") { + None | Some(Value::Null) => None, + Some(v) => { + let at = finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be [x, y]"))?; + Some(g.size_homography(plane, at, snap).ok_or_else(beyond_horizon)?) + } + }; + let undo_before = s.doc()?.history.undo.len(); + let r = s.execute(&command, ¶ms)?; + let id = r.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| EngineError::Other(format!("{command} didn't create an object")))?; + let res = s.edit("Draw in Perspective", |d, _| { + attach_in(d, &mut g, id, plane, snap, map)?; + store_grid(d, &g); + Ok(()) + }); + // One undo step for the whole gesture. + let st = s.doc_mut()?; + if st.interaction.is_none() && st.history.undo.len() > undo_before + 1 { + st.history.undo.truncate(undo_before + 1); + if let Some(e) = st.history.undo.last_mut() { + e.label = "Draw in Perspective".into(); + } + st.history.recost_last(&st.doc); + } + res?; + Ok(json!({ "id": id.0, "plane": plane.id() })) +} + +/// Shape tool previews become `perspective.draw` while the grid is shown with an active plane. +pub(crate) fn perspective_rewrite(s: &Session, cmd: &str, params: &Value) -> Option<(String, Value)> { + const SHAPES: &[&str] = &[ + "shape.rectangle", + "shape.ellipse", + "shape.polygon", + "shape.star", + "shape.line", + "shape.rectangularGrid", + "shape.arc", + "shape.flare", + "shape.spiral", + "shape.polarGrid", + ]; + if !SHAPES.contains(&cmd) { + return None; + } + let g = PerspectiveGrid::current(&s.active()?.doc); + (g.visible && g.plane != Plane::None).then(|| ("perspective.draw".to_string(), json!({"command": cmd, "params": params}))) +} + +/// A click-to-size shape dialog's command (`cmd` with `params`, clicked at `at`) as it runs: on the +/// active plane while the grid shows (`perspective.draw` keeping the sizes in plane units from the +/// click), else `None` (run it as it is). +pub fn perspective_click(s: &Session, cmd: &str, params: &Value, at: Point) -> Option<(String, Value)> { + let (c, mut p) = perspective_rewrite(s, cmd, params)?; + p["at"] = json!([at.x, at.y]); + Some((c, p)) +} + +/// Object › Perspective › Edit Text: type in perspective shown flat where it is drawn, in isolation +/// mode, to be edited; exiting isolation projects it again ([`finish_edit_text`]). +pub(super) fn edit_text(s: &mut Session, p: &Value) -> Result { + let st = s.doc()?; + let id = + id_param(p, "id").or_else(|| st.selection.objects.first().copied()).ok_or_else(|| EngineError::Other("select type in perspective".into()))?; + if !st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)) && n.projection().is_some()) { + return Err(EngineError::Other("select type in perspective".into())); + } + s.edit("Edit Text", |d, _| { + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + let h = n.projection().ok_or_else(|| EngineError::Other("select type in perspective".into()))?; + let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::Other("select type in perspective".into())) }; + // Shown flat where it is drawn: the type moves there and the projection moves the other + // way, so the picture stays. + let (Some(flat), Some(drawn)) = (t.bounds(), t.bounds().and_then(|b| h.map_rect_bbox(b))) else { return Ok(()) }; + let shift = vectorcraft_geom::Affine::translate(drawn.center() - flat.center()); + t.transform(shift); + if let Some(rec) = n.extras_if_any().and_then(|e| e.perspective.as_deref_mut()) { + rec.projection = Some(h.then_after(&Homography::from_affine(shift.inverse())).to_array()); + rec.editing = true; + } + Ok(()) + })?; + let st = s.doc_mut()?; + st.isolation = Some(id); + st.selection.set([id]); + st.revision += 1; + Ok(json!({ "id": id.0 })) +} + +/// Edit Text ends (isolation mode on `id` exits): the type is projected again, in the document and +/// in every undo state (the flat view is never an undo step of its own, and never saved: a saved +/// state stays saved, [`crate::DocState::change_unsaved`]). +pub(crate) fn finish_edit_text(st: &mut crate::DocState, id: NodeId) { + let clear = |doc: &mut Arc| { + // Undo steps keep no lookup cache: look without building one, and drop the one an edit + // builds (the document now keeps its own). + if doc.node_uncached(id).and_then(|n| n.extras().perspective.as_deref()).is_some_and(|p| p.editing) + && let Some(p) = Arc::make_mut(doc).node_mut(id).and_then(|n| n.extras_if_any().and_then(|e| e.perspective.as_deref_mut())) + { + p.editing = false; + } + }; + st.change_unsaved(clear); + for e in st.history.undo.iter_mut().chain(st.history.redo.iter_mut()) { + let saved = Arc::ptr_eq(&e.doc, &st.saved_doc); + clear(&mut e.doc); + e.doc.drop_lookup_cache(); + if saved { + st.saved_doc = e.doc.clone(); + } + } + if let Some(it) = &mut st.interaction { + clear(&mut it.doc); + } + st.revision += 1; +} diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index 65fc0d2f0e..0400ab123e 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; use vectorcraft_color::Paint; -use vectorcraft_doc::{ColorMode, Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{ColorMode, Document, Node, NodeId, NodeKind, RepeatKind, RepeatSpec}; use vectorcraft_geom::{Affine, Rect}; use vectorcraft_text::embed::Embedding; @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Document Info", ["Window", "Document Info"], None, - "{selectionOnly?, category?: document|objects|graphicStyles|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages (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), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its licence lets it be embedded)}", + "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}", has_doc, info ), @@ -35,10 +35,11 @@ pub fn specs() -> Vec { } /// Document Info's categories: (id, title), in the order the panel and the report show them. -pub const CATEGORIES: [(&str, &str); 11] = [ +pub const CATEGORIES: [(&str, &str); 13] = [ ("document", "Document"), ("objects", "Objects"), ("graphicStyles", "Graphic Styles"), + ("brushes", "Brushes"), ("spotColors", "Spot Colors"), ("patterns", "Pattern Objects"), ("gradients", "Gradient Swatches"), @@ -47,6 +48,7 @@ pub const CATEGORIES: [(&str, &str); 11] = [ ("fontDetails", "Font Details"), ("linkedImages", "Linked Images"), ("embeddedImages", "Embedded Images"), + ("repeats", "Repeat Objects"), ]; /// The object counts of `document.info` and their labels. @@ -96,9 +98,47 @@ pub fn embedding_label(fs_type: u16) -> &'static str { /// An image object as Document Info lists it: (name, width, height, linked file). type ImageRow = (String, u32, u32, Option); +/// A Repeat object as Document Info lists it: its `repeatObjects` entry, and its row, which gives +/// its name and then its kind with the number of instances it draws (for a grid, its rows and +/// columns, followed by the number it draws when that is fewer). +fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, String)) { + let name = n.display_name(); + let count = |n: usize, one: &str, many: &str| if n == 1 { format!("1 {one}") } else { format!("{n} {many}") }; + let instances = spec.instances(Some(d)); + let mut entry = json!({ "id": n.id.0, "name": name, "instances": instances }); + let kind = &spec.kind; + let detail = match kind { + RepeatKind::Radial { .. } => { + entry["type"] = json!("radial"); + count(instances, "instance", "instances") + } + RepeatKind::Mirror { .. } => { + entry["type"] = json!("mirror"); + count(instances, "instance", "instances") + } + RepeatKind::Grid { rows, cols, .. } => { + // `repeat_transforms` clamps the rows and columns the same way. + let (rows, cols) = ((*rows).clamp(1, 500), (*cols).clamp(1, 500)); + entry["type"] = json!("grid"); + entry["rows"] = json!(rows); + entry["cols"] = json!(cols); + let grid = format!("{} × {}", count(rows as usize, "row", "rows"), count(cols as usize, "column", "columns")); + if instances < (rows * cols) as usize { format!("{grid}, {}", count(instances, "instance", "instances")) } else { grid } + } + }; + (entry, (name, format!("{}, {detail}", kind.label()))) +} + /// The Document Info categories of `d` (only `category` when given) from `info` (what -/// `document.info` reports), its fonts `(family, style)`, image objects and used patterns. -fn sections(d: &Document, info: &Value, fonts: &BTreeSet, images: &[ImageRow], category: Option<&str>) -> Vec
{ +/// `document.info` reports), its fonts, its image objects and the rows of its Repeat objects. +fn sections( + d: &Document, + info: &Value, + fonts: &BTreeSet, + images: &[ImageRow], + repeats: &[(String, String)], + category: Option<&str>, +) -> Vec
{ let names = |k: &str| -> Vec<(String, String)> { info[k].as_array().into_iter().flatten().filter_map(Value::as_str).map(|n| (n.to_string(), String::new())).collect() }; @@ -138,6 +178,7 @@ fn sections(d: &Document, info: &Value, fonts: &BTreeSet rows } "graphicStyles" => names("graphicStyleNames"), + "brushes" => names("brushNames"), "spotColors" => names("spotColors"), "patterns" => names("patternNames"), "gradients" => d.swatches_iter().filter(|s| matches!(s.paint, Paint::Gradient(_))).map(|s| (s.name.clone(), String::new())).collect(), @@ -174,6 +215,7 @@ fn sections(d: &Document, info: &Value, fonts: &BTreeSet "linkedImages" => { images.iter().filter_map(|(name, w, h, link)| Some((name.clone(), format!("{w} × {h} px — {}", link.as_ref()?)))).collect() } + "repeats" => repeats.to_vec(), _ => images.iter().filter(|i| i.3.is_none()).map(|(name, w, h, _)| (name.clone(), format!("{w} × {h} px"))).collect(), }; Section { id, title, rows } @@ -246,6 +288,11 @@ fn info(s: &mut Session, p: &Value) -> Result { let mut symbols = BTreeSet::new(); 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 = if selection_only { vec![] } else { vectorcraft_brush::library(d).into_iter().map(|b| b.name).collect() }; + // `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 = vec![]; + let mut repeat_rows: Vec<(String, String)> = vec![]; for r in roots { r.walk(&mut |n| { let k = match &n.kind { @@ -319,6 +366,21 @@ fn info(s: &mut Session, p: &Value) -> Result { { 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 let NodeKind::Repeat(spec) = &n.kind { + let (entry, row) = repeat_entry(d, n, spec); + repeats.push(entry); + repeat_rows.push(row); + } }); } let font_names: Vec = fonts.iter().map(super::fonts::font_label).collect(); @@ -333,6 +395,8 @@ fn info(s: &mut Session, p: &Value) -> Result { "swatches": d.swatches_iter().count(), "graphicStyles": d.graphic_styles.len(), "graphicStyleNames": styles, + "brushNames": brushes, + "repeatObjects": repeats, "characterStyles": d.char_styles.len(), "paragraphStyles": d.para_styles.len(), "patterns": d.patterns.len(), @@ -340,7 +404,7 @@ fn info(s: &mut Session, p: &Value) -> Result { }); // The document's name: its file's, else its title. out["document"]["name"] = json!(st.title()); - let sections = sections(d, &out, &fonts, &image_rows, category); + let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, category); if text { return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) })); } @@ -372,8 +436,11 @@ fn snap_xf(b: Rect, half: bool) -> Affine { } fn pixel_perfect(s: &mut Session, p: &Value) -> Result { - let ids: Vec = - if p.get("ids").is_some() { super::edit::outermost(&s.doc()?.doc, targets(s, p)?) } else { super::edit::selected_roots(s)? }; + let ids: Vec = if p.get("ids").is_some() || p.get("id").is_some() { + super::edit::outermost(&s.doc()?.doc, targets(s, p)?) + } else { + super::edit::selected_roots(s)? + }; let n = ids.len(); s.edit("Make Pixel Perfect", |d, _| { for id in &ids { @@ -448,6 +515,109 @@ 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. + #[test] + fn info_lists_the_brushes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let panel: Vec = + 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)); + assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("brushes"), Some("Brushes"))); + let rows: Vec = panel.iter().map(|n| json!([n, ""])).collect(); + assert_eq!(i["sections"][0]["rows"], json!(rows)); + 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": [c], "name": "Charcoal"})).unwrap(); + let names = + |s: &mut Session| s.execute("document.info", &json!({"selectionOnly": true, "category": "brushes"})).unwrap()["brushNames"].clone(); + s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap(); + assert_eq!(names(&mut s), json!(["Charcoal", "Arrow"])); + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + assert_eq!(names(&mut s), json!(["Arrow"])); + // 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}"); + } + + /// Document Info › Repeat Objects lists each Repeat object by name with its kind and the number + /// of instances it makes (for a grid, its rows and columns, followed by the number it draws when + /// that is fewer), one in a group included. With Selection Only it lists the Repeat objects in + /// the selection. + #[test] + fn info_lists_the_repeat_objects() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let square = + |s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let (a, b, c, d) = (square(&mut s, 0.0), square(&mut s, 100.0), square(&mut s, 200.0), square(&mut s, 300.0)); + let radial = s.execute("object.repeat.radial", &json!({"ids": [a], "instances": 6})).unwrap()["id"].clone(); + let grid = s.execute("object.repeat.grid", &json!({"ids": [b], "rows": 2, "cols": 1})).unwrap()["id"].clone(); + s.execute("layer.setProps", &json!({"id": grid, "name": "Tiles"})).unwrap(); + let mirror = s.execute("object.repeat.mirror", &json!({"ids": [c]})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [mirror, d]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].clone(); + let i = s.execute("document.info", &json!({"category": "repeats"})).unwrap(); + assert_eq!( + i["repeatObjects"], + json!([ + {"id": radial, "name": "", "type": "radial", "instances": 6}, + {"id": grid, "name": "Tiles", "type": "grid", "rows": 2, "cols": 1, "instances": 2}, + {"id": mirror, "name": "", "type": "mirror", "instances": 2}, + ]) + ); + assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("repeats"), Some("Repeat Objects"))); + assert_eq!( + i["sections"][0]["rows"], + json!([ + ["", "Radial Repeat, 6 instances"], + ["Tiles", "Grid Repeat, 2 rows × 1 column"], + ["", "Mirror Repeat, 2 instances"], + ]) + ); + let names = |s: &mut Session| -> Vec { + let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "repeats"})).unwrap(); + i["repeatObjects"].as_array().unwrap().iter().map(|r| r["name"].clone()).collect() + }; + s.execute("select.set", &json!({"ids": [grid, group]})).unwrap(); + assert_eq!(names(&mut s), ["Tiles", ""]); + s.execute("select.set", &json!({"ids": [radial]})).unwrap(); + assert_eq!(names(&mut s), [""]); + s.execute("select.set", &json!({"ids": [d]})).unwrap(); + assert!(names(&mut s).is_empty()); + let text = s.execute("document.info", &json!({"category": "repeats", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(text.contains("\nREPEAT OBJECTS\n: Radial Repeat, 6 instances\nTiles: Grid Repeat, 2 rows × 1 column\n"), "{text}"); + assert!(!text.contains("\nOBJECTS\n"), "{text}"); + // A radial of 1,000 copies of a 500 × 500 grid draws one copy within the instance budget, + // and Document Info reports 1 instance. + let e = square(&mut s, 350.0); + let big = s.execute("object.repeat.grid", &json!({"ids": [e], "rows": 500, "cols": 500})).unwrap()["id"].clone(); + let outer = s.execute("object.repeat.radial", &json!({"ids": [big], "instances": 1000})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [outer]})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "repeats"})).unwrap(); + assert_eq!((i["repeatObjects"][0]["id"].clone(), i["repeatObjects"][0]["instances"].clone()), (outer, json!(1))); + assert_eq!((i["repeatObjects"][1]["id"].clone(), i["repeatObjects"][1]["instances"].clone()), (big, json!(250_000))); + assert_eq!(i["sections"][0]["rows"][0], json!(["", "Radial Repeat, 1 instance"])); + // A 500 × 500 grid of a mirror draws 125,000 copies within the budget, and its row gives + // that number after its rows and columns. + let f = square(&mut s, 380.0); + let pair = s.execute("object.repeat.mirror", &json!({"ids": [f]})).unwrap()["id"].clone(); + let tiles = s.execute("object.repeat.grid", &json!({"ids": [pair], "rows": 500, "cols": 500})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [tiles]})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "repeats"})).unwrap(); + assert_eq!((i["repeatObjects"][0]["id"].clone(), i["repeatObjects"][0]["instances"].clone()), (tiles, json!(125_000))); + assert_eq!(i["sections"][0]["rows"][0], json!(["", "Grid Repeat, 500 rows × 500 columns, 125000 instances"])); + } + #[test] fn embedding_permissions_read_from_fs_type() { assert_eq!(embedding_label(0), "embedding allowed"); diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 2cbd4a3b96..88da38361f 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -83,13 +83,18 @@ pub fn specs() -> Vec { "Bristle Brush Strokes", ["Select", "Object"], None, - "{} objects whose brush name contains \"bristle\" → {count}", + "{} objects whose topmost stroke has a bristle brush (type bristle in brush.list), whatever the brush is named → {count}", has_doc, - |s, _| by_kind(s, |n| n - .appearance - .stroke() - .and_then(|st| st.brush.as_deref()) - .is_some_and(|b| b.to_ascii_lowercase().contains("bristle"))) + |s, _| { + let brushes = vectorcraft_brush::library(&s.doc()?.doc); + by_kind(s, |n| { + n.appearance + .stroke() + .and_then(|st| st.brush.as_deref()) + .and_then(|name| brushes.iter().find(|b| b.name == name)) + .is_some_and(|b| matches!(b.kind, vectorcraft_brush::BrushKind::Bristle(_))) + }) + } ), cmd!( "select.save", @@ -264,11 +269,11 @@ fn candidates(s: &Session, f: impl Fn(&Node) -> bool) -> Result> { } fn finish_same(s: &mut Session, cmd: &str, ids: Vec) -> Result { - let n = ids.len(); let from = s.doc()?.selection.objects.clone(); s.select(|_, sel| sel.set(ids))?; - s.doc_mut()?.last_selection_cmd = Some((cmd.to_string(), json!({}), from)); - Ok(json!({ "count": n })) + let st = s.doc_mut()?; + st.last_selection_cmd = Some((cmd.to_string(), json!({}), from)); + Ok(json!({ "count": st.selection.objects.len() })) } fn same(s: &mut Session, cmd: &str, eq: fn(&Node, &Node) -> bool) -> Result { @@ -305,11 +310,11 @@ fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool) finish_same(s, cmd, ids) } -fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result { +fn by_kind(s: &mut Session, f: impl Fn(&Node) -> bool) -> Result { let ids = candidates(s, f)?; - let n = ids.len(); s.select(|_, sel| sel.set(ids))?; - Ok(json!({ "count": n })) + // The objects selected, after Lock Guides has left out guide paths. + Ok(json!({ "count": s.doc()?.selection.objects.len() })) } fn direction_handles(s: &mut Session, _: &Value) -> Result { @@ -538,10 +543,11 @@ fn release_guides(s: &mut Session, p: &Value) -> Result { let roots = if ids.is_some() { checked_ids_param(s, p, "ids", C)? } else { vec![] }; let d = &s.doc()?.doc; let mut paths = vec![]; + let editable = d.editable(); for r in roots { if let Some(n) = d.node(r) { n.walk(&mut |c| { - if matches!(c.kind, NodeKind::Path { guide: true, .. }) && d.is_editable(c.id) && !paths.contains(&c.id) { + if matches!(c.kind, NodeKind::Path { guide: true, .. }) && editable(c.id) && !paths.contains(&c.id) { paths.push(c.id); } }); @@ -557,7 +563,8 @@ fn release_guides(s: &mut Session, p: &Value) -> Result { } else { st.selection.guides.iter().copied().filter(|i| st.doc.guides.get(*i).is_some_and(|g| st.doc.guide_editable(g))).collect() }; - if sel.is_empty() && rulers.is_empty() { (vec![], all.into_iter().filter(|id| st.doc.is_editable(*id)).collect()) } else { (rulers, sel) } + let editable = st.doc.editable(); + if sel.is_empty() && rulers.is_empty() { (vec![], all.into_iter().filter(|id| editable(*id)).collect()) } else { (rulers, sel) } }; // Find each ruler guide's line and its parent: the guide's layer, else where new art goes. let st = s.doc()?; @@ -610,7 +617,7 @@ fn lock_guides(s: &mut Session, p: &Value) -> Result { if v { let active = s.active; for (i, st) in s.docs.iter_mut().enumerate() { - if Some(i) != active && crate::deselect_guides(&st.doc, &mut st.selection) { + if Some(i) != active && crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection) { st.revision += 1; } } diff --git a/crates/engine/src/cmd/docsetup.rs b/crates/engine/src/cmd/docsetup.rs index 4446bc0ad9..0dc6fbad31 100644 --- a/crates/engine/src/cmd/docsetup.rs +++ b/crates/engine/src/cmd/docsetup.rs @@ -17,7 +17,7 @@ pub fn specs() -> Vec { "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), highlightSubstitutedFonts?: bool, highlightSubstitutedGlyphs?: bool, gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour), 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), 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", has_doc, setup )] @@ -31,7 +31,6 @@ pub(crate) fn setup_json(d: &Document) -> Value { "units": d.units.label(), "bleed": s.bleed, "outlineImages": s.outline_images, - "highlightSubstitutedFonts": s.highlight_substituted_fonts, "highlightSubstitutedGlyphs": s.highlight_substituted_glyphs, "gridSize": s.grid_size.id(), "gridColors": s.grid_colors.map(|c| c.to_hex()), @@ -72,9 +71,19 @@ fn setup(s: &mut Session, p: &Value) -> Result { } apply(&mut new, &mut units, k, v, &s.prefs.flattener_presets)?; } + // An older build's reply passed back still applies; the moved key only gets a warning. + let reply = |d: &Document| { + let mut r = setup_json(d); + if o.contains_key("highlightSubstitutedFonts") + && let Some(m) = r.as_object_mut() + { + m.insert("warnings".into(), json!([MOVED_FONTS_HIGHLIGHT])); + } + r + }; let st = s.doc()?; if new == st.doc.setup && units == st.doc.units { - return Ok(setup_json(&st.doc)); + return Ok(reply(&st.doc)); } s.edit("Document Setup", |d, _| { let scripts_changed = @@ -86,9 +95,13 @@ fn setup(s: &mut Session, p: &Value) -> Result { } Ok(()) })?; - Ok(setup_json(&s.doc()?.doc)) + Ok(reply(&s.doc()?.doc)) } +/// The warning for `highlightSubstitutedFonts`, which `document.setup` ignores. +const MOVED_FONTS_HIGHLIGHT: &str = + "highlightSubstitutedFonts is ignored: it is a preference (Preferences › Type), set with prefs.set {key: \"highlightSubstitutedFonts\", value}"; + fn flag(k: &str, v: &Value) -> Result { v.as_bool().ok_or_else(|| bad(C, format!("{k} must be true or false"))) } @@ -102,7 +115,10 @@ fn apply(s: &mut DocSetup, units: &mut vectorcraft_doc::Unit, k: &str, v: &Value "units" => *units = v.as_str().and_then(vectorcraft_doc::Unit::named).ok_or_else(|| bad(C, "unknown units"))?, "bleed" => s.bleed = bleed_param(v, s.bleed, C)?, "outlineImages" => s.outline_images = flag(k, v)?, - "highlightSubstitutedFonts" => s.highlight_substituted_fonts = flag(k, v)?, + // Preferences › Type holds it for every document: ignored, with a warning in the reply. + "highlightSubstitutedFonts" => { + flag(k, v)?; + } "highlightSubstitutedGlyphs" => s.highlight_substituted_glyphs = flag(k, v)?, "gridSize" => s.grid_size = v.as_str().and_then(GridSize::parse).ok_or_else(|| bad(C, "gridSize must be small, medium or large"))?, "gridColors" => s.grid_colors = grid_colors(v)?, @@ -125,7 +141,7 @@ fn apply(s: &mut DocSetup, units: &mut vectorcraft_doc::Unit, k: &str, v: &Value "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)?, // Read-only values `document.setup` reports. - "gridColorsName" => {} + "gridColorsName" | "warnings" => {} _ => return Err(bad(C, format!("unknown setting `{k}`"))), } Ok(()) diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index e349fb9e92..5b884b3eec 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -12,6 +12,7 @@ use vectorcraft_geom::hit::fill_contains; use vectorcraft_geom::{Anchor, AnchorKind, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; use vectorcraft_pathops as po; use vectorcraft_pathops::{BoolOp, Cap, Join, SimplifyOptions}; +use vectorcraft_tools::draw2::{eraser_area, eraser_tip}; use super::create::{add_look, insert_look}; use super::newart::NewArt; @@ -19,1503 +20,13 @@ use super::pathops::{Beside, remove_each}; use super::*; use crate::EngineError; -pub fn specs() -> Vec { - vec![ - cmd!( - "path.freehand", - "Pencil", - [], - None, - "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic brushes with Pressure variation; a point without one presses fully), fidelity?: pt (1.5), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: it is not, and the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; 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 - ), - cmd!( - "path.curvature", - "Curvature", - [], - None, - "{points: [{x, y, corner?}], closed?, id?} create (or with id: replace) a path curving through the points → {id}", - has_doc, - curvature - ), - cmd!( - "path.curvatureEdit", - "Curvature", - [], - None, - "{id, subpath?, op: \"move\"|\"insert\"|\"extend\"|\"close\", anchor?, segment?, t?, end?: \"start\"|\"end\", from?: \"keep\"|\"smooth\"|\"corner\", corner?, x?, y?} edit a path as the Curvature tool does, its shape kept elsewhere; the anchor edited becomes the direct-selected one → {anchor}. move: anchor to x, y, re-curving only its two segments (a smooth anchor takes the Curvature tool's handles, along the circle through it and its neighbours); insert: a smooth anchor at t on segment, the shape unchanged (with x, y: then moved there); extend: an open subpath goes on from its end (default) or start to a new end at x, y, curving into it unless corner is true; close: an open subpath closes from that end. The old end bends into the new segment as from says: keep its curve (default), smooth through its neighbours, or a corner", - has_doc, - curvature_edit - ), - cmd!( - "path.removeAnchor", - "Delete Anchor Point", - [], - None, - "{id, subpath?, anchor} remove one anchor, re-fitting the curve", - has_doc, - remove_anchor - ), - cmd!( - "path.removeAnchors", - "Remove Anchor Points", - ["Object", "Path"], - None, - "{} remove the direct-selected anchors without opening their paths, refitting the curve round each; the anchor after each removed one is selected, so running it again goes on along the path → {removedObjects}", - has_anchors, - remove_anchors - ), - cmd!( - "path.convertAnchor", - "Convert Anchor Point", - [], - None, - "{id, subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)", - has_doc, - convert_anchor - ), - cmd!( - "path.reshapeSegment", - "Reshape Segment", - [], - None, - "{id, subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does", - has_doc, - reshape_segment - ), - cmd!( - "path.split", - "Split Path", - [], - None, - "{id, subpath?, segment, t} or {id, subpath?, anchor}: closed paths open there, open paths become two → {ids}", - has_doc, - split - ), - cmd!( - "path.knife", - "Knife", - [], - None, - "{points: [[x,y]…]} cut closed shapes (selected, or all when nothing is selected) along the polyline → {ids}", - has_doc, - knife - ), - cmd!( - "path.eraseRegion", - "Eraser", - [], - None, - "{points: [[x,y]…], size?: pt (10)} erase a round-brush stroke from paths (selected, or all) → {ids}", - has_doc, - erase_region - ), - cmd!( - "path.eraseSegments", - "Path Eraser", - [], - None, - "{points: [[x,y]…], width?: pt (8)} erase the parts of selected paths under the drag → {ids}", - has_selection, - erase_segments - ), - cmd!( - "path.smoothRegion", - "Smooth", - [], - None, - "{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5)} smooth selected paths near the drag → {ids, before, after}", - has_selection, - smooth_region - ), - cmd!( - "path.joinScrub", - "Join", - [], - None, - "{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over → {id}", - has_doc, - join_scrub - ), - cmd!( - "path.blob", - "Blob Brush", - [], - None, - "{points: [[x,y]…], size?: pt (10), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with touching same-colour blobs → {id}", - has_doc, - blob - ), - ] -} +mod anchors; +mod commands; +mod common; +mod cut; +mod freehand; +mod smooth; -// ---------- helpers ---------- - -/// `[[x,y]…]` or `[{x,y}…]`; non-finite points are dropped. -fn points_param(p: &Value, key: &str, cmd: &str) -> Result> { - Ok(samples_param(p, key, cmd)?.into_iter().map(|(pt, _)| pt).collect()) -} - -/// [`points_param`] with each point's pen pressure, if it has one: `[[x,y,pressure]…]` or -/// `[{x,y,pressure}…]` (0..1). -fn samples_param(p: &Value, key: &str, cmd: &str) -> Result)>> { - let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?; - let pts: Vec<(Point, Option)> = a - .iter() - .filter_map(|v| match v { - Value::Array(xy) => Some((Point::new(xy.first()?.as_f64()?, xy.get(1)?.as_f64()?), xy.get(2).and_then(Value::as_f64))), - Value::Object(_) => Some((Point::new(v.get("x")?.as_f64()?, v.get("y")?.as_f64()?), v.get("pressure").and_then(Value::as_f64))), - _ => None, - }) - .filter(|(p, _)| p.x.is_finite() && p.y.is_finite()) - .collect(); - if pts.is_empty() { - return Err(bad(cmd, "need at least one point")); - } - Ok(pts) -} - -/// The pen pressure along a freehand stroke (positions measured along its polyline), when any of -/// its samples has one; samples without one count as full pressure, as a pen event without one. -fn stroke_pressure(samples: &[(Point, Option)]) -> Option { - if samples.iter().all(|(_, p)| p.is_none()) { - return None; - } - let mut at = 0.0; - let mut prev: Option = None; - let along: Vec<(f64, f64)> = samples - .iter() - .map(|(pt, p)| { - at += prev.map_or(0.0, |q| q.distance(*pt)); - prev = Some(*pt); - (at, p.unwrap_or(1.0)) - }) - .collect(); - PressureProfile::from_samples(along.into_iter().map(|(s, p)| (if at > 1e-9 { s / at } else { 0.0 }, p))) -} - -/// The length of a subpath. -fn subpath_len(sp: &SubPath) -> f64 { - use kurbo::ParamCurveArclen; - PathData::single(sp.clone()).to_bezpath().segments().map(|s| s.arclen(0.01)).sum() -} - -/// The bound, in points, on the length of a `path.reshapeSegment` delta and on the x and y of a -/// point given to `path.convertAnchor` or `path.freehand`. The blend spine commands set the same -/// bound (`object.blend.spine.reshapeSegment`, `object.blend.spine.moveAnchor`). -const MAX_INPUT: f64 = 1e9; - -/// Whether `q` is finite and its x and y are each smaller than [`MAX_INPUT`] in size. -fn within_input_bound(q: Point) -> bool { - q.x.is_finite() && q.y.is_finite() && q.x.abs() < MAX_INPUT && q.y.abs() < MAX_INPUT -} - -fn usize_req(p: &Value, key: &str, cmd: &str) -> Result { - p.get(key).and_then(Value::as_u64).map(|v| v as usize).ok_or_else(|| bad(cmd, format!("missing integer `{key}`"))) -} - -/// The whole number of 0 or more that `key` holds, or `None` when `key` is absent or null. Any other -/// value is [`usize_req`]'s error. -pub(super) fn usize_opt(p: &Value, key: &str, cmd: &str) -> Result> { - match p.get(key) { - None | Some(Value::Null) => Ok(None), - Some(_) => usize_req(p, key, cmd).map(Some), - } -} - -fn path_mut(d: &mut Document, id: NodeId) -> Result<&mut PathData> { - let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; - match &mut n.kind { - NodeKind::Path { path, live, .. } => { - *live = None; - Ok(path) - } - _ => Err(EngineError::Other(format!("object {id} is not a path"))), - } -} - -fn path_of(d: &Document, id: NodeId) -> Result<(PathData, FillRule)> { - match d.node(id).map(|n| &n.kind) { - Some(NodeKind::Path { path, rule, .. }) => Ok((path.clone(), *rule)), - Some(_) => Err(EngineError::Other(format!("object {id} is not a path"))), - None => Err(EngineError::NoNode(id)), - } -} - -fn dist_to_polyline(pts: &[Point], q: Point) -> f64 { - if pts.len() == 1 { - return pts[0].distance(q); - } - pts.windows(2) - .map(|w| { - let (a, b) = (w[0], w[1]); - let ab = b - a; - let l2 = ab.hypot2(); - let t = if l2 < 1e-18 { 0.0 } else { ((q - a).dot(ab) / l2).clamp(0.0, 1.0) }; - (a + ab * t).distance(q) - }) - .fold(f64::INFINITY, f64::min) -} - -fn poly_bounds(pts: &[Point], pad: f64) -> Rect { - let r = pts.iter().fold(Rect::from_points(pts[0], pts[0]), |r, p| r.union_pt(*p)); - r.inflate(pad, pad) -} - -/// The filled area painted by a round brush of diameter `size` along `pts`. -fn brush_region(pts: &[Point], size: f64) -> PathData { - let mut pts = pts.to_vec(); - if pts.len() == 1 { - pts.push(pts[0] + Vec2::new(0.01, 0.0)); - } - po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), size, Cap::Round, Join::Round, 4.0) -} - -/// Path leaves the area tools act on: under the selected objects, or every path when nothing is -/// selected. Only editable, non-guide paths whose bounds meet `area`. -fn target_paths(doc: &Document, sel: &Selection, area: Rect) -> Vec { - let mut out = vec![]; - let mut push = |n: &Node| { - if let NodeKind::Path { guide: false, path, .. } = &n.kind - && path.control_bounds().is_some_and(|b| b.inflate(0.5, 0.5).intersect(area).area() > 0.0 || b.width() == 0.0 || b.height() == 0.0) - && !out.contains(&n.id) - { - out.push(n.id); - } - }; - if sel.is_empty() { - doc.walk(&mut push); - } else { - for id in &sel.objects { - if let Some(n) = doc.node(*id) { - n.walk(&mut |c: &Node| push(c)); - } - } - } - out.retain(|id| doc.is_editable(*id)); - out -} - -/// The members of a compound path with geometry `pd`: one path per subpath, with fresh ids. -fn compound_members(d: &mut Document, pd: PathData) -> Vec> { - pd.subpaths.into_iter().map(|sp| Arc::new(Node::path(d.alloc_id(), PathData::single(sp), Appearance::default()))).collect() -} - -/// Give path or compound path `id` the geometry `pd` (dropping a live shape; a compound's members -/// are rebuilt, one per subpath). -pub(super) fn set_geometry(d: &mut Document, id: NodeId, pd: PathData) -> Result<()> { - if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Compound { .. })) { - let members = compound_members(d, pd); - if let Some(NodeKind::Compound { children, .. }) = d.node_mut(id).map(|n| &mut n.kind) { - *children = members; - } - return Ok(()); - } - *path_mut(d, id)? = pd; - Ok(()) -} - -/// A copy of path or compound path node `id` (fresh ids, no live shape) with geometry `pd`. -fn sibling_with(d: &mut Document, id: NodeId, pd: PathData) -> Result { - let mut n = d.node(id).ok_or(EngineError::NoNode(id))?.clone(); - n.id = d.alloc_id(); - match &mut n.kind { - NodeKind::Path { path, live, .. } => { - *path = pd; - *live = None; - } - NodeKind::Compound { children, .. } => *children = compound_members(d, pd), - _ => {} - } - Ok(n) -} - -/// Replace path or compound path `id` with `pieces` (first keeps the id, the rest go right above -/// it; none removes it). `cut` removes the path or puts the other pieces above it. Returns ids. -pub(super) fn replace_with_pieces(d: &mut Document, cut: &mut Beside, id: NodeId, pieces: Vec) -> Result> { - let mut it = pieces.into_iter(); - let Some(first) = it.next() else { - cut.put(d, id, vec![])?; - return Ok(vec![]); - }; - let mut ids = vec![id]; - let mut above = vec![]; - for pd in it { - let n = sibling_with(d, id, pd)?; - ids.push(n.id); - above.push(n); - } - set_geometry(d, id, first)?; - if !above.is_empty() { - let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?; - cut.put(d, id, [n].into_iter().chain(above).collect())?; - } - Ok(ids) -} - -pub(super) fn ids_json(ids: &[NodeId]) -> Value { - json!({ "ids": ids.iter().map(|i| i.0).collect::>() }) -} - -/// Split a filled path into connected pieces (each outer contour with its holes). -pub(super) fn components(pd: &PathData) -> Vec { - let subs: Vec<&SubPath> = pd.subpaths.iter().filter(|s| s.closed && s.anchors.len() >= 2).collect(); - if subs.len() <= 1 { - return if pd.is_empty() { vec![] } else { vec![pd.clone()] }; - } - let bps: Vec = subs - .iter() - .map(|s| { - let mut b = BezPath::new(); - s.to_bezpath_into(&mut b); - b - }) - .collect(); - let samples: Vec = subs.iter().map(|s| s.segment(0).eval(0.5)).collect(); - let n = subs.len(); - let inside = |j: usize, i: usize| fill_contains(&bps[j], FillRule::NonZero, samples[i]); - let depth: Vec = (0..n).map(|i| (0..n).filter(|&j| j != i && inside(j, i)).count()).collect(); - let areas: Vec = subs.iter().map(|s| s.area().abs()).collect(); - let outers: Vec = (0..n).filter(|&i| depth[i].is_multiple_of(2)).collect(); - let mut groups: Vec> = outers.iter().map(|&o| vec![subs[o].clone()]).collect(); - for h in (0..n).filter(|&i| !depth[i].is_multiple_of(2)) { - let best = outers - .iter() - .enumerate() - .filter(|(_, o)| depth[**o] + 1 == depth[h] && inside(**o, h)) - .min_by(|a, b| areas[*a.1].total_cmp(&areas[*b.1])); - if let Some((k, _)) = best { - groups[k].push(subs[h].clone()); - } - } - groups.into_iter().map(PathData::new).collect() -} - -/// The pieces of `sp` where `remove(point)` is false. `None` when nothing is removed. -fn cut_subpath(sp: &SubPath, remove: &dyn Fn(Point) -> bool) -> Option> { - let nseg = sp.segment_count(); - if nseg == 0 { - return sp.anchors.first().filter(|a| remove(a.p)).map(|_| vec![]); - } - const K: usize = 24; - let mut runs: Vec> = vec![]; - let mut cur: Vec<(usize, f64, f64)> = vec![]; - let mut any = false; - for i in 0..nseg { - let c = sp.segment(i); - let mut prev_t = 0.0; - let mut prev_rm = remove(c.eval(0.0)); - let mut start = if prev_rm { None } else { Some(0.0) }; - if prev_rm { - any = true; - if !cur.is_empty() { - runs.push(std::mem::take(&mut cur)); - } - } - for k in 1..=K { - let t = k as f64 / K as f64; - let rm = remove(c.eval(t)); - if rm != prev_rm { - let (mut lo, mut hi) = (prev_t, t); - for _ in 0..30 { - let m = 0.5 * (lo + hi); - if remove(c.eval(m)) == prev_rm { lo = m } else { hi = m } - } - let b = 0.5 * (lo + hi); - if prev_rm { - start = Some(b); - } else { - any = true; - if let Some(s) = start.take() { - cur.push((i, s, b)); - } - runs.push(std::mem::take(&mut cur)); - } - } - prev_t = t; - prev_rm = rm; - } - if let Some(s) = start { - cur.push((i, s, 1.0)); - } - } - if !cur.is_empty() { - runs.push(cur); - } - runs.retain(|r| !r.is_empty()); - if !any { - return None; - } - // A closed path's last and first runs meet at anchor 0. - if sp.closed && runs.len() >= 2 { - let first_starts = runs.first().and_then(|r| r.first()).is_some_and(|s| s.0 == 0 && s.1 == 0.0); - let last_ends = runs.last().and_then(|r| r.last()).is_some_and(|s| s.0 + 1 == nseg && s.2 == 1.0); - if first_starts && last_ends { - let first = runs.remove(0); - if let Some(last) = runs.last_mut() { - last.extend(first); - } - } - } - let out = runs - .iter() - .filter(|r| r.len() > 1 || r[0].2 - r[0].1 > 1e-4) - .map(|r| { - let mut anchors: Vec = vec![]; - for &(i, t0, t1) in r { - let c = sp.segment(i).subsegment(t0..t1); - let (h1, h2) = if sp.segment_is_line(i) { (c.p0, c.p3) } else { (c.p1, c.p2) }; - match anchors.last_mut() { - Some(a) => a.h_out = h1, - None => anchors.push(Anchor { h_out: h1, ..Anchor::corner(c.p0) }), - } - anchors.push(Anchor { p: c.p3, h_in: h2, h_out: c.p3, kind: AnchorKind::Corner }); - } - for a in &mut anchors { - *a = Anchor::with_handles(a.p, a.h_in, a.h_out); - } - SubPath::new(anchors, false) - }) - .filter(|s| s.anchors.len() >= 2) - .collect(); - Some(out) -} - -/// Erase from an outline path (open or closed) where `remove` holds. Returns the new geometry per -/// output object (one object per piece when the path had a single subpath), or None if unchanged. -pub(super) fn erase_outline(pd: &PathData, remove: &dyn Fn(Point) -> bool) -> Option> { - let mut changed = false; - let mut subs = vec![]; - for sp in &pd.subpaths { - match cut_subpath(sp, remove) { - Some(pieces) => { - changed = true; - subs.extend(pieces); - } - None => subs.push(sp.clone()), - } - } - if !changed { - return None; - } - Some(if pd.subpaths.len() == 1 { - subs.into_iter().map(PathData::single).collect() - } else if subs.is_empty() { - vec![] - } else { - vec![PathData::new(subs)] - }) -} - -fn stroke_paint(s: &Session) -> Paint { - if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() } -} - -fn path_kind(path: PathData) -> NodeKind { - NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false } -} - -// ---------- Pencil / Paintbrush ---------- - -/// Fit a freehand polyline: drop jitter, build a spline through the samples (sharp turns stay -/// corners) and simplify it to `tol`. -fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath { - let min = (tol * 0.3).max(0.05); - let (Some(&p0), Some(&pn)) = (pts.first(), pts.last()) else { return SubPath::new(vec![], closed) }; - let mut kept: Vec = vec![p0]; - for &p in pts.iter().skip(1) { - if kept.last().is_none_or(|k| k.distance(p) >= min) { - kept.push(p); - } - } - // The last sample always ends the stroke. - if kept.len() > 1 { - if let Some(k) = kept.last_mut() { - *k = pn; - } - } else if pts.len() > 1 { - kept.push(pn); - } - let n = kept.len(); - let marked: Vec<(Point, bool)> = (0..n) - .map(|i| { - let corner = if i == 0 || i + 1 == n { - false - } else { - let (a, b) = (kept[i] - kept[i - 1], kept[i + 1] - kept[i]); - a.dot(b) / (a.hypot() * b.hypot()).max(1e-12) < -0.2 // turn > ~100° - }; - (kept[i], corner) - }) - .collect(); - let sp = vectorcraft_tools::draw2::catmull_rom(&marked, closed); - if sp.anchors.len() < 3 { - return sp; - } - let fitted = po::simplify_with(&PathData::single(sp.clone()), &SimplifyOptions { tolerance: tol, corner_angle_deg: 60.0, straight_lines: false }); - fitted.subpaths.into_iter().next().filter(|s| s.anchors.len() >= 2).unwrap_or(sp) -} - -/// Pencil's Edit Selected Paths in the middle of a path: a stroke from one point of a subpath of -/// `pd` to another, each within `within` of it, replaces the section between them (the shorter -/// way round a closed subpath) with the stroke fitted at `tol`. The subpath's index and its new -/// shape; None when the stroke doesn't start and end on the same subpath, or meets it once. -fn redraw_section(pd: &PathData, pts: &[Point], tol: f64, within: f64) -> Option<(usize, SubPath)> { - use kurbo::ParamCurveArclen; - let (first, last) = (*pts.first()?, *pts.last()?); - let (si, _, _, _, d_a) = pd.nearest(first)?; - let (sj, _, _, _, d_b) = pd.nearest(last)?; - if si != sj || d_a > within || d_b > within || pts.len() < 2 { - return None; - } - let mut sp = pd.subpaths.get(si)?.clone(); - if sp.anchors.len() < 2 { - return None; - } - // The anchor nearest to `q`: the one there, else a new one, and whether it was added. Each - // point is looked up on the subpath as it is by then: splitting a straight segment makes two - // new ones, which a `t` along the old one doesn't measure. - let place = |sp: &mut SubPath, q: Point| { - let (_, seg, t, _, _) = PathData::single(sp.clone()).nearest(q)?; - let n = sp.anchors.len(); - Some(if t <= 1e-6 { - (seg % n, false) - } else if t >= 1.0 - 1e-6 { - ((seg + 1) % n, false) - } else { - (sp.insert_anchor(seg, t), true) - }) - }; - let (mut from, _) = place(&mut sp, first)?; - let (to, added) = place(&mut sp, last)?; - if added && to <= from { - from += 1; - } - if from == to { - return None; - } - let n = sp.anchors.len(); - // The length of the run of segments from anchor i forward to anchor j. - let run = |i: usize, j: usize| (0..(j + n - i) % n).map(|k| sp.segment((i + k) % n).arclen(0.01)).sum::(); - // The stroke goes from `start` to `end` and replaces the run between them; `kept` runs from - // `end` round to `start`, then the stroke's inner anchors follow. - let (start, end, reversed) = if sp.closed { - if run(from, to) <= run(to, from) { (from, to, false) } else { (to, from, true) } - } else if from < to { - (from, to, false) - } else { - (to, from, true) - }; - let mut stroke = pts.to_vec(); - if reversed { - stroke.reverse(); - } - let (Some(s0), Some(s1)) = (stroke.first_mut(), sp.anchors.get(start)) else { return None }; - *s0 = s1.p; - let (Some(e0), Some(e1)) = (stroke.last_mut(), sp.anchors.get(end)) else { return None }; - *e0 = e1.p; - let fit = fit_freehand(&stroke, tol, false).anchors; - let (Some(f0), Some(f1)) = (fit.first().copied(), fit.last().copied()) else { return None }; - let inner = fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default(); - let (before, after): (Vec, Vec) = if sp.closed { - ((0..=(start + n - end) % n).filter_map(|k| sp.anchors.get((end + k) % n).copied()).collect(), vec![]) - } else { - (sp.anchors.get(..=start)?.to_vec(), sp.anchors.get(end..)?.to_vec()) - }; - let mut anchors = before; - if let Some(a) = anchors.last_mut() { - *a = Anchor::with_handles(a.p, a.h_in, f0.h_out); - } - anchors.extend_from_slice(inner); - let at_end = anchors.len(); - anchors.extend(after); - // The anchor the stroke ends on: the first after it, or round to the first of a closed one. - let end_at = if sp.closed { 0 } else { at_end }; - if let Some(a) = anchors.get_mut(end_at) { - *a = Anchor::with_handles(a.p, f1.h_in, a.h_out); - } - Some((si, SubPath::new(anchors, sp.closed))) -} - -fn freehand(s: &mut Session, p: &Value) -> Result { - const C: &str = "path.freehand"; - let samples = samples_param(p, "points", C)?; - if samples.iter().any(|(q, _)| !within_input_bound(*q)) { - return Err(bad(C, "x and y must be finite")); - } - let pressure = stroke_pressure(&samples); - let mut pts: Vec = samples.into_iter().map(|(pt, _)| pt).collect(); - let tol = f64_or(p, "fidelity", 1.5).clamp(0.05, 100.0); - let closed = bool_or(p, "closed", false); - let brush = str_param(p, "style") == Some("brush"); - let keep_selected = bool_or(p, "keepSelected", true); - 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 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"))?; - let mut sp = pd.subpaths[si].clone(); - let old_len = subpath_len(&sp); - if at_start { - sp.reverse(); - } - let (Some(first), Some(end)) = (sp.anchors.first().map(|a| a.p), sp.anchors.last().map(|a| a.p)) else { - return Err(bad(C, "path has no open end")); - }; - let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) }; - *p0 = end; - if pts.len() < 2 { - return Ok(json!({ "id": id.0 })); - } - let close_tol = (tol * 4.0).max(6.0); - let closing = 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; - } - let fit = fit_freehand(&pts, tol, false); - let mut add = fit.anchors; - if let (Some(last), Some(a0)) = (sp.anchors.last_mut(), add.first()) { - last.h_out = a0.h_out; - } - if !add.is_empty() { - add.remove(0); - } - sp.anchors.extend(add); - if closing - && sp.anchors.len() > 2 - && let Some(l) = sp.anchors.pop() - && let Some(a0) = sp.anchors.first_mut() - { - a0.h_in = l.h_in; - sp.closed = true; - } - for a in &mut sp.anchors { - *a = Anchor::with_handles(a.p, a.h_in, a.h_out); - } - // The path's pressure (in the direction it is continued in) followed by the stroke's. - let old_pressure = s.doc()?.doc.node(id).and_then(|n| n.appearance.stroke()).and_then(|st| st.pressure.clone()); - let joined = (old_pressure.is_some() || pressure.is_some()).then(|| { - let old = old_pressure.map(|p| if at_start { p.reversed() } else { p }); - let total = subpath_len(&sp); - PressureProfile::extended(old.as_ref(), old_len, pressure.as_ref(), total - old_len) - }); - s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| { - let reverse = at_start && !sp.closed; - if reverse { - sp.reverse(); - } - path_mut(d, id)?.subpaths[si] = sp; - if let Some(joined) = joined - && let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) - { - st.pressure = if reverse { joined.map(|p| p.reversed()) } else { joined }; - } - if keep_selected { - sel.set([id]); - } else { - sel.remove(id); - } - Ok(()) - })?; - 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 within = f64_or(rd, "within", 12.0); - if !within.is_finite() || within < 0.0 { - return Err(bad(C, "redraw within must be a finite distance of 0 or more")); - } - let (pd, _) = path_of(&s.doc()?.doc, id)?; - // shortcut: a stroke pressure profile is left as it was, measured along the old path; fit - // it to the new length if Calligraphic pressure strokes get redrawn. - if let Some((si, sp)) = redraw_section(&pd, &pts, tol, within) { - s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| { - *path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| bad(C, "no such subpath"))? = sp; - if keep_selected { - sel.set([id]); - } else { - sel.remove(id); - } - Ok(()) - })?; - return Ok(json!({ "id": id.0 })); - } - } - if pts.len() < 2 { - return Err(bad(C, "need at least two points")); - } - let sp = fit_freehand(&pts, tol, closed); - let fill = if bool_or(p, "fill", false) { s.paint.fill.clone() } else { Paint::None }; - // A pencil path with a fill keeps a stroke of None (#1679); only one that would show nothing - // gets black. A brush is its stroke. - let stroke = if brush || fill.is_none() { stroke_paint(s) } else { s.paint.stroke.clone() }; - let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1)); - if let Some(st) = look.appearance.stroke_mut() { - st.pressure = pressure; - } - insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected) -} - -// ---------- Curvature ---------- - -fn curvature(s: &mut Session, p: &Value) -> Result { - const C: &str = "path.curvature"; - let arr = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(C, "missing points"))?; - let pts: Vec<(Point, bool)> = arr - .iter() - .filter_map(|v| { - let pt = match v { - Value::Array(xy) => Point::new(xy.first()?.as_f64()?, xy.get(1)?.as_f64()?), - _ => Point::new(v.get("x")?.as_f64()?, v.get("y")?.as_f64()?), - }; - (pt.x.is_finite() && pt.y.is_finite()).then(|| (pt, v.get("corner").and_then(Value::as_bool).unwrap_or(false))) - }) - .collect(); - if pts.is_empty() { - return Err(bad(C, "need at least one point")); - } - let sp = vectorcraft_tools::draw2::curvature_spline(&pts, bool_or(p, "closed", false)); - if let Some(id) = id_param(p, "id") { - s.edit("Curvature", |d, sel| { - *path_mut(d, id)? = PathData::single(sp); - sel.set([id]); - Ok(()) - })?; - return Ok(json!({ "id": id.0 })); - } - let mut look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); - let ap = &mut look.appearance; - if ap.stroke_paint().is_none() && ap.fill_paint().is_none() { - ap.set_stroke(Paint::solid(Color::BLACK)); - } - add_look(s, "Curvature", path_kind(PathData::single(sp)), look, None) -} - -/// An edit `path.curvatureEdit` makes. -enum CurvatureOp { - Move(usize, Point), - Insert(usize, f64, Option), - Extend(Point), - Close, -} - -fn curvature_edit(s: &mut Session, p: &Value) -> Result { - 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 si = usize_opt(p, "subpath", C)?.unwrap_or(0); - let at = match (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) { - (Some(x), Some(y)) if x.is_finite() && y.is_finite() => Some(Point::new(x, y)), - (None, None) => None, - _ => return Err(bad(C, "x and y must be finite numbers")), - }; - let to = || at.ok_or_else(|| bad(C, "missing x, y")); - let start = match str_param(p, "end") { - None | Some("end") => false, - Some("start") => true, - Some(e) => return Err(bad(C, format!("unknown end {e:?}"))), - }; - let how = match str_param(p, "from") { - None => EndCurve::Keep, - Some(f) => EndCurve::parse(f).ok_or_else(|| bad(C, format!("unknown from {f:?}")))?, - }; - let corner = bool_or(p, "corner", false); - let op = match str_param(p, "op") { - Some("move") => CurvatureOp::Move(usize_req(p, "anchor", C)?, to()?), - Some("insert") => CurvatureOp::Insert(usize_req(p, "segment", C)?, f64_or(p, "t", 0.5), at), - Some("extend") => CurvatureOp::Extend(to()?), - Some("close") => CurvatureOp::Close, - Some(o) => return Err(bad(C, format!("unknown op {o:?}"))), - None => return Err(bad(C, "missing op")), - }; - let anchor = s.edit("Curvature", |d, sel| { - let path = path_mut(d, id)?; - let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - if matches!(op, CurvatureOp::Extend(_) | CurvatureOp::Close) && sp.closed { - return Err(EngineError::Other("path is already closed".into())); - } - let ai = match op { - CurvatureOp::Move(ai, q) => curvature_move(sp, ai, q).then_some(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?, - CurvatureOp::Insert(seg, t, q) => { - let ai = curvature_insert(sp, seg, t).ok_or_else(|| EngineError::Other("no such segment".into()))?; - if let Some(q) = q { - curvature_move(sp, ai, q); - } - ai - } - CurvatureOp::Extend(q) => { - curvature_extend(sp, start, q, how, corner); - if start { 0 } else { sp.anchors.len() - 1 } - } - CurvatureOp::Close => { - if sp.anchors.len() < 3 { - return Err(EngineError::Other("closing needs three anchors".into())); - } - curvature_close(sp, start, how); - if start { sp.anchors.len() - 1 } else { 0 } - } - }; - sel.set([id]); - sel.anchors.insert(id, [(si, ai)].into()); - Ok(ai) - })?; - Ok(json!({ "anchor": anchor })) -} - -// ---------- anchor tools ---------- - -fn remove_anchor(s: &mut Session, p: &Value) -> Result { - const C: &str = "path.removeAnchor"; - let id = id_param(p, "id").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 removed = s.edit("Delete Anchor Point", |d, sel| { - let sp = path_mut(d, id)?.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - if ai >= sp.anchors.len() { - 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)])?; - emptied.finish(d)?; - Ok(removed) - })?; - Ok(json!({ "removedObject": removed })) -} - -fn remove_anchors(s: &mut Session, _: &Value) -> Result { - let st = s.doc()?; - let jobs: Vec<(NodeId, Vec<(usize, usize)>)> = st - .selection - .anchors - .iter() - .filter(|(id, set)| !set.is_empty() && st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))) - .map(|(id, set)| (*id, set.iter().copied().collect())) - .collect(); - if jobs.is_empty() { - 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 emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::>()); - 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)? { - removed += 1; - } 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). - sel.anchors.insert(id, next); - } - } - emptied.finish(d)?; - Ok(removed) - })?; - Ok(json!({ "removedObjects": removed })) -} - -/// Where the selection goes once Remove Anchor Points takes `removed` (subpath, anchor) out of a -/// 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. -fn following_anchors(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 = 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 -} - -/// Remove `anchors` (subpath, anchor) of path `id` without opening it, refitting the curve round -/// each one. A subpath left with one anchor is removed, and a path left with no subpath is removed -/// through `emptied`. True when the path went. -fn remove_anchors_of( - d: &mut Document, - sel: &mut Selection, - emptied: &mut Beside, - id: NodeId, - anchors: impl IntoIterator, -) -> Result { - 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) { - po::remove_anchor(sp, ai); - } - } - 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); - } - Ok(gone) -} - -fn convert_anchor(s: &mut Session, p: &Value) -> Result { - const C: &str = "path.convertAnchor"; - let id = id_param(p, "id").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"); - let target = match (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) { - (Some(x), Some(y)) => Some(Point::new(x, y)), - _ => None, - }; - if target.is_some_and(|q| !within_input_bound(q)) { - return Err(bad(C, "x and y must be finite")); - } - s.edit("Convert Anchor Point", |d, _| { - let path = path_mut(d, id)?; - let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - if smooth && target.is_none() { - if ai >= sp.anchors.len() { - return Err(EngineError::Other("no such anchor".into())); - } - // Without a handle position the anchor curves as the Curvature tool curves a point; one - // with no direction to take stays as it is. - vectorcraft_tools::draw2::curvature_smooth(sp, ai); - return Ok(()); - } - let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - match target { - Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t), - _ => a.retract(), - } - Ok(()) - })?; - ok() -} - -fn reshape_segment(s: &mut Session, p: &Value) -> Result { - const C: &str = "path.reshapeSegment"; - let id = id_param(p, "id").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 = f64_or(p, "t", 0.5).clamp(0.05, 0.95); - let dv = Vec2::new(f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0)); - if !(dv.x.is_finite() && dv.y.is_finite() && dv.hypot() < MAX_INPUT) { - return Err(bad(C, "invalid delta")); - } - let perpendicular = bool_or(p, "perpendicular", false); - s.edit("Reshape", |d, _| { - let path = path_mut(d, id)?; - let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) }; - if !bent { - return Err(EngineError::Other("no such segment".into())); - } - Ok(()) - })?; - ok() -} - -// ---------- Scissors ---------- - -fn split(s: &mut Session, p: &Value) -> Result { - const C: &str = "path.split"; - let id = id_param(p, "id").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)?; - if anchor.is_none() && seg.is_none() { - return Err(bad(C, "need `anchor` or `segment` + `t`")); - } - let t = f64_or(p, "t", 0.5); - if !t.is_finite() || p.get("t").is_some_and(|v| !v.is_f64() && !v.is_i64() && !v.is_u64()) { - return Err(bad(C, "invalid t")); - } - let ids = s.edit("Split Path", |d, sel| { - let path = path_mut(d, id)?; - let mut sp = path.subpaths.get(si).cloned().ok_or_else(|| EngineError::Other("no such subpath".into()))?; - let n = sp.anchors.len(); - let k = match (anchor, seg) { - (Some(a), _) if a < n => a, - (Some(_), _) => return Err(EngineError::Other("no such anchor".into())), - (None, Some(g)) if g < sp.segment_count() => { - if t <= 1e-6 { - g - } else if t >= 1.0 - 1e-6 { - (g + 1) % n - } else { - sp.insert_anchor(g, t) - } - } - _ => return Err(EngineError::Other("no such segment".into())), - }; - let mut pieces = sp.cut_at(&std::collections::BTreeSet::from([k])); - if sp.closed { - path.subpaths[si] = pieces.pop().ok_or_else(|| EngineError::Other("no such anchor".into()))?; - sel.set([id]); - return Ok(vec![id]); - } - let [left, right] = <[SubPath; 2]>::try_from(pieces).map_err(|_| EngineError::Other("cannot split an open path at its end point".into()))?; - if path.subpaths.len() == 1 { - path.subpaths[0] = left; - let node = sibling_with(d, id, PathData::single(right))?; - let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?; - let nid = d.insert(parent, idx + 1, node)?; - sel.set([id, nid]); - Ok(vec![id, nid]) - } else { - path.subpaths[si] = left; - path.subpaths.insert(si + 1, right); - sel.set([id]); - Ok(vec![id]) - } - })?; - Ok(ids_json(&ids)) -} - -// ---------- Knife / Eraser ---------- - -/// Width of the slit the knife leaves between pieces. -const KNIFE_GAP: f64 = 0.05; - -fn knife(s: &mut Session, p: &Value) -> Result { - const C: &str = "path.knife"; - let pts = points_param(p, "points", C)?; - if pts.len() < 2 { - return Err(bad(C, "need at least two points")); - } - let st = s.doc()?; - let strip = po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), KNIFE_GAP, Cap::Butt, Join::Round, 4.0); - let mut plan: Vec<(NodeId, Vec)> = vec![]; - for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, 1.0)) { - let (pd, rule) = path_of(&st.doc, id)?; - if !pd.is_closed() { - continue; - } - let pieces = components(&po::boolean(&pd, rule, &strip, FillRule::NonZero, BoolOp::Difference)); - if pieces.len() >= 2 { - plan.push((id, pieces)); - } - } - if plan.is_empty() { - return Ok(json!({ "ids": [] })); - } - let ids = s.edit("Knife", |d, sel| { - let mut all = vec![]; - let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::>()); - for (id, pieces) in plan { - all.extend(replace_with_pieces(d, &mut cut, id, pieces)?); - } - cut.finish(d)?; - sel.set(all.iter().copied()); - Ok(all) - })?; - Ok(ids_json(&ids)) -} - -fn erase_region(s: &mut Session, p: &Value) -> Result { - const C: &str = "path.eraseRegion"; - let pts = points_param(p, "points", C)?; - let size = f64_or(p, "size", 10.0); - if !(size.is_finite() && size > 0.0) { - return Err(bad(C, "size must be positive")); - } - let r = size / 2.0; - let st = s.doc()?; - let region = brush_region(&pts, size); - let mut plan: Vec<(NodeId, Vec)> = vec![]; - for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, r)) { - let (pd, rule) = path_of(&st.doc, id)?; - if pd.is_closed() { - if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { - continue; - } - plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference)))); - } else if let Some(pieces) = erase_outline(&pd, &|q| dist_to_polyline(&pts, q) <= r) { - plan.push((id, pieces)); - } - } - apply_plan(s, "Eraser", plan) -} - -fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec)>) -> Result { - if plan.is_empty() { - return Ok(json!({ "ids": [] })); - } - let ids = s.edit(label, |d, sel| { - let mut all = vec![]; - let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::>()); - for (id, pieces) in plan { - all.extend(replace_with_pieces(d, &mut cut, id, pieces)?); - } - cut.finish(d)?; - sel.set(all.iter().copied()); - Ok(all) - })?; - Ok(ids_json(&ids)) -} - -fn erase_segments(s: &mut Session, p: &Value) -> Result { - const C: &str = "path.eraseSegments"; - let pts = points_param(p, "points", C)?; - let w = f64_or(p, "width", 8.0); - if !(w.is_finite() && w > 0.0) { - return Err(bad(C, "width must be positive")); - } - let st = s.doc()?; - let mut plan = vec![]; - for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, w)) { - let (pd, _) = path_of(&st.doc, id)?; - if let Some(pieces) = erase_outline(&pd, &|q| dist_to_polyline(&pts, q) <= w / 2.0) { - plan.push((id, pieces)); - } - } - apply_plan(s, "Path Eraser", plan) -} - -// ---------- 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 { - let piece = PathData::single(SubPath::new(anchors.to_vec(), false)); - let fitted = po::simplify_with(&piece, &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false }); - let 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; - out[0].p = f.p; - out[0].h_in = f.h_in; - out[last].p = l.p; - out[last].h_out = l.h_out; - for a in &mut out { - *a = Anchor::with_handles(a.p, a.h_in, a.h_out); - } - out -} - -fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Option { - let n = sp.anchors.len(); - let marked: Vec = sp.anchors.iter().map(|a| near(a.p)).collect(); - if n < 3 || !marked.iter().any(|m| *m) { - return None; - } - 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 }); - return f.subpaths.into_iter().next(); - }; - // Rotate so an untouched anchor comes first, duplicate it at the end and treat as open. - let mut open = sp.clone(); - open.anchors.rotate_left(k); - let mut m = marked.clone(); - m.rotate_left(k); - open.anchors.push(open.anchors[0]); - m.push(false); - open.closed = false; - let mut res = smooth_open(&open.anchors, &m, near, tol); - 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)) -} - -/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it -/// enters the reach: the part outside, then the part in reach. `None` when no more than a sliver -/// is outside. -fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez, CubicBez)> { - const STEPS: u32 = 32; - let step = 1.0 / f64::from(STEPS); - // Back from the end in reach to the first sample outside, then halving to the crossing. - let outside = (1..=STEPS).map(|i| 1.0 - f64::from(i) * step).find(|t| !near(c.eval(*t)))?; - let (mut lo, mut hi) = (outside, outside + step); - for _ in 0..20 { - let mid = (lo + hi) / 2.0; - if near(c.eval(mid)) { - hi = mid; - } else { - lo = mid; - } - } - // A straight segment's parts stay straight, their handles on their ends. - let straight = c.p1 == c.p0 && c.p2 == c.p3; - let part = |range| { - let s = c.subsegment(range); - if straight { CubicBez::new(s.p0, s.p0, s.p3, s.p3) } else { s } - }; - (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 { - let n = anchors.len(); - let mut runs = vec![]; - let mut i = 0; - while i < n { - if marked[i] { - let a = i; - while i + 1 < n && marked[i + 1] { - i += 1; - } - runs.push((a, i)); - } - i += 1; - } - let mut out = anchors.to_vec(); - for (a, b) in runs.into_iter().rev() { - let lo = a.saturating_sub(1); - let hi = (b + 1).min(n - 1); - if hi - lo < 2 { - continue; - } - let mut piece = out[lo..=hi].to_vec(); - // The anchors outside the reach, kept with the part of their segment that is outside. - let (mut head, mut tail) = (None, None); - if hi > b - && let [.., inner, outer] = piece.as_mut_slice() - && let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_in, inner.h_out, inner.p), near) - { - inner.h_out = reach.p2; - tail = Some(Anchor { h_in: far.p1, ..*outer }); - *outer = Anchor::with_handles(far.p3, reach.p1, far.p2); - } - if lo < a - && let [outer, inner, ..] = piece.as_mut_slice() - && let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_out, inner.h_in, inner.p), near) - { - inner.h_in = reach.p2; - head = Some(Anchor { h_out: far.p1, ..*outer }); - *outer = Anchor::with_handles(far.p3, far.p2, reach.p1); - } - let new = refit_run(&piece, tol); - out.splice(lo..=hi, head.into_iter().chain(new).chain(tail)); - } - out -} - -fn smooth_region(s: &mut Session, p: &Value) -> Result { - const C: &str = "path.smoothRegion"; - let pts = points_param(p, "points", C)?; - let radius = f64_or(p, "radius", 12.0).max(0.0); - let tol = f64_or(p, "fidelity", 2.5).clamp(0.05, 100.0); - let st = s.doc()?; - let near = |q: Point| dist_to_polyline(&pts, q) <= radius; - let mut plan = vec![]; - let (mut before, mut after) = (0, 0); - for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, radius)) { - let (pd, _) = path_of(&st.doc, id)?; - let mut changed = false; - let subs: Vec = pd - .subpaths - .iter() - .map(|sp| match smooth_subpath(sp, &near, tol) { - Some(n) if n != *sp && n.anchors.len() >= 2 => { - changed = true; - n - } - _ => sp.clone(), - }) - .collect(); - if changed { - let np = PathData::new(subs); - before += pd.anchor_count(); - after += np.anchor_count(); - plan.push((id, np)); - } - } - if plan.is_empty() { - return Ok(json!({ "ids": [], "before": 0, "after": 0 })); - } - let ids: Vec = plan.iter().map(|(id, _)| *id).collect(); - s.edit("Smooth", |d, _| { - for (id, np) in plan { - *path_mut(d, id)? = np; - } - Ok(()) - })?; - let mut v = ids_json(&ids); - v["before"] = json!(before); - v["after"] = json!(after); - Ok(v) -} - -// ---------- Join tool ---------- - -fn join_scrub(s: &mut Session, p: &Value) -> Result { - const C: &str = "path.joinScrub"; - let pts = points_param(p, "points", C)?; - let tol = f64_or(p, "tolerance", 12.0).max(0.0); - let st = s.doc()?; - // Open endpoints near the scrub, ordered along it: (order, id, subpath, at_start). - let poly = { - let mut bp = BezPath::new(); - bp.move_to(pts[0]); - for q in &pts[1..] { - bp.line_to(*q); - } - bp - }; - let order = |q: Point| -> f64 { - poly.segments() - .enumerate() - .map(|(i, sg)| (i as f64 + sg.nearest(q, 1e-6).t, sg.nearest(q, 1e-6).distance_sq)) - .min_by(|a, b| a.1.total_cmp(&b.1)) - .map_or(0.0, |x| x.0) - }; - let mut ends: Vec<(f64, NodeId, usize, bool, Point)> = vec![]; - for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol)) { - let (pd, _) = path_of(&st.doc, id)?; - for (si, sp) in pd.subpaths.iter().enumerate() { - if sp.closed || sp.anchors.len() < 2 { - continue; - } - for (start, a) in [(true, sp.anchors[0].p), (false, sp.anchors[sp.anchors.len() - 1].p)] { - if dist_to_polyline(&pts, a) <= tol { - ends.push((order(a), id, si, start, a)); - } - } - } - } - ends.sort_by(|a, b| a.0.total_cmp(&b.0)); - if ends.len() < 2 { - return Ok(json!({ "id": null })); - } - let (_, ida, sa, starta, pa) = ends[0]; - let (_, idb, sb, startb, pb) = ends[1]; - let mid = pa.midpoint(pb); - let merge = pa.distance(pb) <= tol; - s.edit("Join", |d, sel| { - if ida == idb && sa == sb { - let path = path_mut(d, ida)?; - let sp = &mut path.subpaths[sa]; - if merge - && sp.anchors.len() > 2 - && let Some(l) = sp.anchors.pop() - { - let d0 = mid - sp.anchors[0].p; - sp.anchors[0].translate(d0); - sp.anchors[0].h_in = l.h_in + (mid - l.p); - } - sp.closed = true; - sel.set([ida]); - return Ok(()); - } - let (pdb, _) = path_of(d, idb)?; - let mut x = path_of(d, ida)?.0.subpaths[sa].clone(); - let mut y = pdb.subpaths[sb].clone(); - if starta { - x.reverse(); - } - if !startb { - y.reverse(); - } - if merge - && !y.anchors.is_empty() - && let Some(last) = x.anchors.last_mut() - { - let yf = y.anchors.remove(0); - let lp = last.p; - last.translate(mid - lp); - last.h_out = yf.h_out + (mid - yf.p); - *last = Anchor::with_handles(last.p, last.h_in, last.h_out); - } - x.anchors.extend(y.anchors); - if ida == idb { - let path = path_mut(d, ida)?; - path.subpaths[sa] = x; - path.subpaths.remove(sb); - } else { - path_mut(d, ida)?.subpaths[sa] = x; - let pbm = path_mut(d, idb)?; - pbm.subpaths.remove(sb); - if pbm.is_empty() { - d.remove(idb)?; - } - } - sel.set([ida]); - Ok(()) - })?; - Ok(json!({ "id": ida.0 })) -} - -// ---------- Blob Brush ---------- - -fn blob(s: &mut Session, p: &Value) -> Result { - const C: &str = "path.blob"; - let pts = points_param(p, "points", C)?; - let size = f64_or(p, "size", 10.0); - if !(size.is_finite() && size > 0.0) { - return Err(bad(C, "size must be positive")); - } - let region = brush_region(&pts, size); - if region.is_empty() { - return Err(EngineError::Other("empty brush stroke".into())); - } - let paint = if !s.paint.stroke.is_none() { - s.paint.stroke.clone() - } else if !s.paint.fill.is_none() { - s.paint.fill.clone() - } else { - Paint::solid(Color::BLACK) - }; - let keep_selected = bool_or(p, "keepSelected", false); - let only_selection = bool_or(p, "mergeOnlySelection", false); - let st = s.doc()?; - let mut merge_ids = vec![]; - if bool_or(p, "merge", true) && !(only_selection && st.selection.is_empty()) { - let all = Selection::default(); - let from = if only_selection { &st.selection } else { &all }; - for id in target_paths(&st.doc, from, poly_bounds(&pts, size)) { - let Some(n) = st.doc.node(id) else { continue }; - if n.appearance.fill_paint() != paint || !n.appearance.stroke_paint().is_none() { - continue; - } - let (pd, rule) = path_of(&st.doc, id)?; - if pd.is_closed() && po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) > 1e-6 { - merge_ids.push((id, pd, rule)); - } - } - } - let ap = NewArt::plain(Appearance::basic(paint, Paint::None, 1.0)); - if merge_ids.is_empty() { - return insert_look(s, "Blob Brush", path_kind(region), ap, None, keep_selected); - } - let mut inputs: Vec<(&PathData, FillRule)> = vec![(®ion, FillRule::NonZero)]; - inputs.extend(merge_ids.iter().map(|(_, pd, r)| (pd, *r))); - let merged = po::unite_all(&inputs); - let Some(((keep, _, _), rest)) = merge_ids.split_last() else { - return insert_look(s, "Blob Brush", path_kind(region), ap, None, keep_selected); - }; - let keep = *keep; - let others: Vec = rest.iter().map(|m| m.0).collect(); - s.edit("Blob Brush", |d, sel| { - *path_mut(d, keep)? = merged; - remove_each(d, &others)?; - if keep_selected { - sel.set([keep]); - } else { - sel.remove(keep); - } - Ok(()) - })?; - Ok(json!({ "id": keep.0 })) -} +pub use commands::specs; +pub(super) use common::{ids_json, replace_with_pieces, usize_opt}; +pub(super) use cut::{components, erase_outline}; diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs new file mode 100644 index 0000000000..540627fe00 --- /dev/null +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -0,0 +1,269 @@ +use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, within_input_bound}; +use super::*; + +// ---------- Curvature ---------- + +pub(super) fn curvature(s: &mut Session, p: &Value) -> Result { + const C: &str = "path.curvature"; + let arr = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(C, "missing points"))?; + let pts: Vec<(Point, bool)> = arr.iter().map(|v| Ok((point_entry(v, C)?, switch_or(v, "corner", false, C)?))).collect::>()?; + if pts.is_empty() { + return Err(bad(C, "need at least one point")); + } + let sp = vectorcraft_tools::draw2::curvature_spline(&pts, switch_or(p, "closed", false, C)?); + if let Some(id) = id_param(p, "id") { + s.edit("Curvature", |d, sel| { + *path_mut(d, id)? = PathData::single(sp); + sel.set([id]); + Ok(()) + })?; + return Ok(json!({ "id": id.0 })); + } + let mut look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let ap = &mut look.appearance; + if ap.stroke_paint().is_none() && ap.fill_paint().is_none() { + ap.set_stroke(Paint::solid(Color::BLACK)); + } + add_look(s, "Curvature", path_kind(PathData::single(sp)), look, None) +} + +/// An edit `path.curvatureEdit` makes. +enum CurvatureOp { + Move(usize, Point), + Insert(usize, f64, Option), + Extend(Point), + Close, +} + +pub(super) fn curvature_edit(s: &mut Session, p: &Value) -> Result { + 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 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)) { + (Some(x), Some(y)) if x.is_finite() && y.is_finite() => Some(Point::new(x, y)), + (None, None) => None, + _ => return Err(bad(C, "x and y must be finite numbers")), + }; + let to = || at.ok_or_else(|| bad(C, "missing x, y")); + let start = match str_param(p, "end") { + None | Some("end") => false, + Some("start") => true, + Some(e) => return Err(bad(C, format!("unknown end {e:?}"))), + }; + let how = match str_param(p, "from") { + None => EndCurve::Keep, + Some(f) => EndCurve::parse(f).ok_or_else(|| bad(C, format!("unknown from {f:?}")))?, + }; + let corner = switch_or(p, "corner", false, C)?; + let op = match str_param(p, "op") { + Some("move") => CurvatureOp::Move(usize_req(p, "anchor", C)?, to()?), + Some("insert") => CurvatureOp::Insert(usize_req(p, "segment", C)?, f64_or(p, "t", 0.5), at), + Some("extend") => CurvatureOp::Extend(to()?), + Some("close") => CurvatureOp::Close, + Some(o) => return Err(bad(C, format!("unknown op {o:?}"))), + None => return Err(bad(C, "missing op")), + }; + let anchor = s.edit("Curvature", |d, sel| { + let path = path_mut(d, id)?; + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + if matches!(op, CurvatureOp::Extend(_) | CurvatureOp::Close) && sp.closed { + return Err(EngineError::Other("path is already closed".into())); + } + let ai = match op { + CurvatureOp::Move(ai, q) => curvature_move(sp, ai, q).then_some(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?, + CurvatureOp::Insert(seg, t, q) => { + let ai = curvature_insert(sp, seg, t).ok_or_else(|| EngineError::Other("no such segment".into()))?; + if let Some(q) = q { + curvature_move(sp, ai, q); + } + ai + } + CurvatureOp::Extend(q) => { + curvature_extend(sp, start, q, how, corner); + if start { 0 } else { sp.anchors.len() - 1 } + } + CurvatureOp::Close => { + if sp.anchors.len() < 3 { + return Err(EngineError::Other("closing needs three anchors".into())); + } + curvature_close(sp, start, how); + if start { sp.anchors.len() - 1 } else { 0 } + } + }; + sel.set([id]); + sel.anchors.insert(id, [(si, ai)].into()); + Ok(ai) + })?; + Ok(json!({ "anchor": anchor })) +} + +// ---------- anchor tools ---------- + +pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result { + const C: &str = "path.removeAnchor"; + let id = id_param(p, "id").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 removed = s.edit("Delete Anchor Point", |d, sel| { + let sp = path_mut(d, id)?.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + if ai >= sp.anchors.len() { + 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)])?; + emptied.finish(d)?; + Ok(removed) + })?; + Ok(json!({ "removedObject": removed })) +} + +pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result { + let st = s.doc()?; + let jobs: Vec<(NodeId, Vec<(usize, usize)>)> = st + .selection + .anchors + .iter() + .filter(|(id, set)| !set.is_empty() && st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))) + .map(|(id, set)| (*id, set.iter().copied().collect())) + .collect(); + if jobs.is_empty() { + 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 emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::>()); + 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)? { + removed += 1; + } 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). + sel.anchors.insert(id, next); + } + } + emptied.finish(d)?; + Ok(removed) + })?; + Ok(json!({ "removedObjects": removed })) +} + +/// Where the selection goes once Remove Anchor Points takes `removed` (subpath, anchor) out of a +/// 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. +fn following_anchors(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 = 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 +} + +/// Remove `anchors` (subpath, anchor) of path `id` without opening it, refitting the curve round +/// each one. A subpath left with one anchor is removed, and a path left with no subpath is removed +/// through `emptied`. True when the path went. +fn remove_anchors_of( + d: &mut Document, + sel: &mut Selection, + emptied: &mut Beside, + id: NodeId, + anchors: impl IntoIterator, +) -> Result { + 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) { + po::remove_anchor(sp, ai); + } + } + 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); + } + Ok(gone) +} + +pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result { + const C: &str = "path.convertAnchor"; + let id = id_param(p, "id").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"); + check_numbers(p, &["x", "y"], C)?; + let target = match (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) { + (Some(x), Some(y)) => Some(Point::new(x, y)), + (None, None) => None, + _ => return Err(bad(C, "x and y must be given together")), + }; + if target.is_some_and(|q| !within_input_bound(q)) { + return Err(bad(C, "x and y must be finite")); + } + s.edit("Convert Anchor Point", |d, _| { + let path = path_mut(d, id)?; + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + if smooth && target.is_none() { + if ai >= sp.anchors.len() { + return Err(EngineError::Other("no such anchor".into())); + } + // Without a handle position the anchor curves as the Curvature tool curves a point; one + // with no direction to take stays as it is. + vectorcraft_tools::draw2::curvature_smooth(sp, ai); + return Ok(()); + } + let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + match target { + Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t), + _ => a.retract(), + } + Ok(()) + })?; + ok() +} + +pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result { + const C: &str = "path.reshapeSegment"; + let id = id_param(p, "id").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); + let dv = Vec2::new(number_or(p, "dx", 0.0, C)?, number_or(p, "dy", 0.0, C)?); + if !(dv.x.is_finite() && dv.y.is_finite() && dv.hypot() < MAX_INPUT) { + return Err(bad(C, "invalid delta")); + } + let perpendicular = switch_or(p, "perpendicular", false, C)?; + s.edit("Reshape", |d, _| { + let path = path_mut(d, id)?; + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) }; + if !bent { + return Err(EngineError::Other("no such segment".into())); + } + Ok(()) + })?; + ok() +} diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs new file mode 100644 index 0000000000..84337aa27f --- /dev/null +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -0,0 +1,136 @@ +use super::anchors::{convert_anchor, curvature, curvature_edit, remove_anchor, remove_anchors, reshape_segment}; +use super::cut::{erase_region, erase_segments, knife, split}; +use super::freehand::{blob, freehand}; +use super::smooth::{join_scrub, smooth_region}; +use super::*; + +pub fn specs() -> Vec { + vec![ + cmd!( + "path.freehand", + "Pencil", + [], + None, + "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic brushes with Pressure variation; a point without one presses fully), 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: it is not, and 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 + ), + cmd!( + "path.curvature", + "Curvature", + [], + None, + "{points: [{x, y, corner?}], closed?, id?} create (or with id: replace) a path curving through the points → {id}", + has_doc, + curvature + ), + cmd!( + "path.curvatureEdit", + "Curvature", + [], + None, + "{id, subpath?, op: \"move\"|\"insert\"|\"extend\"|\"close\", anchor?, segment?, t?, end?: \"start\"|\"end\", from?: \"keep\"|\"smooth\"|\"corner\", corner?, x?, y?} edit a path as the Curvature tool does, its shape kept elsewhere; the anchor edited becomes the direct-selected one → {anchor}. move: anchor to x, y, re-curving only its two segments (a smooth anchor takes the Curvature tool's handles, along the circle through it and its neighbours); insert: a smooth anchor at t on segment, the shape unchanged (with x, y: then moved there); extend: an open subpath goes on from its end (default) or start to a new end at x, y, curving into it unless corner is true; close: an open subpath closes from that end. The old end bends into the new segment as from says: keep its curve (default), smooth through its neighbours, or a corner", + has_doc, + curvature_edit + ), + cmd!( + "path.removeAnchor", + "Delete Anchor Point", + [], + None, + "{id, subpath?, anchor} remove one anchor, re-fitting the curve", + has_doc, + remove_anchor + ), + cmd!( + "path.removeAnchors", + "Remove Anchor Points", + ["Object", "Path"], + None, + "{} remove the direct-selected anchors without opening their paths, refitting the curve round each; the anchor after each removed one is selected, so running it again goes on along the path → {removedObjects}", + has_anchors, + remove_anchors + ), + cmd!( + "path.convertAnchor", + "Convert Anchor Point", + [], + None, + "{id, subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)", + has_doc, + convert_anchor + ), + cmd!( + "path.reshapeSegment", + "Reshape Segment", + [], + None, + "{id, subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does", + has_doc, + reshape_segment + ), + cmd!( + "path.split", + "Split Path", + [], + None, + "{id, subpath?, segment, t} or {id, subpath?, anchor}: closed paths open there, open paths become two → {ids}", + has_doc, + split + ), + cmd!( + "path.knife", + "Knife", + [], + None, + "{points: [[x,y]…]} cut closed shapes (selected, or all when nothing is selected) along the polyline → {ids}", + has_doc, + knife + ), + cmd!( + "path.eraseRegion", + "Eraser", + [], + None, + "{points: [[x,y]…], size?: pt (10), angle?: ° (0), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one", + has_doc, + erase_region + ), + cmd!( + "path.eraseSegments", + "Path Eraser", + [], + None, + "{points: [[x,y]…], width?: pt (8)} erase the parts of selected paths under the drag → {ids}", + has_selection, + erase_segments + ), + cmd!( + "path.smoothRegion", + "Smooth", + [], + None, + "{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5)} smooth selected paths near the drag → {ids, before, after}", + has_selection, + smooth_region + ), + cmd!( + "path.joinScrub", + "Join", + [], + None, + "{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over → {id}", + has_doc, + join_scrub + ), + cmd!( + "path.blob", + "Blob Brush", + [], + None, + "{points: [[x,y]…], size?: pt (10), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with touching same-colour blobs → {id}", + has_doc, + blob + ), + ] +} diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs new file mode 100644 index 0000000000..db5d7e3720 --- /dev/null +++ b/crates/engine/src/cmd/draw2/common.rs @@ -0,0 +1,235 @@ +use super::*; + +// ---------- helpers ---------- + +/// `[[x,y]…]` or `[{x,y}…]`. +pub(super) fn points_param(p: &Value, key: &str, cmd: &str) -> Result> { + Ok(samples_param(p, key, cmd)?.into_iter().map(|(pt, _)| pt).collect()) +} + +/// The point `[x, y, …]` or `{x, y, …}` that `v` holds, or an error when its x or y is not a finite +/// number. +pub(super) fn point_entry(v: &Value, cmd: &str) -> Result { + let xy = match v { + Value::Array(xy) => xy.first().and_then(Value::as_f64).zip(xy.get(1).and_then(Value::as_f64)), + Value::Object(_) => v.get("x").and_then(Value::as_f64).zip(v.get("y").and_then(Value::as_f64)), + _ => None, + }; + xy.filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)).ok_or_else(|| bad(cmd, "x and y must both be numbers")) +} + +/// [`points_param`] with each point's pen pressure, if it has one: `[[x,y,pressure]…]` or +/// `[{x,y,pressure}…]` (0..1). A point whose x or y is not a number, or whose pressure is neither a +/// number nor null, is an error. +pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result)>> { + let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?; + let pts: Vec<(Point, Option)> = a + .iter() + .map(|v| { + let pressure = match v { + Value::Array(xy) => xy.get(2), + _ => v.get("pressure"), + }; + match pressure { + None | Some(Value::Null) | Some(Value::Number(_)) => Ok((point_entry(v, cmd)?, pressure.and_then(Value::as_f64))), + Some(f) => Err(bad(cmd, format!("`pressure` must be a number, not {f}"))), + } + }) + .collect::>()?; + if pts.is_empty() { + return Err(bad(cmd, "need at least one point")); + } + Ok(pts) +} + +/// The pen pressure along a freehand stroke (positions measured along its polyline), when any of +/// its samples has one; samples without one count as full pressure, as a pen event without one. +pub(super) fn stroke_pressure(samples: &[(Point, Option)]) -> Option { + if samples.iter().all(|(_, p)| p.is_none()) { + return None; + } + let mut at = 0.0; + let mut prev: Option = None; + let along: Vec<(f64, f64)> = samples + .iter() + .map(|(pt, p)| { + at += prev.map_or(0.0, |q| q.distance(*pt)); + prev = Some(*pt); + (at, p.unwrap_or(1.0)) + }) + .collect(); + PressureProfile::from_samples(along.into_iter().map(|(s, p)| (if at > 1e-9 { s / at } else { 0.0 }, p))) +} + +/// The length of a subpath. +pub(super) fn subpath_len(sp: &SubPath) -> f64 { + use kurbo::ParamCurveArclen; + PathData::single(sp.clone()).to_bezpath().segments().map(|s| s.arclen(0.01)).sum() +} + +/// The bound, in points, on the length of a `path.reshapeSegment` delta and on the x and y of a +/// point given to `path.convertAnchor` or `path.freehand`. The blend spine commands set the same +/// bound (`object.blend.spine.reshapeSegment`, `object.blend.spine.moveAnchor`). +pub(super) const MAX_INPUT: f64 = 1e9; + +/// Whether `q` is finite and its x and y are each smaller than [`MAX_INPUT`] in size. +pub(super) fn within_input_bound(q: Point) -> bool { + q.x.is_finite() && q.y.is_finite() && q.x.abs() < MAX_INPUT && q.y.abs() < MAX_INPUT +} + +/// The whole number of 0 or more that `key` holds, read with [`index`]. +pub(super) fn usize_req(p: &Value, key: &str, cmd: &str) -> Result { + p.get(key).and_then(Value::as_u64).map(index).ok_or_else(|| bad(cmd, format!("missing integer `{key}`"))) +} + +/// The whole number of 0 or more that `key` holds, or `None` when `key` is absent or null. Any other +/// value is [`usize_req`]'s error. +pub(in super::super) fn usize_opt(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(_) => usize_req(p, key, cmd).map(Some), + } +} + +pub(super) fn path_mut(d: &mut Document, id: NodeId) -> Result<&mut PathData> { + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + match &mut n.kind { + NodeKind::Path { path, live, .. } => { + *live = None; + Ok(path) + } + _ => Err(EngineError::Other(format!("object {id} is not a path"))), + } +} + +pub(super) fn path_of(d: &Document, id: NodeId) -> Result<(PathData, FillRule)> { + match d.node(id).map(|n| &n.kind) { + Some(NodeKind::Path { path, rule, .. }) => Ok((path.clone(), *rule)), + Some(_) => Err(EngineError::Other(format!("object {id} is not a path"))), + None => Err(EngineError::NoNode(id)), + } +} + +pub(super) fn dist_to_polyline(pts: &[Point], q: Point) -> f64 { + if pts.len() == 1 { + return pts[0].distance(q); + } + pts.windows(2) + .map(|w| { + let (a, b) = (w[0], w[1]); + let ab = b - a; + let l2 = ab.hypot2(); + let t = if l2 < 1e-18 { 0.0 } else { ((q - a).dot(ab) / l2).clamp(0.0, 1.0) }; + (a + ab * t).distance(q) + }) + .fold(f64::INFINITY, f64::min) +} + +pub(super) fn poly_bounds(pts: &[Point], pad: f64) -> Rect { + let r = pts.iter().fold(Rect::from_points(pts[0], pts[0]), |r, p| r.union_pt(*p)); + r.inflate(pad, pad) +} + +/// The filled area painted by a round brush of diameter `size` along `pts`. +pub(super) fn brush_region(pts: &[Point], size: f64) -> PathData { + let mut pts = pts.to_vec(); + if pts.len() == 1 { + pts.push(pts[0] + Vec2::new(0.01, 0.0)); + } + po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), size, Cap::Round, Join::Round, 4.0) +} + +/// Path leaves the area tools act on: under the selected objects, or every path when nothing is +/// selected. Only editable, non-guide paths whose bounds meet `area`. +pub(super) fn target_paths(doc: &Document, sel: &Selection, area: Rect) -> Vec { + let mut out = vec![]; + let mut push = |n: &Node| { + if let NodeKind::Path { guide: false, path, .. } = &n.kind + && path.control_bounds().is_some_and(|b| b.inflate(0.5, 0.5).intersect(area).area() > 0.0 || b.width() == 0.0 || b.height() == 0.0) + && !out.contains(&n.id) + { + out.push(n.id); + } + }; + if sel.is_empty() { + doc.walk(&mut push); + } else { + for id in &sel.objects { + if let Some(n) = doc.node(*id) { + n.walk(&mut |c: &Node| push(c)); + } + } + } + let editable = doc.editable(); + out.retain(|id| editable(*id)); + out +} + +/// The members of a compound path with geometry `pd`: one path per subpath, with fresh ids. +fn compound_members(d: &mut Document, pd: PathData) -> Vec> { + pd.subpaths.into_iter().map(|sp| Arc::new(Node::path(d.alloc_id(), PathData::single(sp), Appearance::default()))).collect() +} + +/// Give path or compound path `id` the geometry `pd` (dropping a live shape; a compound's members +/// are rebuilt, one per subpath). +pub(in super::super) fn set_geometry(d: &mut Document, id: NodeId, pd: PathData) -> Result<()> { + if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Compound { .. })) { + let members = compound_members(d, pd); + if let Some(NodeKind::Compound { children, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *children = members; + } + return Ok(()); + } + *path_mut(d, id)? = pd; + Ok(()) +} + +/// A copy of path or compound path node `id` (fresh ids, no live shape) with geometry `pd`. +pub(super) fn sibling_with(d: &mut Document, id: NodeId, pd: PathData) -> Result { + let mut n = d.node(id).ok_or(EngineError::NoNode(id))?.clone(); + n.id = d.alloc_id(); + match &mut n.kind { + NodeKind::Path { path, live, .. } => { + *path = pd; + *live = None; + } + NodeKind::Compound { children, .. } => *children = compound_members(d, pd), + _ => {} + } + Ok(n) +} + +/// Replace path or compound path `id` with `pieces` (first keeps the id, the rest go right above +/// it; none removes it). `cut` removes the path or puts the other pieces above it. Returns ids. +pub(in super::super) fn replace_with_pieces(d: &mut Document, cut: &mut Beside, id: NodeId, pieces: Vec) -> Result> { + let mut it = pieces.into_iter(); + let Some(first) = it.next() else { + cut.put(d, id, vec![])?; + return Ok(vec![]); + }; + let mut ids = vec![id]; + let mut above = vec![]; + for pd in it { + let n = sibling_with(d, id, pd)?; + ids.push(n.id); + above.push(n); + } + set_geometry(d, id, first)?; + if !above.is_empty() { + let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?; + cut.put(d, id, [n].into_iter().chain(above).collect())?; + } + Ok(ids) +} + +pub(in super::super) fn ids_json(ids: &[NodeId]) -> Value { + json!({ "ids": ids.iter().map(|i| i.0).collect::>() }) +} + +pub(super) fn stroke_paint(s: &Session) -> Paint { + if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() } +} + +pub(super) fn path_kind(path: PathData) -> NodeKind { + NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false } +} diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs new file mode 100644 index 0000000000..69306ce8f3 --- /dev/null +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -0,0 +1,328 @@ +use super::common::{ + dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, replace_with_pieces, sibling_with, target_paths, usize_opt, +}; +use super::*; + +/// Split a filled path into connected pieces (each outer contour with its holes). +pub(in super::super) fn components(pd: &PathData) -> Vec { + let subs: Vec<&SubPath> = pd.subpaths.iter().filter(|s| s.closed && s.anchors.len() >= 2).collect(); + if subs.len() <= 1 { + return if pd.is_empty() { vec![] } else { vec![pd.clone()] }; + } + let bps: Vec = subs + .iter() + .map(|s| { + let mut b = BezPath::new(); + s.to_bezpath_into(&mut b); + b + }) + .collect(); + let samples: Vec = subs.iter().map(|s| s.segment(0).eval(0.5)).collect(); + let n = subs.len(); + let inside = |j: usize, i: usize| fill_contains(&bps[j], FillRule::NonZero, samples[i]); + let depth: Vec = (0..n).map(|i| (0..n).filter(|&j| j != i && inside(j, i)).count()).collect(); + let areas: Vec = subs.iter().map(|s| s.area().abs()).collect(); + let outers: Vec = (0..n).filter(|&i| depth[i].is_multiple_of(2)).collect(); + let mut groups: Vec> = outers.iter().map(|&o| vec![subs[o].clone()]).collect(); + for h in (0..n).filter(|&i| !depth[i].is_multiple_of(2)) { + let best = outers + .iter() + .enumerate() + .filter(|(_, o)| depth[**o] + 1 == depth[h] && inside(**o, h)) + .min_by(|a, b| areas[*a.1].total_cmp(&areas[*b.1])); + if let Some((k, _)) = best { + groups[k].push(subs[h].clone()); + } + } + groups.into_iter().map(PathData::new).collect() +} + +/// The pieces of `sp` where `remove(point)` is false. `None` when nothing is removed. Each segment +/// is sampled at least every `step` pt (and at least 24 times), so a removed stretch at least +/// `step` long is found. +fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Option> { + let nseg = sp.segment_count(); + if nseg == 0 { + return sp.anchors.first().filter(|a| remove(a.p)).map(|_| vec![]); + } + const K: usize = 24; + const MAX_SAMPLES: usize = 4096; + let mut runs: Vec> = vec![]; + let mut cur: Vec<(usize, f64, f64)> = vec![]; + let mut any = false; + for i in 0..nseg { + let c = sp.segment(i); + // The curve moves at most 3 times its longest control-polygon edge per unit of t, so with + // n samples, neighboring samples are at most 3 · edge / n apart. + let edge = (c.p1 - c.p0).hypot().max((c.p2 - c.p1).hypot()).max((c.p3 - c.p2).hypot()); + let wanted = (3.0 * edge / step).ceil(); + let samples = if wanted.is_finite() && wanted > K as f64 { (wanted as usize).min(MAX_SAMPLES) } else { K }; + let mut prev_t = 0.0; + let mut prev_rm = remove(c.eval(0.0)); + let mut start = if prev_rm { None } else { Some(0.0) }; + if prev_rm { + any = true; + if !cur.is_empty() { + runs.push(std::mem::take(&mut cur)); + } + } + for k in 1..=samples { + let t = k as f64 / samples as f64; + let rm = remove(c.eval(t)); + if rm != prev_rm { + let (mut lo, mut hi) = (prev_t, t); + for _ in 0..30 { + let m = 0.5 * (lo + hi); + if remove(c.eval(m)) == prev_rm { lo = m } else { hi = m } + } + let b = 0.5 * (lo + hi); + if prev_rm { + start = Some(b); + } else { + any = true; + if let Some(s) = start.take() { + cur.push((i, s, b)); + } + runs.push(std::mem::take(&mut cur)); + } + } + prev_t = t; + prev_rm = rm; + } + if let Some(s) = start { + cur.push((i, s, 1.0)); + } + } + if !cur.is_empty() { + runs.push(cur); + } + runs.retain(|r| !r.is_empty()); + if !any { + return None; + } + // A closed path's last and first runs meet at anchor 0. + if sp.closed && runs.len() >= 2 { + let first_starts = runs.first().and_then(|r| r.first()).is_some_and(|s| s.0 == 0 && s.1 == 0.0); + let last_ends = runs.last().and_then(|r| r.last()).is_some_and(|s| s.0 + 1 == nseg && s.2 == 1.0); + if first_starts && last_ends { + let first = runs.remove(0); + if let Some(last) = runs.last_mut() { + last.extend(first); + } + } + } + let out = runs + .iter() + .filter(|r| r.len() > 1 || r[0].2 - r[0].1 > 1e-4) + .map(|r| { + let mut anchors: Vec = vec![]; + for &(i, t0, t1) in r { + let c = sp.segment(i).subsegment(t0..t1); + let (h1, h2) = if sp.segment_is_line(i) { (c.p0, c.p3) } else { (c.p1, c.p2) }; + match anchors.last_mut() { + Some(a) => a.h_out = h1, + None => anchors.push(Anchor { h_out: h1, ..Anchor::corner(c.p0) }), + } + anchors.push(Anchor { p: c.p3, h_in: h2, h_out: c.p3, kind: AnchorKind::Corner }); + } + for a in &mut anchors { + *a = Anchor::with_handles(a.p, a.h_in, a.h_out); + } + SubPath::new(anchors, false) + }) + .filter(|s| s.anchors.len() >= 2) + .collect(); + Some(out) +} + +/// Erase from an outline path (open or closed) where `remove` holds, sampling each segment at least +/// every `step` pt (`f64::INFINITY` for the fixed sampling). Returns the new geometry per output +/// object (one object per piece when the path had a single subpath), or None if unchanged. +pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool) -> Option> { + let mut changed = false; + let mut subs = vec![]; + for sp in &pd.subpaths { + match cut_subpath(sp, step, remove) { + Some(pieces) => { + changed = true; + subs.extend(pieces); + } + None => subs.push(sp.clone()), + } + } + if !changed { + return None; + } + Some(if pd.subpaths.len() == 1 { + subs.into_iter().map(PathData::single).collect() + } else if subs.is_empty() { + vec![] + } else { + vec![PathData::new(subs)] + }) +} + +// ---------- Scissors ---------- + +pub(super) fn split(s: &mut Session, p: &Value) -> Result { + const C: &str = "path.split"; + let id = id_param(p, "id").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)?; + if anchor.is_none() && seg.is_none() { + return Err(bad(C, "need `anchor` or `segment` + `t`")); + } + let t = f64_or(p, "t", 0.5); + if !t.is_finite() || p.get("t").is_some_and(|v| !v.is_f64() && !v.is_i64() && !v.is_u64()) { + return Err(bad(C, "invalid t")); + } + let ids = s.edit("Split Path", |d, sel| { + let path = path_mut(d, id)?; + let mut sp = path.subpaths.get(si).cloned().ok_or_else(|| EngineError::Other("no such subpath".into()))?; + let n = sp.anchors.len(); + let k = match (anchor, seg) { + (Some(a), _) if a < n => a, + (Some(_), _) => return Err(EngineError::Other("no such anchor".into())), + (None, Some(g)) if g < sp.segment_count() => { + if t <= 1e-6 { + g + } else if t >= 1.0 - 1e-6 { + (g + 1) % n + } else { + sp.insert_anchor(g, t) + } + } + _ => return Err(EngineError::Other("no such segment".into())), + }; + let mut pieces = sp.cut_at(&std::collections::BTreeSet::from([k])); + if sp.closed { + path.subpaths[si] = pieces.pop().ok_or_else(|| EngineError::Other("no such anchor".into()))?; + sel.set([id]); + return Ok(vec![id]); + } + let [left, right] = <[SubPath; 2]>::try_from(pieces).map_err(|_| EngineError::Other("cannot split an open path at its end point".into()))?; + if path.subpaths.len() == 1 { + path.subpaths[0] = left; + let node = sibling_with(d, id, PathData::single(right))?; + let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?; + let nid = d.insert(parent, idx + 1, node)?; + sel.set([id, nid]); + Ok(vec![id, nid]) + } else { + path.subpaths[si] = left; + path.subpaths.insert(si + 1, right); + sel.set([id]); + Ok(vec![id]) + } + })?; + Ok(ids_json(&ids)) +} + +// ---------- Knife / Eraser ---------- + +/// Width of the slit the knife leaves between pieces. +const KNIFE_GAP: f64 = 0.05; + +pub(super) fn knife(s: &mut Session, p: &Value) -> Result { + const C: &str = "path.knife"; + let pts = points_param(p, "points", C)?; + if pts.len() < 2 { + return Err(bad(C, "need at least two points")); + } + let st = s.doc()?; + let strip = po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), KNIFE_GAP, Cap::Butt, Join::Round, 4.0); + let mut plan: Vec<(NodeId, Vec)> = vec![]; + for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, 1.0)) { + let (pd, rule) = path_of(&st.doc, id)?; + if !pd.is_closed() { + continue; + } + let pieces = components(&po::boolean(&pd, rule, &strip, FillRule::NonZero, BoolOp::Difference)); + if pieces.len() >= 2 { + plan.push((id, pieces)); + } + } + if plan.is_empty() { + return Ok(json!({ "ids": [] })); + } + let ids = s.edit("Knife", |d, sel| { + let mut all = vec![]; + let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::>()); + for (id, pieces) in plan { + all.extend(replace_with_pieces(d, &mut cut, id, pieces)?); + } + cut.finish(d)?; + sel.set(all.iter().copied()); + Ok(all) + })?; + Ok(ids_json(&ids)) +} + +pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { + const C: &str = "path.eraseRegion"; + let pts = points_param(p, "points", C)?; + let size = number_or(p, "size", 10.0, C)?; + if !(size.is_finite() && size > 0.0) { + return Err(bad(C, "size must be positive")); + } + let angle = number_or(p, "angle", 0.0, C)?; + let roundness = number_or(p, "roundness", 100.0, C)?; + let r = size / 2.0; + // The tip's short axis: an open path is sampled at least every half of it. + let short = size * roundness.clamp(1.0, 100.0) / 100.0; + let st = s.doc()?; + let region = eraser_area(&pts, size, angle, roundness); + // A point is under the tip when, with the tip squashed back into a circle, it is within the + // circle's radius of the squashed drag. + let squash = eraser_tip(angle, roundness).inverse(); + let round: Vec = pts.iter().map(|q| squash * *q).collect(); + let mut plan: Vec<(NodeId, Vec)> = vec![]; + for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, r)) { + let (pd, rule) = path_of(&st.doc, id)?; + if pd.is_closed() { + if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { + continue; + } + plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference)))); + } else if let Some(pieces) = erase_outline(&pd, short / 2.0, &|q| dist_to_polyline(&round, squash * q) <= r) { + plan.push((id, pieces)); + } + } + apply_plan(s, "Eraser", plan) +} + +fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec)>) -> Result { + if plan.is_empty() { + return Ok(json!({ "ids": [] })); + } + let ids = s.edit(label, |d, sel| { + let mut all = vec![]; + let mut cut = Beside::replacing(d, &plan.iter().map(|(id, _)| *id).collect::>()); + for (id, pieces) in plan { + all.extend(replace_with_pieces(d, &mut cut, id, pieces)?); + } + cut.finish(d)?; + sel.set(all.iter().copied()); + Ok(all) + })?; + Ok(ids_json(&ids)) +} + +pub(super) fn erase_segments(s: &mut Session, p: &Value) -> Result { + const C: &str = "path.eraseSegments"; + let pts = points_param(p, "points", C)?; + let w = number_or(p, "width", 8.0, C)?; + if !(w.is_finite() && w > 0.0) { + return Err(bad(C, "width must be positive")); + } + let st = s.doc()?; + let mut plan = vec![]; + for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, w)) { + let (pd, _) = path_of(&st.doc, id)?; + if let Some(pieces) = erase_outline(&pd, w / 2.0, &|q| dist_to_polyline(&pts, q) <= w / 2.0) { + plan.push((id, pieces)); + } + } + apply_plan(s, "Path Eraser", plan) +} diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs new file mode 100644 index 0000000000..e6df1a60b5 --- /dev/null +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -0,0 +1,396 @@ +use super::common::{ + brush_region, path_kind, path_mut, path_of, points_param, poly_bounds, samples_param, stroke_paint, stroke_pressure, subpath_len, target_paths, + within_input_bound, +}; +use super::*; + +// ---------- Pencil / Paintbrush ---------- + +/// Fit a freehand polyline: drop jitter, build a spline through the samples (sharp turns stay +/// corners) and simplify it to `tol`. +fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath { + let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIDELITY * 0.3); + let (Some(&p0), Some(&pn)) = (pts.first(), pts.last()) else { return SubPath::new(vec![], closed) }; + let mut kept: Vec = vec![p0]; + for &p in pts.iter().skip(1) { + if kept.last().is_none_or(|k| k.distance(p) >= min) { + kept.push(p); + } + } + // The last sample always ends the stroke. + if kept.len() > 1 { + if let Some(k) = kept.last_mut() { + *k = pn; + } + } else if pts.len() > 1 { + kept.push(pn); + } + let n = kept.len(); + let marked: Vec<(Point, bool)> = (0..n) + .map(|i| { + let corner = if i == 0 || i + 1 == n { + false + } else { + let (a, b) = (kept[i] - kept[i - 1], kept[i + 1] - kept[i]); + a.dot(b) / (a.hypot() * b.hypot()).max(1e-12) < -0.2 // turn > ~100° + }; + (kept[i], corner) + }) + .collect(); + let sp = vectorcraft_tools::draw2::catmull_rom(&marked, closed); + if sp.anchors.len() < 3 { + return sp; + } + let fitted = po::simplify_with(&PathData::single(sp.clone()), &SimplifyOptions { tolerance: tol, corner_angle_deg: 60.0, straight_lines: false }); + fitted.subpaths.into_iter().next().filter(|s| s.anchors.len() >= 2).unwrap_or(sp) +} + +/// The path of a freehand stroke: fitted at `tol` ([`fit_freehand`]), or with no `tol` the points +/// joined by straight segments (`path.freehand` with `fit: false`). +fn stroke_subpath(pts: &[Point], tol: Option, closed: bool) -> SubPath { + match tol { + Some(tol) => fit_freehand(pts, tol, closed), + None => SubPath::new(pts.iter().map(|&p| Anchor::corner(p)).collect(), closed), + } +} + +/// Pencil's Edit Selected Paths in the middle of a path: a stroke from one point of a subpath of +/// `pd` to another, each within `within` of it, replaces the section between them (the shorter +/// way round a closed subpath) with the stroke fitted at `tol` (with no `tol`, unfitted). The +/// subpath's index and its new shape; None when the stroke doesn't start and end on the same +/// subpath, or meets it once. +fn redraw_section(pd: &PathData, pts: &[Point], tol: Option, within: f64) -> Option<(usize, SubPath)> { + use kurbo::ParamCurveArclen; + let (first, last) = (*pts.first()?, *pts.last()?); + let (si, _, _, _, d_a) = pd.nearest(first)?; + let (sj, _, _, _, d_b) = pd.nearest(last)?; + if si != sj || d_a > within || d_b > within || pts.len() < 2 { + return None; + } + let mut sp = pd.subpaths.get(si)?.clone(); + if sp.anchors.len() < 2 { + return None; + } + // The anchor nearest to `q`: the one there, else a new one, and whether it was added. Each + // point is looked up on the subpath as it is by then: splitting a straight segment makes two + // new ones, which a `t` along the old one doesn't measure. + let place = |sp: &mut SubPath, q: Point| { + let (_, seg, t, _, _) = PathData::single(sp.clone()).nearest(q)?; + let n = sp.anchors.len(); + Some(if t <= 1e-6 { + (seg % n, false) + } else if t >= 1.0 - 1e-6 { + ((seg + 1) % n, false) + } else { + (sp.insert_anchor(seg, t), true) + }) + }; + let (mut from, _) = place(&mut sp, first)?; + let (to, added) = place(&mut sp, last)?; + if added && to <= from { + from += 1; + } + if from == to { + return None; + } + let n = sp.anchors.len(); + // The length of the run of segments from anchor i forward to anchor j. + let run = |i: usize, j: usize| (0..(j + n - i) % n).map(|k| sp.segment((i + k) % n).arclen(0.01)).sum::(); + // The stroke goes from `start` to `end` and replaces the run between them; `kept` runs from + // `end` round to `start`, then the stroke's inner anchors follow. + let (start, end, reversed) = if sp.closed { + if run(from, to) <= run(to, from) { (from, to, false) } else { (to, from, true) } + } else if from < to { + (from, to, false) + } else { + (to, from, true) + }; + let mut stroke = pts.to_vec(); + if reversed { + stroke.reverse(); + } + let (Some(s0), Some(s1)) = (stroke.first_mut(), sp.anchors.get(start)) else { return None }; + *s0 = s1.p; + let (Some(e0), Some(e1)) = (stroke.last_mut(), sp.anchors.get(end)) else { return None }; + *e0 = e1.p; + let fit = stroke_subpath(&stroke, tol, false).anchors; + let (Some(f0), Some(f1)) = (fit.first().copied(), fit.last().copied()) else { return None }; + let inner = fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default(); + let (before, after): (Vec, Vec) = if sp.closed { + ((0..=(start + n - end) % n).filter_map(|k| sp.anchors.get((end + k) % n).copied()).collect(), vec![]) + } else { + (sp.anchors.get(..=start)?.to_vec(), sp.anchors.get(end..)?.to_vec()) + }; + let mut anchors = before; + if let Some(a) = anchors.last_mut() { + *a = Anchor::with_handles(a.p, a.h_in, f0.h_out); + } + anchors.extend_from_slice(inner); + let at_end = anchors.len(); + anchors.extend(after); + // The anchor the stroke ends on: the first after it, or round to the first of a closed one. + let end_at = if sp.closed { 0 } else { at_end }; + if let Some(a) = anchors.get_mut(end_at) { + *a = Anchor::with_handles(a.p, f1.h_in, a.h_out); + } + Some((si, SubPath::new(anchors, sp.closed))) +} + +pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { + const C: &str = "path.freehand"; + let samples = samples_param(p, "points", C)?; + if samples.iter().any(|(q, _)| !within_input_bound(*q)) { + return Err(bad(C, "x and y must be finite")); + } + let pressure = stroke_pressure(&samples); + let mut pts: Vec = samples.into_iter().map(|(pt, _)| pt).collect(); + let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0); + // 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)?; + let brush = str_param(p, "style") == Some("brush"); + 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 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"))?; + let mut sp = pd.subpaths[si].clone(); + let old_len = subpath_len(&sp); + if at_start { + sp.reverse(); + } + let (Some(first), Some(end)) = (sp.anchors.first().map(|a| a.p), sp.anchors.last().map(|a| a.p)) else { + return Err(bad(C, "path has no open end")); + }; + let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) }; + *p0 = end; + if pts.len() < 2 { + return Ok(json!({ "id": id.0 })); + } + // A stroke that ends on an open end of another path connects the two: (that path, its last + // 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"))?; + if other == id { + return Err(bad(C, "connect needs a path other than the one extended")); + } + let (opd, _) = path_of(&s.doc()?.doc, other)?; + let osi = + opd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "connect path has no open end"))?; + let mut y = opd.subpaths[osi].clone(); + let at_end = match str_param(cn, "end") { + Some("start") => false, + Some("end") => true, + _ => return Err(bad(C, "connect end must be \"start\" or \"end\"")), + }; + if at_end { + y.reverse(); + } + Some((other, osi, y, at_end)) + } + None => None, + }; + let close_tol = (tol * 4.0).max(6.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; + } + if let Some((_, _, y, _)) = &connect + && let (Some(l), Some(y0)) = (pts.last_mut(), y.anchors.first()) + { + *l = y0.p; + } + let fit = stroke_subpath(&pts, fit_tol, false); + let mut add = fit.anchors; + if let (Some(last), Some(a0)) = (sp.anchors.last_mut(), add.first()) { + last.h_out = a0.h_out; + } + if !add.is_empty() { + add.remove(0); + } + sp.anchors.extend(add); + if closing + && sp.anchors.len() > 2 + && let Some(l) = sp.anchors.pop() + && let Some(a0) = sp.anchors.first_mut() + { + a0.h_in = l.h_in; + sp.closed = true; + } + for a in &mut sp.anchors { + *a = Anchor::with_handles(a.p, a.h_in, a.h_out); + } + let drawn_len = subpath_len(&sp); + // The other path's anchors follow on from the one the stroke ends on, which takes its + // outgoing handle. + let mut other_len = 0.0; + if let Some((_, _, y, _)) = &connect + && let Some((y0, rest)) = y.anchors.split_first() + { + if let Some(last) = sp.anchors.last_mut() { + *last = Anchor::with_handles(y0.p, last.h_in + (y0.p - last.p), y0.h_out); + } + sp.anchors.extend_from_slice(rest); + other_len = subpath_len(y); + } + // The path's pressure (in the direction it is continued in) followed by the stroke's, and + // by the pressure of the path it connects to. + let pressure_of = |n: NodeId| s.doc().ok()?.doc.node(n).and_then(|n| n.appearance.stroke()).and_then(|st| st.pressure.clone()); + let old_pressure = pressure_of(id); + let other_pressure = connect.as_ref().and_then(|(o, _, _, at_end)| pressure_of(*o).map(|p| if *at_end { p.reversed() } else { p })); + let joined = (old_pressure.is_some() || pressure.is_some() || other_pressure.is_some()).then(|| { + let old = old_pressure.map(|p| if at_start { p.reversed() } else { p }); + let drawn = PressureProfile::extended(old.as_ref(), old_len, pressure.as_ref(), drawn_len - old_len); + if connect.is_some() { PressureProfile::extended(drawn.as_ref(), drawn_len, other_pressure.as_ref(), other_len) } else { drawn } + }); + s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| { + let reverse = at_start && !sp.closed; + if reverse { + sp.reverse(); + } + path_mut(d, id)?.subpaths[si] = sp; + if let Some((other, osi, ..)) = &connect { + let o = path_mut(d, *other)?; + if *osi < o.subpaths.len() { + o.subpaths.remove(*osi); + } + if o.is_empty() { + d.remove(*other)?; + sel.remove(*other); + } + // Direct-selected anchors and segments of the subpaths after the one removed move + // down one; those of the one removed go, and a path left with no selected anchors + // is no longer selected. + let shift = |refs: &mut BTreeSet<(usize, usize)>| { + *refs = refs.iter().filter(|r| r.0 != *osi).map(|&(sub, i)| if sub > *osi { (sub - 1, i) } else { (sub, i) }).collect(); + }; + if let Some(refs) = sel.anchors.get_mut(other) { + shift(refs); + } + if let Some(refs) = sel.segments.get_mut(other) { + shift(refs); + } + if sel.anchors.get(other).is_some_and(BTreeSet::is_empty) { + sel.remove(*other); + } + } + if let Some(joined) = joined + && let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) + { + st.pressure = if reverse { joined.map(|p| p.reversed()) } else { joined }; + } + if keep_selected { + sel.set([id]); + } else { + sel.remove(id); + } + Ok(()) + })?; + 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 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")); + } + let (pd, _) = path_of(&s.doc()?.doc, id)?; + // shortcut: a stroke pressure profile is left as it was, measured along the old path; fit + // it to the new length if Calligraphic pressure strokes get redrawn. + if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within) { + s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| { + *path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| bad(C, "no such subpath"))? = sp; + // A member path of a compound path is redrawn in it: the compound path is what is + // selected. + let whole = d.parent_of(id).filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id); + if keep_selected { + sel.set([whole]); + } else { + sel.remove(whole); + } + Ok(()) + })?; + return Ok(json!({ "id": id.0 })); + } + } + if pts.len() < 2 { + return Err(bad(C, "need at least two points")); + } + let sp = stroke_subpath(&pts, fit_tol, closed); + let fill = if filled { s.paint.fill.clone() } else { Paint::None }; + // A pencil path with a fill keeps a stroke of None (#1679); only one that would show nothing + // gets black. A brush is its stroke. + let stroke = if brush || fill.is_none() { stroke_paint(s) } else { s.paint.stroke.clone() }; + let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1)); + if let Some(st) = look.appearance.stroke_mut() { + st.pressure = pressure; + } + insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected) +} + +// ---------- Blob Brush ---------- + +pub(super) fn blob(s: &mut Session, p: &Value) -> Result { + const C: &str = "path.blob"; + let pts = points_param(p, "points", C)?; + let size = number_or(p, "size", 10.0, C)?; + if !(size.is_finite() && size > 0.0) { + return Err(bad(C, "size must be positive")); + } + let region = brush_region(&pts, size); + if region.is_empty() { + return Err(EngineError::Other("empty brush stroke".into())); + } + let paint = if !s.paint.stroke.is_none() { + s.paint.stroke.clone() + } else if !s.paint.fill.is_none() { + s.paint.fill.clone() + } else { + Paint::solid(Color::BLACK) + }; + let keep_selected = switch_or(p, "keepSelected", false, C)?; + let only_selection = switch_or(p, "mergeOnlySelection", false, C)?; + let merge = switch_or(p, "merge", true, C)?; + let st = s.doc()?; + let mut merge_ids = vec![]; + if merge && !(only_selection && st.selection.is_empty()) { + let all = Selection::default(); + let from = if only_selection { &st.selection } else { &all }; + for id in target_paths(&st.doc, from, poly_bounds(&pts, size)) { + let Some(n) = st.doc.node(id) else { continue }; + if n.appearance.fill_paint() != paint || !n.appearance.stroke_paint().is_none() { + continue; + } + let (pd, rule) = path_of(&st.doc, id)?; + if pd.is_closed() && po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) > 1e-6 { + merge_ids.push((id, pd, rule)); + } + } + } + let ap = NewArt::plain(Appearance::basic(paint, Paint::None, 1.0)); + if merge_ids.is_empty() { + return insert_look(s, "Blob Brush", path_kind(region), ap, None, keep_selected); + } + let mut inputs: Vec<(&PathData, FillRule)> = vec![(®ion, FillRule::NonZero)]; + inputs.extend(merge_ids.iter().map(|(_, pd, r)| (pd, *r))); + let merged = po::try_unite_all(&inputs).map_err(|e| EngineError::Other(e.to_string()))?; + let Some(((keep, _, _), rest)) = merge_ids.split_last() else { + return insert_look(s, "Blob Brush", path_kind(region), ap, None, keep_selected); + }; + let keep = *keep; + let others: Vec = rest.iter().map(|m| m.0).collect(); + s.edit("Blob Brush", |d, sel| { + *path_mut(d, keep)? = merged; + remove_each(d, &others)?; + if keep_selected { + sel.set([keep]); + } else { + sel.remove(keep); + } + Ok(()) + })?; + Ok(json!({ "id": keep.0 })) +} diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs new file mode 100644 index 0000000000..e206654470 --- /dev/null +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -0,0 +1,284 @@ +use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, target_paths}; +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 { + let piece = PathData::single(SubPath::new(anchors.to_vec(), false)); + let fitted = po::simplify_with(&piece, &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false }); + let 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; + out[0].p = f.p; + out[0].h_in = f.h_in; + out[last].p = l.p; + out[last].h_out = l.h_out; + for a in &mut out { + *a = Anchor::with_handles(a.p, a.h_in, a.h_out); + } + out +} + +fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Option { + let n = sp.anchors.len(); + let marked: Vec = sp.anchors.iter().map(|a| near(a.p)).collect(); + if n < 3 || !marked.iter().any(|m| *m) { + return None; + } + 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 }); + return f.subpaths.into_iter().next(); + }; + // Rotate so an untouched anchor comes first, duplicate it at the end and treat as open. + let mut open = sp.clone(); + open.anchors.rotate_left(k); + let mut m = marked.clone(); + m.rotate_left(k); + open.anchors.push(open.anchors[0]); + m.push(false); + open.closed = false; + let mut res = smooth_open(&open.anchors, &m, near, tol); + 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)) +} + +/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it +/// enters the reach: the part outside, then the part in reach. `None` when no more than a sliver +/// is outside. +fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez, CubicBez)> { + const STEPS: u32 = 32; + let step = 1.0 / f64::from(STEPS); + // Back from the end in reach to the first sample outside, then halving to the crossing. + let outside = (1..=STEPS).map(|i| 1.0 - f64::from(i) * step).find(|t| !near(c.eval(*t)))?; + let (mut lo, mut hi) = (outside, outside + step); + for _ in 0..20 { + let mid = (lo + hi) / 2.0; + if near(c.eval(mid)) { + hi = mid; + } else { + lo = mid; + } + } + // A straight segment's parts stay straight, their handles on their ends. + let straight = c.p1 == c.p0 && c.p2 == c.p3; + let part = |range| { + let s = c.subsegment(range); + if straight { CubicBez::new(s.p0, s.p0, s.p3, s.p3) } else { s } + }; + (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 { + let n = anchors.len(); + let mut runs = vec![]; + let mut i = 0; + while i < n { + if marked[i] { + let a = i; + while i + 1 < n && marked[i + 1] { + i += 1; + } + runs.push((a, i)); + } + i += 1; + } + let mut out = anchors.to_vec(); + for (a, b) in runs.into_iter().rev() { + let lo = a.saturating_sub(1); + let hi = (b + 1).min(n - 1); + if hi - lo < 2 { + continue; + } + let mut piece = out[lo..=hi].to_vec(); + // The anchors outside the reach, kept with the part of their segment that is outside. + let (mut head, mut tail) = (None, None); + if hi > b + && let [.., inner, outer] = piece.as_mut_slice() + && let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_in, inner.h_out, inner.p), near) + { + inner.h_out = reach.p2; + tail = Some(Anchor { h_in: far.p1, ..*outer }); + *outer = Anchor::with_handles(far.p3, reach.p1, far.p2); + } + if lo < a + && let [outer, inner, ..] = piece.as_mut_slice() + && let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_out, inner.h_in, inner.p), near) + { + inner.h_in = reach.p2; + head = Some(Anchor { h_out: far.p1, ..*outer }); + *outer = Anchor::with_handles(far.p3, far.p2, reach.p1); + } + let new = refit_run(&piece, tol); + out.splice(lo..=hi, head.into_iter().chain(new).chain(tail)); + } + out +} + +pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { + const C: &str = "path.smoothRegion"; + 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 st = s.doc()?; + let near = |q: Point| dist_to_polyline(&pts, q) <= radius; + let mut plan = vec![]; + let (mut before, mut after) = (0, 0); + for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, radius)) { + let (pd, _) = path_of(&st.doc, id)?; + let mut changed = false; + let subs: Vec = pd + .subpaths + .iter() + .map(|sp| match smooth_subpath(sp, &near, tol) { + Some(n) if n != *sp && n.anchors.len() >= 2 => { + changed = true; + n + } + _ => sp.clone(), + }) + .collect(); + if changed { + let np = PathData::new(subs); + before += pd.anchor_count(); + after += np.anchor_count(); + plan.push((id, np)); + } + } + if plan.is_empty() { + return Ok(json!({ "ids": [], "before": 0, "after": 0 })); + } + let ids: Vec = plan.iter().map(|(id, _)| *id).collect(); + s.edit("Smooth", |d, _| { + for (id, np) in plan { + *path_mut(d, id)? = np; + } + Ok(()) + })?; + let mut v = ids_json(&ids); + v["before"] = json!(before); + v["after"] = json!(after); + Ok(v) +} + +// ---------- Join tool ---------- + +pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result { + const C: &str = "path.joinScrub"; + let pts = points_param(p, "points", C)?; + let tol = number_or(p, "tolerance", 12.0, C)?.max(0.0); + let st = s.doc()?; + // Open endpoints near the scrub, ordered along it: (order, id, subpath, at_start). + let poly = { + let mut bp = BezPath::new(); + bp.move_to(pts[0]); + for q in &pts[1..] { + bp.line_to(*q); + } + bp + }; + let order = |q: Point| -> f64 { + poly.segments() + .enumerate() + .map(|(i, sg)| (i as f64 + sg.nearest(q, 1e-6).t, sg.nearest(q, 1e-6).distance_sq)) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map_or(0.0, |x| x.0) + }; + let (first_pt, last_pt) = (pts.first().copied(), pts.last().copied()); + let mut ends: Vec<(f64, NodeId, usize, bool, Point)> = vec![]; + for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol)) { + let (pd, _) = path_of(&st.doc, id)?; + for (si, sp) in pd.subpaths.iter().enumerate() { + if sp.closed || sp.anchors.len() < 2 { + continue; + } + for (start, a) in [(true, sp.anchors[0].p), (false, sp.anchors[sp.anchors.len() - 1].p)] { + let on_scrub = dist_to_polyline(&pts, a) <= tol; + let near_start = first_pt.is_some_and(|p| a.distance(p) <= tol); + let near_end = last_pt.is_some_and(|p| a.distance(p) <= tol); + if !on_scrub && !near_start && !near_end { + continue; + } + let ord = if on_scrub { + order(a) + } else if near_start && (!near_end || first_pt.is_some_and(|p| a.distance(p) <= a.distance(last_pt.unwrap_or(p)))) { + -1.0 + } else { + 1e30 + }; + ends.push((ord, id, si, start, a)); + } + } + } + ends.sort_by(|a, b| a.0.total_cmp(&b.0)); + if ends.len() < 2 { + return Ok(json!({ "id": null })); + } + let (_, ida, sa, starta, pa) = ends[0]; + let (_, idb, sb, startb, pb) = ends[1]; + let mid = pa.midpoint(pb); + let merge = pa.distance(pb) <= tol; + s.edit("Join", |d, sel| { + if ida == idb && sa == sb { + let path = path_mut(d, ida)?; + let sp = &mut path.subpaths[sa]; + if merge + && sp.anchors.len() > 2 + && let Some(l) = sp.anchors.pop() + { + let d0 = mid - sp.anchors[0].p; + sp.anchors[0].translate(d0); + sp.anchors[0].h_in = l.h_in + (mid - l.p); + } + sp.closed = true; + sel.set([ida]); + return Ok(()); + } + let (pdb, _) = path_of(d, idb)?; + let mut x = path_of(d, ida)?.0.subpaths[sa].clone(); + let mut y = pdb.subpaths[sb].clone(); + if starta { + x.reverse(); + } + if !startb { + y.reverse(); + } + if merge + && !y.anchors.is_empty() + && let Some(last) = x.anchors.last_mut() + { + let yf = y.anchors.remove(0); + let lp = last.p; + last.translate(mid - lp); + last.h_out = yf.h_out + (mid - yf.p); + *last = Anchor::with_handles(last.p, last.h_in, last.h_out); + } + x.anchors.extend(y.anchors); + if ida == idb { + let path = path_mut(d, ida)?; + path.subpaths[sa] = x; + path.subpaths.remove(sb); + } else { + path_mut(d, ida)?.subpaths[sa] = x; + let pbm = path_mut(d, idb)?; + pbm.subpaths.remove(sb); + if pbm.is_empty() { + d.remove(idb)?; + } + } + sel.set([ida]); + Ok(()) + })?; + Ok(json!({ "id": ida.0 })) +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 7798c229a6..fa4878d2c9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -11,6 +11,7 @@ use super::clipboard::SwatchChoices; use super::*; use crate::{Clipboard, EngineError, inspect}; +/// Register editing commands, including document-to-document artwork drops and their parameter contracts. pub fn specs() -> Vec { vec![ cmd!( @@ -24,9 +25,9 @@ pub fn specs() -> Vec { ), cmd!("file.close", "Close", ["File"], Some("Cmd+W"), "{index?}", has_doc, file_close), cmd!("document.activate", "Activate Document", [], None, "{index}", always, doc_activate), - 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 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)} → 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, limit?: max matches (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total}", has_doc, doc_find), + cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find), cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model", has_doc, |s, _| Ok(serde_json::to_value(&*s.doc()?.doc).unwrap_or(Value::Null))), cmd!( "document.setUnits", @@ -73,6 +74,15 @@ pub fn specs() -> Vec { has_doc, global_rulers ), + cmd!( + "edit.dropSelection", + "Drop Artwork", + [], + None, + "{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y]} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step", + has_doc, + drop_selection + ), cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, undo), cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, redo), cmd!( @@ -89,8 +99,8 @@ pub fn specs() -> Vec { "Begin Undo Group", [], None, - "{label?: string} until edit.undoGroup.end, the edits made in the active document are one undo step, named `label` (else after its first edit): for automation, such as MCP command_batch with `atomic` (#1163)", - has_doc, + "{label?: string} until edit.undoGroup.end, the edits made in the document active at the begin, and in each document opened or created before then (also when no document is open; the edits of a command that opens a document and edits it stay that command's undo step), are one undo step in that document, named `label` (else after its first edit); in a document that was open before the begin and is switched to (document.activate), each edit stays its own undo step: for automation, such as MCP command_batch with `atomic` (#1163)", + always, undo_group_begin ), cmd!( @@ -99,7 +109,7 @@ pub fn specs() -> Vec { [], None, "{cancel?: bool} close the undo group: its edits stay one undo step or, with `cancel`, are undone", - has_doc, + always, undo_group_end ), cmd!("edit.cut", "Cut", ["Edit"], Some("Cmd+X"), "{} (the Artboard tool chosen: artboard.cut)", has_selection_or_artboard_tool, cut), @@ -109,7 +119,7 @@ pub fn specs() -> Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [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 (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 → {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], 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 (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) ), @@ -136,7 +146,7 @@ pub fn specs() -> Vec { "Paste in Place", ["Edit"], Some("Cmd+Shift+V"), - "{swatchConflict?, artboard?: index (as edit.pasteInFront)} paste where the objects were copied (resources and layers as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, artboard?: index (as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::InPlace) ), @@ -145,7 +155,7 @@ pub fn specs() -> Vec { "Paste on All Artboards", ["Edit"], Some("Cmd+Alt+Shift+V"), - "{swatchConflict?} paste a copy on every artboard at the offset the objects had to the artboard they were copied from (resources and layers as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?} paste a copy on every artboard at the offset the objects had to the artboard they were copied from (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::AllArtboards) ), @@ -171,7 +181,7 @@ pub fn specs() -> Vec { } fn file_close(s: &mut Session, p: &Value) -> Result { - let i = p.get("index").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?; + let i = p.get("index").and_then(Value::as_u64).map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?; if !s.close_document(i) { return Err(bad("file.close", "no such document")); } @@ -179,7 +189,7 @@ fn file_close(s: &mut Session, p: &Value) -> Result { } fn doc_activate(s: &mut Session, p: &Value) -> Result { - let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("document.activate", "missing index"))? as usize; + let i = p.get("index").and_then(Value::as_u64).map(index).ok_or_else(|| bad("document.activate", "missing index"))?; if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) } } @@ -233,19 +243,82 @@ fn opt_u64(p: &Value, cmd: &str, key: &str) -> Result> { } fn doc_find(s: &mut Session, p: &Value) -> Result { + const C: &str = "document.find"; // A filter of the wrong type is an error, not dropped: dropping it would widen the search. let needle = |key: &str| match p.get(key) { None | Some(Value::Null) => Ok(None), Some(Value::String(v)) => Ok(Some(v.to_lowercase()).filter(|v| !v.is_empty())), - Some(_) => Err(bad("document.find", format!("`{key}` must be a string"))), + Some(_) => Err(bad(C, format!("`{key}` must be a string"))), }; - let filter = inspect::FindFilter { name: needle("name")?, kind: needle("kind")?, text: needle("text")? }; - if filter.is_empty() { - return Err(bad("document.find", "give at least one of `name`, `kind`, `text`")); + let rect = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => match finite_numbers::<4>(v) { + Some([x, y, w, h]) if w >= 0.0 && h >= 0.0 => Ok(Some(vectorcraft_geom::Rect::new(x, y, x + w, y + h))), + _ => Err(bad(C, format!("`{key}` must be [x, y, width, height]: four finite numbers, width and height not negative"))), + }, + }; + let bound = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_f64().filter(|n| n.is_finite() && *n >= 0.0).map(Some).ok_or_else(|| bad(C, format!("`{key}` must be a number not below 0"))), + }; + let range = |name: &str| -> Result { + let (min_key, max_key) = (format!("min{name}"), format!("max{name}")); + let r = inspect::FindRange { min: bound(&min_key)?, max: bound(&max_key)? }; + if let (Some(min), Some(max)) = (r.min, r.max) + && min > max + { + return Err(bad(C, format!("`{min_key}` is greater than `{max_key}`"))); + } + Ok(r) + }; + let anchors = range("Anchors")?; + if [anchors.min, anchors.max].iter().flatten().any(|n| n.fract() != 0.0) { + return Err(bad(C, "`minAnchors` and `maxAnchors` must be whole numbers")); } - let limit = opt_u64(p, "document.find", "limit")?.unwrap_or(100); - let (matches, total) = inspect::find_nodes(&s.doc()?.doc, &filter, limit); - Ok(json!({"matches": matches, "total": total})) + let filter = inspect::FindFilter { + name: needle("name")?, + kind: needle("kind")?, + text: needle("text")?, + within: rect("within")?, + intersects: rect("intersects")?, + width: range("Width")?, + height: range("Height")?, + thickness: range("Thickness")?, + area: range("Area")?, + anchors, + }; + if filter.is_empty() { + return Err(bad( + C, + "give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors`", + )); + } + let select = match p.get("select") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad(C, "`select` must be true or false"))?, + }; + let limit = opt_u64(p, C, "limit")?.unwrap_or(100); + let (matches, ids) = inspect::find_nodes(&s.doc()?.doc, &filter, limit); + let mut reply = json!({"matches": matches, "total": ids.len()}); + if select { + reply["selected"] = select_found(s, p, &ids)?["count"].clone(); + s.journal_query(); + } + Ok(reply) +} + +/// Select the objects among `ids` that Select All and the objects inside them take (none hidden or +/// locked, nor inside a hidden or locked one), leaving out those inside another of them and the +/// members of compound paths, unless a compound path is isolated. Select > Reselect repeats +/// `document.find` with `p`. +fn select_found(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result { + let st = s.doc()?; + let compound = |n: &Node| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }); + let members = st.isolation.and_then(|i| st.doc.ancestry(i)).is_some_and(|a| a.iter().any(|i| st.doc.node(*i).is_some_and(compound))); + let found: BTreeSet = ids.iter().copied().collect(); + super::select::select_where(s, "document.find", p, |d, n| { + found.contains(&n.id) && (members || !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound)) + }) } /// Document Setup's units (also `document.setup {units}`). @@ -354,6 +427,7 @@ fn undo_group_begin(s: &mut Session, p: &Value) -> Result { Some(Value::String(l)) if !l.trim().is_empty() && l.chars().count() <= 200 => Some(l.trim().to_string()), Some(_) => return Err(bad(C, "`label` must be a non-empty name of at most 200 characters")), }; + s.explicit_undo_group = Some(label.clone()); s.begin_named_undo_group(label); ok() } @@ -380,7 +454,7 @@ pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> { fn undo(s: &mut Session, _: &Value) -> Result { settle_interaction(s)?; - let guides_locked = s.menu.guides_locked; + let menu = s.menu.clone(); let st = s.doc_mut()?; let e = st.history.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; let label = e.label.clone(); @@ -395,17 +469,18 @@ fn undo(s: &mut Session, _: &Value) -> Result { st.history.trim(); st.revision += 1; st.selection.prune(&st.doc); - // Guides locked since the step was made stay deselected. - if guides_locked { - crate::deselect_guides(&st.doc, &mut st.selection); - } + // Guides locked and slices locked or hidden since the step was made stay deselected. + crate::deselect_hidden(&menu, &st.doc, &mut st.selection); + st.sync_new_art(); super::maskedit::follow_history(st, editing); + leave_isolation_if_gone(st); + super::globaledit::follow_history(st); Ok(json!({ "undone": label })) } fn redo(s: &mut Session, _: &Value) -> Result { settle_interaction(s)?; - let guides_locked = s.menu.guides_locked; + let menu = s.menu.clone(); let st = s.doc_mut()?; let e = st.history.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; let label = e.label.clone(); @@ -420,13 +495,23 @@ fn redo(s: &mut Session, _: &Value) -> Result { st.history.trim(); st.revision += 1; st.selection.prune(&st.doc); - if guides_locked { - crate::deselect_guides(&st.doc, &mut st.selection); - } + crate::deselect_hidden(&menu, &st.doc, &mut st.selection); + st.sync_new_art(); super::maskedit::follow_history(st, editing); + leave_isolation_if_gone(st); + super::globaledit::follow_history(st); Ok(json!({ "redone": label })) } +/// After undo or redo, isolation mode ends when the isolated object is no longer in the document, +/// such as the clip group Draw Inside made around the isolated object (#3705), rather than naming +/// an id a later object may take. +fn leave_isolation_if_gone(st: &mut crate::DocState) { + if st.isolation.is_some_and(|i| st.doc.node(i).is_none()) { + st.isolation = None; + } +} + /// History panel › Clear History: removes the steps after the current state and the steps before /// it, and leaves the document as it is. Typing or a drag still in progress is first kept as a /// step, as Undo keeps it, so it is removed with the others and its change stays in the document. @@ -569,6 +654,40 @@ fn clear(s: &mut Session, p: &Value) -> Result { ok() } +/// Document ids scope node ids: two tabs may contain objects with the same node id. +fn drop_selection(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "edit.dropSelection"; + let key = "sourceDocument"; + let uid = p[key].as_u64().ok_or_else(|| bad(CMD, format!("missing integer `{key}`")))?; + let point = |key: &str| finite_numbers::<2>(&p[key]).ok_or_else(|| bad(CMD, format!("{key} must be [x, y] with finite coordinates"))); + let grab = point("grab")?; + let at = point("at")?; + let source = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| bad(CMD, "that document is no longer open"))?; + let key = "ids"; + let values = p[key].as_array().ok_or_else(|| bad(CMD, format!("{key} must be an array of non-negative integer object ids")))?; + if values.is_empty() || values.len() > 10000 { + return Err(bad(CMD, "ids must contain 1–10000 object ids")); + } + let ids = values + .iter() + .map(|value| value.as_u64().map(NodeId).ok_or_else(|| bad(CMD, format!("invalid object id {value}: expected a non-negative integer")))) + .collect::>>()?; + // Validate the entire batch in one walk; node ids are local to the source document. + let paths = source.doc.index_paths(ids.iter().copied()); + if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) { + return Err(EngineError::NoNode(*id)); + } + let clip = Clipboard::copy(source, &roots_of(&source.doc, ids)); + let bounds = clip.bounds().ok_or_else(|| bad(CMD, "the art has no bounds"))?; + let center = bounds.center() + Vec2::new(at[0] - grab[0], at[1] - grab[1]); + if !center.x.is_finite() || !center.y.is_finite() { + return Err(bad(CMD, "result would exceed the canvas (coordinates out of range)")); + } + // A drop preserves the source colours even when the flyer has same-named swatches. + let choices = SwatchChoices::parse(PasteMode::Drag.label(), &json!({"swatchConflict": "add"}))?; + paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, &clip, &choices) +} + #[derive(Clone, Copy, PartialEq, Eq)] enum PasteMode { Offset, @@ -578,9 +697,11 @@ enum PasteMode { AllArtboards, /// A graphic from the Libraries panel: centred where it is placed, as Paste centres. Library, + Drag, } impl PasteMode { + /// Return the user-visible action label for this insertion mode. fn label(self) -> &'static str { match self { PasteMode::Front => "Paste in Front", @@ -589,6 +710,7 @@ impl PasteMode { PasteMode::AllArtboards => "Paste on All Artboards", PasteMode::Offset => "Paste", PasteMode::Library => "Place from Library", + PasteMode::Drag => "Drop Artwork", } } } @@ -621,6 +743,7 @@ fn onto_artboard(doc: &Document, p: &Value, clip: &Clipboard) -> Affine { } } +/// Insert clipboard resources atomically in the active editable context using the requested placement mode. fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, choices: &SwatchChoices) -> Result { let off = s.prefs.paste_offset; let st = s.doc()?; @@ -636,22 +759,34 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho .reduce(|a, b| a.union(b)) .filter(|_| mode != PasteMode::AllArtboards) .map(|all| (&clip.artboards, if mode == PasteMode::Offset { super::panelcmds::beside_artboards(&st.doc, all) } else { Vec2::ZERO })); - // Paste Remembers Layers (not while isolating a group: pastes stay in it); an artboard's art - // always goes back into its layers. - let remember = (st.doc.paste_remembers_layers || boards.is_some()) && parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer)); + // Drawing modes (#3705): Draw Inside puts what Paste, Paste in Place and Paste on All + // Artboards bring inside the object it draws into; Draw Behind puts what Paste in Place and + // Paste on All Artboards bring behind the selection, as Paste in Back does. Paste in Front and + // Paste in Back keep their own places, and copied artboards' art goes back into its layers. + let modal = boards.is_none() && matches!(mode, PasteMode::Offset | PasteMode::InPlace | PasteMode::AllArtboards); + // (Only with objects to paste: an artboard copied without art makes no clip group.) + let inside = s.draw_inside.filter(|t| modal && !clip.nodes.is_empty() && s.draw_mode == crate::DrawMode::Inside && st.doc.node(*t).is_some()); + let behind = modal && mode != PasteMode::Offset && s.draw_mode == crate::DrawMode::Behind; + let (front, back) = (mode == PasteMode::Front, mode == PasteMode::Back || behind); + // Paste Remembers Layers (not while isolating a group: pastes stay in it, nor in Draw + // Inside); an artboard's art always goes back into its layers. + // A drop goes into the current editable insertion context, not a same-named source layer. + let remember = mode != PasteMode::Drag + && 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)); // Front/back: relative to the selection (top-most / bottom-most selected object); with // nothing selected, the top / bottom of the current layer. - let anchor = match mode { - PasteMode::Front | PasteMode::Back => { - let order = st.selection.in_paint_order(&st.doc); - let a = if mode == PasteMode::Front { order.last() } else { order.first() }; - a.and_then(|id| st.doc.position(*id)) - } - _ => None, + let anchor = if front || back { + let order = st.selection.in_paint_order(&st.doc); + let a = if front { order.last() } else { order.first() }; + a.and_then(|id| st.doc.position(*id)) + } else { + None }; let placements: Vec = match (mode, boards) { (_, Some((_, dv))) => vec![Affine::translate(dv)], - (PasteMode::Offset | PasteMode::Library, None) => vec![match point_param(p, "center") { + (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))), }], @@ -662,8 +797,10 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho // In place, in front, in back: onto the active artboard when the UI names it. _ => vec![onto_artboard(&st.doc, p, clip)], }; - let (ids, imported, artboards) = s.edit(mode.label(), |d, sel| { + let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| { let imported = clip.import_into(d, choices, same_doc); + // Draw Inside: the clip group of the object drawn into, made on the first paste. + let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?; let artboards: Vec = boards .into_iter() .flat_map(|(all, dv)| all.iter().map(move |a| (a, dv))) @@ -678,21 +815,25 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho let mut c = d.reid(n); imported.apply(&mut c); if xf != Affine::IDENTITY { - c.transform(xf, false); + // A cross-document drag carries the graphic's appearance with it, + // including the pattern phase, independently of transform-tool settings. + c.transform(xf, vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() }); } let layer = match clip.source_layers.get(k) { Some(Some(name)) if remember => Some(*layers.entry(name).or_insert_with(|| layer_named(d, name))), _ => None, }; - let (par, idx) = match (anchor, layer) { + let (par, idx) = match (into, anchor, layer) { + // Inside the object Draw Inside draws into, on top of what is in it already. + (Some(group), ..) => (Some(group), usize::MAX), // Next to the anchor, unless the object goes back to another layer. - (Some((par, i, _)), l) if l.is_none() || l == par => { + (None, Some((par, i, _)), l) if l.is_none() || l == par => { let k = placed.get(&par).copied().unwrap_or(0); - (par, if mode == PasteMode::Front { i + 1 + k } else { i + k }) + (par, if front { i + 1 + k } else { i + k }) } - (_, l) => { + (None, _, l) => { let par = l.or(parent); - (par, if mode == PasteMode::Back { placed.get(&par).copied().unwrap_or(0) } else { usize::MAX }) + (par, if back { placed.get(&par).copied().unwrap_or(0) } else { usize::MAX }) } }; *placed.entry(par).or_default() += 1; @@ -703,8 +844,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho // Pasted type arrives without the layout bounds cache: fill it so boxes and alignment are // right away (opening the file later would, but paste must not depend on a reopen). super::typecmd::refresh_bounds_of(d, &new_ids); - Ok((new_ids, imported, artboards)) + Ok((new_ids, imported, artboards, into)) })?; + if let (Some(target), Some(group)) = (inside, into) { + super::create::isolate_draw_inside_group(s, target, group)?; + } // The Artboard tool selects the pasted artboards, the first one active. if !artboards.is_empty() && s.tool_id() == "artboard" { s.set_tool_option("selected", &json!(artboards)); @@ -752,7 +896,7 @@ pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selectio /// document, each original and its copy before the copy goes in, and must leave the document's /// tree as it is. The copies take new ids in the order of `roots`. Roots listed twice, or inside /// another root, are copied one at a time: each copy is made from the document as the copies -/// before it left it. +/// before it left it. Copied type whose layout caches [`Document::reid`] dropped has them again. pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl FnMut(&mut Document, &Node, &mut Node)) -> Result> { let paths = d.index_paths(roots.iter().copied()); let mut found: Vec<_> = roots.iter().filter_map(|id| paths.get(id)).collect(); @@ -779,6 +923,7 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn } out }; + super::typecmd::refresh_bounds_of(d, &out); Ok(out) } diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index e4660bf67a..e91a621c4e 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -12,7 +12,8 @@ use vectorcraft_doc::{Document, Effect, Node, NodeKind, StrokeLayer}; use vectorcraft_geom::{FillRule, PathData}; use vectorcraft_render::effects; -use super::appearance::{ItemTarget, appearance_targets, index_param, item_target, item_target_at}; +use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_target, item_target_at, shared_stack}; +use super::expand::has_seeded; use super::rasterfx; use super::*; @@ -41,7 +42,7 @@ pub fn specs() -> Vec { "Remove Effect", [], None, - "{index: int (position in the effect list), item?: appearance item index|null (that fill/stroke's effects; omitted: the active item, else the object's), ids?|id?: [..], target?: \"object\"|\"contents\"} → {ids}", + "{index: int (position in the effect list), item?: appearance item index|null (that fill/stroke's effects; 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)} → {ids}", has_doc, remove ), @@ -50,16 +51,25 @@ pub fn specs() -> Vec { "Effect Options", [], None, - "{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place), visible?: bool, item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\"} → {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), visible?: bool, item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} → {ids}", has_doc, set_params ), + cmd!( + "effect.lightingPreset", + "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; one undo step → {ids}", + has_doc, + lighting_preset + ), cmd!( "effect.expandAppearance", "Expand Appearance", ["Object"], None, - "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (strokes outlined, brushed strokes their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; a group's or layer's own fills and strokes become objects among its members, which are expanded too. Hidden fills, strokes and effects are dropped. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (strokes outlined, brushed strokes their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. Hidden fills, strokes and effects are dropped. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", can_expand, expand_appearance ), @@ -68,7 +78,7 @@ pub fn specs() -> Vec { "Duplicate Effect", [], None, - "{index: int, item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\"} insert a copy of the effect right after it → {ids}", + "{index: int, 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)} insert a copy of the effect right after it → {ids}", has_doc, duplicate ), @@ -77,7 +87,7 @@ pub fn specs() -> Vec { "Move Effect", [], None, - "{from: int (position in the source list), to: int (its position in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\"} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", + "{from: int (position in the source list), to: int (its position in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", has_doc, move_effect ), @@ -91,6 +101,35 @@ fn ids_json(ids: &[NodeId]) -> Value { /// One undo step (`label`) running `f` on the effect list `item` addresses on each target (an /// appearance item's own effects, or the object's). Errors with `none` when `f` changed no object; /// returns the changed ids. +/// Each target of an effect edit aimed at `item` and effect `index`: the object, the item whose +/// effects it edits (`None`: the object's own) and the effect's index there. With `aligned` (see +/// [`ItemTarget::per_target`]) `item` and `index` are the first target's, and each other target +/// edits its equal item, or its equal object-level effect; a target without them is left out. +pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: usize, cmd: &str) -> Result, usize)>> { + let roots = appearance_targets(s, p)?; + let d = &s.doc()?.doc; + let per = item.per_target(d, &roots); + let shared = if aligned(p) { shared_stack(d, &roots) } else { None }; + let mut out = Vec::with_capacity(roots.len()); + for (k, (id, item)) in roots.iter().zip(per).enumerate() { + let (Some(item), Some(n)) = (item, d.node(*id)) else { continue }; + let at = item.effects_item(&n.appearance, cmd)?; + // An object-level effect the targets share is, in each, where it is there. + let first = roots.first().and_then(|f| d.node(*f)); + let first_level = first.map(|f| item.effects_item(&f.appearance, cmd)).transpose()?.flatten(); + let index = match (&shared, at, first_level) { + (Some(sh), None, None) if sh.has_effect(index) => match sh.effect_in(index, k) { + Some(i) => i, + None => continue, + }, + _ => index, + }; + out.push((*id, at, index)); + } + Ok(out) +} + +#[allow(clippy::too_many_arguments)] fn edit_effects( s: &mut Session, p: &Value, @@ -98,17 +137,17 @@ fn edit_effects( cmd: &str, label: &str, none: &str, - mut f: impl FnMut(&mut Vec) -> bool, + index: usize, + mut f: impl FnMut(&mut Vec, usize) -> bool, ) -> Result> { - let roots = appearance_targets(s, p)?; + let targets = effect_targets(s, p, item, index, cmd)?; s.edit(label, |d, _| { let mut done = vec![]; - for id in &roots { - let Some(n) = d.node_mut(*id) else { continue }; - let index = item.effects_item(&n.appearance, cmd)?; - if n.appearance.effects_mut(index).is_some_and(&mut f) { + for &(id, at, index) in &targets { + let Some(n) = d.node_mut(id) else { continue }; + if n.appearance.effects_mut(at).is_some_and(|fx| f(fx, index)) { check_revolve_count(n, cmd)?; - done.push(*id); + done.push(id); } } if done.is_empty() { @@ -129,8 +168,11 @@ fn check_revolve_count(n: &Node, cmd: &str) -> Result<()> { Ok(()) } -const ONE_3D: &str = "An object takes one 3D effect. Edit the existing effect's options, or remove it first."; +pub(crate) const ONE_3D: &str = "An object takes one 3D effect. Edit the existing effect's options, or remove it first."; +/// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the +/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one; +/// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`. pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.apply"; let id = str_param(p, "effect").or_else(|| str_param(p, "id")).ok_or_else(|| bad(C, "missing `effect` id"))?; @@ -144,7 +186,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { if id == effects::CROP_MARKS && params.get("style").is_none() { params["style"] = json!(s.crop_mark_style().id()); } - if id == GLASS { + if texture_load_effect(id) { load_texture(&mut params, C)?; } let effect = effects::new_effect(id, ¶ms).ok_or_else(|| bad(C, format!("unknown effect `{id}`")))?; @@ -162,13 +204,9 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { if effects::is_three_d(id) { for target in appearance_targets(s, p)? { let n = s.doc()?.doc.node(target).ok_or(EngineError::NoNode(target))?; - if id == effects::REVOLVE { - effects::validate_revolve(n, &effect.params).map_err(|e| bad(C, e))?; - if effects::has_revolve(n) { - return Err(bad(C, "A profile supports one Revolve effect. Edit the existing effect's options instead.")); - } - } else { - effects::validate_solid(n, id, &effect.params).map_err(|e| bad(C, e))?; + effects::validate_three_d(n, id, &effect.params).map_err(|e| bad(C, e))?; + 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.")); } if effects::has_revolve(n) || effects::has_solid(n) { return Err(bad(C, ONE_3D)); @@ -176,7 +214,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { } } let mut index = 0; - let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", |fx| { + let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", 0, |fx, _| { fx.push(effect.clone()); index = fx.len() - 1; true @@ -232,7 +270,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.remove"; let index = index_param(p, "index", C)?; let item = item_target(s, p, C)?; - let ids = edit_effects(s, p, item, C, "Remove Effect", &format!("{C}: no effect at index {index}"), |fx| { + let ids = edit_effects(s, p, item, C, "Remove Effect", &format!("{C}: no effect at index {index}"), index, |fx, index| { (index < fx.len()).then(|| fx.remove(index)).is_some() })?; Ok(json!({ "ids": ids_json(&ids) })) @@ -242,12 +280,14 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.duplicate"; let index = index_param(p, "index", C)?; let item = item_target(s, p, C)?; - let ids = edit_effects(s, p, item, C, "Duplicate Effect", &format!("{C}: no effect at index {index}"), |fx| match fx.get(index).cloned() { - Some(e) => { - fx.insert(index + 1, e); - true + let ids = edit_effects(s, p, item, C, "Duplicate Effect", &format!("{C}: no effect at index {index}"), index, |fx, index| { + match fx.get(index).cloned() { + Some(e) => { + fx.insert(index + 1, e); + true + } + None => false, } - None => false, })?; Ok(json!({ "ids": ids_json(&ids) })) } @@ -260,6 +300,10 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src }; let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); let roots = appearance_targets(s, p)?; + // Where an aligned effect would go in each of several different stacks isn't one place. + if aligned(p) && super::appearance::appearances_differ(&s.doc()?.doc, &roots) { + return Err(bad(C, "effects of objects whose appearances differ can't be moved together")); + } // Where the effect landed in the first object. let mut landed = None; let ids = s.edit(if copy { "Duplicate Effect" } else { "Move Effect" }, |d, _| { @@ -289,16 +333,40 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { /// (none when `p` doesn't say which: running it reports why). pub(crate) fn set_params_effects(s: &Session, p: &Value) -> Vec { const C: &str = "effect.setParams"; - let (Ok(index), Ok(item), Ok(ids), Ok(st)) = (index_param(p, "index", C), item_target(s, p, C), appearance_targets(s, p), s.doc()) else { + let (Ok(index), Ok(item), Ok(st)) = (index_param(p, "index", C), item_target(s, p, C), s.doc()) else { return vec![]; }; - let effect = |id: &NodeId| { - let ap = &st.doc.node(*id)?.appearance; - Some(ap.effects_at(item.effects_item(ap, C).ok()?)?.get(index)?.id.clone()) - }; - ids.iter().filter_map(effect).collect() + let Ok(targets) = effect_targets(s, p, item, index, C) else { return vec![] }; + let effect = |&(id, at, index): &(NodeId, Option, usize)| Some(st.doc.node(id)?.appearance.effects_at(at)?.get(index)?.id.clone()); + targets.iter().filter_map(effect).collect() } +fn lighting_preset(s: &mut Session, p: &Value) -> Result { + const C: &str = "effect.lightingPreset"; + let patch = str_param(p, "preset") + .and_then(effects::lighting_preset_params) + .ok_or_else(|| bad(C, "preset must be standard, diffuse, topLeft or right"))?; + let index = index_param(p, "index", C)?; + let item = item_target(s, p, C)?; + // Validate the whole selection before changing any object. An unrelated effect or + // a missing index must not leave just some objects with a new lighting rig. + for (id, slot, index) in effect_targets(s, p, item, index, C)? { + let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?; + let effect = n.appearance.effects_at(slot).and_then(|fx| fx.get(index)); + 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))); + } + } + let mut options = p.clone(); + let map = options.as_object_mut().ok_or_else(|| bad(C, "parameters must be an object"))?; + map.remove("preset"); + map.insert("params".into(), patch); + set_params(s, &options) +} + +/// `effect.setParams`: merges `params` into the effect at `index` of the targets' active item, and +/// sets its Warp style (`warpStyle`) or visibility (`visible`), as one undo step. They are checked +/// as `effect.apply` checks them, and a visible 3D effect must still fit. → `{ids}`. fn set_params(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.setParams"; let index = index_param(p, "index", C)?; @@ -320,12 +388,11 @@ fn set_params(s: &mut Session, p: &Value) -> Result { super::params::check_effect_color(C, effect, ¶ms)?; super::params::check_effect_channel(C, effect, ¶ms)?; } - if edited.iter().any(|e| e == GLASS) { + if edited.iter().any(|e| texture_load_effect(e)) { load_texture(&mut params, C)?; } - for id in appearance_targets(s, p)? { + for (id, target, index) in effect_targets(s, p, item, index, C)? { let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?; - let target = item.effects_item(&n.appearance, C)?; let effect = n.appearance.effects_at(target).and_then(|fx| fx.get(index)); if warp_id.is_some() && effect.is_some_and(|e| e.id.strip_prefix("warp.").and_then(effects::WarpStyle::from_id).is_none()) { return Err(bad(C, "warpStyle can only edit an applied Warp effect")); @@ -338,14 +405,10 @@ fn set_params(s: &mut Session, p: &Value) -> Result { if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(&e.id, ¶ms)) { cur.extend(new); } - if e.id == effects::REVOLVE { - effects::validate_revolve(n, &prospective).map_err(|e| bad(C, e))?; - } else { - effects::validate_solid(n, &e.id, &prospective).map_err(|e| bad(C, e))?; - } + effects::validate_three_d(n, &e.id, &prospective).map_err(|e| bad(C, e))?; } } - let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), |fx| { + let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| { let Some(e) = fx.get_mut(index) else { return false }; if let Some(id) = &warp_id { e.id.clone_from(id); @@ -373,6 +436,14 @@ fn set_params(s: &mut Session, p: &Value) -> Result { /// Effect › Distort › Glass. const GLASS: &str = "distort.glass"; +/// Effect › Texture › Texturizer. +const TEXTURIZER: &str = "texture.texturizer"; + +/// Does effect `id` have Load Texture: a `textureImage` that `effect.apply` reads from an image +/// file (Glass, Texturizer)? +pub(crate) fn texture_load_effect(id: &str) -> bool { + id == GLASS || id == TEXTURIZER +} /// Glass's `textureImage` in `params` as Glass stores it: an image file (`{path}`, or `{name?, /// dataBase64}`) is read with [`fileio::texture_image`] and picked (`texture: "loaded"`) unless @@ -442,18 +513,70 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> { Some((rasterfx::raster_image(d, n, below, true)?, below)) } -/// Give the members of `m`, art evaluated from the object of the same id (its pieces share that -/// id), ids of their own and expand the pieces: those made from its own fills and strokes, or with -/// `all` every member. -fn expand_pieces(d: &mut Document, m: &mut Node, all: bool, stroke_art: effects::StrokeArt) { +/// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that +/// id): those made from its own fills and strokes, or with `all` every member. The other members +/// that repeat an id ([`repeats_an_id`]) and hold a random Transform effect ([`has_seeded`]) are +/// expanded as well ([`expand_in_place`]). Then the members get ids of their own. Random in a +/// Transform effect takes its seed from the id, and the canvas draws the pieces with the ids they +/// have before that. Returns what each of those other members' expansions lists, by the member's +/// new id. +fn expand_pieces( + d: &mut Document, + m: &mut Node, + all: bool, + brushes: &[vectorcraft_brush::Brush], + stroke_art: effects::StrokeArt, +) -> std::collections::HashMap> { let id = m.id; let mut seen = std::collections::HashSet::from([id]); + let mut expanded = std::collections::HashMap::new(); for c in m.children_mut().into_iter().flatten() { - let own = all || c.id == id; let c = Arc::make_mut(c); - effects::fresh_ids(d, c, &mut seen); - if own { + let mut listed = None; + if all || c.id == id { effects::expand_art(d, c, stroke_art); + } else if has_seeded(c) && repeats_an_id(c, &seen) { + listed = Some(expand_in_place(d, c, brushes)); + } + fresh_ids_listed(d, c, &mut seen, listed.as_deref_mut().unwrap_or_default()); + if let Some(listed) = listed { + expanded.insert(c.id, listed); + } + } + expanded +} + +/// 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) -> bool { + let mut ids = std::collections::HashSet::new(); + let mut repeats = false; + n.walk(&mut |c| repeats |= seen.contains(&c.id) || !ids.insert(c.id)); + repeats +} + +/// An object whose appearance expanded: its id, and its place in the walk ([`Node::walk`]) of the +/// art it was listed in. Art evaluated from an object can hold one id more than once, and the place +/// tells which of those nodes it is. +type Listed = (NodeId, usize); + +/// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`. +fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush]) -> Vec { + let mut listed = vec![]; + if let Some(e) = expanded_node(d, c.clone(), brushes, &mut listed) { + *c = e; + } + listed +} + +/// [`effects::fresh_ids`] on `c`, with each of `listed` (places in the walk of `c`) given the new +/// id of the node at its place. +fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections::HashSet, listed: &mut [Listed]) { + effects::fresh_ids(d, c, seen); + let mut ids = vec![]; + c.walk(&mut |n| ids.push(n.id)); + for (id, at) in listed { + if let Some(new) = ids.get(*at) { + *id = *new; } } } @@ -462,46 +585,73 @@ fn expand_pieces(d: &mut Document, m: &mut Node, all: bool, stroke_art: effects: /// stroke becomes an object of its own (strokes outlined, brushes as their art), geometry effects /// are baked, raster effects become an embedded image, and the object keeps its transparency. pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec) { - let Some(mut n) = d.node(id).cloned() else { return }; + let Some(n) = d.node(id).cloned() else { return }; + let mut listed = vec![]; + let m = expanded_node(d, n, brushes, &mut listed); + out.extend(listed.into_iter().map(|(id, _)| id)); + if let Some(mut m) = m { + // Art made from type takes its emoji's pixels into the document. + d.adopt_pixels(&mut m); + if let Some(slot) = d.node_mut(id) { + *slot = m; + } + } +} + +/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when +/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk +/// of the expanded `n`, `n`'s first when its own does. +fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], out: &mut Vec) -> Option { + let id = n.id; if !expandable(&n) { - return; + return None; } // Colour adjustments: the colours inside become the adjusted ones (an embedded image a // recoloured copy), then the rest of the appearance expands. + let mut changed = false; + // Is `n` in `out` yet? + let mut listed_n = false; if effects::has_adjustment(&n) && let Some(m) = effects::adjust_in_document(d, &n) - && let Some(slot) = d.node_mut(id) { - *slot = m.clone(); - out.push(id); + out.push((id, 0)); + listed_n = true; n = m; + changed = true; if !expandable(&n) { - return; + return Some(n); } } // (A symbol instance has become its art, a group.) let container = is_container(&n); - // Crop Marks: a group of the object and its marks, then the object expands on its own. + // Crop Marks: the object and its marks become a group. The object expands on its own first, + // with `id`: the canvas draws it with that id, which Random in a Transform effect takes its + // seed from. Then the object and the marks get ids of their own. if let Some(mut m) = effects::crop_marks_art(&n) { let mut seen = std::collections::HashSet::from([id]); - for c in m.children_mut().into_iter().flatten() { - effects::fresh_ids(d, Arc::make_mut(c), &mut seen); + let mut expanded = vec![]; + for (i, c) in m.children_mut().into_iter().flatten().enumerate() { + let c = Arc::make_mut(c); + if i == 0 { + expanded = expand_in_place(d, c, brushes); + fresh_ids_listed(d, c, &mut seen, &mut expanded); + } else { + effects::fresh_ids(d, c, &mut seen); + } } - let object = m.children().and_then(|c| c.first()).map(|c| c.id); - if let Some(slot) = d.node_mut(id) { - *slot = m; - out.push(id); + if !listed_n { + out.push((id, 0)); } - if let Some(object) = object { - expand_node(d, object, brushes, out); - } - return; + out.extend(expanded.into_iter().map(|(id, at)| (id, at + 1))); + return Some(m); } let image = raster_image(d, &n); let mut v = n.clone(); rasterfx::strip_raster(&mut v, false); let mut stroke_art = |d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st); + // Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists. + let mut members = std::collections::HashMap::new(); let expanded = match image { // Blur, feather and inner glow change the object itself: it becomes the image (a layer // keeps it as its only member). @@ -509,21 +659,21 @@ pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_b image => { let m = if container { // A group's or layer's own fills and strokes become art among its members. - effects::evaluate_container(&v).map(|mut m| { - expand_pieces(d, &mut m, false, &mut stroke_art); + effects::evaluate_container(Some(&*d), &v).map(|mut m| { + members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art); m }) - } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && !effects::has_gradient_copies(&v) { + } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && !effects::has_transform_art(&v) { effects::expand_leaf(d, &v, &mut stroke_art) } else { // Type, images, symbol instances, live objects (and paths whose Transform effect copies - // them with a gradient): through their outlines. + // them with a gradient or changes their fills and strokes): through their outlines. let symbol = match &n.kind { NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()), _ => None, }; - effects::expand_outlined(&v, symbol.as_deref()).map(|mut m| { - expand_pieces(d, &mut m, true, &mut stroke_art); + effects::expand_outlined(Some(&*d), &v, symbol.as_deref()).map(|mut m| { + expand_pieces(d, &mut m, true, brushes, &mut stroke_art); m }) }; @@ -537,20 +687,34 @@ pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_b } } }; - if let Some(m) = expanded - && let Some(slot) = d.node_mut(id) - { - *slot = m; - if out.last() != Some(&id) { - out.push(id); + if let Some(m) = expanded { + n = m; + changed = true; + if !listed_n { + out.push((id, 0)); } } if container { - let children: Vec = d.node(id).and_then(|n| n.children()).map(|c| c.iter().map(|c| c.id).collect()).unwrap_or_default(); - for c in children { - expand_node(d, c, brushes, out); + // The place of each member in the walk of `n`: after `n` and the members before it. + let mut at = 1; + for c in n.children_mut().into_iter().flatten() { + let from = out.len(); + match members.remove(&c.id) { + Some(listed) => out.extend(listed), + None => { + if let Some(e) = expanded_node(d, (**c).clone(), brushes, out) { + *c = Arc::new(e); + changed = true; + } + } + } + for (_, place) in &mut out[from..] { + *place += at; + } + at += c.count(); } } + changed.then_some(n) } fn expand_appearance(s: &mut Session, p: &Value) -> Result { @@ -559,9 +723,13 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { let ids = s.edit("Expand Appearance", |d, _| { let brushes = vectorcraft_brush::library(d); let mut out = vec![]; + let threaded = super::threads::frames(d); for id in &roots { expand_node(d, *id, &brushes, &mut out); } + // Outlined frames of threaded text leave their threads with the text they show; type that + // stays type under a new id takes its frame's place. + super::threads::leave_threads(d, &threaded); if out.is_empty() { return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into())); } @@ -576,462 +744,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { } #[cfg(test)] -mod tests { - use serde_json::json; - use vectorcraft_doc::NodeKind; - use vectorcraft_render::effects; +mod lighting_presets_tests; - use crate::{NodeId, Session}; - - fn session_with_rect() -> (Session, NodeId) { - let mut s = Session::new(); - s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); - let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); - (s, NodeId(r["id"].as_u64().unwrap())) - } - - fn node(s: &Session, id: NodeId) -> vectorcraft_doc::Node { - s.doc().unwrap().doc.node(id).cloned().unwrap() - } - - #[test] - fn revolve_commands_keep_profile_live_edit_options_expand_and_undo() { - let mut s = Session::new(); - s.execute("file.new", &json!({"width":300,"height":300})).unwrap(); - let r = s.execute("path.create", &json!({"d":"M 150 40 L 180 60 L 180 140 L 150 160"})).unwrap(); - let id = NodeId(r["id"].as_u64().unwrap()); - let source = node(&s, id).path_data().unwrap().clone(); - s.execute("effect.apply", &json!({"effect":"threeD.revolve","ids":[id.0],"item":null})).unwrap(); - let before = effects_for_test(&s, id); - assert_eq!(node(&s, id).path_data(), Some(&source)); - let doc = &s.doc().unwrap().doc; - let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap(); - assert_eq!(restored.node(id).unwrap().path_data(), Some(&source)); - assert_eq!(effects::revolve_art(restored.node(id).unwrap()).unwrap(), before); - let pdf = s.execute("document.serialize", &json!({"format":"pdf"})).unwrap(); - let bytes = vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap(); - assert!(bytes.starts_with(b"%PDF")); - assert!(s.execute("effect.apply", &json!({"effect":"threeD.revolve","ids":[id.0],"item":null})).is_err()); - assert!(s.execute("effect.duplicate", &json!({"index":0,"ids":[id.0],"item":null})).is_err()); - s.execute("effect.setParams", &json!({"index":0,"params":{"angle":180,"offset":10},"ids":[id.0],"item":null})).unwrap(); - assert_ne!(effects_for_test(&s, id), before); - assert!(s.execute("effect.setParams", &json!({"index":0,"params":{"edge":"invalid"},"ids":[id.0],"item":null})).is_err()); - s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); - assert!(matches!(node(&s, id).kind, NodeKind::Group { .. })); - assert!(!effects::has_revolve(&node(&s, id))); - s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(node(&s, id).path_data(), Some(&source)); - s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(effects_for_test(&s, id), before); - } - - /// Extrude & Bevel, Inflate and Rotate: applied by command, saved and reopened, edited, - /// exported, expanded and undone; one 3D effect per object. - #[test] - fn solid_effects_apply_save_edit_export_expand_and_undo() { - for effect in effects::SOLIDS { - let (mut s, id) = session_with_rect(); - let source = node(&s, id).path_data().unwrap().clone(); - s.execute("effect.apply", &json!({"effect": effect, "ids": [id.0], "item": null})).unwrap(); - let art = effects::solid_art(&node(&s, id)).unwrap(); - assert_eq!(node(&s, id).path_data(), Some(&source), "{effect}: the source stays editable"); - let doc = &s.doc().unwrap().doc; - let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap(); - assert_eq!(effects::solid_art(restored.node(id).unwrap()).unwrap(), art, "{effect}: reopens the same"); - // One 3D effect per object, whichever kind. - for other in ["threeD.revolve", "threeD.extrude", "threeD.rotate"] { - assert!(s.execute("effect.apply", &json!({"effect": other, "ids": [id.0], "item": null})).is_err(), "{effect} + {other}"); - } - s.execute("effect.setParams", &json!({"index": 0, "params": {"rotationY": 50, "rotationX": 10}, "ids": [id.0], "item": null})).unwrap(); - assert_ne!(effects::solid_art(&node(&s, id)).unwrap(), art, "{effect}: options change the art"); - assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"bevel": "nope"}, "ids": [id.0], "item": null})).is_err()); - let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); - let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string()); - assert!(svg.matches("= 2, "{effect}: exported as vector faces"); - s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap(); - assert!(matches!(node(&s, id).kind, NodeKind::Group { .. }), "{effect}"); - assert!(!effects::has_solid(&node(&s, id))); - s.execute("edit.undo", &json!({})).unwrap(); - s.execute("edit.undo", &json!({})).unwrap(); - s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(node(&s, id).appearance.effects.len(), 0, "{effect}: back to the plain rectangle"); - } - // Type has no outline to extrude. - let mut s = Session::new(); - s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); - let t = s.execute("text.create", &json!({"x": 50, "y": 50, "text": "3D"})).unwrap(); - let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [t["id"]], "item": null})).unwrap_err(); - assert!(err.to_string().contains("requires a path"), "{err}"); - } - - /// Scripts from before the Perspective angle give `perspective` as a 0–100 % strength: it is - /// stored as the angle that shows the same view, and a later angle replaces an earlier strength. - #[test] - fn an_earlier_perspective_strength_is_set_as_its_angle() { - let (mut s, id) = session_with_rect(); - s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": {"perspective": 60}})).unwrap(); - let params = |s: &Session| node(s, id).appearance.effects[0].params.clone(); - let angle_of = |pct: f64| effects::merged_params(effects::EXTRUDE, &json!({"perspective": pct}))["perspectiveAngle"].as_f64().unwrap(); - let angle = angle_of(60.0); - assert!((angle - 30.12).abs() < 0.01, "{angle}"); - assert!( - params(&s).get("perspective").is_none() && (params(&s)["perspectiveAngle"].as_f64().unwrap() - angle).abs() < 1e-12, - "{}", - params(&s) - ); - s.execute("effect.setParams", &json!({"index": 0, "params": {"perspective": 100}, "ids": [id.0], "item": null})).unwrap(); - assert!((params(&s)["perspectiveAngle"].as_f64().unwrap() - angle_of(100.0)).abs() < 1e-12); - // A file of then: the strength stored; setting an angle replaces it. - std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.effects[0].params = - json!({"depth": 50, "perspective": 60}); - s.execute("effect.setParams", &json!({"index": 0, "params": {"perspectiveAngle": 120}, "ids": [id.0], "item": null})).unwrap(); - assert_eq!(params(&s), json!({"depth": 50, "perspectiveAngle": 120})); - } - - /// Scripts from before Rotation and Height give the light by `lightAzimuth` and - /// `lightElevation`: stored as the same light; a later Height keeps that light's Rotation. - #[test] - fn an_earlier_light_direction_is_set_as_rotation_and_height() { - let (mut s, id) = session_with_rect(); - s.execute( - "effect.apply", - &json!({"effect": effects::ROTATE, "ids": [id.0], "item": null, "params": {"lightAzimuth": 180, "lightElevation": 0}}), - ) - .unwrap(); - let params = |s: &Session| node(s, id).appearance.effects[0].params.clone(); - // Straight from behind the object, level with it. - assert!(params(&s).get("lightAzimuth").is_none() && params(&s).get("lightElevation").is_none(), "{}", params(&s)); - assert_eq!((params(&s)["lightHeight"].as_f64().unwrap().round(), ¶ms(&s)["lightBehind"]), (90.0, &json!(true))); - std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.effects[0].params = - json!({"lightAzimuth": 90, "lightElevation": 0}); - s.execute("effect.setParams", &json!({"index": 0, "params": {"lightHeight": 60}, "ids": [id.0], "item": null})).unwrap(); - assert_eq!(params(&s), json!({"lightRotation": 0.0, "lightHeight": 60, "lightBehind": false})); - } - - /// Scripts from before Scribble's separate variations give one `variation`, which is stored as the - /// Path Overlap and Spacing variations. An angle is stored above -180° and up to 180°. - #[test] - fn scribble_stores_an_earlier_variation_as_two_and_its_angle_within_180() { - let (mut s, id) = session_with_rect(); - let p = json!({"effect": "stylize.scribble", "ids": [id.0], "item": null, "params": {"angle": 270, "variation": 2}}); - s.execute("effect.apply", &p).unwrap(); - let params = |s: &Session| node(s, id).appearance.effects[0].params.clone(); - assert_eq!((params(&s)["angle"].as_f64(), params(&s).get("variation")), (Some(-90.0), None), "{}", params(&s)); - assert_eq!((¶ms(&s)["overlapVariation"], ¶ms(&s)["spacingVariation"]), (&json!(2), &json!(2))); - s.execute("effect.setParams", &json!({"index": 0, "params": {"angle": -200}, "ids": [id.0], "item": null})).unwrap(); - assert_eq!(params(&s)["angle"].as_f64(), Some(160.0)); - // A file of then stores its variation; setting one of the two keeps it for the other. - std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.effects[0].params = json!({"variation": 3}); - s.execute("effect.setParams", &json!({"index": 0, "params": {"spacingVariation": 1}, "ids": [id.0], "item": null})).unwrap(); - assert_eq!(params(&s), json!({"overlapVariation": 3, "spacingVariation": 1})); - } - - fn effects_for_test(s: &Session, id: NodeId) -> vectorcraft_doc::Node { - effects::revolve_art(&node(s, id)).unwrap() - } - - #[test] - fn smooth_revolve_commands_validate_save_expand_and_undo() { - let mut s = Session::new(); - s.execute("file.new", &json!({"width":300,"height":300})).unwrap(); - let r = s.execute("path.create", &json!({"d":"M150 40 C190 60 190 140 150 160"})).unwrap(); - let id = NodeId(r["id"].as_u64().unwrap()); - s.execute("effect.apply", &json!({"effect":"threeD.revolve","ids":[id.0],"item":null,"params":{"offset":20,"segments":16}})).unwrap(); - let initial = node(&s, id); - let source = initial.path_data().unwrap().clone(); - assert!(!initial.appearance.effects[0].params.as_object().unwrap().contains_key("smoothShading")); - assert!(initial.appearance.effects[0].params["cap"].as_bool().unwrap()); - let mut gradients = 0; - effects_for_test(&s, id).walk(&mut |face| { - gradients += face.appearance.items.iter().filter(|item| { - matches!(item, vectorcraft_doc::AppearanceItem::Fill(fill) if matches!(fill.paint, vectorcraft_doc::color::Paint::Gradient(_))) - }).count(); - }); - assert!(gradients > 0, "commands use smooth vector shading by default"); - s.execute("effect.setParams", &json!({"index":0,"ids":[id.0],"item":null,"params":{"lightAzimuth":30}})).unwrap(); - let smooth = node(&s, id); - assert_eq!(smooth.path_data(), Some(&source)); - assert_ne!(effects_for_test(&s, id), effects::revolve_art(&initial).unwrap()); - let restored = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); - assert_eq!(effects::revolve_art(restored.node(id).unwrap()), Some(effects_for_test(&s, id))); - s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); - assert!(!effects::has_revolve(&node(&s, id))); - s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(node(&s, id), smooth); - s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(node(&s, id), initial); - } - - #[test] - fn revolve_caps_save_export_expand_and_undo_without_changing_the_source() { - let mut s = Session::new(); - s.execute("file.new", &json!({"width":300,"height":300})).unwrap(); - let r = s.execute("path.create", &json!({"d":"M150 40 L150 160"})).unwrap(); - let id = NodeId(r["id"].as_u64().unwrap()); - let source = node(&s, id).path_data().unwrap().clone(); - s.execute( - "effect.apply", - &json!({"effect":"threeD.revolve","ids":[id.0],"item":null, - "params":{"offset":30,"rotationX":-35,"segments":16,"expandVisibleOnly":false,"cap":false}}), - ) - .unwrap(); - let uncapped = node(&s, id); - assert_eq!(uncapped.appearance.effects[0].params["cap"], json!(false)); - let count = |n: &vectorcraft_doc::Node| n.children().unwrap()[0].children().unwrap().len(); - let open_count = count(&effects_for_test(&s, id)); - s.execute("effect.setParams", &json!({"index":0,"ids":[id.0],"item":null,"params":{"cap":true}})).unwrap(); - let capped = node(&s, id); - let art = effects_for_test(&s, id); - assert_eq!(count(&art), open_count + 2, "each endpoint adds one continuous vector cap"); - assert_eq!(capped.path_data(), Some(&source)); - assert!(s.execute("effect.setParams", &json!({"index":0,"ids":[id.0],"item":null,"params":{"cap":"yes"}})).is_err()); - assert_eq!(node(&s, id), capped, "a bad boolean does not mutate the document"); - let restored = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); - assert_eq!(restored.node(id).unwrap().appearance.effects[0].params["cap"], json!(true)); - assert_eq!(effects::revolve_art(restored.node(id).unwrap()), Some(art.clone())); - let pdf = s.execute("document.serialize", &json!({"format":"pdf"})).unwrap(); - assert!(vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap().starts_with(b"%PDF")); - s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); - assert_eq!(count(&node(&s, id)), count(&art)); - assert!(!effects::has_revolve(&node(&s, id))); - s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(node(&s, id), capped); - s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(node(&s, id), uncapped); - } - - #[test] - fn revolve_visibility_parameter_saves_expands_and_undoes_without_other_appearance_changes() { - let mut s = Session::new(); - s.execute("file.new", &json!({"width":300,"height":300})).unwrap(); - let r = s.execute("path.create", &json!({"d":"M 150 40 L 180 60 L 180 140 L 150 160"})).unwrap(); - let id = NodeId(r["id"].as_u64().unwrap()); - s.execute("effect.apply", &json!({"effect":"threeD.revolve","ids":[id.0],"item":null})).unwrap(); - let live = node(&s, id); - let restored = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); - assert_eq!(restored.node(id).unwrap().appearance.effects[0].params["expandVisibleOnly"], json!(true)); - let count = |n: &vectorcraft_doc::Node| n.children().unwrap()[0].children().unwrap().len(); - s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); - let visible = count(&node(&s, id)); - s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(node(&s, id), live); - s.execute("effect.setParams", &json!({"index":0,"item":null,"ids":[id.0],"params":{"expandVisibleOnly":false}})).unwrap(); - s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); - assert!(count(&node(&s, id)) > visible); - s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(node(&s, id).appearance.effects[0].params["expandVisibleOnly"], json!(false)); - s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(node(&s, id), live); - // The shared command still expands ordinary multiple-fill artwork as before. - let r = s.execute("shape.rectangle", &json!({"x":10,"y":10,"width":20,"height":20})).unwrap(); - let ordinary = NodeId(r["id"].as_u64().unwrap()); - s.execute("effect.apply", &json!({"effect":"distort.twist","ids":[ordinary.0],"params":{"angle":15}})).unwrap(); - s.execute("effect.expandAppearance", &json!({"ids":[ordinary.0]})).unwrap(); - assert!(node(&s, ordinary).appearance.effects.is_empty()); - } - - #[test] - fn apply_uses_catalog_defaults_and_undoes() { - let (mut s, id) = session_with_rect(); - let r = s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"x": 3}})).unwrap(); - assert_eq!(r["index"], json!(0)); - let n = node(&s, id); - assert_eq!(n.appearance.effects.len(), 1); - assert_eq!(n.appearance.effects[0].params["x"], json!(3)); - assert_eq!(n.appearance.effects[0].params["opacity"], json!(75.0)); - s.execute("edit.undo", &json!({})).unwrap(); - assert!(node(&s, id).appearance.effects.is_empty()); - assert!(s.execute("effect.apply", &json!({"effect": "nope"})).is_err()); - } - - #[test] - fn warp_options_style_change_preserves_slot_and_visibility() { - let (mut s, id) = session_with_rect(); - for effect in ["path.offsetPath", "warp.arc", "stylize.roundCorners"] { - s.execute("effect.apply", &json!({"effect": effect, "item": 1})).unwrap(); - } - s.execute("effect.setParams", &json!({"index": 1, "item": 1, "visible": false})).unwrap(); - s.doc_mut().unwrap().mark_saved(); - let before = s.doc().unwrap().doc.clone(); - let undo = s.doc().unwrap().history.undo.len(); - let result = s.execute("effect.setParams", &json!({"index": 1, "item": 1, "warpStyle": "flag", "params": {"bend": 25.0}})); - assert!(result.is_ok(), "an applied warp can change style in place: {result:?}"); - let old = before.node(id).unwrap().appearance.effects_at(Some(1)).unwrap(); - let n = node(&s, id); - let new = n.appearance.effects_at(Some(1)).unwrap(); - assert_eq!(new.len(), 3); - assert_eq!(new[0], old[0]); - assert_eq!(new[2], old[2]); - assert_eq!(new[1].id, "warp.flag"); - assert_eq!(new[1].params["bend"], 25.0); - assert!(!new[1].visible); - assert!(n.appearance.effects.is_empty()); - assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); - let after = s.doc().unwrap().doc.clone(); - s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(s.doc().unwrap().doc, before); - assert!(!s.doc().unwrap().is_dirty()); - s.execute("edit.redo", &json!({})).unwrap(); - assert_eq!(s.doc().unwrap().doc, after); - } - - #[test] - fn warp_options_non_warp_target_rejection_is_atomic() { - let (mut s, first) = session_with_rect(); - s.execute("effect.apply", &json!({"effect": "warp.arc", "item": null})).unwrap(); - let second = s.execute("shape.rectangle", &json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].clone(); - s.execute("effect.apply", &json!({"effect": "distort.twist", "item": null})).unwrap(); - s.execute("select.set", &json!({"ids": [first.0, second]})).unwrap(); - s.doc_mut().unwrap().mark_saved(); - let before = s.doc().unwrap().doc.clone(); - let selection = s.doc().unwrap().selection.clone(); - let undo = s.doc().unwrap().history.undo.len(); - assert!(s.execute("effect.setParams", &json!({"index": 0, "item": null, "warpStyle": "flag"})).is_err()); - let state = s.doc().unwrap(); - assert_eq!(state.doc, before); - assert_eq!(state.selection, selection); - assert_eq!(state.history.undo.len(), undo); - assert!(!state.is_dirty()); - } - - #[test] - fn list_remove_and_set_params() { - let (mut s, id) = session_with_rect(); - s.execute("effect.apply", &json!({"effect": "distort.twist"})).unwrap(); - s.execute("effect.apply", &json!({"effect": "stylize.outerGlow"})).unwrap(); - let l = s.execute("effect.list", &json!({})).unwrap(); - assert!(l["catalog"].as_array().unwrap().len() >= 34); - assert_eq!(l["applied"][0]["effects"].as_array().unwrap().len(), 2); - s.execute("effect.setParams", &json!({"index": 0, "params": {"angle": 45}, "visible": false})).unwrap(); - let e = &node(&s, id).appearance.effects[0]; - assert_eq!(e.params["angle"], json!(45)); - assert!(!e.visible); - s.execute("effect.remove", &json!({"index": 0})).unwrap(); - let n = node(&s, id); - assert_eq!(n.appearance.effects.len(), 1); - assert_eq!(n.appearance.effects[0].id, "stylize.outerGlow"); - assert!(s.execute("effect.remove", &json!({"index": 5})).is_err()); - } - - #[test] - fn expand_appearance_bakes_geometry() { - let (mut s, id) = session_with_rect(); - s.execute("paint.setStroke", &json!({"none": true})).unwrap(); - s.execute("effect.apply", &json!({"effect": "path.offsetPath", "params": {"offset": 10}})).unwrap(); - s.execute("effect.expandAppearance", &json!({})).unwrap(); - // One fill: the path itself, reshaped. - let n = node(&s, id); - let b = n.geometric_bounds().unwrap(); - assert!((b.width() - 120.0).abs() < 0.1, "{b:?}"); - assert!(n.appearance.effects.is_empty()); - assert!(matches!(n.kind, NodeKind::Path { live: None, .. })); - // Nothing left to expand. - assert!(s.execute("effect.expandAppearance", &json!({})).is_err()); - } - - #[test] - fn expand_transform_copies_makes_compound() { - let (mut s, id) = session_with_rect(); - s.execute("paint.setStroke", &json!({"none": true})).unwrap(); - s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 120, "copies": 1}})).unwrap(); - s.execute("effect.expandAppearance", &json!({})).unwrap(); - let n = node(&s, id); - assert!(matches!(n.kind, NodeKind::Compound { .. })); - let b = n.geometric_bounds().unwrap(); - assert!((b.x1 - 320.0).abs() < 1e-6, "{b:?}"); - } - - #[test] - fn pathfinder_effect_on_loose_objects_groups_them_first() { - let (mut s, a) = session_with_rect(); - let b = NodeId(s.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); - s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); - let r = s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap(); - assert_eq!(r["grouped"], true); - let g = NodeId(r["ids"][0].as_u64().unwrap()); - let gn = node(&s, g); - assert_eq!(gn.children().unwrap().iter().map(|c| c.id).collect::>(), [a, b], "stacking order kept"); - assert!(vectorcraft_render::effects::has_pathfinder(&gn)); - assert_eq!(s.doc().unwrap().selection.objects, [g]); - // Live: one united shape, so expanding leaves a single path. - s.execute("effect.expandAppearance", &json!({})).unwrap(); - assert_eq!(node(&s, g).children().unwrap().len(), 1); - // Grouping and applying are one undo step. - s.execute("edit.undo", &json!({})).unwrap(); - s.execute("edit.undo", &json!({})).unwrap(); - let d = &s.doc().unwrap().doc; - assert!(d.node(g).is_none()); - assert!(d.node(a).is_some_and(|n| n.appearance.effects.is_empty()) && d.parent_of(a) == d.parent_of(b)); - // A selection holding a group applies to each object as before; so does a single object. - s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); - let r = s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap(); - assert!(r.get("grouped").is_none()); - assert_eq!(node(&s, a).appearance.effects.len(), 1); - } - - #[test] - fn pathfinder_effect_on_a_group_with_type_cuts_the_glyphs_out() { - let (mut s, a) = session_with_rect(); - let t = NodeId(s.execute("text.create", &json!({"x": 110, "y": 180, "text": "H", "size": 100})).unwrap()["id"].as_u64().unwrap()); - let glyphs = effects::outline_text(&node(&s, t)).unwrap(); - let b = glyphs.geometric_bounds().unwrap(); - assert!(b.x0 > 105.0 && b.y0 > 105.0 && b.x1 < 195.0 && b.y1 < 195.0, "the type lies inside the square: {b:?}"); - let area = |n: &vectorcraft_doc::Node| effects::member_shapes(n).iter().map(|(p, r)| vectorcraft_pathops::area(p, *r)).sum::(); - let glyph_area = area(&glyphs); - s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); - let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); - s.execute("effect.apply", &json!({"effect": "pathfinder.subtract"})).unwrap(); - // Live: the renderer leaves the glyph's place in the square empty. - let doc = s.doc().unwrap().doc.clone(); - let img = vectorcraft_render::Renderer::new().render(&doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()); - let empty = (105..195).flat_map(|y| (105..195).map(move |x| (x, y))).filter(|&(x, y)| img.pixel(x, y)[3] == 0).count(); - assert!(empty as f64 > glyph_area / 2.0, "{empty} empty pixels for a glyph area of {glyph_area}"); - // Expanded: the group holds the square minus the glyph. - s.execute("effect.expandAppearance", &json!({})).unwrap(); - let left = area(&node(&s, g)); - assert!((left - (10_000.0 - glyph_area)).abs() < 0.5, "{left} left of the square for a glyph area of {glyph_area}"); - } - - #[test] - fn pathfinder_effect_on_a_group_renders_live_and_expands() { - let (mut s, a) = session_with_rect(); - let b = s.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap(); - s.execute("select.set", &json!({"ids": [a.0, b["id"]]})).unwrap(); - let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); - s.execute("effect.apply", &json!({"effect": "pathfinder.subtract"})).unwrap(); - // Live: the renderer shows only the back square minus the front one. - let doc = s.doc().unwrap().doc.clone(); - let img = vectorcraft_render::Renderer::new().render(&doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()); - assert!(img.pixel(125, 150)[3] > 0); - assert_eq!(img.pixel(200, 150)[3], 0); - s.execute("effect.expandAppearance", &json!({})).unwrap(); - let n = node(&s, g); - assert!(n.appearance.effects.is_empty()); - let ch = n.children().unwrap(); - assert_eq!(ch.len(), 1); - assert!((ch[0].geometric_bounds().unwrap().width() - 50.0).abs() < 1e-6); - } - #[test] - fn expand_appearance_gives_each_copy_of_a_transform_its_own_gradient() { - use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; - let (mut s, id) = session_with_rect(); - let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; - let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient { kind: GradientKind::Linear, stops }))); - s.edit("gradient", |d, _| { - let n = d.node_mut(id).unwrap(); - n.appearance.set_fill(ramp); - Ok(()) - }) - .unwrap(); - s.execute("effect.apply", &json!({"effect":"distort.transform","ids":[id.0],"item":null})).unwrap(); - s.execute("effect.setParams", &json!({"index":0,"params":{"moveH":150,"copies":2},"ids":[id.0],"item":null})).unwrap(); - s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); - let mut boxes = vec![]; - node(&s, id).walk(&mut |n| { - if matches!(n.kind, NodeKind::Path { .. }) && matches!(n.appearance.fill_paint(), Paint::Gradient(_)) { - boxes.push(n.geometric_bounds().unwrap().width()); - } - }); - assert_eq!(boxes, vec![100.0; 3], "three squares, each with its own gradient"); - } -} +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs b/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs new file mode 100644 index 0000000000..82426c5ea0 --- /dev/null +++ b/crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs @@ -0,0 +1,93 @@ +#![allow(clippy::unwrap_used, clippy::panic)] +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_render::effects::{LIGHTING_PRESETS, matching_lighting_preset}; + +use crate::Session; + +fn setup(effect: &str, item: Value) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap(); + s.execute( + "effect.apply", + &json!({"effect":effect,"item":item,"params":{ + "rotationX":13,"rotationY":17,"rotationZ":9,"shade":false,"ambient":17, + "lights":[{"color":"#ff8040"},{"color":"#4080ff","rotation":-35}] + }}), + ) + .unwrap(); + (s, id) +} + +#[test] +fn lighting_presets_preserve_source_and_view_and_round_trip_in_one_undo_step() { + for effect in ["threeD.revolve", "threeD.extrude", "threeD.inflate", "threeD.rotate"] { + for (i, preset) in LIGHTING_PRESETS.iter().enumerate() { + let (mut s, id) = setup(effect, Value::Null); + s.doc_mut().unwrap().mark_saved(); + let before = s.doc().unwrap().doc.clone(); + let history = s.doc().unwrap().history.undo.len(); + let p = json!({"index":0,"item":null,"preset":preset.id}); + s.check_params("effect.lightingPreset", &p).unwrap(); + s.execute("effect.lightingPreset", &p).unwrap(); + let after = s.doc().unwrap().doc.clone(); + let actual = &after.node(id).unwrap().appearance.effects[0].params; + let mut expected = before.node(id).unwrap().appearance.effects[0].params.clone(); + expected.as_object_mut().unwrap().extend(preset.params().as_object().unwrap().clone()); + assert_eq!(*actual, expected); + assert_eq!(matching_lighting_preset(actual), Some(i)); + assert_eq!(after.node(id).unwrap().path_data(), before.node(id).unwrap().path_data()); + assert_eq!(actual["rotationX"], 13); + assert_eq!(actual["shade"], false); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + let reopened = vectorcraft_format::load(&vectorcraft_format::save(&after, false)).unwrap(); + assert_eq!(reopened.node(id).unwrap().appearance.effects[0].params, *actual); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + assert!(!s.doc().unwrap().is_dirty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, after); + } + } +} + +#[test] +fn lighting_presets_target_fill_effects_and_reject_invalid_requests_atomically() { + let (mut s, id) = setup("threeD.rotate", json!(0)); + for p in [ + json!({"index":0,"item":0,"preset":"unknown"}), + json!({"index":0,"item":0,"preset":12}), + json!({"index":1,"item":0,"preset":"right"}), + json!({"index":0,"item":null,"preset":"right"}), + json!({"index":0,"item":0,"preset":"right","params":{"ambient":200}}), + ] { + s.doc_mut().unwrap().mark_saved(); + let before = s.doc().unwrap().doc.clone(); + let history = s.doc().unwrap().history.undo.len(); + assert!(s.execute("effect.lightingPreset", &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + assert!(!s.doc().unwrap().is_dirty()); + } + s.execute("effect.lightingPreset", &json!({"ids":[id.0],"index":0,"item":0,"preset":"topLeft"})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(n.appearance.effects.is_empty()); + assert_eq!(n.appearance.effects_at(Some(0)).unwrap()[0].params["lightRotation"], 135.0); +} + +#[test] +fn lighting_presets_reject_a_mixed_selection_before_changing_any_effect() { + let (mut s, first) = setup("threeD.rotate", Value::Null); + let second = s.execute("shape.rectangle", &json!({"x":250,"y":100,"width":80,"height":80})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect":"path.offsetPath","item":null})).unwrap(); + s.execute("select.set", &json!({"ids":[first.0,second]})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + let before = s.doc().unwrap().doc.clone(); + let history = s.doc().unwrap().history.undo.len(); + assert!(s.execute("effect.lightingPreset", &json!({"index":0,"item":null,"preset":"right"})).is_err()); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + assert!(!s.doc().unwrap().is_dirty()); +} diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs new file mode 100644 index 0000000000..c23c578d06 --- /dev/null +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -0,0 +1,450 @@ +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_render::effects; + +use crate::{NodeId, Session}; + +fn session_with_rect() -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + (s, NodeId(r["id"].as_u64().unwrap())) +} + +fn node(s: &Session, id: NodeId) -> vectorcraft_doc::Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +#[test] +fn revolve_commands_keep_profile_live_edit_options_expand_and_undo() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":300,"height":300})).unwrap(); + let r = s.execute("path.create", &json!({"d":"M 150 40 L 180 60 L 180 140 L 150 160"})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let source = node(&s, id).path_data().unwrap().clone(); + s.execute("effect.apply", &json!({"effect":"threeD.revolve","ids":[id.0],"item":null})).unwrap(); + let before = effects_for_test(&s, id); + assert_eq!(node(&s, id).path_data(), Some(&source)); + let doc = &s.doc().unwrap().doc; + let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap(); + assert_eq!(restored.node(id).unwrap().path_data(), Some(&source)); + assert_eq!(effects::revolve_art(restored.node(id).unwrap()).unwrap(), before); + let pdf = s.execute("document.serialize", &json!({"format":"pdf"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap(); + assert!(bytes.starts_with(b"%PDF")); + assert!(s.execute("effect.apply", &json!({"effect":"threeD.revolve","ids":[id.0],"item":null})).is_err()); + assert!(s.execute("effect.duplicate", &json!({"index":0,"ids":[id.0],"item":null})).is_err()); + s.execute("effect.setParams", &json!({"index":0,"params":{"angle":180,"offset":10},"ids":[id.0],"item":null})).unwrap(); + assert_ne!(effects_for_test(&s, id), before); + assert!(s.execute("effect.setParams", &json!({"index":0,"params":{"edge":"invalid"},"ids":[id.0],"item":null})).is_err()); + s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); + assert!(matches!(node(&s, id).kind, NodeKind::Group { .. })); + assert!(!effects::has_revolve(&node(&s, id))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, id).path_data(), Some(&source)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(effects_for_test(&s, id), before); +} + +/// Extrude & Bevel, Inflate and Rotate: applied by command, saved and reopened, edited, +/// exported, expanded and undone; one 3D effect per object. +#[test] +fn solid_effects_apply_save_edit_export_expand_and_undo() { + for effect in effects::SOLIDS { + let (mut s, id) = session_with_rect(); + let source = node(&s, id).path_data().unwrap().clone(); + s.execute("effect.apply", &json!({"effect": effect, "ids": [id.0], "item": null})).unwrap(); + let art = effects::solid_art(&node(&s, id)).unwrap(); + assert_eq!(node(&s, id).path_data(), Some(&source), "{effect}: the source stays editable"); + let doc = &s.doc().unwrap().doc; + let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap(); + assert_eq!(effects::solid_art(restored.node(id).unwrap()).unwrap(), art, "{effect}: reopens the same"); + // One 3D effect per object, whichever kind. + for other in ["threeD.revolve", "threeD.extrude", "threeD.rotate"] { + assert!(s.execute("effect.apply", &json!({"effect": other, "ids": [id.0], "item": null})).is_err(), "{effect} + {other}"); + } + s.execute("effect.setParams", &json!({"index": 0, "params": {"rotationY": 50, "rotationX": 10}, "ids": [id.0], "item": null})).unwrap(); + assert_ne!(effects::solid_art(&node(&s, id)).unwrap(), art, "{effect}: options change the art"); + assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"bevel": "nope"}, "ids": [id.0], "item": null})).is_err()); + let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap(); + let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string()); + assert!(svg.matches("= 2, "{effect}: exported as vector faces"); + s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap(); + assert!(matches!(node(&s, id).kind, NodeKind::Group { .. }), "{effect}"); + assert!(!effects::has_solid(&node(&s, id))); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, id).appearance.effects.len(), 0, "{effect}: back to the plain rectangle"); + } + // Type has no outline to extrude. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let t = s.execute("text.create", &json!({"x": 50, "y": 50, "text": "3D"})).unwrap(); + let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [t["id"]], "item": null})).unwrap_err(); + assert!(err.to_string().contains("requires a path"), "{err}"); +} + +/// Scripts from before the Perspective angle give `perspective` as a 0–100 % strength: it is +/// stored as the angle that shows the same view, and a later angle replaces an earlier strength. +#[test] +fn an_earlier_perspective_strength_is_set_as_its_angle() { + let (mut s, id) = session_with_rect(); + s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": {"perspective": 60}})).unwrap(); + let params = |s: &Session| node(s, id).appearance.effects[0].params.clone(); + let angle_of = |pct: f64| effects::merged_params(effects::EXTRUDE, &json!({"perspective": pct}))["perspectiveAngle"].as_f64().unwrap(); + let angle = angle_of(60.0); + assert!((angle - 30.12).abs() < 0.01, "{angle}"); + assert!(params(&s).get("perspective").is_none() && (params(&s)["perspectiveAngle"].as_f64().unwrap() - angle).abs() < 1e-12, "{}", params(&s)); + s.execute("effect.setParams", &json!({"index": 0, "params": {"perspective": 100}, "ids": [id.0], "item": null})).unwrap(); + assert!((params(&s)["perspectiveAngle"].as_f64().unwrap() - angle_of(100.0)).abs() < 1e-12); + // A file of then: the strength stored; setting an angle replaces it. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.effects[0].params = + json!({"depth": 50, "perspective": 60}); + s.execute("effect.setParams", &json!({"index": 0, "params": {"perspectiveAngle": 120}, "ids": [id.0], "item": null})).unwrap(); + assert_eq!(params(&s), json!({"depth": 50, "perspectiveAngle": 120})); +} + +/// Scripts from before Rotation and Height give the light by `lightAzimuth` and +/// `lightElevation`: stored as the same light; a later Height keeps that light's Rotation. +#[test] +fn an_earlier_light_direction_is_set_as_rotation_and_height() { + let (mut s, id) = session_with_rect(); + s.execute("effect.apply", &json!({"effect": effects::ROTATE, "ids": [id.0], "item": null, "params": {"lightAzimuth": 180, "lightElevation": 0}})) + .unwrap(); + let params = |s: &Session| node(s, id).appearance.effects[0].params.clone(); + // Straight from behind the object, level with it. + assert!(params(&s).get("lightAzimuth").is_none() && params(&s).get("lightElevation").is_none(), "{}", params(&s)); + assert_eq!((params(&s)["lightHeight"].as_f64().unwrap().round(), ¶ms(&s)["lightBehind"]), (90.0, &json!(true))); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.effects[0].params = + json!({"lightAzimuth": 90, "lightElevation": 0}); + s.execute("effect.setParams", &json!({"index": 0, "params": {"lightHeight": 60}, "ids": [id.0], "item": null})).unwrap(); + assert_eq!(params(&s), json!({"lightRotation": 0.0, "lightHeight": 60, "lightBehind": false})); +} + +/// Scripts from before Scribble's separate variations give one `variation`, which is stored as the +/// Path Overlap and Spacing variations. An angle is stored above -180° and up to 180°. +#[test] +fn scribble_stores_an_earlier_variation_as_two_and_its_angle_within_180() { + let (mut s, id) = session_with_rect(); + let p = json!({"effect": "stylize.scribble", "ids": [id.0], "item": null, "params": {"angle": 270, "variation": 2}}); + s.execute("effect.apply", &p).unwrap(); + let params = |s: &Session| node(s, id).appearance.effects[0].params.clone(); + assert_eq!((params(&s)["angle"].as_f64(), params(&s).get("variation")), (Some(-90.0), None), "{}", params(&s)); + assert_eq!((¶ms(&s)["overlapVariation"], ¶ms(&s)["spacingVariation"]), (&json!(2), &json!(2))); + s.execute("effect.setParams", &json!({"index": 0, "params": {"angle": -200}, "ids": [id.0], "item": null})).unwrap(); + assert_eq!(params(&s)["angle"].as_f64(), Some(160.0)); + // A file of then stores its variation; setting one of the two keeps it for the other. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.effects[0].params = json!({"variation": 3}); + s.execute("effect.setParams", &json!({"index": 0, "params": {"spacingVariation": 1}, "ids": [id.0], "item": null})).unwrap(); + assert_eq!(params(&s), json!({"overlapVariation": 3, "spacingVariation": 1})); +} + +fn effects_for_test(s: &Session, id: NodeId) -> vectorcraft_doc::Node { + effects::revolve_art(&node(s, id)).unwrap() +} + +#[test] +fn smooth_revolve_commands_validate_save_expand_and_undo() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":300,"height":300})).unwrap(); + let r = s.execute("path.create", &json!({"d":"M150 40 C190 60 190 140 150 160"})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("effect.apply", &json!({"effect":"threeD.revolve","ids":[id.0],"item":null,"params":{"offset":20,"segments":16}})).unwrap(); + let initial = node(&s, id); + let source = initial.path_data().unwrap().clone(); + assert!(!initial.appearance.effects[0].params.as_object().unwrap().contains_key("smoothShading")); + assert!(initial.appearance.effects[0].params["cap"].as_bool().unwrap()); + let mut gradients = 0; + effects_for_test(&s, id).walk(&mut |face| { + gradients += face.appearance.items.iter().filter(|item| { + matches!(item, vectorcraft_doc::AppearanceItem::Fill(fill) if matches!(fill.paint, vectorcraft_doc::color::Paint::Gradient(_))) + }).count(); + }); + assert!(gradients > 0, "commands use smooth vector shading by default"); + s.execute("effect.setParams", &json!({"index":0,"ids":[id.0],"item":null,"params":{"lightAzimuth":30}})).unwrap(); + let smooth = node(&s, id); + assert_eq!(smooth.path_data(), Some(&source)); + assert_ne!(effects_for_test(&s, id), effects::revolve_art(&initial).unwrap()); + let restored = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!(effects::revolve_art(restored.node(id).unwrap()), Some(effects_for_test(&s, id))); + s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); + assert!(!effects::has_revolve(&node(&s, id))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, id), smooth); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, id), initial); +} + +#[test] +fn revolve_caps_save_export_expand_and_undo_without_changing_the_source() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":300,"height":300})).unwrap(); + let r = s.execute("path.create", &json!({"d":"M150 40 L150 160"})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let source = node(&s, id).path_data().unwrap().clone(); + s.execute( + "effect.apply", + &json!({"effect":"threeD.revolve","ids":[id.0],"item":null, + "params":{"offset":30,"rotationX":-35,"segments":16,"expandVisibleOnly":false,"cap":false}}), + ) + .unwrap(); + let uncapped = node(&s, id); + assert_eq!(uncapped.appearance.effects[0].params["cap"], json!(false)); + let count = |n: &vectorcraft_doc::Node| n.children().unwrap()[0].children().unwrap().len(); + let open_count = count(&effects_for_test(&s, id)); + s.execute("effect.setParams", &json!({"index":0,"ids":[id.0],"item":null,"params":{"cap":true}})).unwrap(); + let capped = node(&s, id); + let art = effects_for_test(&s, id); + assert_eq!(count(&art), open_count + 2, "each endpoint adds one continuous vector cap"); + assert_eq!(capped.path_data(), Some(&source)); + assert!(s.execute("effect.setParams", &json!({"index":0,"ids":[id.0],"item":null,"params":{"cap":"yes"}})).is_err()); + assert_eq!(node(&s, id), capped, "a bad boolean does not mutate the document"); + let restored = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!(restored.node(id).unwrap().appearance.effects[0].params["cap"], json!(true)); + assert_eq!(effects::revolve_art(restored.node(id).unwrap()), Some(art.clone())); + let pdf = s.execute("document.serialize", &json!({"format":"pdf"})).unwrap(); + assert!(vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap().starts_with(b"%PDF")); + s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); + assert_eq!(count(&node(&s, id)), count(&art)); + assert!(!effects::has_revolve(&node(&s, id))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, id), capped); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, id), uncapped); +} + +#[test] +fn revolve_visibility_parameter_saves_expands_and_undoes_without_other_appearance_changes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":300,"height":300})).unwrap(); + let r = s.execute("path.create", &json!({"d":"M 150 40 L 180 60 L 180 140 L 150 160"})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("effect.apply", &json!({"effect":"threeD.revolve","ids":[id.0],"item":null})).unwrap(); + let live = node(&s, id); + let restored = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!(restored.node(id).unwrap().appearance.effects[0].params["expandVisibleOnly"], json!(true)); + let count = |n: &vectorcraft_doc::Node| n.children().unwrap()[0].children().unwrap().len(); + s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); + let visible = count(&node(&s, id)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, id), live); + s.execute("effect.setParams", &json!({"index":0,"item":null,"ids":[id.0],"params":{"expandVisibleOnly":false}})).unwrap(); + s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); + assert!(count(&node(&s, id)) > visible); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, id).appearance.effects[0].params["expandVisibleOnly"], json!(false)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, id), live); + // The shared command still expands ordinary multiple-fill artwork as before. + let r = s.execute("shape.rectangle", &json!({"x":10,"y":10,"width":20,"height":20})).unwrap(); + let ordinary = NodeId(r["id"].as_u64().unwrap()); + s.execute("effect.apply", &json!({"effect":"distort.twist","ids":[ordinary.0],"params":{"angle":15}})).unwrap(); + s.execute("effect.expandAppearance", &json!({"ids":[ordinary.0]})).unwrap(); + assert!(node(&s, ordinary).appearance.effects.is_empty()); +} + +#[test] +fn apply_uses_catalog_defaults_and_undoes() { + let (mut s, id) = session_with_rect(); + let r = s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"x": 3}})).unwrap(); + assert_eq!(r["index"], json!(0)); + let n = node(&s, id); + assert_eq!(n.appearance.effects.len(), 1); + assert_eq!(n.appearance.effects[0].params["x"], json!(3)); + assert_eq!(n.appearance.effects[0].params["opacity"], json!(75.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, id).appearance.effects.is_empty()); + assert!(s.execute("effect.apply", &json!({"effect": "nope"})).is_err()); +} + +#[test] +fn warp_options_style_change_preserves_slot_and_visibility() { + let (mut s, id) = session_with_rect(); + for effect in ["path.offsetPath", "warp.arc", "stylize.roundCorners"] { + s.execute("effect.apply", &json!({"effect": effect, "item": 1})).unwrap(); + } + s.execute("effect.setParams", &json!({"index": 1, "item": 1, "visible": false})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let result = s.execute("effect.setParams", &json!({"index": 1, "item": 1, "warpStyle": "flag", "params": {"bend": 25.0}})); + assert!(result.is_ok(), "an applied warp can change style in place: {result:?}"); + let old = before.node(id).unwrap().appearance.effects_at(Some(1)).unwrap(); + let n = node(&s, id); + let new = n.appearance.effects_at(Some(1)).unwrap(); + assert_eq!(new.len(), 3); + assert_eq!(new[0], old[0]); + assert_eq!(new[2], old[2]); + assert_eq!(new[1].id, "warp.flag"); + assert_eq!(new[1].params["bend"], 25.0); + assert!(!new[1].visible); + assert!(n.appearance.effects.is_empty()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let after = s.doc().unwrap().doc.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + assert!(!s.doc().unwrap().is_dirty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, after); +} + +#[test] +fn warp_options_non_warp_target_rejection_is_atomic() { + let (mut s, first) = session_with_rect(); + s.execute("effect.apply", &json!({"effect": "warp.arc", "item": null})).unwrap(); + let second = s.execute("shape.rectangle", &json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "distort.twist", "item": null})).unwrap(); + s.execute("select.set", &json!({"ids": [first.0, second]})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + let before = s.doc().unwrap().doc.clone(); + let selection = s.doc().unwrap().selection.clone(); + let undo = s.doc().unwrap().history.undo.len(); + assert!(s.execute("effect.setParams", &json!({"index": 0, "item": null, "warpStyle": "flag"})).is_err()); + let state = s.doc().unwrap(); + assert_eq!(state.doc, before); + assert_eq!(state.selection, selection); + assert_eq!(state.history.undo.len(), undo); + assert!(!state.is_dirty()); +} + +#[test] +fn list_remove_and_set_params() { + let (mut s, id) = session_with_rect(); + s.execute("effect.apply", &json!({"effect": "distort.twist"})).unwrap(); + s.execute("effect.apply", &json!({"effect": "stylize.outerGlow"})).unwrap(); + let l = s.execute("effect.list", &json!({})).unwrap(); + assert!(l["catalog"].as_array().unwrap().len() >= 34); + assert_eq!(l["applied"][0]["effects"].as_array().unwrap().len(), 2); + s.execute("effect.setParams", &json!({"index": 0, "params": {"angle": 45}, "visible": false})).unwrap(); + let e = &node(&s, id).appearance.effects[0]; + assert_eq!(e.params["angle"], json!(45)); + assert!(!e.visible); + s.execute("effect.remove", &json!({"index": 0})).unwrap(); + let n = node(&s, id); + assert_eq!(n.appearance.effects.len(), 1); + assert_eq!(n.appearance.effects[0].id, "stylize.outerGlow"); + assert!(s.execute("effect.remove", &json!({"index": 5})).is_err()); +} + +#[test] +fn expand_appearance_bakes_geometry() { + let (mut s, id) = session_with_rect(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("effect.apply", &json!({"effect": "path.offsetPath", "params": {"offset": 10}})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + // One fill: the path itself, reshaped. + let n = node(&s, id); + let b = n.geometric_bounds().unwrap(); + assert!((b.width() - 120.0).abs() < 0.1, "{b:?}"); + assert!(n.appearance.effects.is_empty()); + assert!(matches!(n.kind, NodeKind::Path { live: None, .. })); + // Nothing left to expand. + assert!(s.execute("effect.expandAppearance", &json!({})).is_err()); +} + +#[test] +fn expand_transform_copies_makes_compound() { + let (mut s, id) = session_with_rect(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 120, "copies": 1}})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let n = node(&s, id); + assert!(matches!(n.kind, NodeKind::Compound { .. })); + let b = n.geometric_bounds().unwrap(); + assert!((b.x1 - 320.0).abs() < 1e-6, "{b:?}"); +} + +#[test] +fn pathfinder_effect_on_loose_objects_groups_them_first() { + let (mut s, a) = session_with_rect(); + let b = NodeId(s.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let r = s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap(); + assert_eq!(r["grouped"], true); + let g = NodeId(r["ids"][0].as_u64().unwrap()); + let gn = node(&s, g); + assert_eq!(gn.children().unwrap().iter().map(|c| c.id).collect::>(), [a, b], "stacking order kept"); + assert!(vectorcraft_render::effects::has_pathfinder(&gn)); + assert_eq!(s.doc().unwrap().selection.objects, [g]); + // Live: one united shape, so expanding leaves a single path. + s.execute("effect.expandAppearance", &json!({})).unwrap(); + assert_eq!(node(&s, g).children().unwrap().len(), 1); + // Grouping and applying are one undo step. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(g).is_none()); + assert!(d.node(a).is_some_and(|n| n.appearance.effects.is_empty()) && d.parent_of(a) == d.parent_of(b)); + // A selection holding a group applies to each object as before; so does a single object. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap(); + assert!(r.get("grouped").is_none()); + assert_eq!(node(&s, a).appearance.effects.len(), 1); +} + +#[test] +fn pathfinder_effect_on_a_group_with_type_cuts_the_glyphs_out() { + let (mut s, a) = session_with_rect(); + let t = NodeId(s.execute("text.create", &json!({"x": 110, "y": 180, "text": "H", "size": 100})).unwrap()["id"].as_u64().unwrap()); + let glyphs = effects::outline_text(&node(&s, t)).unwrap(); + let b = glyphs.geometric_bounds().unwrap(); + assert!(b.x0 > 105.0 && b.y0 > 105.0 && b.x1 < 195.0 && b.y1 < 195.0, "the type lies inside the square: {b:?}"); + let area = |n: &vectorcraft_doc::Node| effects::member_shapes(None, n).iter().map(|(p, r)| vectorcraft_pathops::area(p, *r)).sum::(); + let glyph_area = area(&glyphs); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("effect.apply", &json!({"effect": "pathfinder.subtract"})).unwrap(); + // Live: the renderer leaves the glyph's place in the square empty. + let doc = s.doc().unwrap().doc.clone(); + let img = vectorcraft_render::Renderer::new().render(&doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + let empty = (105..195).flat_map(|y| (105..195).map(move |x| (x, y))).filter(|&(x, y)| img.pixel(x, y)[3] == 0).count(); + assert!(empty as f64 > glyph_area / 2.0, "{empty} empty pixels for a glyph area of {glyph_area}"); + // Expanded: the group holds the square minus the glyph. + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let left = area(&node(&s, g)); + assert!((left - (10_000.0 - glyph_area)).abs() < 0.5, "{left} left of the square for a glyph area of {glyph_area}"); +} + +#[test] +fn pathfinder_effect_on_a_group_renders_live_and_expands() { + let (mut s, a) = session_with_rect(); + let b = s.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b["id"]]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("effect.apply", &json!({"effect": "pathfinder.subtract"})).unwrap(); + // Live: the renderer shows only the back square minus the front one. + let doc = s.doc().unwrap().doc.clone(); + let img = vectorcraft_render::Renderer::new().render(&doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + assert!(img.pixel(125, 150)[3] > 0); + assert_eq!(img.pixel(200, 150)[3], 0); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let n = node(&s, g); + assert!(n.appearance.effects.is_empty()); + let ch = n.children().unwrap(); + assert_eq!(ch.len(), 1); + assert!((ch[0].geometric_bounds().unwrap().width() - 50.0).abs() < 1e-6); +} +#[test] +fn expand_appearance_gives_each_copy_of_a_transform_its_own_gradient() { + use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; + let (mut s, id) = session_with_rect(); + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + s.edit("gradient", |d, _| { + let n = d.node_mut(id).unwrap(); + n.appearance.set_fill(ramp); + Ok(()) + }) + .unwrap(); + s.execute("effect.apply", &json!({"effect":"distort.transform","ids":[id.0],"item":null})).unwrap(); + s.execute("effect.setParams", &json!({"index":0,"params":{"moveH":150,"copies":2},"ids":[id.0],"item":null})).unwrap(); + s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); + let mut boxes = vec![]; + node(&s, id).walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) && matches!(n.appearance.fill_paint(), Paint::Gradient(_)) { + boxes.push(n.geometric_bounds().unwrap().width()); + } + }); + assert_eq!(boxes, vec![100.0; 3], "three squares, each with its own gradient"); +} diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index ebeacf63a4..efcccd241b 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -5,14 +5,15 @@ //! gradient becomes a mesh shaped like the object. A pattern fill becomes the tiles it paints inside a clip //! group shaped like the object. Create Gradient Mesh shares the sampling. +use std::collections::BTreeSet; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::cms::Model; use vectorcraft_color::freeform::spread_scale; -use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, Paint}; +use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, Paint}; use vectorcraft_doc::appearance::{AppearanceItem, FillLayer}; -use vectorcraft_doc::live::{GradientMesh, lerp_color}; +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}; @@ -412,6 +413,45 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { }) } +/// Expand the pattern fills under `root` that paint a transparent image into the tiles they paint +/// ([`expand_patterns_where`]), so each tile image becomes an object of its own; the other +/// pattern fills stay. A tile image counts as +/// transparent when its key is in `see_through` (it has see-through pixels), or when it, a group +/// in the tile art, the fill, the shape or a group the shape is in has opacity or a blending +/// mode. Returns how many shapes changed. +pub(crate) fn expand_transparent_image_patterns(d: &mut Document, root: NodeId, see_through: &BTreeSet) -> Result { + let (_, n) = replace_leaves(d, root, |d, l| { + // Most leaves have no pattern fill: skip the ancestry walk for them. + if !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { + return None; + } + let shape = d.ancestry(l.id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(blended); + let transparent = |d: &Document, i: &AppearanceItem| { + pattern_fill(d, i).is_some_and(|(f, def, _)| { + let on = shape || f.opacity < 1.0 || f.blend != BlendMode::Normal; + def.art.iter().any(|a| transparent_image(a, see_through, on)) + }) + }; + expand_patterns_where(d, l, transparent) + })?; + Ok(n) +} + +/// Whether `n` has opacity or a blending mode of its own. +fn blended(n: &Node) -> bool { + n.opacity < 1.0 || n.blend != BlendMode::Normal +} + +/// Whether `n` is or holds a transparent image: one with see-through pixels (key in `keys`), or +/// with opacity or a blending mode of its own or of a group in `n`, or anywhere when `on`. +fn transparent_image(n: &Node, keys: &BTreeSet, on: bool) -> bool { + let on = on || blended(n); + match &n.kind { + NodeKind::Image(im) => on || keys.contains(&im.key), + _ => n.children().is_some_and(|ch| ch.iter().any(|c| transparent_image(c, keys, on))), + } +} + /// Path `l` with each pattern fill turned into the tiles it paints over the box of the outline it /// fills, in a clip group shaped like that outline with the fill's opacity, blend mode and effects /// other than geometry effects, in appearance order: the other items stay on plain copies of the @@ -420,7 +460,15 @@ fn expand_pattern_fills(s: &mut Session) -> Result<()> { /// ([`pattern_tiles`]). A pattern fill that lays no tile there stays. `None` when no pattern fill /// lays a tile. fn expand_patterns(d: &mut Document, l: &Node) -> Option { - if !matches!(l.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()) { + expand_patterns_where(d, l, |_, _| true) +} + +/// [`expand_patterns`] for only the pattern fills `which` picks: the others stay like the other +/// items. +fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool) -> Option { + if !matches!(l.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + || !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some() && which(d, i)) + { return None; } let reshaped = reshaped(l); @@ -431,7 +479,7 @@ fn expand_patterns(d: &mut Document, l: &Node) -> Option { let mut rest = vec![]; let mut expanded = false; for item in &l.appearance.items { - let fill = pattern_fill(d, item).map(|(f, def, xf)| (f, def.clone(), xf)); + let fill = pattern_fill(d, item).filter(|_| which(d, item)).map(|(f, def, xf)| (f, def.clone(), xf)); let tiles = fill.and_then(|(f, def, xf)| { let (fl, _, bounds) = fill_shape(l, item, &path, bounds)?; let t = pattern_tiles(d, &def, xf, bounds); @@ -604,7 +652,7 @@ fn seeded_here(n: &Node) -> bool { /// Does `n`, something in it or one of their opacity masks have a random Transform effect /// ([`seeded_here`])? -fn has_seeded(n: &Node) -> bool { +pub(crate) fn has_seeded(n: &Node) -> bool { seeded_here(n) || n.extras().mask.as_ref().is_some_and(|m| has_seeded(&m.art)) || (!matches!(n.kind, NodeKind::Compound { .. }) && n.children().is_some_and(|c| c.iter().any(|c| has_seeded(c)))) @@ -736,7 +784,7 @@ pub(crate) fn gradient_sampler(g: &GradientPaint, bounds: Rect, doc_model: Model }); } let geom = g.resolve(bounds); - Box::new(move |p| g.gradient.sample_with(geom.param_at(g.gradient.kind, p) as f32, lerp_color)) + Box::new(move |p| g.gradient.sample_keep_model(geom.param_at(g.gradient.kind, p) as f32)) } /// Where the colour changes along a gradient between parameters `t0` and `t1`: both ends, every @@ -745,8 +793,13 @@ pub(crate) fn gradient_sampler(g: &GradientPaint, bounds: Rect, doc_model: Model /// are over `max_gap` apart. The colour is linear in display RGB between neighbours, as the /// canvas draws it. fn breaks(g: &Gradient, t0: f64, t1: f64, max_gap: f64) -> Vec<(f64, (Color, f32))> { - let at = |t: f64| (t, g.sample_with(t as f32, lerp_color)); + 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. + if !g.method.is_classic() { + v.extend(g.expanded().map(|(o, ..)| f64::from(o)).filter(|o| *o > t0 && *o < t1).map(at)); + } for (i, s) in g.stops.iter().enumerate() { let o = s.offset as f64; if o > t0 && o < t1 { @@ -844,7 +897,7 @@ impl Frame { /// is just its band, so nothing doubles up. fn pieces(&self, g: &Gradient, n: usize) -> Vec<(PathData, (Color, f32))> { let step = (self.t1 - self.t0) / n as f64; - let color = |k: usize| g.sample_with((self.t0 + (k as f64 + 0.5) * step) as f32, lerp_color); + let color = |k: usize| g.sample_keep_model((self.t0 + (k as f64 + 0.5) * step) as f32); let opaque = g.stops.iter().all(|s| s.opacity >= 1.0); if self.radial { let ellipse = |t: f64| { diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs new file mode 100644 index 0000000000..6e5c9402ef --- /dev/null +++ b/crates/engine/src/cmd/fileio.rs @@ -0,0 +1,208 @@ +//! Document file I/O for every frontend (desktop, web, CLI, control channel, headless MCP): open, +//! 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). +//! - `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…). +//! - `export`: `document.export` / `serialize` / `exportSelection` / `exportForOffice`. +//! - `screens`: Export for Screens (`document.exportForScreens`, `document.exportSettings`); `zip` +//! packs its files as one download, and reads the files of Word documents placed as type. +//! - `save`: `document.save`, Save As / a Copy / as Template, New from Template, Revert and the +//! 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). +//! - `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. +//! +//! [`FORMATS`] is the single list of formats (append-only); open dialogs use [`open_filters`], +//! agents query `document.formats`. + +mod action_batch; +mod affinity; +mod batch; +pub mod dxf; +pub mod dxfimport; +mod encode; +pub mod eps; +mod export; +pub(crate) mod imagemap; +mod legacy_ai; +mod load; +pub(crate) use load::{MAX_RASTER_ALLOC, size_note}; +mod metafile; +mod naming; +mod native; +pub mod pdf; +mod pdfimport; +pub mod pngtext; +pub mod ppi; +pub mod progress; +pub mod psdread; +mod save; +mod screens; +mod svg; +mod text; +mod tgaread; +pub mod zip; + +use serde_json::{Value, json}; + +pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; +pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, encode, encode_all, encode_with_warnings}; +pub(crate) use encode::{anti_alias, background, with_single_artboard}; +pub use export::export_source; +pub(crate) use export::{export_crop, isolated}; +pub(crate) use load::check_not_lossy_overwrite; +use load::err; +pub(crate) use load::import_svg; +pub(crate) use load::is_placeholder; +pub(crate) use load::native_file; +pub(crate) use load::page_or_editing_data; +pub(crate) use load::source; +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 use load::{losses_summary, overwrite_losses}; +pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name}; +pub(crate) use native::preview_png; +pub use native::with_compression_pref; +pub use pdfimport::{LoadOptions, page_document}; +pub(crate) use save::job_for; +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, +}; +pub use screens::{ + PRESET_KEYS as SCREEN_EXPORT_PRESET_KEYS, PRESETS as SCREEN_PRESETS, ScreenExport, ScreenExportPreset, ScreenSize, + builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_rows as screen_preset_rows, +}; +pub(crate) use screens::{ + SHARED_KEYS as SCREEN_SETTINGS_KEYS, check_settings as check_screen_settings, export as export_screens, safe_file_name, + store_settings as store_screen_settings, +}; +pub use svg::options_map as svg_options; +/// Atomic file writes (a temporary file renamed over the target: a failed write never damages the +/// file it replaces), for the apps' own writers too. +#[cfg(not(target_arch = "wasm32"))] +pub use vectorcraft_format::write_atomic; + +use super::*; +use crate::EngineError; + +mod access; +mod commands; +mod export_names; +mod formats; + +#[cfg(not(target_arch = "wasm32"))] +use access::list_dir; +pub use access::write_file_with; +#[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}; +#[cfg(all(test, windows))] +pub(crate) use access::{document_path_on, document_path_with}; +#[cfg(test)] +pub(crate) use access::{drive_share_of, share_of}; +#[cfg(test)] +pub(crate) use access::{drive_share_path, share_path, touched}; +#[cfg(not(target_arch = "wasm32"))] +use access::{may_read, may_write}; +pub use commands::specs; +pub use export_names::artboard_file_names; +pub(crate) use export_names::{default_name, merge, unique_file_names, with_black_output, write_or_return}; +use export_names::{distinct_names, write_encoded}; +use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, writable}; +pub use formats::{ + DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, export_extensions, extension, file_stem, + format, format_for_name, has_own_title, library_open_filters, open_filters, place_filters, plugin_formats, titled_for_export, writable_format, +}; + +#[cfg(test)] +mod tests; +#[cfg(test)] +mod tests_affinity; +#[cfg(test)] +mod tests_pdf; +#[cfg(test)] +mod tests_pdfcolor; +#[cfg(test)] +mod tests_pdfedit; +#[cfg(test)] +mod tests_pdffidelity; +#[cfg(test)] +mod tests_pdfimport; +#[cfg(test)] +mod tests_svg; +#[cfg(test)] +mod tests_svgedit; + +#[cfg(test)] +mod tests_raster; + +#[cfg(test)] +mod tests_exportas; + +#[cfg(test)] +mod tests_jpeg; + +#[cfg(test)] +mod tests_palette; + +#[cfg(test)] +mod tests_batch; +#[cfg(test)] +mod tests_screens; +#[cfg(test)] +mod tests_text; + +#[cfg(test)] +mod tests_dxf; + +#[cfg(test)] +mod tests_pdfsecurity; +#[cfg(test)] +mod tests_svgenc; +#[cfg(test)] +mod tests_svgimport; + +#[cfg(test)] +mod tests_eps; + +#[cfg(test)] +mod tests_dxfimport; +#[cfg(test)] +mod tests_metafile; + +#[cfg(test)] +mod tests_pdfoutput; +#[cfg(test)] +mod tests_tiffbmp; + +#[cfg(test)] +mod tests_pdfx; +#[cfg(test)] +mod tests_psd; +#[cfg(test)] +mod tests_psdread; + +#[cfg(test)] +mod tests_epsimport; + +#[cfg(test)] +mod tests_aiimport; + +#[cfg(test)] +mod tests_pdflayers; + +#[cfg(test)] +mod tests_pdfwebview; + +#[cfg(test)] +mod tests_pdf13; diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs new file mode 100644 index 0000000000..8dfbead2d1 --- /dev/null +++ b/crates/engine/src/cmd/fileio/access.rs @@ -0,0 +1,418 @@ +use super::*; + +// ---------- the file system (none on the web, where commands take and return bytes) ---------- +// +// Every path a command reads or writes goes through these, which check it against the automation +// roots in force ([`crate::file_access`]): a path outside them is an error (`file_stamp` and +// `file_created`: no file), as is any path once roots are in force without its kind of access. + +/// `path` checked for reading against the automation roots in force. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn may_read(path: &str) -> Result<()> { + #[cfg(test)] + touch(path); + crate::file_access::check_read(path).map_err(EngineError::Other) +} + +/// Paths read while [`touched`] runs, on any thread (the SVG importer reads on one of its own). +#[cfg(test)] +static TOUCHED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +#[cfg(test)] +static RECORDING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +#[cfg(test)] +fn touch(path: &str) { + if RECORDING.load(std::sync::atomic::Ordering::SeqCst) > 0 { + TOUCHED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(path.to_string()); + } +} + +/// Run `f` and list the paths read through this module meanwhile (by any test running then). +#[cfg(test)] +pub(crate) fn touched(f: impl FnOnce() -> T) -> (T, Vec) { + use std::sync::atomic::Ordering::SeqCst; + let start = TOUCHED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).len(); + RECORDING.fetch_add(1, SeqCst); + let out = f(); + RECORDING.fetch_sub(1, SeqCst); + let seen = TOUCHED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(start..).unwrap_or_default().to_vec(); + (out, seen) +} + +/// `path` checked for writing against the automation roots in force. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn may_write(path: &str) -> Result<()> { + crate::file_access::check_write(path).map_err(EngineError::Other) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_file(path: &str) -> Result> { + may_read(path)?; + // A device or pipe may never end: only a regular file is read to its end. + if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() { + return Err(EngineError::Other(format!("{path}: not a file"))); + } + std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}"))) +} + +/// The first `max` bytes of the file at `path` (all of it when it is shorter). Anything but a +/// regular file (a folder, a pipe, a device) is refused, also through a link. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_file_head(path: &str, max: usize) -> Result> { + use std::io::Read; + may_read(path)?; + if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() { + return Err(EngineError::Other(format!("{path}: not a file"))); + } + let mut out = vec![]; + std::fs::File::open(path).and_then(|f| f.take(max as u64).read_to_end(&mut out)).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + Ok(out) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { + // Work that stops early for a cancel can leave a truncated result: none of it is written. + vectorcraft_doc::cancel::check()?; + may_write(path)?; + // Never a half-written file: see [`write_atomic`]. + write_atomic(std::path::Path::new(path), bytes).map_err(|e| EngineError::Other(format!("{path}: {e}"))) +} + +/// [`write_file`] with what `fill` writes into the file (a save streamed into it). +#[cfg(not(target_arch = "wasm32"))] +pub fn write_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| EngineError::Other(format!("{path}: {e}"))) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn create_dir(path: &str) -> Result<()> { + may_write(path)?; + std::fs::create_dir_all(path).map_err(|e| EngineError::Other(format!("{path}: {e}"))) +} + +/// Write `bytes` to a new file at `path`. A file already at `path` is an error and is never +/// replaced. When the write fails part way, the file it started is removed. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn write_new_file(path: &str, bytes: &[u8]) -> Result<()> { + use std::io::Write as _; + may_write(path)?; + let err = |e: std::io::Error| EngineError::Other(format!("{path}: {e}")); + let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(path).map_err(err)?; + let written = f.write_all(bytes).and_then(|()| vectorcraft_format::sync_file(&f)); + drop(f); + written.map_err(|e| { + // Best effort: the partly written file is all there is to clean up. + let _ = std::fs::remove_file(path); + err(e) + }) +} + +/// The highest number [`copy_new`] gives a copy's name (`Name 99.png`). +#[cfg(not(target_arch = "wasm32"))] +const MAX_COPY_NUMBER: u32 = 99; + +/// Where [`copy_new`] put a file. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) enum Placed { + /// Copied to this new file. + Copied(std::path::PathBuf), + /// Kept as this file, which holds the same contents. + Kept(std::path::PathBuf), +} + +/// Put a copy of the file `from` into the folder `dir`, never replacing a file there. It tries +/// `Name.ext`, then `Name 2.ext` up to `Name 99.ext`, and stops at the first name that is free, +/// where `create` makes the copy, or that is a file holding the same contents (`same`, given that +/// file and its metadata), which is kept. When `create` fails with `AlreadyExists` (the name was +/// taken meanwhile), it tries the next name. `None` when no name is free or holds the same +/// contents; a name whose metadata can't be read counts as taken. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn copy_new( + from: &std::path::Path, + dir: &std::path::Path, + create: impl Fn(&std::path::Path) -> std::io::Result<()>, + same: impl Fn(&std::path::Path, &std::fs::Metadata) -> bool, +) -> std::io::Result> { + use std::io::ErrorKind; + let (Some(name), Some(stem)) = (from.file_name(), from.file_stem()) else { return Err(ErrorKind::InvalidInput.into()) }; + let ext = from.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default(); + for n in 1..=MAX_COPY_NUMBER { + let to = if n == 1 { dir.join(name) } else { dir.join(format!("{} {n}{ext}", stem.to_string_lossy())) }; + match std::fs::symlink_metadata(&to) { + Err(e) if e.kind() == ErrorKind::NotFound => match create(&to) { + Ok(()) => return Ok(Some(Placed::Copied(to))), + // Taken meanwhile: the next name. + Err(e) if e.kind() == ErrorKind::AlreadyExists => {} + Err(e) => return Err(e), + }, + Ok(m) if m.is_file() && same(&to, &m) => return Ok(Some(Placed::Kept(to))), + _ => {} + } + } + Ok(None) +} + +/// The most entries `file.list` returns. +const LIST_MAX: usize = 5000; + +pub(super) fn file_list(_: &mut Session, p: &Value) -> Result { + let path = p.get("path").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| bad("file.list", "missing `path`"))?; + let (entries, truncated) = list_dir(path, LIST_MAX)?; + Ok(json!({ "path": absolute_path(path), "entries": entries, "truncated": truncated })) +} + +/// The entries of folder `path`, sorted by name: at most `max`, and whether there were more. A +/// link isn't followed: its target may lie outside the automation roots. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn list_dir(path: &str, max: usize) -> Result<(Vec, bool)> { + may_read(path)?; + let dir = std::fs::read_dir(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + let mut entries: Vec<(String, Value)> = vec![]; + let mut truncated = false; + for e in dir.flatten() { + if entries.len() == max { + truncated = true; + break; + } + let name = e.file_name().to_string_lossy().into_owned(); + let Ok(t) = e.file_type() else { continue }; + let entry = if t.is_symlink() { + json!({ "name": name, "kind": "link" }) + } else if t.is_dir() { + json!({ "name": name, "kind": "folder" }) + } else { + json!({ "name": name, "kind": "file", "size": e.metadata().map(|m| m.len()).ok() }) + }; + entries.push((name, entry)); + } + entries.sort_by(|a, b| a.0.cmp(&b.0)); + Ok((entries.into_iter().map(|(_, v)| v).collect(), truncated)) +} + +#[cfg(target_arch = "wasm32")] +pub(super) fn list_dir(_: &str, _: usize) -> Result<(Vec, bool)> { + Err(EngineError::Other("no file system here".into())) +} + +/// A file's size (bytes) and modification time (ms since the Unix epoch, when the file system +/// keeps one); `None` when there is no file at `path` (or automation may not read it). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn file_stamp(path: &str) -> Option<(u64, Option)> { + let m = file_metadata(path).filter(std::fs::Metadata::is_file)?; + let modified = m.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_millis() as u64); + Some((m.len(), modified)) +} + +/// When the file at `path` was created (ms since the Unix epoch), when the file system keeps it +/// (and automation may read it). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn file_created(path: &str) -> Option { + let t = file_metadata(path)?.created().ok()?; + t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| d.as_millis() as u64) +} + +/// The file system's metadata of `path`, following links (when automation may read it). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn file_metadata(path: &str) -> Option { + may_read(path).ok()?; + std::fs::metadata(path).ok() +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn file_created(_: &str) -> Option { + None +} + +/// `path` made absolute against the working directory (as given when absolute already, or when +/// that fails). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn absolute_path(path: &str) -> String { + if std::path::Path::new(path).is_absolute() { + return path.to_string(); + } + std::path::absolute(path).map_or_else(|_| path.to_string(), |p| p.to_string_lossy().into_owned()) +} + +/// The file to open for `stored`, a path or `file:` URL stored in a document (a linked file, an +/// SVG image's href), or why it is not followed. `document` is the path of the document it is +/// stored in, when it has one: a relative path is taken from its folder. Only files on this +/// computer, or on the network share the document is on, are followed (see `craft_docpath`); a +/// path that is still relative (no document) is refused, as the working directory isn't the +/// document's choice. On Windows, a document on a mapped drive is on the share behind the drive +/// ([`share_path`]): a path refused as on another computer is checked again against the +/// document's path on that share. A path on a drive mapped to a network share other than the +/// document's ([`drive_share_path`]) is refused as on another computer. Every stored path +/// reaches the file system through this. +pub(crate) fn document_path(stored: &str, document: Option<&str>) -> std::result::Result { + document_path_on(stored, document, share_path, drive_share_path) +} + +/// [`document_path`], with `share` giving a document's path on the network share behind its drive. +pub(crate) fn document_path_with( + stored: &str, + document: Option<&str>, + share: impl FnOnce(&str) -> Option, +) -> std::result::Result { + use craft_docpath::Refused; + let document = document.map(absolute_path); + let resolve = |document: Option<&str>| craft_docpath::resolve_absolute(stored, document.map(std::path::Path::new)); + let path = match resolve(document.as_deref()) { + Err(Refused::Network) => { + let share = document.as_deref().and_then(share).ok_or(Refused::Network)?; + resolve(Some(share.as_str()))? + } + path => path?, + }; + path.into_os_string().into_string().map_err(|_| Refused::Invalid) +} + +/// [`document_path_with`], also refusing a path on a drive that is mapped to a network share other +/// than the document's (or, for a document on this computer or without a path, to any share) as +/// [`craft_docpath::Refused::Network`]. `drive_share` gives a path's path on the share behind its +/// drive (`Y:\art\x.png` on `\\server\other\art\x.png`), or `None` for a path on this computer. A +/// path on the document's own drive is not looked up. A document written `\\?\Z:\…` is looked up +/// on its share as `Z:\…` is. +pub(crate) fn document_path_on( + stored: &str, + document: Option<&str>, + share: impl Fn(&str) -> Option, + drive_share: impl FnOnce(&str) -> Option, +) -> std::result::Result { + let share = |d: &str| share(d.strip_prefix(r"\\?\").filter(|d| drive_letter(d).is_some()).unwrap_or(d)); + let path = document_path_with(stored, document, share)?; + let document = document.map(absolute_path); + let Some(drive) = drive_letter(&path) else { return Ok(path) }; + if document.as_deref().and_then(drive_letter).is_some_and(|d| d.eq_ignore_ascii_case(&drive)) { + return Ok(path); + } + let Some(on_share) = drive_share(&path) else { return Ok(path) }; + let home = document.map(|d| share(&d).unwrap_or(d)); + craft_docpath::resolve(&on_share, home.as_deref().map(std::path::Path::new))?; + Ok(path) +} + +/// The drive letter of an absolute path on a drive (`C:\…`, `C:/…` or `\\?\C:\…`). +fn drive_letter(path: &str) -> Option { + let mut chars = path.strip_prefix(r"\\?\").unwrap_or(path).chars(); + match (chars.next(), chars.next(), chars.next()) { + (Some(l), Some(':'), Some('\\' | '/')) if l.is_ascii_alphabetic() => Some(l), + _ => None, + } +} + +/// The path of `path` (on a drive, `Y:\art\x.png`) on the network share the drive is mapped to +/// (`\\server\other\art\x.png`), when the drive's root folder is on one and automation may read +/// `path`. The root folder's final path ([`std::fs::canonicalize`]) names the share. +#[cfg(windows)] +pub(crate) fn drive_share_path(path: &str) -> Option { + may_read(path).ok()?; + drive_share_of(path, |root| std::fs::canonicalize(root).ok()) +} + +#[cfg(not(windows))] +pub(crate) fn drive_share_path(_: &str) -> Option { + None +} + +/// The path of `path` on the network share its drive is mapped to, given `final_path`, which +/// returns the final path of the drive's root folder (`Y:\`): as [`share_of`] gives it for a +/// document, also for a path written `\\?\Y:\…`. +#[cfg(any(windows, test))] +pub(crate) fn drive_share_of(path: &str, final_path: impl FnOnce(&str) -> Option) -> Option { + let path = path.strip_prefix(r"\\?\").unwrap_or(path); + share_of(path, |folder| { + let (root, rest) = (folder.get(..3)?, folder.get(3..)?); + let root = final_path(root)?; + let root = root.to_str()?.trim_end_matches('\\'); + Some(if rest.is_empty() { root.into() } else { format!(r"{root}\{rest}").into() }) + }) +} + +/// The path of `document` (on a drive, `Z:\jobs\doc.vectorcraft`) on the network share the drive is +/// mapped to (`\\server\share\jobs\doc.vectorcraft`), when its folder is on one and automation may +/// read the folder. The folder's final path ([`std::fs::canonicalize`]) names the share as +/// `\\?\UNC\server\share\…`. +#[cfg(windows)] +pub(crate) fn share_path(document: &str) -> Option { + share_of(document, |folder| { + may_read(folder).ok()?; + std::fs::canonicalize(folder).ok() + }) +} + +#[cfg(not(windows))] +pub(crate) fn share_path(_: &str) -> Option { + None +} + +/// The path of `document` on the network share its drive is mapped to, given `final_path`, which +/// returns the final path of a folder: `None` when `document` is not on a drive (`C:\` or `C:/`) +/// or `final_path` gives no share (`\\?\UNC\server\share\…`), such as a folder on a local volume. +#[cfg(any(windows, test))] +pub(crate) fn share_of(document: &str, final_path: impl FnOnce(&str) -> Option) -> Option { + let mut chars = document.chars(); + if !matches!((chars.next(), chars.next(), chars.next()), (Some(l), Some(':'), Some('\\' | '/')) if l.is_ascii_alphabetic()) { + return None; + } + // The drive's root folder keeps its separator (`Z:\`). + let split = document.rfind(['\\', '/'])?; + let (folder, name) = (document.get(..split.max(3))?, document.get(split + 1..)?); + if name.is_empty() { + return None; + } + let target = final_path(folder)?; + let target = target.to_str()?; + let unc = target.get(..8).filter(|p| p.eq_ignore_ascii_case(r"\\?\UNC\")).and(target.get(8..))?.trim_end_matches('\\'); + if unc.split('\\').filter(|c| !c.is_empty()).count() < 2 { + return None; + } + Some(format!(r"\\{unc}\{name}")) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn file_stamp(_: &str) -> Option<(u64, Option)> { + None +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn absolute_path(path: &str) -> String { + path.to_string() +} + +#[cfg(target_arch = "wasm32")] +fn no_fs(path: &str) -> EngineError { + EngineError::Other(format!("{path}: no file system here (pass dataBase64 to open; omit the path to get dataBase64)")) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_file(path: &str) -> Result> { + Err(no_fs(path)) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_file_head(path: &str, _: usize) -> Result> { + Err(no_fs(path)) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn write_file(path: &str, _: &[u8]) -> Result<()> { + Err(no_fs(path)) +} + +#[cfg(target_arch = "wasm32")] +pub fn write_file_with(path: &str, _: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { + Err(no_fs(path)) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn create_dir(path: &str) -> Result<()> { + Err(no_fs(path)) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn write_new_file(path: &str, _: &[u8]) -> Result<()> { + Err(no_fs(path)) +} diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 7e757eb190..90856aaa47 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -56,7 +56,13 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "batches cannot nest")); } if find_command(id).is_none() { - return Err(bad(C, format!("commands[{i}]: unknown command `{id}`"))); + return Err(bad( + C, + match super::super::params::nearest_command(id) { + Some(near) => format!("commands[{i}]: unknown command `{id}`; did you mean `{near}`?"), + None => format!("commands[{i}]: unknown command `{id}`"), + }, + )); } } let source = str_param(p, "source").unwrap_or("folder"); diff --git a/crates/engine/src/cmd/fileio/affinity.rs b/crates/engine/src/cmd/fileio/affinity.rs index 0a5a2f0313..671bc04b63 100644 --- a/crates/engine/src/cmd/fileio/affinity.rs +++ b/crates/engine/src/cmd/fileio/affinity.rs @@ -1,6 +1,6 @@ //! Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): the native layers, curves, -//! shapes, artboards, text and images that `vectorcraft-affinity` reads, mapped to editable -//! VectorCraft art. Whatever the reader could not map is listed in the warnings. A file whose +//! shapes, artboards, text, tables, master pages, layer effects and images that +//! `vectorcraft-affinity` reads, mapped to editable VectorCraft art. Whatever the reader could not map is listed in the warnings. A file whose //! native document can't be read opens as its embedded preview instead, with a warning that says //! why, and can't be placed. @@ -8,63 +8,28 @@ use std::io::Cursor; use std::sync::Arc; use kurbo::{Affine, BezPath, Point, Rect, Vec2}; +use serde_json::json; use vectorcraft_affinity::model::{self as af, Align as AfAlign, Blend, Kind, Pixels}; use vectorcraft_affinity::paint::{self as ap, Cap, GradientKind as AfKind, Join}; use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; -use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer}; +use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, Effect, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer}; use vectorcraft_doc::geom::{FillRule, PathData, shapes}; -use vectorcraft_doc::text::{CharStyle, Justify, TextKind, TextObject, TextRun}; +use vectorcraft_doc::text::{CharStyle, FirstBaseline, Justify, TextKind, TextObject, TextRun, VerticalAlign}; use vectorcraft_doc::{Artboard, Document, ImageObject, LayerColor, Node, NodeKind, OpacityMask}; use super::load::{err, raster_doc}; use crate::Result; -/// What an Affinity file opened as. -pub(super) struct Imported { - pub doc: Document, - pub warnings: Vec, - /// Only the embedded preview: never placed, used as a template or mined for styles. - pub preview_only: bool, -} +mod document; +mod import; +mod layout; +mod master_copies; +mod nodes; +mod paint; +mod text; -pub(super) fn import(name: &str, bytes: &[u8]) -> Result { - match vectorcraft_affinity::read(bytes, vectorcraft_affinity::Limits::default()) { - Ok(d) => { - let mut b = Builder { doc: Document::new(0.0, 0.0), warnings: Vec::new(), k: 72.0 / d.dpi, layer: 0 }; - b.document(&d)?; - b.doc.limit_depth_noting(&mut b.warnings); - let mut warnings = d.warnings.iter().map(|w| format!("Affinity: not imported or approximated: {w}.")).collect::>(); - warnings.extend(b.warnings.iter().map(|w| format!("Affinity: {w}."))); - Ok(Imported { doc: b.doc, warnings, preview_only: false }) - } - Err(native) => { - let (doc, w) = preview(name, bytes, &native)?; - Ok(Imported { doc, warnings: vec![w], preview_only: true }) - } - } -} - -/// The embedded preview, for files whose native document can't be read. -fn preview(name: &str, bytes: &[u8], native: &vectorcraft_affinity::Error) -> Result<(Document, String)> { - let p = vectorcraft_affinity::preview(bytes).map_err(|e| err(format!("{native}; its embedded preview can't be read either ({e})")))?; - // `raster_doc` normally probes PNG dimensions and keeps its encoded bytes. Verify this - // untrusted preview's complete pixels first, so corrupt data cannot create a blank image. - let mut reader = image::ImageReader::with_format(Cursor::new(p.png), image::ImageFormat::Png); - let mut limits = image::Limits::default(); - limits.max_image_width = Some(4096); - limits.max_image_height = Some(4096); - limits.max_alloc = Some(128 << 20); - reader.limits(limits); - let _pixels = reader.decode().map_err(err)?; - let d = raster_doc(name, p.png)?; - Ok(( - d, - format!( - "The native Affinity document could not be read ({native}). Opened only its embedded {}×{} PNG preview, which may be smaller than the document: no layers, vectors, text or pages. Save a new copy; the Affinity source cannot be saved back. Export SVG or PDF from Affinity for editable vectors.", - p.width, p.height - ), - )) -} +pub(super) use import::import; +use master_copies::{CopyCost, MasterPart}; struct Builder { doc: Document, @@ -73,471 +38,21 @@ struct Builder { k: f64, /// Layers made so far (their colours cycle). layer: u8, -} - -fn rect_of(r: af::Rect) -> Rect { - Rect::new(r.x0, r.y0, r.x1, r.y1) -} - -fn affine(a: af::Affine) -> Affine { - Affine::new(a.0) -} - -impl Builder { - fn warn(&mut self, w: &str) { - if !self.warnings.iter().any(|x| x == w) { - self.warnings.push(w.to_string()); - } - } - - fn document(&mut self, d: &af::Document) -> Result<()> { - // Spreads (Publisher pages) sit side by side, 36 pt apart; a single spread keeps its origin. - let mut layers = Vec::new(); - let mut artboards = Vec::new(); - let mut x = 0.0; - for (i, spread) in d.spreads.iter().enumerate() { - let shift = if i == 0 { 0.0 } else { x - spread.bounds.x0 * self.k }; - let to_doc = Affine::translate((shift, 0.0)) * Affine::scale(self.k); - let before = artboards.len(); - let mut loose: Vec> = Vec::new(); - for n in &spread.nodes { - let top = match &n.kind { - Kind::Layer => self.node(n, to_doc, &mut artboards, true), - Kind::Artboard { .. } => self.node(n, to_doc, &mut artboards, true).map(|art| self.layer_of(&n.name, art, n.visible, n.locked)), - _ => { - if let Some(art) = self.node(n, to_doc, &mut artboards, false) { - loose.push(art); - } - continue; - } - }; - if !loose.is_empty() { - layers.push(self.layer_with(None, std::mem::take(&mut loose))); - } - layers.extend(top); - } - if !loose.is_empty() { - layers.push(self.layer_with(None, loose)); - } - // Without artboards, each page (or the spread) becomes one. - if artboards.len() == before { - let rects = if spread.pages.is_empty() { vec![spread.bounds] } else { spread.pages.clone() }; - for r in rects { - let name = format!("{} {}", if d.spreads.len() > 1 || spread.pages.len() > 1 { "Page" } else { "Artboard" }, artboards.len() + 1); - artboards.push((name, to_doc.transform_rect_bbox(rect_of(r)))); - } - } - x = artboards.iter().map(|(_, r)| r.x1).fold(x, f64::max) + 36.0; - if spread.transparent && i == 0 { - self.warn("transparent page backgrounds show as white artboards"); - } - } - self.doc.artboards = artboards - .into_iter() - .enumerate() - .filter(|(_, (_, r))| r.width() > 0.0 && r.height() > 0.0) - .map(|(i, (name, rect))| Artboard { id: i as u32 + 1, name, rect, show_center_mark: false, show_cross_hairs: false }) - .collect(); - if self.doc.artboards.is_empty() { - return Err(err("the Affinity document has no page with a size")); - } - // Bottom to top, as Affinity lists them. - self.doc.layers = layers; - if self.doc.layers.is_empty() { - let empty = self.layer_with(None, Vec::new()); - self.doc.layers.push(empty); - } - Ok(()) - } - - fn layer_with(&mut self, name: Option<&str>, children: Vec>) -> Arc { - let id = self.doc.alloc_id(); - self.layer = self.layer.wrapping_add(1); - let label = name.map(str::to_string).unwrap_or_else(|| format!("Layer {}", self.layer)); - let mut n = Node::layer(id, &label, LayerColor::Preset(self.layer % 9)); - if let Some(c) = n.children_mut() { - *c = children; - } - Arc::new(n) - } - - /// An artboard at the top level becomes a layer of its name holding its clip group. - fn layer_of(&mut self, name: &str, art: Arc, visible: bool, locked: bool) -> Arc { - let mut l = (*self.layer_with(Some(if name.is_empty() { "Artboard" } else { name }), vec![art])).clone(); - l.visible = visible; - l.locked = locked; - Arc::new(l) - } - - fn base(&mut self, n: &af::Node, kind: NodeKind) -> Node { - let mut out = Node::new(self.doc.alloc_id(), kind); - out.name = (!n.name.is_empty()).then(|| n.name.clone()); - out.visible = n.visible; - out.locked = n.locked; - out.opacity = n.opacity as f32; - out.blend = self.blend(n.blend); - out - } - - fn blend(&mut self, b: Blend) -> BlendMode { - match b { - Blend::Normal | Blend::PassThrough => BlendMode::Normal, - Blend::Darken => BlendMode::Darken, - Blend::Multiply => BlendMode::Multiply, - Blend::ColorBurn => BlendMode::ColorBurn, - Blend::Lighten => BlendMode::Lighten, - Blend::Screen => BlendMode::Screen, - Blend::ColorDodge => BlendMode::ColorDodge, - Blend::Overlay => BlendMode::Overlay, - Blend::SoftLight => BlendMode::SoftLight, - Blend::HardLight => BlendMode::HardLight, - Blend::Difference => BlendMode::Difference, - Blend::Exclusion => BlendMode::Exclusion, - Blend::Hue => BlendMode::Hue, - Blend::Saturation => BlendMode::Saturation, - Blend::Color => BlendMode::Color, - Blend::Luminosity => BlendMode::Luminosity, - _ => { - self.warn("blend modes VectorCraft doesn't have (Add, Linear Light, Vivid Light, Pin Light, Hard Mix, Subtract, Darker/Lighter Colour, Average, Negation, Reflect, Glow, Erase) import as Normal"); - BlendMode::Normal - } - } - } - - /// One Affinity node (and its subtree) as VectorCraft art; `to_doc` maps document pixels to - /// points. `layer_level`: the node is directly in a spread or a layer, so a layer stays a layer. - fn node(&mut self, n: &af::Node, to_doc: Affine, boards: &mut Vec<(String, Rect)>, layer_level: bool) -> Option> { - // Register before descending so nested artboards keep their document order. - if let Kind::Artboard { rect, .. } = &n.kind { - boards.push(( - if n.name.is_empty() { format!("Artboard {}", boards.len() + 1) } else { n.name.clone() }, - to_doc.transform_rect_bbox(rect_of(*rect)), - )); - } - let child_level = matches!(n.kind, Kind::Layer) && layer_level; - let children: Vec> = n.children.iter().filter_map(|c| self.node(c, to_doc, boards, child_level)).collect(); - let mut out = match &n.kind { - Kind::Layer if layer_level => { - let mut l = (*self.layer_with(Some(if n.name.is_empty() { "Layer" } else { &n.name }), children)).clone(); - l.visible = n.visible; - l.locked = n.locked; - l.opacity = n.opacity as f32; - l.blend = self.blend(n.blend); - l - } - Kind::Layer | Kind::Group => { - let mut g = self.base(n, NodeKind::Group { children, clip: false }); - // Affinity groups isolate their blending unless they pass through. - g.isolate = n.blend != Blend::PassThrough; - g - } - Kind::Shape { path, fills, strokes, even_odd } => { - let data = self.path(path, to_doc); - let rule = if *even_odd { FillRule::EvenOdd } else { FillRule::NonZero }; - let appearance = self.appearance(fills, strokes, to_doc); - if children.is_empty() { - let mut p = self.base(n, NodeKind::Path { path: data, rule, live: None, clipping: false, guide: false }); - p.appearance = appearance.into(); - p - } else { - // A shape clips its children: VectorCraft's clipping path keeps its paint, its - // fill behind the clipped art and its stroke over it, as Affinity draws it. - let mut clip = Node::new(self.doc.alloc_id(), NodeKind::Path { path: data, rule, live: None, clipping: true, guide: false }); - clip.appearance = appearance.into(); - let mut kids = vec![Arc::new(clip)]; - kids.extend(children); - self.base(n, NodeKind::Group { children: kids, clip: true }) - } - } - Kind::Artboard { path, even_odd, background, strokes, .. } => { - let mut clip = Node::new( - self.doc.alloc_id(), - NodeKind::Path { - path: self.path(path, to_doc), - rule: if *even_odd { FillRule::EvenOdd } else { FillRule::NonZero }, - live: None, - clipping: true, - guide: false, - }, - ); - clip.appearance = self.appearance(background, strokes, to_doc).into(); - let mut kids = vec![Arc::new(clip)]; - kids.extend(children); - let mut g = self.base(n, NodeKind::Group { children: kids, clip: true }); - g.name = Some(if n.name.is_empty() { "Artboard".into() } else { n.name.clone() }); - g - } - Kind::Text(t) => { - let text = self.text(t, to_doc); - let mut node = self.base(n, NodeKind::Text(Box::new(text))); - if !children.is_empty() { - let mut kids = vec![Arc::new(node)]; - kids.extend(children); - node = Node::group(self.doc.alloc_id(), kids); - } - node - } - Kind::Image(img) => match self.image(img, to_doc) { - Some(kind) => self.base(n, kind), - None if children.is_empty() => return None, - None => self.base(n, NodeKind::Group { children, clip: false }), - }, - Kind::Unsupported if children.is_empty() => return None, - Kind::Unsupported => self.base(n, NodeKind::Group { children, clip: false }), - }; - if let Some(img) = &n.pixel_mask { - // A pixel mask: its grey levels show (white) or hide (black) the node, and nothing - // shows outside it, as an opacity mask that clips. - if let Some(kind) = self.image(img, to_doc) { - let art = Node::new(self.doc.alloc_id(), kind); - out.extras_mut().mask = Some(Box::new(OpacityMask::new(art, true))); - } - } - if let Some(mask) = &n.mask { - // A vector mask: the node shows only inside it. - let clip = Node::new( - self.doc.alloc_id(), - NodeKind::Path { path: self.path(mask, to_doc), rule: FillRule::NonZero, live: None, clipping: true, guide: false }, - ); - let (opacity, blend, visible, name) = (out.opacity, out.blend, out.visible, out.name.clone()); - out.opacity = 1.0; - out.blend = BlendMode::Normal; - let mut g = Node::new(self.doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(out)], clip: true }); - (g.opacity, g.blend, g.visible, g.name) = (opacity, blend, visible, name); - out = g; - } - Some(Arc::new(out)) - } - - fn path(&self, p: &af::Path, to_doc: Affine) -> PathData { - let mut bp = BezPath::new(); - for s in &p.subpaths { - let pt = |q: af::Point| Point::new(q.x, q.y); - bp.move_to(pt(s.start)); - for [c1, c2, e] in &s.segments { - if c1 == c2 && c2 == e { - bp.line_to(pt(*e)); - } else { - bp.curve_to(pt(*c1), pt(*c2), pt(*e)); - } - } - if s.closed { - bp.close_path(); - } - } - PathData::from_bezpath(&(to_doc * bp)) - } - - fn color(c: ap::Color) -> (Color, f32) { - let f = |v: f64| v.clamp(0.0, 1.0) as f32; - match c { - ap::Color::Rgb { r, g, b, a } => (Color::Rgb { r: f(r), g: f(g), b: f(b) }, f(a)), - ap::Color::Cmyk { c, m, y, k, a } => (Color::Cmyk { c: f(c), m: f(m), y: f(y), k: f(k) }, f(a)), - ap::Color::Gray { v, a } => (Color::Gray { k: 1.0 - f(v) }, f(a)), - ap::Color::Lab { l, a, b, alpha } => (Color::Lab { l: l as f32, a: a as f32, b: b as f32 }, f(alpha)), - } - } - - /// A paint and the opacity its colour's alpha becomes. - fn paint(&mut self, p: &ap::Paint, to_doc: Affine) -> Option<(Paint, f32)> { - match p { - ap::Paint::None => None, - ap::Paint::Solid(c) => { - let (color, a) = Self::color(*c); - Some((Paint::solid(color), a)) - } - ap::Paint::Gradient(g) => { - let stops = g - .stops - .iter() - .map(|s| { - let (color, opacity) = Self::color(s.color); - let mut stop = GradientStop::new(s.offset as f32, color); - stop.opacity = opacity; - stop.midpoint = s.half_point().clamp(0.13, 0.87) as f32; - stop - }) - .collect(); - let m = to_doc * affine(g.transform); - let (o, x, y) = (m * Point::ZERO, m * Point::new(1.0, 0.0), m * Point::new(0.0, 1.0)); - let kind = match g.kind { - AfKind::Linear => GradientKind::Linear, - AfKind::Radial => GradientKind::Radial, - AfKind::Conical => { - self.warn("conical gradients import as radial gradients"); - GradientKind::Radial - } - }; - let (u, v): (Vec2, Vec2) = (x - o, y - o); - if kind == GradientKind::Radial && u.hypot() > 0.0 && (u.dot(v) / (u.hypot() * v.hypot().max(1e-12))).abs() > 0.01 { - self.warn("skewed elliptical gradients import as upright ellipses"); - } - let aspect = if u.hypot() > 0.0 { (v.hypot() / u.hypot()).clamp(0.01, 100.0) } else { 1.0 }; - let geom = GradientGeom { start: o, end: x, aspect: if kind == GradientKind::Radial { aspect } else { 1.0 }, focal: None }; - let mut gp = GradientPaint::new(Gradient { kind, stops }); - gp.angle = (-(u.y)).atan2(u.x).to_degrees(); - gp.geom = Some(geom); - Some((Paint::Gradient(Box::new(gp)), 1.0)) - } - } - } - - fn appearance(&mut self, fills: &[ap::Paint], strokes: &[ap::Stroke], to_doc: Affine) -> Appearance { - let mut items = Vec::new(); - let mut above = Vec::new(); - for f in fills { - if let Some((paint, opacity)) = self.paint(f, to_doc) { - let mut l = FillLayer::new(paint); - l.opacity = opacity; - items.push(AppearanceItem::Fill(l)); - } - } - for s in strokes { - let Some((paint, opacity)) = self.paint(&s.paint, to_doc) else { continue }; - let mut l = StrokeLayer::new(paint, s.width * self.k); - l.opacity = opacity; - l.cap = match s.cap { - Cap::Butt => LineCap::Butt, - Cap::Round => LineCap::Round, - Cap::Square => LineCap::Square, - }; - l.join = match s.join { - Join::Miter => LineJoin::Miter, - Join::Round => LineJoin::Round, - Join::Bevel => LineJoin::Bevel, - }; - l.miter_limit = s.miter_limit; - l.align = match s.align { - ap::Align::Center => StrokeAlign::Center, - ap::Align::Inside => StrokeAlign::Inside, - ap::Align::Outside => StrokeAlign::Outside, - }; - l.dash = s.dash.as_ref().map(|(pattern, phase)| Dash { - pattern: pattern.iter().map(|v| v * self.k).collect(), - offset: phase * self.k, - align_corners: false, - }); - if s.behind { - items.insert(0, AppearanceItem::Stroke(l)); - } else { - above.push(AppearanceItem::Stroke(l)); - } - } - items.extend(above); - Appearance { items, ..Appearance::default() } - } - - fn text(&mut self, t: &af::Text, to_doc: Affine) -> TextObject { - let origin = match t.frame { - Some(f) => Point::new(f.x0, f.y0), - None => Point::new(t.anchor.x, t.anchor.y), - }; - // Text space: origin at the anchor (or frame corner), the transform's uniform scale moved - // into the type size so sizes read in points. - let m = to_doc * affine(t.transform) * Affine::translate(origin.to_vec2()); - let c = m.as_coeffs(); - let k = (c[0] * c[3] - c[1] * c[2]).abs().sqrt().max(1e-9); - let xf = m * Affine::scale(1.0 / k); - let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default()); - obj.xf = xf; - obj.runs = t - .runs - .iter() - .map(|r| { - let mut style = CharStyle::default(); - if !r.family.is_empty() { - style.font_family = r.family.clone(); - } else if !r.postscript.is_empty() { - style.font_family = r.postscript.clone(); - } else { - self.warn("text without a font name uses the default font"); - } - // A family/weight pair cannot identify width variants such as Arial Narrow. - // Resolve a known PostScript identity to the exact installed family and style. - if let Some((family, face_style)) = vectorcraft_text::FontDb::global().by_postscript_name(&r.postscript) { - style.font_family = family; - style.font_style = face_style; - } else { - style.font_style = font_style(r.weight, r.italic); - } - style.features = r.features.clone(); - if r.features.iter().any(|feature| !vectorcraft_text::OtFeatures::known_tag(feature)) { - self.warn("unsupported text OpenType features (retained but not rendered)"); - } - style.all_caps = r.all_caps; - style.size = r.size * k; - style.leading = r.leading.map(|l| l * k); - style.tracking = r.tracking * 1000.0; - style.fill = match self.paint(&r.fill, to_doc) { - Some((p, a)) => { - if a < 0.999 { - self.warn("translucent text colours import opaque"); - } - p - } - None => Paint::None, - }; - // Affinity separates paragraphs with U+2029 and lines with U+2028. - TextRun::new(r.text.replace(['\u{2029}', '\u{2028}'], "\n"), style) - }) - .collect(); - obj.para.justify = match t.align { - AfAlign::Left => Justify::Left, - AfAlign::Center => Justify::Center, - AfAlign::Right => Justify::Right, - AfAlign::Justify => Justify::JustifyLeft, - }; - if let Some(f) = t.frame { - obj.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, (f.x1 - f.x0) * k, (f.y1 - f.y0) * k)) }; - // Affinity shows a line in a frame shorter than it (#1423); here none of it would draw. - if vectorcraft_text::fit_first_line(vectorcraft_text::FontDb::global(), &mut obj) { - self.warn("text frames too short for their first line (made taller so the line shows)"); - } - } - obj - } - - fn image(&mut self, img: &af::Image, to_doc: Affine) -> Option { - let bytes = match &img.pixels { - Pixels::Encoded(b) => b.clone(), - Pixels::Rgba8(rgba) => { - let buf = image::RgbaImage::from_raw(img.width, img.height, rgba.clone())?; - let mut png = Vec::new(); - buf.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; - png - } - }; - let r = match super::load::raster_image(&bytes) { - Ok(r) => r, - Err(_) => { - self.warn("an embedded image that could not be decoded was left out"); - return None; - } - }; - // The pixel grid maps onto the Affinity image's own size, whatever the stored file's. - let sx = img.width as f64 / f64::from(r.width.max(1)); - let sy = img.height as f64 / f64::from(r.height.max(1)); - let xf = to_doc * affine(img.transform) * Affine::scale_non_uniform(sx, sy); - self.doc.images.entry(r.key.clone()).or_insert(r.blob); - Some(NodeKind::Image(Box::new(ImageObject { key: r.key, width: r.width, height: r.height, xf, link: None, placement: Default::default() }))) - } -} - -fn font_style(weight: i64, italic: bool) -> String { - let w = match weight { - ..=150 => "Thin", - 151..=250 => "ExtraLight", - 251..=325 => "Light", - 326..=450 => "Regular", - 451..=550 => "Medium", - 551..=650 => "SemiBold", - 651..=750 => "Bold", - 751..=850 => "ExtraBold", - _ => "Black", - }; - match (w, italic) { - ("Regular", true) => "Italic".into(), - (w, true) => format!("{w} Italic"), - (w, false) => w.into(), - } + /// How deep inside embedded Affinity documents the node being mapped is: their artboards + /// are only clip groups, never artboards of this document. + embedded: usize, + /// Each master spread's art as shown on pages, in the order the masters are first used. + masters: Vec<(usize, Vec>)>, + /// The document's CMYK profile, until [`Builder::document_cmyk`] makes its table. + cmyk_profile: Option>, + /// That table, once made (`Some(None)`: there is none). + cmyk_lut: Option>>, + /// The working CMYK profile's table, once a CMYK pixel layer needs it. + working_cmyk: Option>, + /// What baking colour and gradient overlays may still take ([`overlay::MAX_WORK`]). + overlay_work: u64, + /// What copying master pages onto the pages that show them may still take. + copy_left: CopyCost, + /// Each master spread's objects as its pages show them, made the first time one does. + master_parts: std::collections::HashMap>, } diff --git a/crates/engine/src/cmd/fileio/affinity/document.rs b/crates/engine/src/cmd/fileio/affinity/document.rs new file mode 100644 index 0000000000..0d74d1d813 --- /dev/null +++ b/crates/engine/src/cmd/fileio/affinity/document.rs @@ -0,0 +1,211 @@ +use super::layout::{master_instances, master_prefix, page_masters}; +use super::master_copies::{CopyCost, MAX_MASTER_COPIES, MasterPart, copy_cost}; +use super::nodes::rect_of; +use super::*; + +impl Builder { + pub(super) fn new(k: f64) -> Self { + Self { + doc: Document::new(0.0, 0.0), + warnings: Vec::new(), + k, + layer: 0, + embedded: 0, + masters: Vec::new(), + cmyk_profile: None, + cmyk_lut: None, + working_cmyk: None, + overlay_work: vectorcraft_affinity::overlay::MAX_WORK, + copy_left: MAX_MASTER_COPIES, + master_parts: std::collections::HashMap::new(), + } + } + + pub(super) fn warn(&mut self, w: &str) { + if !self.warnings.iter().any(|x| x == w) { + self.warnings.push(w.to_string()); + } + } + + pub(super) fn document(&mut self, d: &af::Document) -> Result<()> { + self.cmyk_profile = d.cmyk_profile.clone(); + // Spreads (Publisher pages) sit side by side, 36 pt apart; a single spread keeps its origin. + let mut layers = Vec::new(); + let mut artboards = Vec::new(); + let mut x = 0.0; + for (i, spread) in d.spreads.iter().enumerate() { + let shift = if i == 0 { 0.0 } else { x - spread.bounds.x0 * self.k }; + let to_doc = Affine::translate((shift, 0.0)) * Affine::scale(self.k); + let before = artboards.len(); + let mut loose: Vec> = Vec::new(); + for n in &spread.nodes { + let top = match &n.kind { + Kind::Layer => self.node(n, to_doc, &mut artboards, true, 0), + Kind::Artboard { .. } => { + self.node(n, to_doc, &mut artboards, true, 0).map(|art| self.layer_of(&n.name, art, n.visible, n.locked)) + } + _ => { + if let Some(art) = self.node(n, to_doc, &mut artboards, false, 0) { + loose.push(art); + } + continue; + } + }; + if !loose.is_empty() { + layers.push(self.layer_with(None, std::mem::take(&mut loose))); + } + layers.extend(top); + } + if !loose.is_empty() { + layers.push(self.layer_with(None, loose)); + } + self.master_pages(d, spread, to_doc); + // Without artboards, each page (or the spread) becomes one. + if artboards.len() == before { + let rects = if spread.pages.is_empty() { vec![spread.bounds] } else { spread.pages.clone() }; + for r in rects { + let name = format!("{} {}", if d.spreads.len() > 1 || spread.pages.len() > 1 { "Page" } else { "Artboard" }, artboards.len() + 1); + artboards.push((name, to_doc.transform_rect_bbox(rect_of(r)))); + } + } + // (Earlier spreads' artboards are all left of `x` already.) + x = artboards.get(before..).unwrap_or_default().iter().map(|(_, r)| r.x1).fold(x, f64::max) + 36.0; + if spread.transparent && i == 0 { + self.warn("transparent page backgrounds show as white artboards"); + } + } + self.doc.artboards = artboards + .into_iter() + .enumerate() + .filter(|(_, (_, r))| r.width() > 0.0 && r.height() > 0.0) + .map(|(i, (name, rect))| Artboard { + id: i as u32 + 1, + name, + rect, + locked: false, + show_center_mark: false, + show_cross_hairs: false, + show_video_safe_areas: false, + video_ruler_pixel_aspect_ratio: 1.0, + color: None, + }) + .collect(); + if self.doc.artboards.is_empty() { + return Err(err("the Affinity document has no page with a size")); + } + // Master pages are behind everything on the pages that show them. + let mut masters = std::mem::take(&mut self.masters); + masters.sort_by_key(|(m, _)| *m); + let mut bottom = Vec::new(); + for (m, art) in masters { + let mut l = (*self.layer_with(Some(&format!("Master {}", master_prefix(m))), art)).clone(); + l.locked = true; + bottom.push(Arc::new(l)); + } + // Bottom to top, as Affinity lists them. + bottom.extend(layers); + self.doc.layers = bottom; + if self.doc.layers.is_empty() { + let empty = self.layer_with(None, Vec::new()); + self.doc.layers.push(empty); + } + Ok(()) + } + + /// The master pages `spread`'s pages show, placed on those pages (`to_doc` places the spread). + /// Each master page shows only the objects on it, moved from its page to the one showing it. + fn master_pages(&mut self, d: &af::Document, spread: &af::Spread, to_doc: Affine) { + let instances = master_instances(&spread.nodes); + if instances.is_empty() { + return; + } + let owners = page_masters(&instances, spread.pages.len()); + for (pi, page) in spread.pages.iter().enumerate() { + let Some(&Some((master, first, master_page))) = owners.get(pi) else { continue }; + let Some(m) = d.masters.get(master) else { continue }; + let index = master_page.saturating_add(pi.saturating_sub(first)); + let r = m.pages.get(index).or_else(|| m.pages.last()).copied().unwrap_or(m.bounds); + let parts = self.master_parts(master, m); + let on_page = |b: &Option| b.is_some_and(|b| b.x1 > r.x0 && b.x0 < r.x1 && b.y1 > r.y0 && b.y0 < r.y1); + // Looking through the master's objects takes one each, copying them what they hold. + let looked = CopyCost { work: parts.len() as u64, pixels: 0 }; + let cost = parts.iter().filter(|p| on_page(&p.bounds)).fold(looked, |c, p| c.plus(p.cost)); + let Some(left) = self.copy_left.minus(cost) else { + self.warn("master pages shown on more pages than one import copies them to (left out on the rest)"); + return; + }; + self.copy_left = left; + let place = to_doc * Affine::translate((page.x0 - r.x0, page.y0 - r.y0)); + let mut art = Vec::new(); + let mut boards = Vec::new(); + self.embedded += 1; + let mut i = 0; + while let Some(p) = parts.get(i).copied() { + let Some(n) = m.nodes.get(p.node) else { + i += 1; + continue; + }; + if p.child.is_none() { + if on_page(&p.bounds) { + art.extend(self.node(n, place, &mut boards, false, 0)); + } + i += 1; + continue; + } + // A layer of the master spread: just its objects on this page. + let mut kids: Vec> = Vec::new(); + while let Some(q) = parts.get(i).copied().filter(|q| q.node == p.node) { + if on_page(&q.bounds) + && let Some(c) = q.child.and_then(|c| n.children.get(c)) + { + kids.extend(self.node(c, place, &mut boards, false, 1)); + } + i += 1; + } + if !kids.is_empty() { + let mut g = self.base(n, NodeKind::Group { children: kids, clip: false }); + g.isolate = n.blend != Blend::PassThrough; + art.push(Arc::new(g)); + } + } + self.embedded -= 1; + if art.is_empty() { + continue; + } + let mut g = Node::group(self.doc.alloc_id(), art); + g.name = Some(format!("Master {} (page {})", master_prefix(master), pi + 1)); + match self.masters.iter_mut().find(|(i, _)| *i == master) { + Some((_, v)) => v.push(Arc::new(g)), + None => self.masters.push((master, vec![Arc::new(g)])), + } + } + } + + /// The objects of master spread `m` (number `index`) as its pages show them: its layers' + /// objects one by one and its other top-level objects, with their bounds and costs. + fn master_parts(&mut self, index: usize, m: &af::Spread) -> Arc<[MasterPart]> { + if let Some(parts) = self.master_parts.get(&index) { + return parts.clone(); + } + if !master_instances(&m.nodes).is_empty() { + self.warn("master pages based on other master pages (only their own objects are used)"); + } + let part = |node: usize, child: Option, n: &af::Node| MasterPart { + node, + child, + bounds: af::nodes_bounds(std::slice::from_ref(n)), + cost: copy_cost(n, 0), + }; + let mut parts = Vec::new(); + for (i, n) in m.nodes.iter().enumerate() { + if matches!(n.kind, Kind::Layer) { + parts.extend(n.children.iter().enumerate().map(|(c, child)| part(i, Some(c), child))); + } else { + parts.push(part(i, None, n)); + } + } + let parts: Arc<[MasterPart]> = parts.into(); + self.master_parts.insert(index, parts.clone()); + parts + } +} diff --git a/crates/engine/src/cmd/fileio/affinity/import.rs b/crates/engine/src/cmd/fileio/affinity/import.rs new file mode 100644 index 0000000000..625df1e3b8 --- /dev/null +++ b/crates/engine/src/cmd/fileio/affinity/import.rs @@ -0,0 +1,48 @@ +use super::*; + +/// What an Affinity file opened as. +pub(in super::super) struct Imported { + pub doc: Document, + pub warnings: Vec, + /// Only the embedded preview: never placed, used as a template or mined for styles. + pub preview_only: bool, +} + +pub(in super::super) fn import(name: &str, bytes: &[u8]) -> Result { + match vectorcraft_affinity::read(bytes, vectorcraft_affinity::Limits::default()) { + Ok(d) => { + let mut b = Builder::new(72.0 / d.dpi); + b.document(&d)?; + b.doc.limit_depth_noting(&mut b.warnings); + let mut warnings = d.warnings.iter().map(|w| format!("Affinity: not imported or approximated: {w}.")).collect::>(); + warnings.extend(b.warnings.iter().map(|w| format!("Affinity: {w}."))); + Ok(Imported { doc: b.doc, warnings, preview_only: false }) + } + Err(native) => { + let (doc, w) = preview(name, bytes, &native)?; + Ok(Imported { doc, warnings: vec![w], preview_only: true }) + } + } +} + +/// The embedded preview, for files whose native document can't be read. +fn preview(name: &str, bytes: &[u8], native: &vectorcraft_affinity::Error) -> Result<(Document, String)> { + let p = vectorcraft_affinity::preview(bytes).map_err(|e| err(format!("{native}; its embedded preview can't be read either ({e})")))?; + // `raster_doc` normally probes PNG dimensions and keeps its encoded bytes. Verify this + // untrusted preview's complete pixels first, so corrupt data cannot create a blank image. + let mut reader = image::ImageReader::with_format(Cursor::new(p.png), image::ImageFormat::Png); + let mut limits = image::Limits::default(); + limits.max_image_width = Some(4096); + limits.max_image_height = Some(4096); + limits.max_alloc = Some(128 << 20); + reader.limits(limits); + let _pixels = reader.decode().map_err(err)?; + let d = raster_doc(name, p.png)?; + Ok(( + d, + format!( + "The native Affinity document could not be read ({native}). Opened only its embedded {}×{} PNG preview, which may be smaller than the document: no layers, vectors, text or pages. Save a new copy; the Affinity source cannot be saved back. Export SVG or PDF from Affinity for editable vectors.", + p.width, p.height + ), + )) +} diff --git a/crates/engine/src/cmd/fileio/affinity/layout.rs b/crates/engine/src/cmd/fileio/affinity/layout.rs new file mode 100644 index 0000000000..157a388365 --- /dev/null +++ b/crates/engine/src/cmd/fileio/affinity/layout.rs @@ -0,0 +1,223 @@ +use super::nodes::MAX_DEPTH; +use super::*; + +/// The master page instances among `nodes` (also inside layers and groups): (master, first page, +/// first master page, page count). +pub(super) fn master_instances(nodes: &[af::Node]) -> Vec<(usize, usize, usize, usize)> { + fn visit(n: &af::Node, depth: usize, out: &mut Vec<(usize, usize, usize, usize)>) { + if depth > MAX_DEPTH || !n.visible { + return; + } + match n.kind { + Kind::MasterInstance { master, page, master_page, count } => out.push((master, page, master_page, count)), + Kind::Layer | Kind::Group => n.children.iter().for_each(|c| visit(c, depth + 1, out)), + _ => {} + } + } + let mut out = Vec::new(); + nodes.iter().for_each(|n| visit(n, 0, &mut out)); + out +} + +/// Which master page instance each of `pages` pages shows: (master, first page, first master +/// page) of the first instance in `instances` that covers it. Each page is settled once (the +/// next page still open is found by a path-halving jump), so this is about linear in pages and +/// instances however much their ranges overlap. +pub(super) fn page_masters(instances: &[(usize, usize, usize, usize)], pages: usize) -> Vec> { + fn open_from(next: &mut [usize], mut i: usize) -> usize { + while let Some(&n) = next.get(i) { + if n == i { + break; + } + let skip = next.get(n).copied().unwrap_or(n); + if let Some(slot) = next.get_mut(i) { + *slot = skip; + } + i = n; + } + i + } + let mut owner = vec![None; pages]; + // `next[p]` leads towards the first page from `p` on with no master yet (`pages`: none). + let mut next: Vec = (0..=pages).collect(); + for &(master, first, master_page, count) in instances { + let end = first.saturating_add(count).min(pages); + let mut p = open_from(&mut next, first.min(pages)); + while p < end { + if let Some(o) = owner.get_mut(p) { + *o = Some((master, first, master_page)); + } + if let Some(n) = next.get_mut(p) { + *n = p + 1; + } + p = open_from(&mut next, p + 1); + } + } + owner +} + +/// Master names: A, B … Z, then A1, B1 …. +pub(super) fn master_prefix(index: usize) -> String { + let letter = char::from(b'A' + (index % 26) as u8); + match index / 26 { + 0 => letter.to_string(), + n => format!("{letter}{n}"), + } +} + +/// A table cell's text `w` × `h` at the origin, placed as Affinity places it. Affinity aligns the +/// block from the first line's capitals' tops to the last baseline in the cell, and draws it even +/// where it doesn't fit (centred cells measured on a document's thumbnail: two lines in a cell +/// shorter than them reach out of it at both ends). VectorCraft aligns the block down to the last +/// line's descenders and keeps lines inside the frame: the frame moves by what this returns (down +/// the cell) and grows where the lines need more room. +pub(super) fn place_cell(obj: &mut TextObject, w: f64, h: f64) -> f64 { + let share = match obj.area.vertical_align { + VerticalAlign::Center => 0.5, + VerticalAlign::Bottom => 1.0, + _ => 0.0, + }; + let mut tall = obj.clone(); + tall.area.vertical_align = VerticalAlign::Top; + tall.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, h * 4.0 + 10_000.0)) }; + let lines = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &tall).lines; + let Some(last) = lines.iter().rfind(|l| l.region == 0) else { return 0.0 }; + let (baseline, descent) = (last.baseline, last.descent); + if !(baseline.is_finite() && descent.is_finite() && h.is_finite()) { + return 0.0; + } + // (A little more than the lines need, for the rounding of the layout.) + let frame = h.max(baseline + descent + 0.05); + obj.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, frame)) }; + // Where Affinity has the block's top, less where VectorCraft puts it in the frame. + (h - baseline) * share - (frame - baseline - descent) * share +} + +/// Area type `w` × `h` at the origin whose lines don't all fit. Affinity shows each line whose +/// baseline is inside the frame, its descenders hanging out of it; VectorCraft's area type leaves +/// such a line out. The frame is made taller, from its top, by what those lines need. Whether it was. +pub(super) fn fit_lines(obj: &mut TextObject, w: f64, h: f64) -> bool { + let db = vectorcraft_text::FontDb::global(); + if !(w > 0.0 && h > 0.0 && h.is_finite()) { + return false; + } + let first = vectorcraft_text::layout(db, obj); + if !first.overflow { + return false; + } + // Where the lines go in a frame with room for all of them. + let mut tall = obj.clone(); + tall.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, h * 4.0 + 10_000.0)) }; + let need = vectorcraft_text::layout(db, &tall) + .lines + .iter() + .filter(|l| l.region == 0 && l.baseline <= h + 1e-6) + .map(|l| l.baseline + l.descent) + .filter(|b| b.is_finite()) + .fold(0.0, f64::max); + if need <= h { + return false; + } + let before = first.lines.len(); + // (A little more than they need, for the rounding of the layout.) + let short = std::mem::replace(&mut obj.kind, TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, need + 0.05)) }); + // Something else keeps the lines out: as the source has it. + if vectorcraft_text::layout(db, obj).lines.len() <= before { + obj.kind = short; + return false; + } + true +} + +/// RGBA pixels as a PNG file. +pub(super) fn png(width: u32, height: u32, rgba: Vec) -> Option> { + let buf = image::RgbaImage::from_raw(width, height, rgba)?; + let mut png = Vec::new(); + buf.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + Some(png) +} + +/// Where a line of `w` starts in a span from 0 to `room` (as a share of `room - w`). +fn share(j: Justify) -> f64 { + match j { + Justify::Center | Justify::JustifyCenter => 0.5, + Justify::Right | Justify::JustifyRight => 1.0, + _ => 0.0, + } +} + +/// Artistic text whose paragraphs are aligned differently. Affinity aligns each line within the +/// width of the longest, and places that block at the anchor by the text's own alignment (its +/// first paragraph's); VectorCraft's point type aligns each line on the anchor. Indents move the +/// lines to where Affinity has them and keep their alignment: a centred line centres between its +/// indents and a right-aligned one ends at its right indent, whatever its width. +pub(super) fn align_lines(obj: &mut TextObject) { + let block = share(obj.para.justify); + if obj.paras.iter().all(|p| share(p.justify) == block) { + return; + } + let lines = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), obj).lines; + let w = lines.iter().map(|l| l.x1 - l.x0).filter(|w| w.is_finite()).fold(0.0, f64::max); + if !(w > 0.0 && w < 1e6) { + return; + } + // The block's left edge, from the anchor. + let left = -w * block; + for p in &mut obj.paras { + let at = share(p.justify); + let shift = left + w * at; + // A left-aligned line starts at its left indent, a right-aligned one ends at minus its right + // indent, and a centred one centres on half their difference. + if at < 0.25 { + p.left_indent += shift; + } else if at > 0.75 { + p.right_indent -= shift; + } else { + p.left_indent += shift; + p.right_indent -= shift; + } + } + if let Some(first) = obj.paras.first() { + obj.para = first.clone(); + } +} + +pub(super) fn justify(a: AfAlign) -> Justify { + match a { + AfAlign::Left => Justify::Left, + AfAlign::Center => Justify::Center, + AfAlign::Right => Justify::Right, + AfAlign::Justify => Justify::JustifyLeft, + } +} + +/// A font's line gap in em, as VectorCraft will set it (the installed face, or the fallback for +/// a missing one); 0 when no font is loaded. +pub(super) fn line_gap(family: &str, style: &str) -> f64 { + let defaults = CharStyle::default(); + let family = if family.is_empty() { defaults.font_family.as_str() } else { family }; + let style = if style.is_empty() { defaults.font_style.as_str() } else { style }; + let Some(face) = vectorcraft_text::FontDb::global().face(family, style) else { return 0.0 }; + let upem = face.units_per_em(); + let gap = if upem > 0.0 { face.line_gap() / upem } else { 0.0 }; + if gap.is_finite() { gap.clamp(0.0, 2.0) } else { 0.0 } +} + +pub(super) fn font_style(weight: i64, italic: bool) -> String { + let w = match weight { + ..=150 => "Thin", + 151..=250 => "ExtraLight", + 251..=325 => "Light", + 326..=450 => "Regular", + 451..=550 => "Medium", + 551..=650 => "SemiBold", + 651..=750 => "Bold", + 751..=850 => "ExtraBold", + _ => "Black", + }; + match (w, italic) { + ("Regular", true) => "Italic".into(), + (w, true) => format!("{w} Italic"), + (w, false) => w.into(), + } +} diff --git a/crates/engine/src/cmd/fileio/affinity/master_copies.rs b/crates/engine/src/cmd/fileio/affinity/master_copies.rs new file mode 100644 index 0000000000..bc55dbc259 --- /dev/null +++ b/crates/engine/src/cmd/fileio/affinity/master_copies.rs @@ -0,0 +1,47 @@ +use super::nodes::MAX_DEPTH; +use super::*; + +/// What copying a subtree takes: its nodes, characters and table cells (`work`), and its pixels. +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct CopyCost { + pub(super) work: u64, + pub(super) pixels: u64, +} + +impl CopyCost { + pub(super) fn plus(self, o: CopyCost) -> CopyCost { + CopyCost { work: self.work.saturating_add(o.work), pixels: self.pixels.saturating_add(o.pixels) } + } + pub(super) fn minus(self, o: CopyCost) -> Option { + Some(CopyCost { work: self.work.checked_sub(o.work)?, pixels: self.pixels.checked_sub(o.pixels)? }) + } +} + +/// Master page copies of one import together: as many objects, characters and pixels as a +/// document may hold, a few times over. A master shown on thousands of pages, or a huge one +/// on many, would otherwise multiply them. +pub(super) const MAX_MASTER_COPIES: CopyCost = CopyCost { work: 1 << 23, pixels: 512 << 20 }; + +/// One object a master spread shows on the pages that show it: a top-level node of the spread +/// (`child` `None`) or one object in one of its layers, with its bounds and what copying it takes. +#[derive(Clone, Copy, Debug)] +pub(super) struct MasterPart { + pub(super) node: usize, + pub(super) child: Option, + pub(super) bounds: Option, + pub(super) cost: CopyCost, +} + +pub(super) fn copy_cost(n: &af::Node, depth: usize) -> CopyCost { + if depth > MAX_DEPTH { + return CopyCost::default(); + } + let len = |runs: &[af::TextRun]| runs.iter().map(|r| r.text.len() as u64).sum::(); + let own = match &n.kind { + Kind::Text(t) => CopyCost { work: 1 + len(&t.runs), pixels: 0 }, + Kind::Table(t) => CopyCost { work: 1 + t.cells.iter().map(|c| 1 + len(&c.runs)).sum::(), pixels: 0 }, + Kind::Image(img) => CopyCost { work: 1, pixels: u64::from(img.width) * u64::from(img.height) }, + _ => CopyCost { work: 1, pixels: 0 }, + }; + n.children.iter().fold(own, |c, ch| c.plus(copy_cost(ch, depth + 1))) +} diff --git a/crates/engine/src/cmd/fileio/affinity/nodes.rs b/crates/engine/src/cmd/fileio/affinity/nodes.rs new file mode 100644 index 0000000000..a3867d0bd6 --- /dev/null +++ b/crates/engine/src/cmd/fileio/affinity/nodes.rs @@ -0,0 +1,249 @@ +use super::*; + +/// Deepest node tree mapped (the reader bounds trees well below this). +pub(super) const MAX_DEPTH: usize = 160; + +pub(super) fn rect_of(r: af::Rect) -> Rect { + Rect::new(r.x0, r.y0, r.x1, r.y1) +} + +pub(super) fn affine(a: af::Affine) -> Affine { + Affine::new(a.0) +} + +impl Builder { + pub(super) fn layer_with(&mut self, name: Option<&str>, children: Vec>) -> Arc { + let id = self.doc.alloc_id(); + self.layer = self.layer.wrapping_add(1); + let label = name.map(str::to_string).unwrap_or_else(|| format!("Layer {}", self.layer)); + let mut n = Node::layer(id, &label, LayerColor::Preset(self.layer % 9)); + if let Some(c) = n.children_mut() { + *c = children; + } + Arc::new(n) + } + + /// An artboard at the top level becomes a layer of its name holding its clip group. + pub(super) fn layer_of(&mut self, name: &str, art: Arc, visible: bool, locked: bool) -> Arc { + let mut l = (*self.layer_with(Some(if name.is_empty() { "Artboard" } else { name }), vec![art])).clone(); + l.visible = visible; + l.locked = locked; + Arc::new(l) + } + + pub(super) fn base(&mut self, n: &af::Node, kind: NodeKind) -> Node { + let mut out = Node::new(self.doc.alloc_id(), kind); + out.name = (!n.name.is_empty()).then(|| n.name.clone()); + out.visible = n.visible; + out.locked = n.locked; + out.opacity = n.opacity as f32; + out.blend = self.blend(n.blend); + out + } + + fn blend(&mut self, b: Blend) -> BlendMode { + match b { + Blend::Normal | Blend::PassThrough => BlendMode::Normal, + Blend::Darken => BlendMode::Darken, + Blend::Multiply => BlendMode::Multiply, + Blend::ColorBurn => BlendMode::ColorBurn, + Blend::Lighten => BlendMode::Lighten, + Blend::Screen => BlendMode::Screen, + Blend::ColorDodge => BlendMode::ColorDodge, + Blend::Overlay => BlendMode::Overlay, + Blend::SoftLight => BlendMode::SoftLight, + Blend::HardLight => BlendMode::HardLight, + Blend::Difference => BlendMode::Difference, + Blend::Exclusion => BlendMode::Exclusion, + Blend::Hue => BlendMode::Hue, + Blend::Saturation => BlendMode::Saturation, + Blend::Color => BlendMode::Color, + Blend::Luminosity => BlendMode::Luminosity, + _ => { + self.warn("blend modes VectorCraft doesn't have (Add, Linear Light, Vivid Light, Pin Light, Hard Mix, Subtract, Darker/Lighter Colour, Average, Negation, Reflect, Glow, Erase) import as Normal"); + BlendMode::Normal + } + } + } + + /// `n` with its colour and gradient overlays baked into its paint and pixels (VectorCraft has + /// no overlay effect). + fn overlaid<'n>(&mut self, n: &'n af::Node) -> std::borrow::Cow<'n, af::Node> { + // Each kind of message once, however often it is heard. + let mut warnings: Vec = Vec::new(); + let mut work = self.overlay_work; + let out = vectorcraft_affinity::overlay::apply(n, &mut work, &mut |w| { + if !warnings.iter().any(|x| x == w) { + warnings.push(w.to_string()); + } + }); + self.overlay_work = work; + for w in warnings { + self.warn(&w); + } + out + } + + /// One Affinity node (and its subtree) as VectorCraft art; `to_doc` maps document pixels to + /// points. `layer_level`: the node is directly in a spread or a layer, so a layer stays a layer. + pub(super) fn node( + &mut self, + n: &af::Node, + to_doc: Affine, + boards: &mut Vec<(String, Rect)>, + layer_level: bool, + depth: usize, + ) -> Option> { + if depth > MAX_DEPTH { + self.warn("objects nested too deeply (left out)"); + return None; + } + // VectorCraft documents stay within `MAX_COORD` of the origin (renderers and exports rely + // on it): objects reaching beyond it are left out. + if let Some(b) = af::kind_bounds(&n.kind) { + let r = to_doc.transform_rect_bbox(rect_of(b)); + if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD) { + self.warn("objects beyond the document range VectorCraft supports (left out)"); + return None; + } + } + let n = &*self.overlaid(n); + // Register before descending so nested artboards keep their document order. Inside an + // embedded document an artboard is just its content's frame. + if let Kind::Artboard { rect, .. } = &n.kind + && self.embedded == 0 + { + boards.push(( + if n.name.is_empty() { format!("Artboard {}", boards.len() + 1) } else { n.name.clone() }, + to_doc.transform_rect_bbox(rect_of(*rect)), + )); + } + let child_level = matches!(n.kind, Kind::Layer) && layer_level; + let embeds = n.class == vectorcraft_affinity::stream::Tag::of(b"EmbN"); + self.embedded += usize::from(embeds); + let children: Vec> = n.children.iter().filter_map(|c| self.node(c, to_doc, boards, child_level, depth + 1)).collect(); + self.embedded -= usize::from(embeds); + let mut out = match &n.kind { + Kind::Layer if layer_level => { + let mut l = (*self.layer_with(Some(if n.name.is_empty() { "Layer" } else { &n.name }), children)).clone(); + l.visible = n.visible; + l.locked = n.locked; + l.opacity = n.opacity as f32; + l.blend = self.blend(n.blend); + l + } + Kind::Layer | Kind::Group => { + let mut g = self.base(n, NodeKind::Group { children, clip: false }); + // Affinity groups isolate their blending unless they pass through. + g.isolate = n.blend != Blend::PassThrough; + g + } + Kind::Shape { path, fills, strokes, even_odd } => { + let data = self.path(path, to_doc); + let rule = if *even_odd { FillRule::EvenOdd } else { FillRule::NonZero }; + let mut appearance = self.appearance(fills, strokes, to_doc); + // An outline effect on a shape is one more stroke. + self.outline_stroke(&n.effects, &mut appearance); + if children.is_empty() { + let mut p = self.base(n, NodeKind::Path { path: data, rule, live: None, clipping: false, guide: false }); + p.appearance = appearance.into(); + p + } else { + // A shape clips its children: VectorCraft's clipping path keeps its paint, its + // fill behind the clipped art and its stroke over it, as Affinity draws it. + let mut clip = Node::new(self.doc.alloc_id(), NodeKind::Path { path: data, rule, live: None, clipping: true, guide: false }); + clip.appearance = appearance.into(); + let mut kids = vec![Arc::new(clip)]; + kids.extend(children); + self.base(n, NodeKind::Group { children: kids, clip: true }) + } + } + Kind::Artboard { path, even_odd, background, strokes, .. } => { + let mut clip = Node::new( + self.doc.alloc_id(), + NodeKind::Path { + path: self.path(path, to_doc), + rule: if *even_odd { FillRule::EvenOdd } else { FillRule::NonZero }, + live: None, + clipping: true, + guide: false, + }, + ); + clip.appearance = self.appearance(background, strokes, to_doc).into(); + let mut kids = vec![Arc::new(clip)]; + kids.extend(children); + let mut g = self.base(n, NodeKind::Group { children: kids, clip: true }); + g.name = Some(if n.name.is_empty() { "Artboard".into() } else { n.name.clone() }); + g + } + Kind::Text(t) => { + let Some((mut text, alpha)) = self.text(t, to_doc) else { + // The text is left out (warned); what it holds still comes in. + if children.is_empty() { + return None; + } + let g = self.base(n, NodeKind::Group { children, clip: false }); + return Some(Arc::new(g)); + }; + self.outline_text(&n.effects, &mut text); + let mut node = self.base(n, NodeKind::Text(Box::new(text))); + node.opacity *= alpha; + if !children.is_empty() { + let mut kids = vec![Arc::new(node)]; + kids.extend(children); + node = Node::group(self.doc.alloc_id(), kids); + } + node + } + Kind::Table(t) => { + let mut kids = self.table(t, to_doc); + if kids.is_empty() && children.is_empty() { + return None; + } + kids.extend(children); + let mut g = self.base(n, NodeKind::Group { children: kids, clip: false }); + g.name.get_or_insert_with(|| "Table".into()); + g + } + Kind::Image(img) => match self.image(img, to_doc) { + Some(kind) => self.base(n, kind), + None if children.is_empty() => return None, + None => self.base(n, NodeKind::Group { children, clip: false }), + }, + // Shown on the pages through the master's layer (see `master_pages`). + Kind::MasterInstance { .. } => return None, + Kind::Unsupported if children.is_empty() => return None, + Kind::Unsupported => self.base(n, NodeKind::Group { children, clip: false }), + }; + if !matches!(n.kind, Kind::Shape { .. } | Kind::Text(_)) && n.effects.iter().any(|e| matches!(e, af::Effect::Outline { .. })) { + self.warn("outline effects on groups, images and tables (left out)"); + } + if let Some(img) = &n.pixel_mask { + // A pixel mask: its grey levels show (white) or hide (black) the node, and nothing + // shows outside it, as an opacity mask that clips. + if let Some(kind) = self.image(img, to_doc) { + let art = Node::new(self.doc.alloc_id(), kind); + out.extras_mut().mask = Some(Box::new(OpacityMask::new(art, true))); + } + } + if let Some(mask) = &n.mask { + // A vector mask: the node shows only inside it. + let clip = Node::new( + self.doc.alloc_id(), + NodeKind::Path { path: self.path(mask, to_doc), rule: FillRule::NonZero, live: None, clipping: true, guide: false }, + ); + let (opacity, blend, visible, name) = (out.opacity, out.blend, out.visible, out.name.clone()); + out.opacity = 1.0; + out.blend = BlendMode::Normal; + let mut g = Node::new(self.doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(out)], clip: true }); + (g.opacity, g.blend, g.visible, g.name) = (opacity, blend, visible, name); + out = g; + } + // Shadows and glows apply to what the node shows, mask and all. + let fx = self.effects(&n.effects); + if !fx.is_empty() { + out.appearance.effects.extend(fx); + } + Some(Arc::new(out)) + } +} diff --git a/crates/engine/src/cmd/fileio/affinity/paint.rs b/crates/engine/src/cmd/fileio/affinity/paint.rs new file mode 100644 index 0000000000..a60911e0d5 --- /dev/null +++ b/crates/engine/src/cmd/fileio/affinity/paint.rs @@ -0,0 +1,387 @@ +use super::layout::png; +use super::nodes::affine; +use super::text::Placement; +use super::*; + +impl Builder { + /// Drop shadows, inner shadows and outer glows as VectorCraft's Stylize effects. Affinity's + /// blur radius sets the same Gaussian as VectorCraft's blur (σ = half of it), and its angle + /// is the direction the shadow goes in. + pub(super) fn effects(&mut self, effects: &[af::Effect]) -> Vec { + let k = self.k; + let len = move |v: f64| if v.is_finite() { (v * k).clamp(0.0, 1000.0) } else { 0.0 }; + let num = |v: f64| (v * 1000.0).round() / 1000.0; + let mut out = Vec::new(); + for e in effects { + let (id, params) = match e { + af::Effect::DropShadow { color, opacity, radius, distance, angle } => { + let (color, alpha) = Self::color(*color); + let d = len(*distance); + let a = if angle.is_finite() { *angle } else { 0.0 }; + let p = json!({ + "mode": "normal", + "opacity": num(opacity * f64::from(alpha) * 100.0), + "x": num(d * a.cos()), + "y": num(d * a.sin()), + "blur": num(len(*radius)), + "color": color, + }); + ("stylize.dropShadow", p) + } + af::Effect::InnerShadow { color, opacity, radius, distance, .. } => { + self.warn("inner shadows (imported as inner glows at the edge, without their offset)"); + let (color, alpha) = Self::color(*color); + let p = json!({ + "mode": "normal", + "opacity": num(opacity * f64::from(alpha) * 100.0), + "blur": num(len(*radius) + len(*distance)), + "color": color, + "source": "edge", + }); + ("stylize.innerGlow", p) + } + af::Effect::OuterGlow { color, opacity, radius } => { + let (color, alpha) = Self::color(*color); + let p = + json!({ "mode": "normal", "opacity": num(opacity * f64::from(alpha) * 100.0), "blur": num(len(*radius)), "color": color }); + ("stylize.outerGlow", p) + } + af::Effect::Bevel { .. } => { + self.warn("bevel and emboss effects (left out)"); + continue; + } + // Outlines become strokes (`outline_stroke`, `outline_text`), overlays are baked + // into the paint (`overlaid`). + af::Effect::Outline { .. } | af::Effect::ColorOverlay { .. } | af::Effect::GradientOverlay { .. } => continue, + }; + out.push(Effect { id: id.into(), params, visible: true }); + } + out + } + + /// An outline effect on a shape: a stroke layer. Affinity outlines what the shape shows, its own + /// strokes included: an outline outside goes under them (from the path out to as far past them as + /// it is wide), one centred on or inside that edge over them. A centred one reaches as far into + /// the shape as out of it here, which only differs by the width of the shape's own stroke. + pub(super) fn outline_stroke(&mut self, effects: &[af::Effect], appearance: &mut Appearance) { + // How far the shape's own strokes reach outside its path. + let reach = appearance + .items + .iter() + .filter_map(|i| match i { + AppearanceItem::Stroke(s) => Some(match s.align { + StrokeAlign::Center => s.width / 2.0, + StrokeAlign::Outside => s.width, + StrokeAlign::Inside => 0.0, + }), + _ => None, + }) + .filter(|w| w.is_finite()) + .fold(0.0, f64::max); + for e in effects { + let af::Effect::Outline { color, opacity, width, align } = e else { continue }; + let w = width * self.k; + if !(w.is_finite() && w > 0.0) { + continue; + } + let (c, alpha) = Self::color(*color); + let (align, w) = match align { + 1 => (StrokeAlign::Inside, w), + 2 => (StrokeAlign::Center, w + 2.0 * reach), + _ => (StrokeAlign::Outside, w + reach), + }; + let mut l = StrokeLayer::new(Paint::solid(c), w.min(1000.0)); + l.opacity = (opacity.clamp(0.0, 1.0) as f32) * alpha; + l.join = LineJoin::Round; + l.align = align; + let item = AppearanceItem::Stroke(l); + if align == StrokeAlign::Outside { + // Under the shape's strokes, over its fills. + let at = appearance.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(_))).unwrap_or(appearance.items.len()); + appearance.items.insert(at, item); + } else { + appearance.items.push(item); + } + } + } + + /// An outline effect on text: the characters' stroke, where they have none of their own. + pub(super) fn outline_text(&mut self, effects: &[af::Effect], text: &mut TextObject) { + for e in effects { + let af::Effect::Outline { color, opacity, width, align } = e else { continue }; + let w = width * self.k; + if !(w.is_finite() && w > 0.0) { + continue; + } + let (c, alpha) = Self::color(*color); + if opacity * f64::from(alpha) < 0.999 { + self.warn("semi-transparent outline effects on text (imported opaque)"); + } + if *align != 2 { + self.warn("outline effects on text inside or outside the characters (centred on them)"); + } + for r in &mut text.runs { + if r.style.stroke == Paint::None { + r.style.stroke = Paint::solid(c); + // Centred on the outline, so twice as wide to show as far outside. + r.style.stroke_width = if *align == 2 { w } else { 2.0 * w }.min(1000.0); + } + } + } + } + + pub(super) fn path(&self, p: &af::Path, to_doc: Affine) -> PathData { + let mut bp = BezPath::new(); + for s in &p.subpaths { + let pt = |q: af::Point| Point::new(q.x, q.y); + bp.move_to(pt(s.start)); + for [c1, c2, e] in &s.segments { + if c1 == c2 && c2 == e { + bp.line_to(pt(*e)); + } else { + bp.curve_to(pt(*c1), pt(*c2), pt(*e)); + } + } + if s.closed { + bp.close_path(); + } + } + PathData::from_bezpath(&(to_doc * bp)) + } + + fn color(c: ap::Color) -> (Color, f32) { + let f = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) as f32 } else { 0.0 }; + match c { + ap::Color::Rgb { r, g, b, a } => (Color::Rgb { r: f(r), g: f(g), b: f(b) }, f(a)), + ap::Color::Cmyk { c, m, y, k, a } => (Color::Cmyk { c: f(c), m: f(m), y: f(y), k: f(k) }, f(a)), + ap::Color::Gray { v, a } => (Color::Gray { k: 1.0 - f(v) }, f(a)), + ap::Color::Lab { l, a, b, alpha } => (Color::Lab { l: l as f32, a: a as f32, b: b as f32 }, f(alpha)), + } + } + + /// A paint and the opacity its colour's alpha becomes. + pub(super) fn paint(&mut self, p: &ap::Paint, to_doc: Affine) -> Option<(Paint, f32)> { + match p { + ap::Paint::None => None, + ap::Paint::Solid(c) => { + let (color, a) = Self::color(*c); + Some((Paint::solid(color), a)) + } + ap::Paint::Gradient(g) => { + let stops = g + .stops + .iter() + .map(|s| { + let (color, opacity) = Self::color(s.color); + let mut stop = GradientStop::new(s.offset as f32, color); + stop.opacity = opacity; + stop.midpoint = s.half_point().clamp(0.13, 0.87) as f32; + stop + }) + .collect(); + let m = to_doc * affine(g.transform); + let (o, x, y) = (m * Point::ZERO, m * Point::new(1.0, 0.0), m * Point::new(0.0, 1.0)); + let kind = match g.kind { + AfKind::Linear => GradientKind::Linear, + AfKind::Radial => GradientKind::Radial, + AfKind::Conical => { + self.warn("conical gradients import as radial gradients"); + GradientKind::Radial + } + }; + let (u, v): (Vec2, Vec2) = (x - o, y - o); + if kind == GradientKind::Radial && u.hypot() > 0.0 && (u.dot(v) / (u.hypot() * v.hypot().max(1e-12))).abs() > 0.01 { + self.warn("skewed elliptical gradients import as upright ellipses"); + } + let aspect = if u.hypot() > 0.0 { (v.hypot() / u.hypot()).clamp(0.01, 100.0) } else { 1.0 }; + let geom = GradientGeom { start: o, end: x, aspect: if kind == GradientKind::Radial { aspect } else { 1.0 }, focal: None }; + let mut gp = GradientPaint::new(Gradient::new(kind, stops)); + gp.angle = (-(u.y)).atan2(u.x).to_degrees(); + gp.geom = Some(geom); + Some((Paint::Gradient(Box::new(gp)), 1.0)) + } + } + } + + pub(super) fn stroke_layer(&mut self, s: &ap::Stroke, to_doc: Affine) -> Option { + let (paint, opacity) = self.paint(&s.paint, to_doc)?; + let mut l = StrokeLayer::new(paint, s.width * self.k); + l.opacity = opacity; + l.cap = match s.cap { + Cap::Butt => LineCap::Butt, + Cap::Round => LineCap::Round, + Cap::Square => LineCap::Square, + }; + l.join = match s.join { + Join::Miter => LineJoin::Miter, + Join::Round => LineJoin::Round, + Join::Bevel => LineJoin::Bevel, + }; + l.miter_limit = s.miter_limit; + l.align = match s.align { + ap::Align::Center => StrokeAlign::Center, + ap::Align::Inside => StrokeAlign::Inside, + ap::Align::Outside => StrokeAlign::Outside, + }; + l.dash = s.dash.as_ref().map(|(pattern, phase)| Dash { + pattern: pattern.iter().map(|v| v * self.k).collect(), + offset: phase * self.k, + align_corners: false, + }); + Some(l) + } + + pub(super) fn appearance(&mut self, fills: &[ap::Paint], strokes: &[ap::Stroke], to_doc: Affine) -> Appearance { + let mut items = Vec::new(); + let mut above = Vec::new(); + for f in fills { + if let Some((paint, opacity)) = self.paint(f, to_doc) { + let mut l = FillLayer::new(paint); + l.opacity = opacity; + items.push(AppearanceItem::Fill(l)); + } + } + for s in strokes { + let Some(l) = self.stroke_layer(s, to_doc) else { continue }; + if s.behind { + items.insert(0, AppearanceItem::Stroke(l)); + } else { + above.push(AppearanceItem::Stroke(l)); + } + } + items.extend(above); + Appearance { items, ..Appearance::default() } + } + + /// Where text placed by `m` (node space to points) goes, its type scaled by `type_m`. + pub(super) fn placement(&mut self, m: Affine, type_m: Affine) -> Option { + let [a, b, c, d, e, f] = m.as_coeffs(); + let sx = a.hypot(b); + let det = a * d - b * c; + if !(sx > 1e-9 && det.is_finite() && det.abs() > 1e-12 && e.is_finite() && f.is_finite()) { + self.warn("text with an invalid transform (left out)"); + return None; + } + let sy = det / sx; + let shear = (a * c + b * d) / (sx * sx); + if shear.abs() > 1e-3 || sy < 0.0 { + self.warn("skewed or flipped text (imported without the skew or flip)"); + } + // The type's vertical scale gives the font size, its horizontal scale relative to that the + // characters' width. + let [ta, tb, tc, td, ..] = type_m.as_coeffs(); + let (tsx, tdet) = (ta.hypot(tb), ta * td - tb * tc); + let (size_scale, h_scale) = if tsx > 1e-9 && tdet.is_finite() && tdet.abs() > 1e-12 { + let tsy = (tdet / tsx).abs(); + (tsy, tsx / tsy) + } else { + self.warn("text with an invalid text scale (imported unscaled)"); + (det.abs().sqrt(), 1.0) + }; + Some(Placement { + to_frame: Affine::scale_non_uniform(sx, sy.abs()), + place: Affine::translate((e, f)) * Affine::rotate(b.atan2(a)), + size_scale, + h_scale, + }) + } + + /// A CMYK pixel layer as an image file. Through the document's own CMYK profile when it + /// embeds one (as Affinity shows it): RGBA. Otherwise, opaque, a CMYK image that keeps its + /// inks (shown and separated through the working CMYK profile, as placed CMYK images are); + /// with transparency, RGBA through the working CMYK profile. + fn cmyk_image(&mut self, width: u32, height: u32, cmyka: &[u8]) -> Option> { + let n = (width as usize).checked_mul(height as usize)?; + let px = cmyka.get(..n.checked_mul(5)?)?.as_chunks::<5>().0; + if let Some(lut) = self.document_cmyk() { + let rgba = px + .iter() + .flat_map(|p| { + let [r, g, b, _] = lut.apply8([p[0], p[1], p[2], p[3]]); + [r, g, b, p[4]] + }) + .collect(); + return png(width, height, rgba); + } + if px.iter().all(|p| p[4] == 255) { + let inks = px.iter().flat_map(|p| [p[0], p[1], p[2], p[3]]).collect(); + if let Some(blob) = vectorcraft_doc::cmyk::Inks::new(width, height, inks).and_then(|i| vectorcraft_doc::ImageBlob::cmyk_tiff(&i)) { + return Some(Arc::unwrap_or_clone(blob.bytes)); + } + } + self.warn("CMYK pixel layers with transparency (converted to RGB through the working CMYK profile)"); + let lut = self + .working_cmyk + .get_or_insert_with(|| { + Arc::new(vectorcraft_color::cms::CmykLut::build(|[c, m, y, k]| { + let [r, g, b] = Color::cmyk(c, m, y, k).to_rgb(); + [r, g, b, 0.0] + })) + }) + .clone(); + let rgba = px + .iter() + .flat_map(|p| { + let [r, g, b, _] = lut.apply8([p[0], p[1], p[2], p[3]]); + [r, g, b, p[4]] + }) + .collect(); + png(width, height, rgba) + } + + /// The document's CMYK profile as a table from ink amounts to sRGB (relative colorimetric, + /// with black-point compensation, as Affinity's pixel layers convert), made once; `None` when + /// the document embeds none, or not one that converts. + fn document_cmyk(&mut self) -> Option> { + use vectorcraft_color::cms::{self, CmykLut, IccProfile, Intent}; + if let Some(lut) = &self.cmyk_lut { + return lut.clone(); + } + let embedded = self.cmyk_profile.is_some(); + let lut = self.cmyk_profile.take().and_then(|bytes| { + let profile = IccProfile::from_bytes(None, &bytes).ok()?; + let srgb = cms::icc::builtin_rgb(cms::SRGB)?; + profile.to_rgb_of(&srgb, &[0.0; 4], Intent::RelativeColorimetric, true)?; + Some(Arc::new(CmykLut::build(|inks| { + let [r, g, b] = profile + .to_rgb_of(&srgb, &inks, Intent::RelativeColorimetric, true) + .unwrap_or_else(|| Color::cmyk(inks[0], inks[1], inks[2], inks[3]).to_rgb()); + [r, g, b, 0.0] + }))) + }); + if embedded && lut.is_none() { + self.warn("CMYK pixel layers whose document's colour profile could not be read (shown through the working CMYK profile)"); + } + self.cmyk_lut = Some(lut.clone()); + lut + } + + pub(super) fn image(&mut self, img: &af::Image, to_doc: Affine) -> Option { + let bytes = match &img.pixels { + Pixels::Encoded(b) => b.clone(), + Pixels::Rgba8(rgba) => png(img.width, img.height, rgba.clone())?, + Pixels::Cmyka8(cmyka) => self.cmyk_image(img.width, img.height, cmyka)?, + }; + let r = match crate::cmd::fileio::load::raster_image(&bytes) { + Ok(r) => r, + Err(_) => { + self.warn("an embedded image that could not be decoded was left out"); + return None; + } + }; + // The pixel grid maps onto the Affinity image's own size, whatever the stored file's. + let sx = img.width as f64 / f64::from(r.width.max(1)); + let sy = img.height as f64 / f64::from(r.height.max(1)); + let xf = to_doc * affine(img.transform) * Affine::scale_non_uniform(sx, sy); + self.doc.images.entry(r.key.clone()).or_insert(r.blob); + Some(NodeKind::Image(Box::new(ImageObject { + key: r.key, + width: r.width, + height: r.height, + xf, + link: None, + placement: Default::default(), + pixels: None, + }))) + } +} diff --git a/crates/engine/src/cmd/fileio/affinity/text.rs b/crates/engine/src/cmd/fileio/affinity/text.rs new file mode 100644 index 0000000000..cae76dc7b3 --- /dev/null +++ b/crates/engine/src/cmd/fileio/affinity/text.rs @@ -0,0 +1,326 @@ +use super::layout::{align_lines, fit_lines, font_style, justify, line_gap, place_cell}; +use super::nodes::affine; +use super::*; + +/// Where text goes: a rigid placement (translation and rotation) and the scale that maps node +/// space into it (applied to the frame's geometry, not the type), plus the type's own scale. +pub(super) struct Placement { + /// Node space to the frame's space, before `place`. + pub(super) to_frame: Affine, + pub(super) place: Affine, + /// Points per node unit of type size. + pub(super) size_scale: f64, + /// Horizontal scale of the type relative to `size_scale`. + pub(super) h_scale: f64, +} + +impl Builder { + /// Text → its object and the opacity its characters' shared transparency gives the node. + pub(super) fn text(&mut self, t: &af::Text, to_doc: Affine) -> Option<(TextObject, f32)> { + let p = self.placement(to_doc * affine(t.transform), to_doc * affine(t.text_transform))?; + let alpha = self.text_alpha(&t.runs); + let mut obj = self.type_object(&t.runs, &p)?; + obj.para.justify = justify(t.align); + if let Some(first) = obj.paras.first_mut() { + first.justify = obj.para.justify; + } + match t.frame { + Some(f) => { + let (a, b) = (p.to_frame * Point::new(f.x0, f.y0), p.to_frame * Point::new(f.x1, f.y1)); + let r = Rect::from_points(a, b); + obj.xf = p.place * Affine::translate(r.origin().to_vec2()); + obj.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, r.width(), r.height())) }; + // Affinity hangs a frame's first line from its capitals' tops, not the font's ascent. + obj.area.first_baseline = FirstBaseline::CapHeight; + if fit_lines(&mut obj, r.width(), r.height()) { + self.warn("text frames whose last lines hang out of them (made taller so the lines show)"); + } + // Affinity shows a line in a frame shorter than it (#1423); here none of it would draw. + if vectorcraft_text::fit_first_line(vectorcraft_text::FontDb::global(), &mut obj) { + self.warn("text frames too short for their first line (made taller so the line shows)"); + } + } + None => { + align_lines(&mut obj); + obj.xf = p.place * Affine::translate((p.to_frame * Point::new(t.anchor.x, t.anchor.y)).to_vec2()); + } + } + Some((obj, alpha)) + } + + /// The opacity text takes from its characters' colour: VectorCraft's characters have none of + /// their own, so text whose characters share one becomes an object with that opacity. + fn text_alpha(&mut self, runs: &[af::TextRun]) -> f32 { + let alphas: Vec = + runs.iter().filter_map(|r| if let ap::Paint::Solid(c) = &r.fill { Some(c.alpha()) } else { None }).filter(|a| a.is_finite()).collect(); + let (lo, hi) = alphas.iter().fold((1.0f64, 0.0f64), |(lo, hi), a| (lo.min(*a), hi.max(*a))); + if alphas.is_empty() || lo >= 1.0 { + return 1.0; + } + if hi - lo > 0.01 { + self.warn("text with characters of different transparency (imported opaque)"); + return 1.0; + } + lo.clamp(0.0, 1.0) as f32 + } + + /// The characters and paragraphs of `runs` as a text object at the origin of text space. + fn type_object(&mut self, runs: &[af::TextRun], p: &Placement) -> Option { + let (v, h) = (p.size_scale, p.size_scale * p.h_scale); + let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default()); + let mut formats: Vec = Vec::new(); + let mut out: Vec = Vec::new(); + let mut paragraph = 0usize; + // Whether each paragraph here continues the one before after a line break (U+2028): + // VectorCraft has no line break inside a paragraph, so the lines become paragraphs. + let mut continues = vec![false]; + for r in runs { + for c in r.text.chars() { + match c { + '\u{2028}' => continues.push(true), + '\u{2029}' | '\r' | '\n' => continues.push(false), + _ => {} + } + } + // Affinity separates paragraphs with U+2029 and lines with U+2028; other control + // characters don't show. + let text: String = r + .text + .chars() + .filter_map(|c| match c { + '\u{2029}' | '\u{2028}' | '\r' | '\n' => Some('\n'), + '\t' => Some('\t'), + c if c.is_control() => None, + c => Some(c), + }) + .collect(); + if text.is_empty() { + continue; + } + for c in text.chars() { + if formats.len() <= paragraph { + formats.push(r.paragraph); + } + if c == '\n' { + paragraph += 1; + } + } + let mut style = self.char_style(r, (v, p.h_scale)); + if style.leading.is_none() { + style.leading = r.paragraph.leading.map(|l| l * v).filter(|l| l.is_finite() && *l > 0.0).map(|l| l.min(5000.0)); + } + out.push(TextRun::new(text, style)); + } + // Affinity ends a story with a paragraph mark; VectorCraft's last paragraph has none. + if let Some(last) = out.last_mut() + && last.text.ends_with('\n') + { + last.text.pop(); + if last.text.is_empty() { + out.pop(); + } + } + obj.runs = out; + let count = obj.runs.iter().map(|r| r.text.matches('\n').count()).sum::() + 1; + let mut paras = Vec::with_capacity(count); + let mut previous_after = 0.0; + // The run of each paragraph's first character. + let mut first_runs = Vec::with_capacity(count); + { + let mut at_start = true; + for (i, r) in obj.runs.iter().enumerate() { + for c in r.text.chars() { + if at_start { + first_runs.push(i); + at_start = false; + } + if c == '\n' { + at_start = true; + } + } + } + } + // Line gaps by font, each looked up once. + let mut gaps: std::collections::HashMap<(&str, &str), f64> = std::collections::HashMap::new(); + for i in 0..count { + let f = formats.get(i).or(formats.last()).copied().unwrap_or_default(); + let pt = |x: f64, k: f64| if (x * k).is_finite() { (x * k).clamp(-5000.0, 5000.0) } else { 0.0 }; + let mut ps = vectorcraft_doc::text::ParaStyle { justify: justify(f.align), ..Default::default() }; + // Affinity places the first line and the others from the left edge; VectorCraft's + // first-line indent is relative to its left indent. + ps.left_indent = pt(f.left, h); + ps.first_line_indent = pt(f.first - f.left, h); + ps.right_indent = pt(f.right, h); + // Between two paragraphs Affinity keeps the larger of the space after the first and + // before the second; VectorCraft adds them. + let (mut before, mut after) = (pt(f.space_before, v).max(0.0), pt(f.space_after, v).max(0.0)); + // The lines of one Affinity paragraph: no space between them, and the first-line + // indent only on its first. + if continues.get(i).copied().unwrap_or(false) { + before = 0.0; + ps.first_line_indent = 0.0; + } + if continues.get(i + 1).copied().unwrap_or(false) { + after = 0.0; + } + ps.space_before = if i == 0 { before } else { (before - previous_after).max(0.0) }; + ps.space_after = after; + previous_after = after; + // Automatic leading: the font size plus the font's line gap, times the paragraph's + // factor, for artistic and frame text alike. Fitted on Affinity's thumbnails: Bebas + // Neue Pro and Impact lines about 1 em apart, DIN Condensed (a gap of 0.2 em) 1.2 em, + // and the public Arial frame fixture fits this better than the font's line height. + let (family, style) = + first_runs.get(i).and_then(|r| obj.runs.get(*r)).map_or(("", ""), |r| (r.style.font_family.as_str(), r.style.font_style.as_str())); + let gap = *gaps.entry((family, style)).or_insert_with(|| line_gap(family, style)); + let ratio = (1.0 + gap) * f.auto_leading; + // Affinity documents use tiny factors for spacer paragraphs (0.15 of a line); VectorCraft + // takes 0–500 %. + if ratio.is_finite() && (0.01..=5.0).contains(&ratio) { + ps.justification.auto_leading = ratio * 100.0; + } + paras.push(ps); + } + if let Some(first) = paras.first() { + obj.para = first.clone(); + } + obj.paras = paras; + obj.normalize_paras(); + Some(obj) + } + + /// A run's character style; `(size_scale, h_scale)` the type's vertical scale to points and + /// its horizontal scale relative to that. + fn char_style(&mut self, r: &af::TextRun, (size_scale, h_scale): (f64, f64)) -> CharStyle { + let finite = |v: f64, d: f64| if v.is_finite() { v } else { d }; + let mut style = CharStyle::default(); + if !r.family.is_empty() { + style.font_family = r.family.clone(); + } else if !r.postscript.is_empty() { + style.font_family = r.postscript.clone(); + } else { + self.warn("text without a font name uses the default font"); + } + // A family/weight pair cannot identify width variants such as Arial Narrow. + // Resolve a known PostScript identity to the exact installed family and style. + if let Some((family, face_style)) = vectorcraft_text::FontDb::global().by_postscript_name(&r.postscript) { + style.font_family = family; + style.font_style = face_style; + } else { + style.font_style = font_style(r.weight, r.italic); + } + style.features = r.features.clone(); + if r.features.iter().any(|feature| !vectorcraft_text::OtFeatures::known_tag(feature)) { + self.warn("unsupported text OpenType features (retained but not rendered)"); + } + style.all_caps = r.all_caps; + style.underline = r.underline; + style.strikethrough = r.strikethrough; + style.size = finite(r.size * size_scale, 12.0).clamp(0.1, 1296.0); + style.leading = r.leading.map(|l| finite(l * size_scale, 0.0)).filter(|l| *l > 0.0).map(|l| l.min(5000.0)); + style.tracking = finite(r.tracking * 1000.0, 0.0).clamp(-1000.0, 10000.0); + // Text squeezed or stretched by its transform keeps that as horizontal scale, on top of + // its own. + let hs = h_scale * r.h_scale; + if hs.is_finite() && (hs - 1.0).abs() > 1e-3 { + style.h_scale = (hs * 100.0).clamp(1.0, 1000.0); + } + // Transparency is the object's (see `text_alpha`); the paint's transform doesn't matter + // for a solid colour, and gradients on type are laid out in text space. + style.fill = match self.paint(&r.fill, Affine::scale(size_scale)) { + Some((p, _)) => p, + None => Paint::None, + }; + if let Some(st) = &r.stroke { + let w = st.width * size_scale; + if let Some((paint, _)) = self.paint(&st.paint, Affine::scale(size_scale)) + && w.is_finite() + && w > 0.0 + { + style.stroke = paint; + style.stroke_width = w.min(1000.0); + } + } + style + } + + /// A table: its cells as area type and the lines on their edges, as VectorCraft has no + /// tables. + pub(super) fn table(&mut self, t: &af::Table, to_doc: Affine) -> Vec> { + let mut out = Vec::new(); + let (ncols, nrows) = (t.ncols(), t.nrows()); + if ncols == 0 || nrows == 0 { + return out; + } + self.warn("tables (imported as text frames and lines)"); + let m = to_doc * affine(t.transform); + let Some(p) = self.placement(m, to_doc * affine(t.text_transform)) else { return out }; + let col = |i: usize| t.columns.get(i).copied().unwrap_or(0.0); + let row = |i: usize| t.rows.get(i).copied().unwrap_or(0.0); + for (i, cell) in t.cells.iter().enumerate() { + if cell.merged_left || cell.runs.is_empty() { + continue; + } + let (r, c) = (i / ncols, i % ncols); + // Cells to the right merged into this one widen it. + let span = 1 + t.cells.iter().skip(i + 1).take(ncols - c - 1).take_while(|n| n.merged_left).count(); + let [l, tp, rt, bt] = cell.inset; + let node = af::Rect { x0: col(c) + l, y0: row(r) + tp, x1: col(c + span) - rt, y1: row(r + 1) - bt }; + let (a, b) = (p.to_frame * Point::new(node.x0, node.y0), p.to_frame * Point::new(node.x1, node.y1)); + let rect = Rect::from_points(a, b); + if !(rect.width() > 0.0 && rect.height() > 0.0) { + continue; + } + let Some(mut obj) = self.type_object(&cell.runs, &p) else { continue }; + obj.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, rect.width(), rect.height())) }; + obj.area.vertical_align = match cell.valign { + af::VAlign::Top => VerticalAlign::Top, + af::VAlign::Center => VerticalAlign::Center, + af::VAlign::Bottom => VerticalAlign::Bottom, + }; + obj.area.first_baseline = FirstBaseline::CapHeight; + let dy = place_cell(&mut obj, rect.width(), rect.height()); + obj.xf = p.place * Affine::translate(rect.origin().to_vec2() + Vec2::new(0.0, dy)); + // A cell's text never vanishes for want of a line's height. + vectorcraft_text::fit_first_line(vectorcraft_text::FontDb::global(), &mut obj); + let alpha = self.text_alpha(&cell.runs); + let mut n = Node::new(self.doc.alloc_id(), NodeKind::Text(Box::new(obj))); + n.opacity = alpha; + out.push(Arc::new(n)); + } + // Lines over the cells: the vertical edges row by row (none inside merged cells), then + // the horizontal ones. + let mut line = |b: &mut Self, s: &Option, from: (f64, f64), to: (f64, f64)| { + let Some(s) = s else { return }; + let Some(layer) = b.stroke_layer(s, to_doc) else { return }; + let mut bp = BezPath::new(); + bp.move_to(m * Point::new(from.0, from.1)); + bp.line_to(m * Point::new(to.0, to.1)); + let mut n = Node::new( + b.doc.alloc_id(), + NodeKind::Path { path: PathData::from_bezpath(&bp), rule: FillRule::NonZero, live: None, clipping: false, guide: false }, + ); + n.appearance = Appearance { items: vec![AppearanceItem::Stroke(layer)], ..Appearance::default() }.into(); + out.push(Arc::new(n)); + }; + for r in 0..nrows { + for k in 0..=ncols { + let merged = k > 0 && k < ncols && t.cells.get(r * ncols + k).is_some_and(|c| c.merged_left); + if merged { + continue; + } + if let Some(s) = t.vertical.get(r * (ncols + 1) + k) { + line(self, s, (col(k), row(r)), (col(k), row(r + 1))); + } + } + } + for j in 0..=nrows { + for k in 0..ncols { + if let Some(s) = t.horizontal.get(j * ncols + k) { + line(self, s, (col(k), row(j)), (col(k + 1), row(j))); + } + } + } + out + } +} diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 02d8c7246a..ff8b8aece6 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -1,6 +1,9 @@ //! `command.batch`: several commands as one undo step (in each document they edit). +use std::sync::Arc; + use serde_json::{Value, json}; +use vectorcraft_doc::Document; use super::super::*; use crate::{DocState, EngineError}; @@ -11,8 +14,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // The active artboard the app passes, for the steps that act on it. let artboard = p.get("artboard").and_then(Value::as_u64); // What an error rolls back besides the documents: session-level state a step may change - // (paint defaults, drawing mode, clipboard, the Untitled-N count). - let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter); + // (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group). + let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone()); // A drag or typing still in progress is a step of its own, as before Undo: the batch's steps // would otherwise run inside it and take its baseline as theirs (#1697). if s.active().is_some() { @@ -23,14 +26,18 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { let start = s.docs.clone(); let active = s.active; s.batch_stash = Some(vec![]); - let r = run_steps(s, &label, artboard, &mut cmds); + let mut grouped = Vec::with_capacity(cmds.len()); + let r = run_steps(s, &label, artboard, &mut cmds, &mut grouped); let stash = s.batch_stash.take().unwrap_or_default(); let results = match r { - Ok(results) => results, + Ok(results) => { + s.batch_steps = Some(grouped); + results + } Err(e) => { roll_back(s, start, &stash); s.active = active; - (s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter) = saved; + (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); } @@ -57,7 +64,14 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { /// `artboard`, as the Artboards panel shows it in the document the step runs in: past that /// document's last artboard, the last one. A step that resizes the active artboard /// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`. -fn run_steps(s: &mut Session, label: &str, artboard: Option, cmds: &mut [Value]) -> Result> { +/// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them. +fn run_steps( + s: &mut Session, + label: &str, + artboard: Option, + cmds: &mut [Value], + grouped: &mut Vec<(Vec, Option)>, +) -> Result> { let mut results = Vec::with_capacity(cmds.len()); for c in cmds { let id = c.get("command").and_then(Value::as_str).unwrap_or("").to_string(); @@ -81,8 +95,12 @@ fn run_steps(s: &mut Session, label: &str, artboard: Option, cmds: &mut [Va { o.insert(key.into(), json!(usize::try_from(a).map_or(last, |a| a.min(last)))); } + // 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)> = s.docs.iter().filter(|st| st.undo_group.is_some()).map(|st| (st.uid, st.doc.clone())).collect(); let (v, noted) = s.execute_step(&id, ¶ms).map_err(|e| EngineError::Other(format!("batch step {} (`{id}`) failed: {e}", results.len())))?; + 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 @@ -95,11 +113,36 @@ fn run_steps(s: &mut Session, label: &str, artboard: Option, cmds: &mut [Va Ok(results) } +/// The undo groups a step belongs to, as [`Session::execute`] notes a command's journal entry in +/// them: the group of each document in `held` (the grouped documents before the step) that the step +/// changed, each group it opened and edited, and the group of the document with [`DocState::uid`] +/// `start` when it started there and ended there. With the index of the document it left active +/// when it changed the active document. +fn step_groups(s: &Session, start: Option, held: &[(u64, Arc)]) -> (Vec, Option) { + let end = s.active().map(|d| d.uid); + let uids = s + .docs + .iter() + .filter(|st| { + st.undo_group.as_ref().is_some_and(|g| { + let edited = match held.iter().find(|(uid, _)| *uid == st.uid) { + Some((_, d)) => !Arc::ptr_eq(d, &st.doc), + None => g.first.is_some(), + }; + edited || (start == Some(st.uid) && end == start) + }) + }) + .map(|st| st.uid) + .collect(); + (uids, if end == start { None } else { s.active }) +} + /// The documents as they were before the batch (`start`), whatever the steps did to them: opened /// ones close, closed or replaced ones (`stash`) come back, and each has its art, selection, /// history, file, format and saved state again (#1697: undoing the batch's interaction alone left /// a Save As step's new file and an Undo step's history in place). Files the steps wrote stay -/// written. Lock Guides stays as the steps left it, and while it is on the guides are deselected. +/// written. Lock Guides, Lock Slices and Hide Slices stay as the steps left them, and the guides +/// and slices they keep from being selected are deselected. fn roll_back(s: &mut Session, start: Vec, stash: &[DocState]) { let open = std::mem::take(&mut s.docs); s.docs = start; @@ -107,8 +150,6 @@ fn roll_back(s: &mut Session, start: Vec, stash: &[DocState]) { // Past the newest revision the document reached, so the restored one redraws. let newest = open.iter().chain(stash).filter(|d| d.uid == st.uid).map(|d| d.revision).max().unwrap_or(st.revision); st.revision = newest.saturating_add(1); - if s.menu.guides_locked { - crate::deselect_guides(&st.doc, &mut st.selection); - } + crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection); } } diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs new file mode 100644 index 0000000000..0a0a8549fd --- /dev/null +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -0,0 +1,146 @@ +use super::access::file_list; +use super::formats::formats; +use super::*; + +pub fn specs() -> Vec { + vec![ + cmd!( + "document.open", + "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), 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)} → {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). 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 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)", + always, + load::open + ), + cmd!( + query "file.list", + "List Folder", + [], + None, + "{path} the files and folders in folder `path`, by name: what an agent may open there (held to the automation read root when one is in force) → {path, entries: [{name, kind: file|folder|link, size? (files, bytes)}], truncated (more than 5000 entries)} (#1163)", + always, + file_list + ), + cmd!( + query "document.serialize", + "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 their layers)} → {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}]", + has_doc, + export::serialize + ), + cmd!( + "document.export", + "Export Document", + [], + None, + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", + has_doc, + export::export + ), + cmd!( + "document.exportSelection", + "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), scale?: 1, …the format's options} the selected objects cropped to their bounds (template layers left out) → {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", + has_selection, + export::export_selection + ), + cmd!( + "document.exportForScreens", + "Export for Screens", + ["File", "Export"], + None, + "{folder?, zip?: false (one store-only .zip of every file: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,