diff --git a/.cargo/config.toml b/.cargo/config.toml index 35049cbcb1..6c26ee582a 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,9 @@ [alias] xtask = "run --package xtask --" + +# WebAssembly SIMD for the web build: without it vello_cpu's SIMD layer (fearless_simd) runs its +# scalar fallback on wasm32 and the canvas renders about 2.4x slower (#2786). The web build then +# needs Chrome/Edge 91+, Firefox 89+ or Safari 16.4+. A RUSTFLAGS environment variable replaces +# these flags. +[target.wasm32-unknown-unknown] +rustflags = ["-C", "target-feature=+simd128"] diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 0000000000..de64ad3ee4 --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/.github/workflows/print.yml b/.github/workflows/print.yml index 400a819442..058705ce29 100644 --- a/.github/workflows/print.yml +++ b/.github/workflows/print.yml @@ -13,27 +13,27 @@ on: workflow_dispatch: permissions: contents: read -env: - CARGO_TERM_COLOR: always - CARGO_INCREMENTAL: 0 +# A newer push to a PR branch cancels its older run. +concurrency: + group: print-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: + # Desktop printing on Windows, through the suite's shared gate. Pull requests restore the cache + # but never save one; a manual run on main saves the cache they restore. windows: - runs-on: windows-2022 - timeout-minutes: 90 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: dtolnay/rust-toolchain@e2a55d2ffb04f378e9626c28d38b36d230d1e12f # master - with: - toolchain: stable - components: clippy - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - with: - key: desktop-print - - run: cargo clippy --locked -p vectorcraft --all-targets -- -D warnings - - run: cargo test --locked -p vectorcraft - - name: Check pending submission and queue refusal feedback - shell: bash - # A filter that matches nothing still passes, so fail unless some test ran. - run: | - cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee printps.log - grep -Eq 'test result: ok\. [1-9][0-9]* passed' printps.log || { echo "::error::tests::printps matched no tests"; exit 1; } + # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["windows-2022"]' + timeout-minutes: 90 + # As before: printing builds and tests without craft-fonts, nextest or the wasm target. + craft-fonts-ref: "" + tools: "" + targets: "" + # A filter that matches nothing still passes, so the printps run fails unless some test ran. + command: | + cargo clippy --locked -p vectorcraft --all-targets -- -D warnings + cargo test --locked -p vectorcraft + log="$RUNNER_TEMP/printps.log" + cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log" + grep -Eq 'test result: ok\. [1-9][0-9]* passed' "$log" || { echo "::error::tests::printps matched no tests"; exit 1; } diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d1677e538c..0a57e0e6b0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,6 +20,12 @@ concurrency: cancel-in-progress: false jobs: + # Regenerates contributors/contributors.json for the release commit; every build bundles it. + credits: + permissions: + contents: read + pull-requests: read + uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main git-sources: name: Git dependencies come from storytold runs-on: ubuntu-latest @@ -60,9 +66,10 @@ jobs: PY release: - needs: git-sources + needs: [git-sources, credits] permissions: contents: write + packages: write # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: @@ -71,6 +78,7 @@ jobs: craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 web-craft-fonts: true version: ${{ inputs.version }} + contributors-artifact: ${{ needs.credits.outputs.artifact-name }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} @@ -81,6 +89,7 @@ jobs: WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }} WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index 7fc9b59251..b121ce45f1 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -27,8 +27,8 @@ permissions: jobs: windows-arm64: - # Immutable supporting workflow revision until the new install contract lands upstream. - uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f + # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. + uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main with: app-name: vectorcraft app-dir: VectorCraft diff --git a/AGENTS.md b/AGENTS.md index 61f141079e..58ab2d6d27 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,56 @@ + +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. + + +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. + + # VectorCraft — instructions for agents VectorCraft is a clean-room, open-source, Rust-native vector illustration app targeting Adobe Illustrator parity (and beyond). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings: `../photocraft` (Photoshop-class) and `../pdfcraft` (Acrobat-class); same conventions. @@ -6,10 +59,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format ## Start every session here 1. Read [`ROADMAP.md`](ROADMAP.md) (stage, numbers by dimension, what's next) and the ranked work list in [`docs/gaps.md`](docs/gaps.md). Unless the user gives you a task, pick work from that list. -2. Read `plan/STATUS.md` (local session notes, may lag the ROADMAP), then the task in `plan/execution-plan.md` §3 and the relevant `plan/architecture.md` section. Behaviour reference: public documentation only (see Clean-room below); `plan/illustrator/*.md` holds notes from it. -3. Follow the autonomous operation protocol (`plan/execution-plan.md` §7): orient → plan → implement + test → verify → record → commit. Don't stop to ask unless §7 lists the decision as the user's. - -`plan/` is gitignored (local only). +2. `plan/` is an optional gitignored notebook. Behaviour notes may be in `plan/illustrator/*.md`. Do not ask for it and do not stop when it is absent. Orient, implement, test, verify, then record in the public docs. ## Non-negotiables - **Clean-room: never use Adobe software (absolute rule, from the project owner).** Adobe's Terms of Use forbid reverse engineering, including observing a program's inputs and outputs to recreate it. So: @@ -28,7 +78,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format - Creative Commons with redistribution allowed. - **Every asset file must have a row in [`ASSETS.md`](ASSETS.md)** (path, author, source URL, licence, notes). Put licence texts next to the assets (e.g. `assets/fonts/OFL-*.txt`) and summarize them in `NOTICE`. - `cargo xtask assets` (run by `cargo xtask ci`) fails on any unattributed asset. - - **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo** (rules: craftrules [`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)). Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts. + - **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo**. Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts. - Code and original assets are MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). The ArtCraft logos in `docs/brand/` are trademarks, not open source, under `docs/brand/LICENSE-brand.txt`: never modify them or use them outside VectorCraft. - Prefer art generated in code for defaults (swatches, brushes, symbols, patterns, cursors). If the provenance of an asset is unclear, don't add it. - Reference screenshots of Illustrator stay local under the gitignored `plan/` and are never committed, published or used as assets. @@ -45,8 +95,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`. +- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`. - **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`). ## Running and looking at the app @@ -59,7 +108,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; write manifests atomically. Each target dir grows to ~30 GB: delete yours when you finish (a full disk fails links with `errno=28`). ## Roadmap and progress docs -The progress docs follow craftrules' [`standards/progress-docs.md`](https://github.com/storytold/craftrules/blob/main/standards/progress-docs.md): +The progress docs: - [`ROADMAP.md`](ROADMAP.md): stage, headline numbers, dimensions, features, languages, upcoming, progress log. - [`docs/target-app-parity.md`](docs/target-app-parity.md): the authoritative parity assessment (area table, methodology, calibration, evidence of what ships). - [`docs/gaps.md`](docs/gaps.md): every known shortfall, ranked; the work list. [`docs/roadmap.md`](docs/roadmap.md): milestones and current focus. @@ -72,17 +121,21 @@ When a task lands, update in the same PR: the area row in `docs/target-app-parit ## Contributor credits (About window) - About ▸ Contributors/Models are compiled into the binary from `contributors/contributors.json` - (commit stats; generated, never hand-edit) and `contributors/people.toml` (names people chose for + (commit stats; never hand-edit) and `contributors/people.toml` (names people chose for themselves). See `docs/contributors.md`. - **Agents working for a contributor:** when you prepare a PR, check whether your human's GitHub username has a `[people.]` entry in `contributors/people.toml`. If not, ask them once whether they want to be credited by more than their username: a real name, a display name, and/or their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry - (copy the template at the top of the file, or run - `python3 ../../craftrules/scripts/contributors.py --add-me . --real-name "…" --sync-github-name`) + (copy the template at the top of the file) and include it in their PR, committed as them. If no, change nothing: they are credited as `@username` anyway. - Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or GitHub profiles). Never hand-edit `contributors.json`. -- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also - re-verifies who wrote each `people.toml` entry; `--check` only verifies). + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. + +New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. diff --git a/ASSETS.md b/ASSETS.md index 26d4630911..17ab680ff4 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -1,12 +1,28 @@ # Asset attribution +## Indic hyphenation patterns + +| Asset | Author | Source | Licence | Notes | +|---|---|---|---|---| +| `crates/text/patterns/hyph-hi.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-hi.tex | MIT (selected option) | Unmodified; full license in file | +| `crates/text/patterns/hyph-mr.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-mr.tex | MIT (selected option) | Unmodified; full license in file | +| `crates/text/patterns/hyph-gu.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-gu.tex | MIT (selected option) | Unmodified; full license in file | +| `crates/text/patterns/hyph-bn.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-bn.tex | MIT (selected option) | Unmodified; full license in file | +| `crates/text/patterns/hyph-pa.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-pa.tex | MIT (selected option) | Unmodified; full license in file | +| `crates/text/patterns/hyph-ta.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-ta.tex | MIT (selected option) | Unmodified; full license in file | +| `crates/text/patterns/hyph-te.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-te.tex | MIT (selected option) | Unmodified; full license in file | +| `crates/text/patterns/hyph-kn.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-kn.tex | MIT (selected option) | Unmodified; full license in file | +| `crates/text/patterns/hyph-ml.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-ml.tex | MIT (selected option) | Unmodified; full license in file | +| `crates/text/patterns/hyph-or.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-or.tex | MIT (selected option) | Unmodified; full license in file | +| `crates/text/patterns/hyph-as.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-as.tex | MIT (selected option) | Unmodified; full license in file | + Every non-code asset in this repository (icons, images, fonts, example art, colour profiles, presets) is listed here with its author, source and licence. `cargo xtask assets` (part of `cargo xtask ci`) fails if an asset file is missing from this table. **Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets and the vector tool cursors (`crates/ui-egui/src/cursors.rs`). -**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts) (rules: craftrules [`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)). The small Latin UI/document fonts below predate that rule and stay. +**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay. **Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. @@ -115,6 +131,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | | | `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-dash-align.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -224,13 +241,16 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-swap.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-swatch-kinds.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-symbol-sprayer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | -| `assets/icons/dc-touch-type.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-touch-type.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-transform-panel.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-transparency.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-twirl.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | -| `assets/icons/dc-type-area.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | -| `assets/icons/dc-type-path.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | -| `assets/icons/dc-type-vertical.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-type.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-type-area.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-type-path.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-type-vertical.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-type-vertical-area.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-type-vertical-path.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-width-profile.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-width.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-wrinkle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | @@ -345,6 +365,21 @@ Generated-in-code art is original and has no file to list. This covers the defau | `examples/ribbons.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | | `examples/feature-sheet.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | | `examples/perspective-city.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | | +| `crates/engine/tests/fixtures/jpeg2000/checker.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `3de9c2bb5b8aaec241d939b795002a68eb3d50e41d51c43368000804ad3de057` | +| `crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `76fa51ab8ccbc2534098b26b8e7fe16dd886e2b6298ba52d06a6b1bde9b61d9e` | +| `crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `1b1aeed8975d3cdc832da6ecf5855852d07d0c490105121e61a8aefb31af009b` | +| `crates/engine/tests/fixtures/heif/quadrants.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 red, green, blue and white quadrants encoded with libheif's `heif-enc` 1.23.2 (x265); SHA-256 `122d14963fe899daa736cd216902cf4fc8f2192b3a0ba81f94004adcd71a0ff5` | +| `crates/engine/tests/fixtures/heif/quadrants-alpha.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants with a transparent right half, encoded with `heif-enc` 1.23.2; SHA-256 `55b5a537401ead742714c3a1bc526559ec8c1ba97cdb7f43ac63f4037167475b` | +| `crates/engine/tests/fixtures/heif/quadrants-10bit.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants at 10 bits, encoded with `heif-enc` 1.23.2; SHA-256 `11014848c6a838e5799d87e034eff1b06b816712ed70ba451bd582d72741774f` | +| `crates/engine/tests/fixtures/heif/quadrants-grid.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 128 × 128 quadrants as a 2 × 2 grid of 64 × 64 tiles, encoded with `heif-enc` 1.23.2; SHA-256 `5802f8715110954eb9c58d4bdcc10d1200426a48cf726f1b88dfb60da825ba7a` | +| `crates/engine/tests/fixtures/heif/quadrants-300ppi.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants with EXIF resolution tags of 300 ppi, encoded with `heif-enc` 1.23.2; SHA-256 `6a344a6de04fc5fceaee46b6e0028b12478c90bdcb6f6f14ed8c86a44cb203d7` | +| `crates/engine/tests/fixtures/heif/wide-rotated.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 16 red and blue halves stored with a quarter-turn rotation, encoded with `heif-enc` 1.23.2; SHA-256 `e3a2c3a9beb4066c13d6deb8e1311805c6aac485fde8784f1ee317dd95b89973` | +| `crates/engine/tests/fixtures/heif/wide-rotated-300x150.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the rotated halves with EXIF resolution tags of 300 ppi across and 150 ppi down, encoded with `heif-enc` 1.23.2; SHA-256 `79ad7945cd2c1ea9d3e70ac9b93d9a162fd8ce37541a0f3de44e12f04745921d` | +| `crates/engine/tests/fixtures/heif/tones.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 quadrants of four mid tones, encoded with `heif-enc` 1.23.2; SHA-256 `29ed7d75fbfbc4c298eb2da3a6b62625a150cd6bfe5b7ff1d847437501b1b4b1` | +| `crates/engine/tests/fixtures/heif/tones-p3-nclx.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones labeled Display P3 in an `nclx` color box, encoded with `heif-enc` 1.23.2; SHA-256 `baeb32ffa58ac1ac29a00c9e388b9281f4acb4695c4681e4933d0ad061447101` | +| `crates/engine/tests/fixtures/heif/tones-p3-icc.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones with VectorCraft's own Display P3 ICC profile (`vectorcraft_color::cms::icc_bytes`), encoded with `heif-enc` 1.23.2; SHA-256 `472e1a123b9515926a8985a04c3f680387e8c410dbf8f7ff0cfb8cb99c89e93b` | +| `crates/engine/tests/fixtures/heif/tones-p3-icc-only.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones with VectorCraft's own Display P3 ICC profile as their only color box, encoded with `heif-enc` 1.23.2; SHA-256 `2654fdd21e56641107db20b3f4d0a66a86420ac040d42ddf55e20f7e789d5c55` | +| `crates/engine/tests/fixtures/heif/quadrants-grid16.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 quadrants as a 2 × 2 grid of 16 × 16 tiles, each cropped from a 64 × 64 picture, encoded with `heif-enc` 1.23.2; SHA-256 `bd114ee66cdac10142729dc9dddfa1cd96993a5cefa54c2f25b65496652f007f` | ## Assets embedded by the PDF backend @@ -352,20 +387,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/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 | +| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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/ATTRIBUTION.md b/ATTRIBUTION.md new file mode 100644 index 0000000000..f28ed3dde9 --- /dev/null +++ b/ATTRIBUTION.md @@ -0,0 +1,17 @@ +# Attribution + +The complete historical asset manifest is [ASSETS.md](ASSETS.md). These hyphenation assets use the MIT option, with the complete copyright and permission notices preserved in each file. + +| Asset | Author | Source | SPDX license | Notes | +|---|---|---|---|---| +| `crates/text/patterns/hyph-hi.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-hi.tex | MIT | Unmodified; full license in file | +| `crates/text/patterns/hyph-mr.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-mr.tex | MIT | Unmodified; full license in file | +| `crates/text/patterns/hyph-gu.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-gu.tex | MIT | Unmodified; full license in file | +| `crates/text/patterns/hyph-bn.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-bn.tex | MIT | Unmodified; full license in file | +| `crates/text/patterns/hyph-pa.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-pa.tex | MIT | Unmodified; full license in file | +| `crates/text/patterns/hyph-ta.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-ta.tex | MIT | Unmodified; full license in file | +| `crates/text/patterns/hyph-te.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-te.tex | MIT | Unmodified; full license in file | +| `crates/text/patterns/hyph-kn.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-kn.tex | MIT | Unmodified; full license in file | +| `crates/text/patterns/hyph-ml.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-ml.tex | MIT | Unmodified; full license in file | +| `crates/text/patterns/hyph-or.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-or.tex | MIT | Unmodified; full license in file | +| `crates/text/patterns/hyph-as.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-as.tex | MIT | Unmodified; full license in file | diff --git a/CLAUDE.md b/CLAUDE.md index 0460b61925..43c994c2d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,71 +1 @@ -# VectorCraft — instructions for agents - -VectorCraft is a clean-room, open-source, Rust-native vector illustration app targeting Adobe Illustrator parity (and beyond). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings: `../photocraft` (Photoshop-class) and `../pdfcraft` (Acrobat-class); same conventions. - -Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format": "drawcraft"` headers still open (`vectorcraft_format::LEGACY_EXTENSION`), and preferences migrate from the old config folder. Keep those paths working; use the new name everywhere else. - -## Start every session here -1. Read [`ROADMAP.md`](ROADMAP.md) (stage, numbers by dimension, what's next) and the ranked work list in [`docs/gaps.md`](docs/gaps.md). Unless the user gives you a task, pick work from that list. -2. Read `plan/STATUS.md` (local session notes, may lag the ROADMAP), then the task in `plan/execution-plan.md` §3 and the relevant `plan/architecture.md` section. Behaviour reference: public documentation only (see Clean-room below); `plan/illustrator/*.md` holds notes from it. -3. Follow the autonomous operation protocol (`plan/execution-plan.md` §7): orient → plan → implement + test → verify → record → commit. Don't stop to ask unless §7 lists the decision as the user's. - -`plan/` is gitignored (local only). - -## Non-negotiables -- **Clean-room: never use Adobe software (absolute rule, from the project owner).** Adobe's Terms of Use forbid reverse engineering, including observing a program's inputs and outputs to recreate it. So: - - Never launch, run, script, automate (COM, AppleScript, ExtendScript, UI automation), screenshot or measure Illustrator or any other Adobe application, and never compare our output against one. Don't make test files with them, not even "synthetic" ones. - - Never read, disassemble or copy anything inside an Adobe install (binaries, plug-ins, presets, procsets, resources, help files, fonts, ICC profiles). - - Never copy Adobe-authored code or text into this repo, tests included: no PostScript procsets or prologs (AGM, CoolType, the Illustrator prologs), no sample files. Write test inputs from scratch from the public specifications (PostScript Language Reference, PDF / ISO 32000, TIFF, EPSF/DCS). - - Behaviour comes only from public documentation (helpx, published specs, public forum posts), cited by URL, and from files users send us that they own (used locally, never committed). Never copy Adobe icons, artwork, presets or wording beyond feature names. - - If a task seems to need any of this, stop and say so instead. `cargo xtask cleanroom` (run by `cargo xtask ci`) fails on Adobe copyright notices and on fixtures made with Adobe applications. - - Never copy GPL/AGPL code (Inkscape, lib2geom…). -- **Assets: no Adobe iconography or images — ever (absolute rule, from the project owner).** - - Never add, copy, trace, redraw-from, embed or ship any icon, image, artwork, cursor, preset, swatch/brush/symbol/pattern/style library, ICC profile or screenshot from Adobe products or from any other source whose licence doesn't allow it. - - Every image, icon, font or other asset must be one of: - - original work created for VectorCraft by a contributor (who licenses it MIT OR Apache-2.0); - - OSI open source; - - public domain / CC0; - - Creative Commons with redistribution allowed. - - **Every asset file must have a row in [`ASSETS.md`](ASSETS.md)** (path, author, source URL, licence, notes). Put licence texts next to the assets (e.g. `assets/fonts/OFL-*.txt`) and summarize them in `NOTICE`. - - `cargo xtask assets` (run by `cargo xtask ci`) fails on any unattributed asset. - - **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo** (rules: craftrules [`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)). Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts. - - Code and original assets are MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). The ArtCraft logos in `docs/brand/` are trademarks, not open source, under `docs/brand/LICENSE-brand.txt`: never modify them or use them outside VectorCraft. - - Prefer art generated in code for defaults (swatches, brushes, symbols, patterns, cursors). If the provenance of an asset is unclear, don't add it. - - Reference screenshots of Illustrator stay local under the gitignored `plan/` and are never committed, published or used as assets. -- **Never crash: no panics in shipped code.** A crash loses the user's unsaved work. Files, pasted data, MCP and control messages, and command params are all untrusted input. - - Fallible work returns `Result` (or `Option`); callers handle it or propagate it with `?`. Failures reach the user as an error message (`EngineError` for commands, the crate's own error type or `String` below the engine), never as an abort. - - Workspace clippy lints ban these outside tests, so `cargo xtask ci` fails on them: `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`. Use instead: `?`, `.ok_or(…)?`, `let … else { return … }`, `if let`, `unwrap_or` / `unwrap_or_default` / `unwrap_or_else`, `.first()` / `.last()` / `.split_last()`, and a real error for a match arm you believe is impossible. - - New workspace crates must include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. Production crate roots must declare `#![forbid(unsafe_code)]` before modules or other crate items; crate-level `//!` documentation may precede it. - - Don't panic implicitly either: use `.get(i)` instead of `v[i]` or `&s[a..b]` when the index comes from data. Don't divide integers by something that can be zero, cap sizes and counts read from input (allocations, images, loops), and check that floats are finite before casting them or looping on them. - - Don't silence errors just to satisfy the lint: use `let _ =` or `.ok()` only where ignoring the failure is the right behaviour, with a comment saying why. - - Tests may unwrap and panic (`#[test]`, `#[cfg(test)]`, `tests/`, `testkit`). Integration-test files start with an `#![allow(…)]` for that. - - `vectorcraft_engine::guard` is the last line of defence. Every entry point (commands, tool events, MCP requests, the UI frame, control requests) catches a panic, rolls the document back and reports an internal error. It exists for bugs and doesn't replace `Result`: wasm aborts on panic, so the web app has no safety net. - - Untrusted input is fuzzed (`engine/tests/import_fuzz.rs`, `engine/tests/command_sweep.rs`, `format/tests/prop_format.rs`, `mcp/tests/protocol_props.rs`). Extend these when you add an importer, a parser or a protocol method. -- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`) + tests. Tools emit commands (Begin/Preview/Commit). UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The control channel and MCP reach all of them. -- **Adding a cursor.** The app decides which cursors exist; whoever draws them works from the list. For a new tool state with a cursor of its own: add the `Cursor` variant (`crates/tools/src/lib.rs`, with a doc comment), return it from the tool's `cursor()` with a tool test, cover it in `cursor_icon` (`crates/ui-egui/src/canvas.rs`), draw it in `crates/ui-egui/src/cursors.rs` or give it a stand-in in `Cursor::stand_in()` until it's drawn, and add its `[[cursor]]` entry to `crates/tools/src/cursors.toml` (when it shows, in plain behaviour terms, and its hotspot; never another app's look). A missing entry only warns (`cargo xtask cursors`): the cursor still works. -- **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`). - -## Running and looking at the app -- `cargo run --release -p vectorcraft -- --control 7979 [file.svg|file.vectorcraft]` (sibling apps' agents use the same default port: if the log says it failed to bind, pick another port — otherwise your requests reach a different app). -- Drive it: JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"shape.rectangle","params":{"x":10,"y":10,"width":100,"height":50}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`. -- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and compare with the public documentation (`plan/illustrator/02-ui-ux.md` notes). `ui.screenshot` needs a presented frame: if it errors (screen locked), check the art with `ui.render` / `vectorcraft-cli run … --export x.png`, and cover panels with a headless egui frame test (see `panels/transparency.rs` tests). -- **Performance:** `vectorcraft-cli perf` checks the budgets (render/pan/zoom, hit test, save/open, SVG, Pathfinder) on a synthetic 50k-path document; `vectorcraft-cli bench FILE` times one file. Run them before and after renderer, format or geometry changes, on an idle machine (the report warns when the load average makes timings noise). -- MCP: `vectorcraft-cli mcp` (see `docs/mcp.md`). -- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`. -- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; write manifests atomically. Each target dir grows to ~30 GB: delete yours when you finish (a full disk fails links with `errno=28`). - -## Roadmap and progress docs -The progress docs follow craftrules' [`standards/progress-docs.md`](https://github.com/storytold/craftrules/blob/main/standards/progress-docs.md): -- [`ROADMAP.md`](ROADMAP.md): stage, headline numbers, dimensions, features, languages, upcoming, progress log. -- [`docs/target-app-parity.md`](docs/target-app-parity.md): the authoritative parity assessment (area table, methodology, calibration, evidence of what ships). -- [`docs/gaps.md`](docs/gaps.md): every known shortfall, ranked; the work list. [`docs/roadmap.md`](docs/roadmap.md): milestones and current focus. -- Checklists: [`ui-parity.md`](docs/ui-parity.md), [`file-format-parity.md`](docs/file-format-parity.md), [`hardware-parity.md`](docs/hardware-parity.md), [`localization-parity.md`](docs/localization-parity.md), [`effects-parity.md`](docs/effects-parity.md), [`type-parity.md`](docs/type-parity.md); [`architecture.md`](docs/architecture.md). - -When a task lands, update in the same PR: the area row in `docs/target-app-parity.md` (score, missing items, hours) and its evidence list, the gap entry in `docs/gaps.md` if it closed or shrank, the checklist it belongs to, the milestone row in `docs/roadmap.md`, and the ROADMAP's tables and progress log when a headline number moves. Update each touched doc's status line and revision history. -- Grade by behaviour against the public documentation (`plan/illustrator/` notes), not by whether a menu item exists. Scores are self-assessed, so err low; mark each number measured or estimated. -- Keep the README's Status section in step with the ROADMAP headline. +@AGENTS.md diff --git a/Cargo.lock b/Cargo.lock index 78306baae3..ee3905a8a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -303,7 +303,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "slab", "windows-sys 0.61.2", ] @@ -334,7 +334,7 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -360,7 +360,7 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix 1.1.5", + "rustix 1.1.6", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -665,7 +665,7 @@ checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" dependencies = [ "bitflags 2.13.2", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "tracing", ] @@ -688,7 +688,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" dependencies = [ "calloop 0.14.5", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-client", ] @@ -705,6 +705,17 @@ dependencies = [ "shlex", ] +[[package]] +name = "cfb" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f13298d9178622b7916ec5d01d470425c04273c8ed07e87b1c38b34c4f4612b" +dependencies = [ + "fnv", + "uuid", + "web-time", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -763,9 +774,9 @@ dependencies = [ [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ] @@ -959,17 +970,17 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" dependencies = [ "fixed_decimal", "icu_decimal", @@ -992,7 +1003,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" dependencies = [ "egui", "serde", @@ -1002,7 +1013,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1013,11 +1024,12 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" dependencies = [ "craft-winprint-gdi", + "log", "miniz_oxide 0.9.1", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "tempfile", "winprint", "winsafe", @@ -1026,7 +1038,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1047,13 +1059,14 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" dependencies = [ "chrono", "dunce", "egui", "flate2", "getrandom 0.3.4", + "image", "log", "plist", "semver", @@ -1069,10 +1082,32 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-vectorcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" +dependencies = [ + "flate2", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-web-api" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505" +dependencies = [ + "js-sys", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", +] + [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" dependencies = [ "egui", "objc2 0.6.5", @@ -1407,7 +1442,7 @@ dependencies = [ "itertools", "log", "profiling", - "resvg", + "resvg 0.45.1", ] [[package]] @@ -1887,7 +1922,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "windows-link", ] @@ -1939,6 +1974,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "gif" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b" +dependencies = [ + "color_quant", + "weezl 0.1.12", +] + [[package]] name = "gif" version = "0.14.2" @@ -2172,7 +2217,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" dependencies = [ "brotli", "hayro-postscript", @@ -2181,7 +2226,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2199,7 +2244,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2217,12 +2262,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" dependencies = [ "flate2", "hayro-ccitt", @@ -2232,7 +2277,7 @@ dependencies = [ "rustc-hash 2.1.3", "smallvec", "stringprep", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -2241,6 +2286,15 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "heic-rs" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8883c3bfa6b4ff19a40e52a6dc051c5612cbe21bf408fc6d4875e8dfd777cb66" +dependencies = [ + "rayon", +] + [[package]] name = "hermit-abi" version = "0.5.3" @@ -2608,14 +2662,14 @@ dependencies = [ "bytemuck", "byteorder-lite", "color_quant", - "gif", + "gif 0.14.2", "image-webp", "moxcms", "num-traits", "png 0.18.1", "tiff", - "zune-core", - "zune-jpeg", + "zune-core 0.5.3", + "zune-jpeg 0.5.15", ] [[package]] @@ -2830,13 +2884,13 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" dependencies = [ "base64 0.22.1", "bumpalo", "flate2", "float-cmp", - "gif", + "gif 0.14.2", "image-webp", "imagesize 0.14.0", "indexmap", @@ -2851,7 +2905,7 @@ dependencies = [ "tiny-skia-path 0.12.0", "xmp-writer", "yoke", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -2933,8 +2987,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a25df1b0c5432893f41bba817150e323703ee5f6d974f3a6808ac7fd7f046d18" +source = "git+https://github.com/storytold/craft-libs?rev=481f66d287b2a06845f3667a19daf35f0fe958ed#481f66d287b2a06845f3667a19daf35f0fe958ed" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -3899,7 +3952,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -4379,12 +4432,33 @@ version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" dependencies = [ + "gif 0.13.3", + "image-webp", "log", "pico-args", "rgb", "svgtypes 0.15.3", - "tiny-skia", + "tiny-skia 0.11.4", "usvg 0.45.1", + "zune-jpeg 0.4.21", +] + +[[package]] +name = "resvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd" +dependencies = [ + "bytemuck", + "gif 0.14.2", + "image-webp", + "log", + "pico-args", + "rgb", + "svgtypes 0.16.1", + "tiny-skia 0.12.0", + "usvg 0.48.1", + "zune-jpeg 0.5.15", ] [[package]] @@ -4445,9 +4519,9 @@ checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" [[package]] name = "roxmltree" -version = "0.21.1" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" dependencies = [ "memchr", ] @@ -4488,9 +4562,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", @@ -4671,7 +4745,7 @@ checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" dependencies = [ "log", "smithay-client-toolkit 0.19.2", - "tiny-skia", + "tiny-skia 0.11.4", ] [[package]] @@ -5096,9 +5170,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.16.3" +version = "1.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" dependencies = [ "serde", ] @@ -5141,7 +5215,7 @@ dependencies = [ "libc", "log", "memmap2", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "wayland-backend", "wayland-client", @@ -5416,7 +5490,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -5489,7 +5563,7 @@ dependencies = [ "half", "quick-error 2.0.1", "weezl 0.1.12", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] @@ -5537,6 +5611,21 @@ dependencies = [ "tiny-skia-path 0.11.4", ] +[[package]] +name = "tiny-skia" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png 0.18.1", + "tiny-skia-path 0.12.0", +] + [[package]] name = "tiny-skia-path" version = "0.11.4" @@ -5992,7 +6081,7 @@ dependencies = [ "kurbo 0.13.1", "log", "pico-args", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "simplecss", "siphasher", "skrifa 0.44.0", @@ -6036,7 +6125,7 @@ dependencies = [ [[package]] name = "vectorcraft" -version = "0.18.0" +version = "0.21.0" dependencies = [ "arboard", "block2 0.6.2", @@ -6061,8 +6150,11 @@ dependencies = [ "raw-window-handle", "rfd", "serde_json", + "smithay-clipboard", "socket2", + "tempfile", "vectorcraft-engine", + "vectorcraft-render", "vectorcraft-text", "vectorcraft-ui-egui", "wayland-backend", @@ -6079,7 +6171,7 @@ dependencies = [ [[package]] name = "vectorcraft-affinity" -version = "0.18.0" +version = "0.21.0" dependencies = [ "crc32fast", "flate2", @@ -6090,7 +6182,7 @@ dependencies = [ [[package]] name = "vectorcraft-brush" -version = "0.18.0" +version = "0.21.0" dependencies = [ "kurbo 0.13.1", "serde", @@ -6102,7 +6194,7 @@ dependencies = [ [[package]] name = "vectorcraft-cad" -version = "0.18.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6118,12 +6210,13 @@ dependencies = [ [[package]] name = "vectorcraft-cli" -version = "0.18.0" +version = "0.21.0" dependencies = [ "log", "objc2-core-foundation", "objc2-core-text", "serde_json", + "tempfile", "vectorcraft-color", "vectorcraft-doc", "vectorcraft-engine", @@ -6140,7 +6233,7 @@ dependencies = [ [[package]] name = "vectorcraft-color" -version = "0.18.0" +version = "0.21.0" dependencies = [ "kurbo 0.13.1", "moxcms", @@ -6152,7 +6245,7 @@ dependencies = [ [[package]] name = "vectorcraft-doc" -version = "0.18.0" +version = "0.21.0" dependencies = [ "chrono", "hayro-ccitt", @@ -6166,16 +6259,18 @@ dependencies = [ "tiff", "vectorcraft-color", "vectorcraft-geom", - "zune-jpeg", + "zune-jpeg 0.5.15", ] [[package]] name = "vectorcraft-effects" -version = "0.18.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", + "resvg 0.48.1", "serde_json", + "svgtypes 0.16.1", "vectorcraft-color", "vectorcraft-doc", "vectorcraft-geom", @@ -6187,17 +6282,22 @@ dependencies = [ [[package]] name = "vectorcraft-engine" -version = "0.18.0" +version = "0.21.0" dependencies = [ + "cfb", + "chrono", "craft-docpath", "crc32fast", "flate2", + "hayro-jpeg2000", + "heic-rs", "image", "kurbo 0.13.1", "log", "proptest", - "roxmltree 0.21.1", - "rustix 1.1.5", + "rayon", + "roxmltree 0.21.2", + "rustix 1.1.6", "ruzstd", "serde", "serde_json", @@ -6210,6 +6310,7 @@ dependencies = [ "vectorcraft-eps", "vectorcraft-format", "vectorcraft-geom", + "vectorcraft-js", "vectorcraft-metafile", "vectorcraft-pathops", "vectorcraft-pdf", @@ -6226,8 +6327,9 @@ dependencies = [ [[package]] name = "vectorcraft-eps" -version = "0.18.0" +version = "0.21.0" dependencies = [ + "craft-pdf", "fax", "flate2", "hayro-ccitt", @@ -6236,12 +6338,14 @@ dependencies = [ "memchr", "ruzstd", "serde_json", + "skrifa 0.47.0", "vectorcraft-brush", "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", "vectorcraft-geom", "vectorcraft-metafile", + "vectorcraft-pathops", "vectorcraft-pdf", "vectorcraft-render", "vectorcraft-testkit", @@ -6250,11 +6354,12 @@ dependencies = [ [[package]] name = "vectorcraft-format" -version = "0.18.0" +version = "0.21.0" dependencies = [ + "craft-vectorcraft-format", "flate2", "proptest", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_json", "thiserror 2.0.21", @@ -6265,7 +6370,7 @@ dependencies = [ [[package]] name = "vectorcraft-geom" -version = "0.18.0" +version = "0.21.0" dependencies = [ "kurbo 0.13.1", "proptest", @@ -6275,9 +6380,18 @@ dependencies = [ "vectorcraft-testkit", ] +[[package]] +name = "vectorcraft-js" +version = "0.21.0" +dependencies = [ + "chrono", + "proptest", + "unicode-general-category", +] + [[package]] name = "vectorcraft-mcp" -version = "0.18.0" +version = "0.21.0" dependencies = [ "image", "log", @@ -6296,7 +6410,7 @@ dependencies = [ [[package]] name = "vectorcraft-metafile" -version = "0.18.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6310,7 +6424,7 @@ dependencies = [ [[package]] name = "vectorcraft-pathops" -version = "0.18.0" +version = "0.21.0" dependencies = [ "kurbo 0.13.1", "linesweeper", @@ -6322,7 +6436,7 @@ dependencies = [ [[package]] name = "vectorcraft-pdf" -version = "0.18.0" +version = "0.21.0" dependencies = [ "aes", "chrono", @@ -6335,7 +6449,7 @@ dependencies = [ "kurbo 0.13.1", "log", "md-5", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "serde", "serde_json", "sha2", @@ -6354,10 +6468,12 @@ dependencies = [ [[package]] name = "vectorcraft-plugins" -version = "0.18.0" +version = "0.21.0" dependencies = [ + "log", "serde", "serde_json", + "sha2", "thiserror 2.0.21", "vectorcraft-color", "vectorcraft-doc", @@ -6368,10 +6484,10 @@ dependencies = [ [[package]] name = "vectorcraft-render" -version = "0.18.0" +version = "0.21.0" dependencies = [ "flate2", - "gif", + "gif 0.14.2", "image", "jpeg-encoder", "log", @@ -6380,6 +6496,7 @@ dependencies = [ "psd", "serde_json", "tiff", + "unicode-general-category", "vectorcraft-brush", "vectorcraft-color", "vectorcraft-doc", @@ -6397,23 +6514,24 @@ dependencies = [ [[package]] name = "vectorcraft-scriptcheck" -version = "0.18.0" +version = "0.21.0" dependencies = [ "proptest", ] [[package]] name = "vectorcraft-svg" -version = "0.18.0" +version = "0.21.0" dependencies = [ "craft-docpath", "flate2", "image", "kurbo 0.13.1", "proptest", - "resvg", + "resvg 0.45.1", "serde", "serde_json", + "simplecss", "skrifa 0.47.0", "svgtypes 0.16.1", "thiserror 2.0.21", @@ -6423,13 +6541,14 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-effects", "vectorcraft-geom", + "vectorcraft-pathops", "vectorcraft-testkit", "vectorcraft-text", ] [[package]] name = "vectorcraft-testkit" -version = "0.18.0" +version = "0.21.0" dependencies = [ "fax", "image", @@ -6447,7 +6566,7 @@ dependencies = [ [[package]] name = "vectorcraft-text" -version = "0.18.0" +version = "0.21.0" dependencies = [ "harfrust 0.13.3", "icu_segmenter", @@ -6468,7 +6587,7 @@ dependencies = [ [[package]] name = "vectorcraft-three-d" -version = "0.18.0" +version = "0.21.0" dependencies = [ "vectorcraft-geom", "vectorcraft-pathops", @@ -6476,12 +6595,13 @@ dependencies = [ [[package]] name = "vectorcraft-tools" -version = "0.18.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", "serde", "serde_json", + "vectorcraft-brush", "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", @@ -6492,7 +6612,7 @@ dependencies = [ [[package]] name = "vectorcraft-trace" -version = "0.18.0" +version = "0.21.0" dependencies = [ "image", "kurbo 0.13.1", @@ -6504,7 +6624,7 @@ dependencies = [ [[package]] name = "vectorcraft-ui-egui" -version = "0.18.0" +version = "0.21.0" dependencies = [ "bytemuck", "craft-keymap", @@ -6515,7 +6635,7 @@ dependencies = [ "egui_kittest", "image", "log", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_json", "toml", @@ -6542,8 +6662,9 @@ dependencies = [ [[package]] name = "vectorcraft-web" -version = "0.18.0" +version = "0.21.0" dependencies = [ + "craft-web-api", "eframe", "egui", "js-sys", @@ -6709,12 +6830,12 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.262.0" +version = "0.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +checksum = "0b883a26aea02eaabe2d2c3fba7eb039ef5cdcb5d5201ae5551e73d5e251a81f" dependencies = [ "leb128fmt", - "wasmparser 0.262.0", + "wasmparser 0.263.0", ] [[package]] @@ -6769,9 +6890,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.262.0" +version = "0.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +checksum = "4f5fa0a054ae153606df820eb0a84213e28cda41bbe04ba2628e71b6ba100fcb" dependencies = [ "bitflags 2.13.2", "indexmap", @@ -6780,9 +6901,9 @@ dependencies = [ [[package]] name = "wast" -version = "262.0.0" +version = "263.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30612a0c29249b5f185888a107e8a519d920226b7d07f9d351fd094e9f75eb23" +checksum = "69d90bcf581b501aa1c358bc5dc0faa979cd375796908860ebcb6d1d70b907c7" dependencies = [ "bumpalo", "leb128fmt", @@ -6793,9 +6914,9 @@ dependencies = [ [[package]] name = "wat" -version = "1.262.0" +version = "1.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e228027f2b07bbaf946980ebbe2437fca73be6f54c40c2a8d4f42f277075f8d1" +checksum = "bbc9c5aca783b3f1838be89f3f9937c528b90ec5faa6fb62d809726c16a7d8f7" dependencies = [ "wast", ] @@ -6808,7 +6929,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "scoped-tls", "smallvec", "wayland-sys", @@ -6821,7 +6942,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -6843,7 +6964,7 @@ version = "0.31.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "wayland-client", "xcursor", ] @@ -7518,7 +7639,7 @@ dependencies = [ "libc", "log", "os_pipe", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "tree_magic_mini", "wayland-backend", @@ -7577,7 +7698,7 @@ dependencies = [ "libc", "libloading", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "x11rb-protocol", ] @@ -7619,7 +7740,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -7673,7 +7794,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.18.0" +version = "0.21.0" dependencies = [ "serde_json", ] @@ -7723,7 +7844,7 @@ dependencies = [ "hex", "libc", "ordered-stream", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_repr", "tracing", @@ -7907,9 +8028,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.1.0" +version = "9.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704" +checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb" dependencies = [ "crc32fast", "flate2", @@ -7946,19 +8067,34 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "zune-core" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" + [[package]] name = "zune-core" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +[[package]] +name = "zune-jpeg" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713" +dependencies = [ + "zune-core 0.4.12", +] + [[package]] name = "zune-jpeg" version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" dependencies = [ - "zune-core", + "zune-core 0.5.3", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index c134a3c19d..a3e3e98907 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,22 +4,25 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"] [workspace.package] -version = "0.18.0" +version = "0.21.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 = "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" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["serde"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } # Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] } +# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } +# craft-update: app-specific pretend versions apply to startup and manual checks. +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -50,6 +53,7 @@ vectorcraft-metafile = { path = "crates/metafile" } vectorcraft-plugins = { path = "crates/plugins" } vectorcraft-affinity = { path = "crates/affinity" } vectorcraft-scriptcheck = { path = "crates/scriptcheck" } +vectorcraft-js = { path = "crates/js" } # foundation kurbo = { version = "0.13", features = ["serde"] } @@ -144,12 +148,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -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" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "481f66d287b2a06845f3667a19daf35f0fe958ed" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/NOTICE b/NOTICE index 0d0758820e..c5c5511ba0 100644 --- a/NOTICE +++ b/NOTICE @@ -20,10 +20,15 @@ list (author, source, license) is in ASSETS.md. (Ubuntu Font Licence 1.0), Hack (MIT), Noto Emoji (SIL Open Font License 1.1) and emoji-icon-font (MIT). Their license texts ship with that crate. -Rust dependencies (vello_cpu, kurbo, peniko, skrifa, harfrust, usvg, linesweeper, egui, eframe, …) are +Rust dependencies (vello_cpu, kurbo, peniko, skrifa, harfrust, usvg, egui, eframe, …) are fetched through crates.io under their own permissive licenses (mostly MIT and/or Apache-2.0; also BSD, ISC, Zlib, BSL-1.0 and Unicode-3.0). +linesweeper 0.5.0 (MIT OR Apache-2.0) is fetched from https://github.com/storytold/craft-libs at +revision 481f66d287b2a06845f3667a19daf35f0fe958ed. The copy in craft-libs' vendor/linesweeper is +the crates.io package with no file changed, and it keeps the package's LICENSE-MIT and +LICENSE-APACHE. + JPEG export uses the jpeg-encoder crate (MIT OR Apache-2.0, and the IJG License): this software is based in part on the work of the Independent JPEG Group. @@ -72,10 +77,10 @@ Shared PDF backend 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 +9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb. 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/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/README.craft-reader.md. +https://github.com/storytold/craft-libs/blob/9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb/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. @@ -136,3 +141,8 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of 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. + +Indic hyphenation patterns (crates/text/patterns/): +Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option. +Original copyright and full license notices are preserved in each hyph-*.tex file. +Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5. diff --git a/README.md b/README.md index fd45eb9cdd..08aa022a3b 100644 --- a/README.md +++ b/README.md @@ -205,10 +205,10 @@ drag-and-drop, set **Preferences › Performance › Linux Display Server** to * the app with `WAYLAND_DISPLAY= vectorcraft`: the window then opens through XWayland, where drops work (see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)). -On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft doesn't respond to a drawing tablet's -pen yet (#491, #2028). Open the window through XWayland instead, where the pen works as a mouse and the app reads its -pressure: set the same preference to **X11 (XWayland)**, or to **X11 (XWayland) When a Pen Is Attached** to use -XWayland only when a pen is attached as VectorCraft starts, and restart; or start the app with +On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft can't get a drawing tablet's pen +input on native Wayland yet (#491, #2028). When a pen is attached as VectorCraft starts, the window opens through +XWayland, where the pen works as a mouse and the app reads its pressure (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps +Wayland). For a pen attached later, set the same preference to **X11 (XWayland)** and restart, or start the app with `WAYLAND_DISPLAY= vectorcraft` (see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)). ### Use it from Claude Code and other agents @@ -253,7 +253,7 @@ The scores are self-assessed from our code against public documentation; [target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them. **What's missing:** -- reliable exchange of .ai files (layer structure in real files; proprietary editing data isn't written); +- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art); - an interaction-fidelity pass covering every tool's modifiers and small behaviours; - 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials); - filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in); @@ -317,7 +317,7 @@ Installers and executables are code-signed. | Build | File | Notes | |---|---|---| -| Static site | `vectorcraft-web-.zip` | Runs in a modern browser; host it on any static server | +| Static site | `vectorcraft-web-.zip` | Runs in a browser with WebAssembly SIMD (Chrome/Edge 91, Firefox 89, Safari 16.4 or newer), see `packaging/web/README.md`; host it on any static server | ## The Crafting Apps @@ -328,12 +328,21 @@ stand on its own. | | App | What it's for | Code | Learn more | |:-:|---|---|---|---| | | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) | -| | **VectorCraft** | **Vector illustration · you are here** | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) | +| | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) | | | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) | | | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) | | | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) | | | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) | | | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) | +| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) | +| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) | +| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) | +| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) | +| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) | +| | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) | +| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) | +| | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) | +| | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | | And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control. diff --git a/ROADMAP.md b/ROADMAP.md index 8231428eeb..1bedf0b95c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,5 +1,11 @@ # VectorCraft Roadmap +- Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. +- Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. + +- Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. +- UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged. + - PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document. - PDF.W1: PDF export and print composition use the shared optional writer for configuration, metadata, font preparation and guarded finalization; drawing and output policy remain app-owned. @@ -9,7 +15,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (OpenType SVG colour fonts draw and export as vector art; previously: COLR colour fonts (v0 and v1) draw and export as vector art; previously: G2: the Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step; remaining: filter thumbnails and a preview area inside the dialog; G2 estimate 4–6 → 1–2 h; Raster effects 82% → 85% (power-user view 49% → 52%), estimated, a modest move because the named missing dialog landed without thumbnails or an in-dialog preview; previously: colour emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; headline numbers unchanged; previously:; Affinity import AF.5: master pages, tables, paragraph formats, shadows, glows, outlines, overlays and embedded documents; ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); headline numbers unchanged; previously:; 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged; Print: Japanese paper sizes in the Print dialog's Media list — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (which keep their ISO 216 sizes), はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; about 90 community PRs of 2026-10-19: Objects on Path, the Simplify slider, Pencil Edit Selected Paths in the middle of a path, Georgian, and more; Background Export progress dialog with Cancel, #2564; about 85 community PRs of 2026-10-18: Justification…, Word .docx placed as area type, CCITT Group 3 TIFF, Roman Hanging Punctuation, blend spines edited with the Anchor Point tool, shadows and glows in stack order, coloured 3D lights, a Dutch catalog completed; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; about 145 community PRs of 2026-10-17: image-decode overflow guards, opaque floating panels, MCP export cancel and progress, editable Illustrator EPS import, scoped `doc_inspect`, Dutch, Danish and Indonesian, Simplified Chinese messages, screen-reader names; headline numbers unchanged; about 160 community PRs of 2026-10-15/16: PDF import crash fixes, Dimension tool, legacy `.ai` save, Intertwine, web pen input, Image Trace fixes, `.ai`/EPS/PDF import fidelity, Bulgarian, Greek, Swedish and Finnish catalogs; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -18,8 +24,8 @@ and the work list in [`docs/gaps.md`](docs/gaps.md). **Why alpha:** the core workflows exist end to end (drawing and path editing, Pathfinder, paint and appearance, type, SVG/PDF/EPS, print, export) and feature depth is ~75%, but a professional can't yet switch: Illustrator's -own `.ai` files open with a wrong layer structure in real cases and can't be saved back with Illustrator's -editing data, the interaction details have never been checked side by side, and some machines fail to start the +own `.ai` files open with a wrong layer structure in real cases and are saved back with an editing copy that +keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), and writes live objects as their art, the interaction details have never been checked side by side, and some machines fail to start the app. Beta needs those closed (the beta list in [gaps.md](docs/gaps.md)). It passes the core-workflow gate: all six core workflows (path drawing and editing, paint and style, type, layers/artboards/export, print production, file exchange) work end to end on macOS with save and reopen, and only the last is partial, without @@ -29,6 +35,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)). | | Value | Kind | |---|---|---| +| 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. | | **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) | | **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated | | **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated | @@ -102,7 +109,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta | English | `en` | full | 100% | | Simplified Chinese | `zh-hans` | partial (messages in English) | 85% | | Spanish | `es` | full | 100% | -| Hindi | `hi` | none | 0% | +| Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner | | Arabic | `ar` | none (no right-to-left interface) | 0% | | French | `fr` | full | 100% | | Portuguese (Brazil) | `pt-br` | full | 100% | @@ -110,6 +117,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta | Japanese | `ja` | full | 100% | | German | `de` | full | 98% | | Korean | `ko` | full | 100% | +| Bosnian | `bs` | full (AI-assisted, native review pending) | 100% | | Vietnamese | `vi` | full | 100% | Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian and Georgian (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending). @@ -128,6 +136,23 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged. +- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. +- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. +- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. +- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). +- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). +- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). +- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). +- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). +- 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. +- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. +- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. +- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. +- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. +- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. +- 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged. +- 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`). - 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged. - 2026-10-23: OpenType SVG colour fonts draw as vector art: each glyph's SVG document is read by the SVG importer, in the text's colours where it asks for them, and draws, exports and outlines as COLR glyphs do; all colour font formats are now drawn. - 2026-10-23: COLR colour fonts (v0 and v1, as in Noto Color Emoji's vector build, Segoe UI Emoji, Nabla) draw as vector art: their layers' colours, gradients, clips and blend modes on the canvas and in SVG, EPS, legacy `.ai` and PDF, and as editable paths with Create Outlines; glyphs using sweep gradients or compositing modes are drawn as images of the glyph. @@ -137,6 +162,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 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-22: Pen tilt, bearing and barrel rotation (part of #764): Calligraphic and Scatter brushes take Tilt, Bearing and Rotation beside Pressure, the Paintbrush records them along each stroke, and the app reads a pen's tilt and an Art Pen's barrel rotation from XInput2 on Linux under X11 and XWayland and from AppKit's tablet events on macOS. 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. @@ -144,6 +170,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap | Date | What landed | |---|---| +| 2026-10-29 | Linux: the Flatpak on GNOME copies and pastes text with other apps through the compositor's core Wayland protocol (smithay-clipboard on the window's connection), where arboard has neither data-control nor X11. Scores and estimates unchanged. | +| 2026-10-29 | Linux: a clipboard that can't be opened (the Flatpak on GNOME, where arboard has neither data-control nor X11) is retried after 1 s, doubling to a minute, and logged once, where the background Paste check used to reconnect and log a warning every 250 ms (267k warnings in 18 h). Scores and estimates unchanged. | | 2026-10-21 | 3D lighting: four original lighting presets shared by Revolve, Extrude & Bevel, Inflate and Rotate, with command access and manual Custom settings; scores and estimates unchanged. | | 2026-10-21 | Print: the Print dialog's Media list has the Japanese papers — JIS B4 (257 × 364 mm), JIS B5 (182 × 257 mm) and JIS B6 next to the ISO B4/B5 (which keep their ISO 216 dimensions for settings saved before them), はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm / 長形4号 90 × 225 mm / 角形2号 240 × 332 mm / 角形3号 216 × 277 mm and 四六判 127 × 188 mm. A paper is named by its JSON id or its dialog label, any case and spacing (`B5 (JIS)` or `b5jis`), and every added size prints as its own PDF page size. Headline numbers unchanged. | | 2026-10-18 | Inch rulers divide the inch in half, not in ten. Zooming in stepped an inch ruler through 0.2, 0.1 and 0.05 of an inch, marks an inch ruler does not carry; below an inch the steps are binary fractions now, 1/2 down to 1/16, with the unlabelled ticks between them binary too (down to 1/128, so the 32nds, 64ths and 128ths appear as the report expects), while the metric units, points, pixels and picas keep their tenths. A label carries the decimals its step needs, so a sixteenth reads 0.0625 rather than the rounded 0.06, with trailing zeros dropped (#2827). Headline numbers unchanged. | @@ -182,7 +210,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap | 2026-10-12 | Graphs: Object › Graph › Design… and Marker… (designs with a preview, New Design, Rename, Delete Design, Paste Design, Select Unused, and markers drawn with a design or None) (#1092); Graph Data opens as a worksheet with Import Data…, column width and decimals (#1138), and takes Transpose, Switch x/y, `|` line breaks in labels and the pie Legend, Position and Sort options (#1115); Graph Type adds Add Drop Shadow and Add Legend Across Top (#1119), widths past 100%, First Row and First Column in Front, and Draw Filled Lines (#1136); graphs keep their label formatting when drawn again (#1137). Align: a Horizontal & Vertical Align Center button (#1073); Align to Key Object makes the topmost selected object the key (#1221), and the palette's key entry reads Cancel Key Object (#1224). Pen: the nearest end wins over snapping, Alt on the last anchor edits it, and Enter, Escape or a tool switch finish a handle preview as one undo step (#821). Direct Selection: a click on an anchor of an already selected path selects that anchor alone (#1237). Make Compound Path keeps the backmost object's paint, and a selected member reads and changes the compound's fill rule (#1225). Shape Builder and Live Paint no longer turn a line's loose end past a crossing into a piece that runs out and back (#1230). Art moved or duplicated with an artboard follows Transform Pattern Tiles (#1219). A click with the Rectangular Grid tool opens its options dialog (#1169). Commands that change nothing (Lock, Hide, Transform Each, Rearrange Artboards and others) add no undo step (#1233). Saving with missing placed files keeps their relink data, and .ai export honours the chosen artboards (#718). SVG export keeps Unicode data-attribute names, and SVG Options refuses an invalid artboard range (#989). CMYK colours given in percent with a component under 1 keep their scale (#1249). Colour Image Trace keeps close dark tones apart (#1247). macOS: the Save sheet has a Format menu (#1235). The Hand and Zoom tools show drawn cursors on every platform (#1238). Czech: the remaining strings are translated, and Pathfinder's Add reads "Sjednotit" (#1226). MCP: a lost reply reports that the edit may have happened instead of replaying it (#1246); `select.key` checks its id and agents can read the key object (#1222). Tests: the command sweeps and import fuzz tests fail on a panic caught by the engine's guard (#1218), and the envelope export test ignores PDF dates and file IDs (#1220). Effect › Artistic › Film Grain (Grain, Highlight Area, Intensity; Photoshop-style filters 29/57) (#1282), and Craquelure, Mosaic Tiles and Stained Glass redraw 25–30% faster with identical pixels (#1265). Direct Selection: clicking a segment selects only that segment, and Delete removes just it (#1300); Shift-click deselects one anchor of a path selected whole (#1263). Pen + Alt converts anchors of paths inside a selected group or compound path (#1306). The Curvature tool shows circular point markers without direction handles (#1284). Snap to Point: pressing near an anchor drags by that anchor, with Smart Guides on or off (#1313). Transform Again repeats the options of the transform it repeats (#1303). Aligning anchors that are already aligned adds no undo step (#1276), and type commands that change nothing record none either (#1316). Simplify keeps the path selected with its new anchors, and its dialog previews and shows the anchor count (#1305). Adding a stroke colour to an unpainted zero-width stroke gives it a visible 1 pt width (#1256). The Eyedropper samples locked objects, template layers and art outside isolation mode (#1260), and shows a pipette cursor (#1288). Fonts named by their full name resolve to the right face (#1267), and Proportional Metrics brings the matching kerning (`apkn`, `vkrn`, `vapk`) (#1291). Artboards: Escape leaves Artboard editing (#1296), Document Setup's Edit Artboards switches to the Artboard tool (#1294), and the Artboard tool starts on the active artboard (#1309). New and imported documents use the Gridline every and Subdivisions preferences (#1314). Send to Current Layer refuses a hidden or locked current layer (#1301), and layer row commands check explicit ids (#1255). Links: Find in Folder… finds missing linked files in a folder and its subfolders and can copy them into the document's folder (#1287). Image Trace traces images over 64 megapixels scaled down instead of refusing them (#1315). DXF export marks closed curves as closed SPLINE entities (#1320). EPS import: closepath respects the path size limit (#1311). The interface is available in Hungarian (#1302), and more Czech labels are translated (#1259). Linux RPMs declare shared-library capabilities (#1290). CI pins every third-party action to a verified commit (#1321). Select menu commands skip hidden and locked art and stay inside the isolated group in isolation mode (#1325). Fill, stroke, gradient and Appearance panel commands that change nothing add no undo step (#1331). EPS import no longer hangs on shading functions fanned out through shared arrays (#1330), looped huge arcs, fine dashes and rectangle arrays (#1329), or very long dash patterns (#1332). Plug-in whole-number fields keep values past 2^53 exactly as typed (#1327). Large documents use far less memory: decoded images are shared and capped, undo history is bounded by memory, native files open in the background and save as a stream, and Data Recovery writes images once (#1245). Opacity mask commands (#1336), Simplify and Add Anchor Points (#1337) add no undo step when they change nothing. EPS files with thousands of tiling patterns, spot inks or clipped shadings open several times faster with the same result (#1341). A `.ai` or PDF saved from a CMYK document with transparency no longer opens blank in applications that read soft masks by luminosity (#1359, part of #1286). Gradient-filled shapes in a PDF or `.ai` open as one path with the gradient instead of a clip group round a rectangle, so Shape Builder, Live Paint and Pathfinder work on their outlines (#1351). A `.ai` saved with a bleed opens on its artboard with the bleed round it as the document's bleed, from its layers, and Crop To › Trim does the same for a PDF (#1349); a PDF saved with its editing data opens from it, with its layers, groups and art past the page, as a `.ai` does (#1345). Art moved into a hidden or locked layer (row drag, Merge Selected, Flatten Artwork, Collect in New Layer) or hidden by a data set is deselected (#1355), and hiding or locking a layer with a large selection deselects its objects in linear time (200,000 objects: 3.9 s to 24 ms) (#1353). Objects moved whole together with direct-selected anchors follow Preferences › Transform Pattern Tiles (#1354). Preferences › Appearance of Black › On Screen works: Display All Blacks as Rich Black shows 100K black as RGB black on the canvas (#1350). DXF: a closed control-point SPLINE opens as a closed path (#1318). Numeric fields: dragging over part of a value in an unfocused field selects that part instead of the whole value (#1339). Pathfinder Divide: an open line or curve across a filled shape cuts it into separate pieces (#1335); Unite, Minus Front, Minus Back, Intersect and Exclude results keep the source object's name, so exported SVG keeps its id (#1308). Object › Align follows the Align To choice (one object aligns to the artboard), and the choice is kept across restarts (#1347). Artboard tool: a click on an object creates an artboard fitted to it (#1252). Rulers: drag the ruler corner to move the zero point, double-click it to reset; the X/Y fields measure from it (#1250). Live Corners: with Direct Selection, a click on a corner widget selects that corner, so the next drag rounds it alone (#1239). A click with the Polar Grid tool opens a dialog for its size and divider counts, as the Rectangular Grid tool does (#1192). A `.ai` whose editing data holds an image on hidden lines is no longer misread (#1364, part of #1264). PDF export leaves out art placed beyond 1,000,000,000 pt instead of aborting debug and test builds (#1360). Affinity import: rectangles keep per-corner radii and straight (cut) corners (#1369, part of #666). Tools panel: the tool buttons are centred inside the panel border, in one and two columns (#1363). Spanish: 371 more interface strings translated (presets, shortcut editor, print and PDF options, Save for Web and more) (#1371). The Properties panel no longer widens and cuts off its labels when an Image Trace object is selected (#1374, part of #1358). Art drawn flush with an artboard (a background a rounding error outside it) moves, copies and scales with the artboard again (#1375, from #1295). A character no installed font had is looked for again after the fonts are rescanned, so installing a font fixes it without a restart (#1376, from #992). A PDF saved with its editing data and a bleed opens on its artboard with the bleed round it, as a `.ai` does (#1379, follow-up to #1349 and #1345). Dialogs opened from a menu focus their first field every time they open, not only the first time, so typing, Tab and Enter work (#1382, fixes #1367); a dialog whose first field is greyed out (Blend Options on Smooth Color, Layers Panel Options) gives the keyboard focus to that field once it is enabled (#1395). In a `.ai` opened from its editing data, a gradient with stops in the middle draws across its whole shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392) (follow-ups to #1264). `--control` without a valid port (or a bad `VECTORCRAFT_CONTROL_PORT`) stops the desktop app with an error instead of starting without a control server, and `--control=` works too (#1383). Documents with many symbol instances or inline graphics redraw faster and use less memory: the art placed for each instance is kept between frames (#1386). PDF and `.ai` import and placed PDFs keep overprint (`/OP`, `/op`), so overprinting spot colours still overprint after export (#1413, fixes #1388). A `.ai` whose PDF part draws only text opens from that part when its editing data can't be read, instead of being refused (#1414, fixes #1387). In a `.ai` opened from its editing data, a compound path takes the paint of its last path, so its gradient no longer comes in black, and paths grouped inside a compound path stay its paths (#1426, fixes #1410). With anchors selected with Direct Selection, the Scale, Rotate, Reflect and Shear tools, their dialogs and Move transform only those anchors (#1427, fixes #1408). The Move, Rotate, Scale, Reflect and Shear dialogs have a live Preview, and the arrow keys step their angles and percentages by 1 (Shift: 10) (#1428, fixes #1412). A stroke wider than its closed shape (a small ellipse or rectangle with a heavy stroke) paints solid on the canvas, as in exports, instead of showing a hole (#1409, fixes #1396). The bounding box hides while a corner radius is dragged with the Selection tool (#1402, fixes #1229). Pasting a picture works when the clipboard also holds a blank text item beside it (#1404). `document.inspect` reports a compound path's fill, stroke and weight and every node's blend mode when it isn't Normal (#1397, fixes #1389); `object.isolate` with an id that doesn't exist says there is no such object (#1415); the MCP guide covers Spacing Guides and four more preferences, all resources, and the symbol, brush, variable and Image Trace commands (#1418). PDF and `.ai` import keep a stroke opaque and unmasked when the fill under it was faded or masked by its group, and a `.ai` read as its PDF part keeps its RGB numbers (#1434). SVG export writes knockout groups of opaque art without masks (smaller files, no edge seams), and `vectorcraft-cli convert` takes `--decimals` (#1435). Delete, Cut, Group, Ungroup, Make and Release Compound Path, Make Clipping Mask, Send to Current Layer, Duplicate and the copying transforms of thousands of objects take a fraction of a second instead of seconds (#1430, part of #1429), and an Alt-drag with the selection and transform tools copies the selection once per drag instead of on every move (#1464, part of #1429). An Affinity text frame too short for its first line (a 64 pt title in a 54 pt frame) is made taller on import, with a note, instead of showing nothing (#1449, fixes #1423). Fit Headline no longer pushes the tracking to its ceiling and loses glyphs when the frame holds one line (#1445, fixes #1444). Text frames, wrap shapes and type paths with coordinates beyond a billion points (from damaged files) hold no text instead of hanging the layout (#1451). Czech: 128 more strings translated (#1461). Plug-ins: a numeric parameter's default stays inside its declared range (#1463). Split Into Grid has the documented options: number, height or width, gutter and total for rows and columns, Add Guides and Preview; several selected paths become one grid painted as the topmost one (#1488, fixes #1462). Grayscale TIFFs with an alpha channel or other extra channels can be placed, relinked and opened, the alpha as the image's transparency (#1489, part of #1466). Selected text in numeric and dialog fields is drawn in white or black instead of blue on the blue highlight (#1490, part of #1465). The Pathfinder panel works on a group selected alone (its members are combined), and a greyed-out button says what it needs (#1493, for #1450). Transform Objects joins Transform Patterns in the Move, Rotate, Scale, Reflect and Shear dialogs and in Transform Each (off: only the pattern tiles transform), and Reflect takes an angle for its axis (#1494, fixes #1448 and #1460). A window larger than 8192 px (several monitors, a display-scale change) keeps its surface instead of closing the app (#1495, part of #1459). Commands run through MCP, the control channel and the CLI refuse a parameter key they don't take, naming it and the nearest accepted key (#1496, fixes #1442). A focused number field follows its value when a slider or preview changes it, so the next key no longer puts the old value back (#1497, fixes #1457). Effect › 3D and Materials: outlined words and other shapes of many small curves take Rotate, Extrude & Bevel and Inflate (curves are sampled by a tolerance; Rotate takes up to 65,536 outline points; #1481), Extrude & Bevel's Twist runs 0° to 360°, as the public panel reference gives it (#1524), and a twisted extrusion keeps its walls (from about 45° they were dropped; #1525). Text commands and the MCP `add_text` tool say when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). A tab stop in the Tabs panel drags from where the press landed, including one just added (#1487, fixes #1458). `graph.setData`'s CSV keeps each value exactly instead of rounding it to two decimals, so applying the returned CSV changes nothing (#1485). In Outline view a template layer keeps drawing in Preview, dimmed, so a picture placed to be traced stays visible (#1505, fixes #1486). Sliders in Save for Web, the raster export options, Preferences and the opacity popup show their rail, filled up to the handle (#1506, fixes #1483). Direct Selection picks the anchor of the selected object where anchors of overlapping objects coincide, also under another object (#1509, fixes #1508). Print-size images (past 512 MB decoded, up to 2 GB) draw in the canvas and in raster exports and can be trimmed with Crop Image; an image whose side is past 65,535 px is shrunk to fit, a raster export says when an image could not be decoded, and Crop Image's trim leaves CMYK images alone (#1517). On Windows, `vectorcraft-cli perf` reports the cores busy and, with `--deep`, its working set, and warns on a busy machine as on macOS and Linux (#1502). French: 423 missing strings added and 188 entries reworded to the feature names French users know (#1511). Hungarian: one message uses the informal address like the rest of the interface (#1474). | | 2026-10-12 | Georgian interface (`ka`, ქართული): the whole catalog, plurals and messages, tested complete; Georgian letters come from an installed font (SF Georgian, Sylfaen, Noto Sans Georgian, DejaVu Sans) from the first frame; Type › Change Case › Title Case and Sentence case leave Georgian lower case instead of turning it into Mtavruli. | | 2026-10-11 | Effect › Brush Strokes: Accented Edges, Angled Strokes, Crosshatch, Dark Strokes, Ink Outlines, Spatter, Sprayed Strokes, Sumi-e (G2). Command parameters from agents and files checked before anything changes (paint, place, cuts, dashes, crop, asset ids, anchors, paths, distort; #984–#999); command dialogs keep whole numbers whole, so Create Object Mosaic takes the tiles typed (#1000); stepper arrows take Shift (×10) and Ctrl/Cmd (÷10) like the arrow keys (#991). Exports and Rasterize supersample Art Optimized edges, so shapes meeting edge to edge leave no seam (#983). Character and paragraph styles take leading, kerning, mojikumi and the other attributes left out at their defaults (#1001). Drawing, typing and pasting with no layer shown and unlocked is refused instead of adding art to a hidden or locked layer (#1002). MCP `add_text` gives type on or in a path the colour asked for (#1003). MCP `screenshot` of a connected app renders the artboard asked for (#1004). `vectorcraft-cli run` ends quietly when its reader closes early (#1005). Select › All on Active Artboard selects on the artboard made active, not always the first (#1006). Reverse Gradient keeps off-centre midpoints, mirrored (#1007). A polar grid with no radial dividers draws none (#1008). Use Precise Cursors also covers the Pen's join pointer (#1009). SVGs with one absolute and one unitless root side import at their size, unstretched (#1010). DXF US survey inches, yards and miles open at their size and name (#1011). A file placed into a document with no other links follows its first change even while the app sits idle (#1031). PDF import keeps the style a font name says when the file doesn't embed the font (#1023). Shift selects ruler guides and art together, and Delete removes both (#1022). Open filled paths are hit by their fill on every side, the rotate cursor bows around the corner it is at, the flip icons match their flips, the Color Picker previews on the selection, and Properties › Transform reaches Scale Corners and Scale Strokes & Effects (#1036). Offset Path and the other booleans finish on outlines where the sweep used to loop until memory ran out (linesweeper 0.5, #1028). Floating panel groups stack into sets that move together, collapse to their tabs and dock as extra dock columns that scroll (#1020). Ruler guides live on layers: listed in the Layers panel, shown, hidden, locked, duplicated, merged and deleted with their layer, and moved between layers (#1021). A `.ai` whose editing data uses global process colours (`Xk`/`XK`) or pattern fills keeps its sublayers: the colours come in as global swatches at their tint, the patterns as pattern swatches (#1025). A `.ai` in PostScript form opens through its layers, read from the program itself, also when it names the prolog defining its operators without including it, as Rhino and other CAD apps write it (#1027). A fill or stroke chosen while the Type tool has characters selected colours just those characters (#1063). Scaled type shows its scaled font size, leading, baseline shift and horizontal scale in the Character panel, and a size typed there is the size you get (#1034). Character panel menu › Proportional Metrics sets Japanese and Chinese full-width glyphs on the font's proportional widths in horizontal type (#966). Align, Distribute, Move, Arrange, Lock, Hide, Ungroup and other Object commands that would change nothing no longer record an undo step or mark the document changed (#1060). Spot colours defined in Lab open with their Lab values from `.ai` and PDF files, instead of as wrong RGB colours or their CMYK equivalents (#1032). Build scripts leave a generated source they wouldn't change untouched, so the next build doesn't compile most of the workspace again where file times lose their sub-second part (#1051). A fill colour recolours the gradient mesh point last clicked with the Mesh tool or Direct Selection, and a Mesh tool click on a mesh's point selects that mesh (#1052). The All Tools drawer stays two tools wide instead of filling a wide window (#1054). Text Wrap's Make, Release and Options refuse a list of object ids with a malformed or unknown id instead of skipping it (#1055). A freeform gradient line with a malformed point index is refused instead of being shortened to the indices that are valid (#1056). The Corners dialog (`ui.corners`) refuses a malformed object id or a listed anchor that isn't a corner instead of editing the selection or the other corners (#1057). New View refuses a centre that isn't exactly [x, y] and a rotation that isn't a number, instead of trimming the one and saving the other as 0° (#1058). The command sweeps try junk scale, spacing and artboard values too, which they had skipped since before those bugs were fixed (#1059). EPS and PostScript `arc` and `arcn` with huge angles no longer hang the import, and an arc whose angles are whole turns apart is empty, as the PostScript reference defines it (#1062). Align and Distribute Spacing keep the key object still also when it is inside a selected group or compound path (#1074). A `.ai` whose layers can't be read yet still opens with its artboards where they were (in a grid, say), not in a row (#1068). Layer Options (`ui.layerOptions`) refuses a malformed or unknown row id instead of skipping it or opening on the highlighted rows (#1077). Shaper scribbles given a list of object ids refuse a malformed or unknown id instead of skipping it and editing the shapes that remain (#1078). Delete Width Point (`stroke.widthPoint.remove`) refuses a list of indices with a malformed entry instead of deleting the points that remain, and no longer wraps a huge index round on the web (#1079). Preferences' checkboxes have an outline when the pointer isn't over them, in every interface brightness, as the app's other dialogs' checkboxes do (#1080). The last plain checkboxes (Properties panel snapping and Scale Strokes & Effects, Revolve, Save options, Export for Screens, Variables, plug-in forms) keep a visible box at rest in every theme too (#885). Setting or copying a width point with a malformed index is refused instead of adding a new point or wrapping a huge index round (follow-up to #1079). An Illustrator EPS opened through its layers keeps its own page size and the red outline of text stacked over a dark one, as 0.8.0 did (#1102). The macOS DMG is built so the app in it passes `codesign --verify --strict --deep`, and the release checks that it does (#1085). Swatch and graphic style libraries, Libraries panel files, presets and plug-ins dropped on the window open as File › Open opens them instead of being placed on the canvas (#1083). A key object needs another selected object outside it: a change that leaves one object selected lets the key go, and one selected object aligns to the artboard whatever Align To says (#1088). Align to Artboard aligns to the active artboard, and actions play their Align to Artboard, All on Active Artboard and Paste in Place, in Front and in Back steps on the artboard active when they play (#1105). Align refuses a call with neither direction, and Align, Distribute, Reflect and Shear refuse a direction, axis, target or bounds they don't take instead of falling back to a default (#1106). `object.setProps` deselects the objects it hides or locks, the key object included, as the Layers panel's eye and lock do (#1107). Align, Distribute and Distribute Spacing move pattern tiles with the art when General › Transform Pattern Tiles is on (#1108). Object › Lock › All Artwork Above and Object › Hide › All Artwork Above deselect the selected objects they lock or hide, the key object included (#1109). Save Swatch Library's `count` is the number of swatches the file holds: `.gpl` and `.ase` hold solid colors only, and CSS leaves freeform gradients out (#1110). In a rotated view (Rotate View), an artboard's name stays at its own top-left corner (#1095). Ctrl+Shift+L, C, R, J and F align or justify the paragraphs of the selected type, or those the Type tool's selection touches (#1111). On macOS, file dialogs are sheets on the document window, so resizing one no longer crashes the app; while one is open the menus, Quit and Close wait, and its answer goes to the document that asked (#867). Shape Builder merges regions that crossing lines cut along the lines' own edges, so a strip merged across a grid of lines is one outline with no seams left inside (#1081). Proportional Metrics also works in vertical type: upright glyphs take the font's proportional heights (`vpal`), and Line-end Punctuation Half Width takes nothing more off the punctuation it re-spaced (#1082). Plug-in whole-number parameters keep their exact value however large, and stay in the range the manifest gives (#1091). PDF and `.ai` import keeps type spaced glyph by glyph (character tightening, optical kerning) with each glyph in its place, giving each character its own tracking when the file's font is installed, and CJK punctuation closed up by its proportional width continues its line (#1101). Direct Selection: pressing an anchor of a path selected whole keeps all its anchors selected, so the drag moves them all; Alt-dragging by an anchor copies the whole path, held by that anchor, which snaps onto other anchors and onto the original the copy leaves behind; Alt pressed or released during the drag turns the copy on and off, as with the Selection tool, whose copies snap to their original too, and the undo step is named Copy or Move for what the drag did (#1104). The toolbar's Fill/Stroke proxy and Color, Gradient and None buttons grow in two columns, where the three drawing modes sit side by side (#1129). An image copied in a browser that puts its `` markup on the clipboard as text pastes as the picture, not the markup (#1089). `file.place` of an SVG with `crop: "crop"` frames and clips it by its viewBox, so art drawn on a shared canvas keeps its place and scale (#788). While a star is dragged, Ctrl/Cmd keeps its inner radius as the outer one grows and Alt keeps its shoulders straight (#812). Edit Toolbar opens the All Tools drawer beside the toolbar, dims the tools already in it, and adds, removes and moves tools by drag and drop while it is open (#1018). The Selection tool's arrow is black and Direct Selection's white in every theme, as users know them: in the dark themes they looked swapped. The font menu keeps its highlight on the same font when the list changes under it (a family's styles listed above it, fonts that finish loading, a favourite unstarred), and ends the live preview when that font leaves the list (#1116). The Windows installer has a Shortcuts page with a ticked "Create a desktop shortcut" box, and a silent install adds the shortcut unless `INSTALLDESKTOPSHORTCUT=""` is passed (#1128). Image Trace's Noise merges specks until none under its size is left beside another colour, so a higher Noise never gives more paths (#1130). `cargo clippy -D warnings` passes for the wasm32 web build (#1132). Gradient stops with opacity blend colour and opacity apart on the canvas, as Illustrator and the PDF and SVG exports do: a transparent stop's colour still tints the fade (#1142). An SVG mask whose art is all hidden imports as an empty opacity mask, so its object stays hidden as browsers draw it (#1143). Shift-click with the Artboard tool, or in the Artboards panel, selects several artboards, which then move, duplicate (Alt-drag) and delete together (#1139). A shape far beyond any page (from a malformed file) is left undrawn instead of making the renderer abort the app. Live Corners round corners where curved segments meet too, trimming each curve to what the cut leaves of it (#1144). Effect › Distort & Transform › Zig Zag's dialog has sliders for Size and Ridges per segment, and Relative / Absolute and Smooth / Corner as radio buttons (#1133). Object › Path › Offset Path opens on the offset, joins and miter limit it was last applied with (#1152). A marquee selects only the objects whose paths it touches: one drawn over a background, in Preview or Outline, no longer selects the background too (#1103). On Linux, Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland on a Wayland session, where files dropped from a file manager arrive (#1151). A selected gradient mesh shows its mesh lines and points with the Selection and Direct Selection tools too, not only with the Mesh tool (#1111). A blend's spine bends: the Anchor Point tool drags any of its segments into a curve, straight ones too, and Direct Selection reshapes its curved segments (`object.blend.spine.reshapeSegment`, #1111). Alt-click on a hidden layer's eye shows that layer as it hides the others, and on a locked layer's lock unlocks it as it locks the others: the layer clicked is the one left in view (#1158). Object › Compound Path › Release splits a path of several subpaths (an SVG `d` with several `M`s, a path drawn in one go over MCP) into one path per subpath, with its paint and stacking order, as it does a compound path (#1163). MCP `render_preview` takes an `artboard` index, so an agent can look at every page of a multi-artboard document (#1163). The MCP drawing tools say that omitted paint follows the new-art appearance (a white fill and 1 pt black stroke at first), and `export` says which formats take `outlineText` (#1148). The desktop app refuses a malformed `--automation-read-root` / `--automation-write-root` (no folder, an empty one, another option or the flag twice) before it starts, instead of dropping the root its environment variable set and leaving the control channel unconfined (#1157). PDF export warns, once per object, when the 64 million pixel cap renders its raster effects below the document's raster effects resolution, with the requested and the achieved ppi (#1147). MCP `command_batch` with `atomic: true` makes the whole batch one undo step, named by `label` (`edit.undoGroup.begin`/`end`, #1163). `file.list {path}` lists a folder's files and folders for agents, held to the automation read root (#1163). Thai typed in a font without Thai glyphs is set in an installed font made for Thai (Leelawadee UI, Tahoma, Thonburi, Sukhumvit Set, Noto Sans Thai…) instead of whichever face with Thai glyphs loaded first, and Lao, Khmer and Myanmar likewise. With the Type tool, the Left and Right arrows and Delete step over whole clusters (a Thai consonant with its vowel and tone marks, a letter with a combining accent, an emoji sequence), so the caret never lands inside one; Backspace still takes back one character at a time, a mistyped tone mark say. Thai, Lao, Khmer and Myanmar area type breaks its lines between words, which those scripts don't separate with spaces, instead of running on to the next space; the words come from ICU4X's line segmenter (its dictionaries on the desktop, its smaller LSTM models on the web). The font menu's script filter has Thai beside Japanese and Latin: the families whose character map has Thai. With craft-fonts' Noto Sans Thai, Thai is set in it where no Thai font is installed, and the web build fetches it before the app starts, so Thai no longer shows as empty boxes there. With the Type tool, Ctrl/Alt+arrows and double-click take Thai, Lao, Khmer and Myanmar text word by word (ภาษา, ไทย…) instead of a whole run without spaces, and a word's vowel and tone marks (and combining accents) stay part of it. Releases embed the current craft-fonts (Noto Sans Thai, Noto Sans Arabic and Noto Sans CJK SC beside the Japanese fonts), as the other craft apps' releases do. Object › Compound Path › Make cuts holes where the paths in front overlap the backmost one, also when they were drawn running the same way (#1197). On Windows, Direct3D 12 shaders compile with FXC, part of Windows, so a dxcompiler.dll another program left on the search path without its dxil.dll no longer loses the graphics device at start-up and drops the app to OpenGL (#1194). With anchor points selected by Direct Selection, the Align buttons align those points (to their own bounds or the artboard) instead of moving the whole path (#1180). With Smart Guides, an object grabbed by an anchor and dropped near another object's anchor lands exactly on it, instead of its bounds lining up a fraction of a point beside it (#955). .ai import: a copied area type or type-on-a-path object now sits where its own art puts it, not on top of the original (#1208). EPS/.ai import: a font is found by its exact PostScript name before the name is split, so families with hyphens keep their name (#1207). EPS/.ai import: type from the text document keeps its line spacing across paragraphs instead of applying the paragraph spacing twice (#1206). Brazilian Portuguese translates the remaining UI labels and engine messages (#1205). Czech joins the complete languages: panels, dialogs, plurals and status and error messages (#1189). Type: Digits (Character panel menu, with the Middle Eastern options) draws every digit in the Default, Arabic, Hindi or Farsi numeral system (#1201). Linux: under Wayland, Automatic draws on the GPU the compositor says it draws with, so a hybrid laptop whose compositor runs on the discrete GPU no longer opens an empty window (#1200). Large documents: editing a big selection takes time linear in the document (a 25,000-path nudge 3.5 s → 48 ms), live geometry effects are kept across frames, Pathfinder Trim, Merge, Crop and Outline are 9–20× faster with identical output, and undo history holds 41% less (#1173). | -| 2026-10-10 | Initial live Revolve (Effect › 3D and Materials, #846, #605), in its own `three-d` crate. Progress docs re-measured and restructured to the craftrules standard (this page, `docs/target-app-parity.md`, `gaps.md`, `ui-parity.md`, the format, hardware, localization, effects and type checklists). Same day: v0.8.0; Effect › Distort, Pixelate and Texture filters (13); German interface; Variables (data merge); Graph Type value axes and tick marks; restart when the first frame never reaches the screen (#964) | +| 2026-10-10 | Initial live Revolve (Effect › 3D and Materials, #846, #605), in its own `three-d` crate. Progress docs re-measured and restructured (this page, `docs/target-app-parity.md`, `gaps.md`, `ui-parity.md`, the format, hardware, localization, effects and type checklists). Same day: v0.8.0; Effect › Distort, Pixelate and Texture filters (13); German interface; Variables (data merge); Graph Type value axes and tick marks; restart when the first frame never reaches the screen (#964) | | 2026-10-09 | Radial Blur, Smart Blur, Unsharp Mask (gap 2 begins); 340 commits, the busiest day | | 2026-10-08 | v0.5.0–v0.7.0; community contributions: Pen and shape-tool modifiers, Layers, Artboards, Japanese composition, Hebrew/Arabic type, interface languages, saved selections | | 2026-10-07 | v0.4.0; issue fixes; Layers panel rework | @@ -192,12 +220,29 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap | 2026-10-01 | Renamed from DrawCraft to VectorCraft | | 2026-09-30 | Repository history begins | -The full pre-standard record of what landed is kept in [docs/roadmap.md](docs/roadmap.md#progress-log-before-the-progress-docs-standard). +The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap.md#earlier-progress-log). ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. | +| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged | +| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. | +| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. | +| 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. | +| 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Sort Objects (#4917); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for the Document Tools add-on's New Symbols from Layers (#4927); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for the Document Tools add-on's Save a Timestamped Copy (#4926); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for Divide into Dashes (Path Precision Tools add-on, #4950); headline numbers unchanged. | +| 2026-11-01 | minor | Progress log row for Group Overlapping Objects (Arrange Tools add-on, #4928); headline numbers unchanged. | +| 2026-10-31 | minor | Progress log row for Export for Screens laid out as the reference app's (#4895) and the 2026-10-31 community landings; headline numbers unchanged. | +| 2026-10-31 | minor | Progress log row for the Arrange Tools add-on; headline numbers unchanged. | +| 2026-10-29 | minor | Progress log row for the Linux Flatpak clipboard's core Wayland protocol text fallback; headline numbers unchanged. | +| 2026-10-29 | minor | Progress log row for the Linux clipboard retry backoff; headline numbers unchanged. | | 2026-10-23 | minor | Progress log row for Pathfinder › Trap; Live vector effects hours 6–10 → 4–8; headline numbers unchanged. | | 2026-10-23 | minor | Progress log row for OpenType SVG colour fonts; headline numbers unchanged. | | 2026-10-23 | minor | Progress log row for COLR colour fonts; headline numbers unchanged. | @@ -217,7 +262,7 @@ The full pre-standard record of what landed is kept in [docs/roadmap.md](docs/ro | 2026-10-13 | minor | Bounded synthetic control input (#1709): counts and queued events validated before mutation; control-channel bursts yield between frames. Scores and hours unchanged. | | 2026-10-14 | minor | Progress log row for the merges of 2026-10-14 (#1641–#1808 as listed there) and Image Trace's #1647 and #1657; the 2026-10-13 row now says that a guide's position in the Transform panel (#1659) is not established by the documentation found and is kept as a convenience pending the owner's decision; headline numbers unchanged. | | 2026-10-13 | minor | Control transport deadlines (#1726): idle and partial clients and blocked replies release connection slots; parity scores and estimates unchanged. | -| 2026-10-10 | minor | Method aligned with the standard, no new evidence: full ready for real work is the additive weighted sum, ~62%; hours per audience; beta ~13 points away | +| 2026-10-10 | minor | Method changed, no new evidence: full ready for real work is the additive weighted sum, ~62%; hours per audience; beta ~13 points away | | 2026-10-10 | minor | Added the essentials-user readiness score (~75%) | | 2026-10-10 | minor | Ready for real work re-examined against the issue tracker and user feedback: 50% → 55% (full), 65% mainstream added; see target-app-parity.md | | 2026-10-10 | minor | Applied the core-workflow gate (docs/roadmap.md › Alpha gate): passes, stage stays alpha | diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index cb9183315f..376f431903 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, features = ["bundled-fonts"] } +vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] } vectorcraft-format = { workspace = true } vectorcraft-geom = { workspace = true } vectorcraft-svg = { workspace = true } @@ -34,8 +34,9 @@ winsafe = { version = "0.0.29", default-features = false, features = ["kernel", # DirectWrite's system font collection and GDI's font list (the desktop app's src/system_fonts.rs, # shared): fonts that font services such as Adobe Fonts load in place (#579, #1258). MIT OR -# Apache-2.0. -windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi"] } +# Apache-2.0. Win32_System_Threading has `GetProcessAffinityMask`, which the desktop app's +# src/windows_cores.rs, shared, uses to count the cores the process may run on. +windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading"] } # CoreText's font manager (the desktop app's src/mac_fonts.rs, shared): fonts that apps and font # managers register from their own folders (#579). Zlib OR Apache-2.0 OR MIT. @@ -44,5 +45,6 @@ objc2-core-foundation = { version = "0.3", default-features = false, features = objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFontManager"] } [dev-dependencies] +tempfile = "3" vectorcraft-testkit = { workspace = true } serde_json = { workspace = true } diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index bba1976c1d..8fc2661dc1 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -1,10 +1,11 @@ //! `vectorcraft-cli`: VectorCraft from the command line. //! //! ```text +//! vectorcraft-cli --safe-mode SUBCOMMAND ... //! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... -//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] +//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] //! vectorcraft-cli commands -//! 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 convert IN OUT [--scale 2] [--ppi 300] [--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] @@ -49,6 +50,10 @@ mod prefs_dir; #[cfg(windows)] #[path = "../../vectorcraft/src/system_fonts.rs"] mod system_fonts; +/// The desktop app's affinity-mask reader, shared: renders start workers only for usable cores. +#[cfg(windows)] +#[path = "../../vectorcraft/src/windows_cores.rs"] +mod windows_cores; use serde_json::{Value, json}; use vectorcraft_engine::file_access::{self, AutomationRoots}; @@ -68,6 +73,11 @@ const USAGE: &str = "\ vectorcraft-cli — VectorCraft automation USAGE: + vectorcraft-cli --safe-mode SUBCOMMAND ... + Run any subcommand without plug-ins: none loads or runs, and plug-in commands report that + Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and + does not take --connect. + vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979 (vectorcraft --control 7979), falling back to a headless in-process session. @@ -77,11 +87,12 @@ USAGE: 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] | --commands FILE|-]... [--export FILE]... [--scale N] + vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi 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. + is a template, written as file.saveAsTemplate writes it). Raster exports use the document's + raster effects resolution unless --scale (pixels per point) or --ppi (pixels per inch, wins + over --scale) is given; other formats leave them 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. @@ -90,10 +101,10 @@ USAGE: 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] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] + vectorcraft-cli convert IN OUT [--scale N] [--ppi 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 + formats). Raster resolution: --ppi, else 72 times --scale, else the document's raster effects + resolution; other formats leave them out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard unless one of them is given, EPS the bounds of the art, the other formats the first artboard. A .ait OUT is a template of every artboard, written as file.saveAsTemplate writes it (not with --artboard or --range). @@ -123,12 +134,17 @@ USAGE: Render FILE (any readable format) fitted to WxH (default 2880x1800) and print ms per frame (warm), multithreaded and single-threaded. - vectorcraft-cli perf [--paths N] [--deep] + vectorcraft-cli perf [--paths N] [--deep] [--native-io [--artboards 1..4]] Check the performance budgets (render, pan, hit test, save/load, SVG, Pathfinder, handle and segment drags) on a synthetic N-path document (default 50000). Exits non-zero if a budget is exceeded, unless the report says the machine is busy. --deep also times work with no budget yet and prints memory use (the working set on Windows), with the peak so far on Windows and Linux. + --native-io instead measures the application's native save/open commands (one warmup, + five samples, no disk I/O), including preview, PDF, compression and API base64 costs. + It reports the default and explicit PDF opt-out, with and without preview/compression; + --artboards repeats the same artwork + on 1 to 4 overlapping artboards. This mode allows at most 50000 paths. "; /// The usage text plus the formats `document.open` reads and `document.export` writes. @@ -161,18 +177,27 @@ fn help() -> Result<(), String> { } fn main() -> ExitCode { + // Before the first render: the cores the process may run on. + #[cfg(windows)] + windows_cores::install(); // Before any font lookup: the fonts font services load (#579). #[cfg(windows)] system_fonts::install(); #[cfg(target_os = "macos")] mac_fonts::install(); prefs_dir::install_fonts(); - let args: Vec = std::env::args().skip(1).collect(); + let mut args: Vec = std::env::args().skip(1).collect(); + // Before any subcommand attaches the plug-in folder. + let safe_mode = args.first().is_some_and(|a| a == "--safe-mode"); + if safe_mode { + args.remove(0); + vectorcraft_engine::cmd::plugin::start_in_safe_mode(); + } let r = match args.first().map(String::as_str) { // `commands` and `info` take no options, so `--help` or `-h` anywhere after them prints the // usage. The other subcommands check for it themselves. Some("commands" | "info") if help_requested(&args[1..], &[]) => help(), - Some("mcp") => mcp(&args[1..]), + Some("mcp") => mcp(&args[1..], safe_mode), Some("run") => run(&args[1..]), Some("commands") => commands(), Some("convert") => convert(&args[1..]), @@ -205,7 +230,9 @@ fn with_stores(mut h: Headless) -> Headless { h } -fn mcp(args: &[String]) -> Result<(), String> { +/// `mcp`. With `--safe-mode` (`safe_mode`) it serves a headless session: a running app loads its own +/// plug-ins, so `--connect` is refused and the default does not connect. +fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> { if help_requested(args, &["--connect", "--automation-read-root", "--automation-write-root"]) { return help(); } @@ -232,6 +259,9 @@ fn mcp(args: &[String]) -> Result<(), String> { if headless && connect.is_some() { return Err("use either --connect or --headless".into()); } + if safe_mode && connect.is_some() { + return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control `".into()); + } let read: Vec<&Path> = read_roots.iter().map(Path::new).collect(); let write: Vec<&Path> = write_roots.iter().map(Path::new).collect(); let roots = AutomationRoots::new(&read, &write)?; @@ -244,7 +274,7 @@ fn mcp(args: &[String]) -> Result<(), String> { file_access::confine_process(roots.clone()); eprintln!("vectorcraft-cli: files confined: {}", roots.describe()); Box::new(Headless::with_document().with_automation_roots(Some(roots))) - } else if headless { + } else if headless || safe_mode { Box::new(with_stores(Headless::with_document())) } else if let Some(addr) = connect { // Explicit address: fail loudly if the app isn't there. @@ -272,13 +302,15 @@ 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"]; + let valued = + ["--scale", "-s", "--ppi", "--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, mut preserve_editing) = - (1.0f64, None::, None::, false, false, false, false); + (None::, None::, None::, false, false, false, false); + let mut ppi = None::; let mut decimals = None::; // Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`, // `transparentImages`); the engine checks their values. @@ -286,7 +318,15 @@ fn convert(args: &[String]) -> Result<(), String> { let mut it = args.iter(); while let Some(a) = it.next() { match a.as_str() { - "--scale" | "-s" => scale = it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?, + "--scale" | "-s" => scale = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?), + "--ppi" => { + ppi = Some( + it.next() + .and_then(|v| v.parse().ok()) + .filter(|n: &f64| n.is_finite() && *n > 0.0) + .ok_or("--ppi needs a positive finite number")?, + ); + } "--artboard" | "-a" => artboard = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--artboard needs an index")?), "--range" | "-r" => range = Some(it.next().cloned().ok_or("--range needs artboards such as 1-3,5")?), "--outline-text" => outline_text = true, @@ -319,7 +359,7 @@ fn convert(args: &[String]) -> Result<(), String> { // A conversion keeps hidden layers and objects, written hidden, where the format can (SVG, // PSD). let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy}); - let mut params = with_pixel_scale(params, &output, scale); + let mut params = with_pixel_scale(params, &output, scale, ppi); if let Some(decimals) = decimals { params["decimals"] = json!(decimals); } @@ -365,12 +405,17 @@ fn is_template(path: &str) -> bool { vectorcraft_engine::cmd::fileio::format_for_name(path).is_some_and(|f| f.id == "ait") } -/// The export `params` for `path`, with `--scale` (pixels per point) when its format is raster. +/// The export `params` for `path`, with explicit raster resolution options only for raster formats. /// DXF has a `scale` of its own (drawing units per unit), which would resize the drawing and leave /// its units unset. -fn with_pixel_scale(mut params: Value, path: &str, scale: f64) -> Value { +fn with_pixel_scale(mut params: Value, path: &str, scale: Option, ppi: Option) -> Value { if vectorcraft_engine::cmd::fileio::writable_format(None, Some(path)).is_ok_and(|f| f.raster) { - params["scale"] = json!(scale); + if let Some(scale) = scale { + params["scale"] = json!(scale); + } + if let Some(ppi) = ppi { + params["ppi"] = json!(ppi); + } } params } @@ -478,7 +523,7 @@ fn command_step(v: Value) -> Result { } fn run(args: &[String]) -> Result<(), String> { - let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s"]; + let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s", "--ppi"]; if help_requested(args, &valued) { return help(); } @@ -487,7 +532,8 @@ fn run(args: &[String]) -> Result<(), String> { // 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 scale = None::; + let mut ppi = None::; 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}")); @@ -524,7 +570,16 @@ fn run(args: &[String]) -> Result<(), String> { } "--scale" | "-s" => { let raw = val("a number")?; - scale = raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?; + scale = Some(raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?); + } + "--ppi" => { + let raw = val("a number")?; + ppi = Some( + raw.parse::() + .ok() + .filter(|n| n.is_finite() && *n > 0.0) + .ok_or_else(|| format!("--ppi {raw}: needs a positive finite number"))?, + ); } other => return Err(format!("unknown run option `{other}`")), } @@ -569,7 +624,7 @@ fn run(args: &[String]) -> Result<(), String> { let r = if is_template(&path) { h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": path, "format": "ait"}})) } else { - h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale)) + h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale, ppi)) }; let r = r.map_err(|e| format!("step {n}: export {path}: {e}"))?; emit(json!({"step": "export", "result": r}))?; diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs index 8fe3d23b74..e533d00b73 100644 --- a/apps/vectorcraft-cli/src/perf.rs +++ b/apps/vectorcraft-cli/src/perf.rs @@ -64,6 +64,61 @@ fn median_ms(runs: usize, mut f: impl FnMut()) -> f64 { v.get(v.len() / 2).copied().unwrap_or(0.0) } +/// Exercise the application's native save/open commands, including previews, PDF output, +/// compression and API base64 conversion. Session setup and validation are outside timing. +/// Five measured runs follow one warmup; no filesystem or GPU window is involved. +fn native_io(doc: &Document) -> Result<(), String> { + for (label, compatible, preview) in [ + ("default options", None, false), + ("PDF disabled", Some(false), false), + ("preview+gzip", None, true), + ("preview+gzip, PDF disabled", Some(false), true), + ] { + let mut session = vectorcraft_engine::Session::new(); + session.add_document(doc.clone(), None); + let mut params = json!({"format":"vectorcraft","modified":null,"preview":preview,"compress":preview}); + if let Some(value) = compatible { + params["pdfCompatible"] = json!(value); + } + let (mut saves, mut opens) = (Vec::new(), Vec::new()); + let (mut size, mut has_pdf, mut compressed) = (0, false, false); + for run in 0..6 { + let start = Instant::now(); + let saved = session.execute("file.saveAs", ¶ms).map_err(|e| e.to_string())?; + let save_ms = start.elapsed().as_secs_f64() * 1000.0; + let data = saved["dataBase64"].as_str().ok_or("native save returned no dataBase64")?; + let bytes = vectorcraft_format::base64_decode(data).ok_or("native save returned invalid base64")?; + size = bytes.len(); + has_pdf = vectorcraft_format::pdf_content(&bytes).is_some(); + if compatible == Some(false) && has_pdf { + return Err("native save ignored the explicit PDF opt-out".into()); + } + compressed = vectorcraft_format::is_compressed(&bytes); + if compressed != preview || vectorcraft_format::preview(&bytes).is_some() != preview { + return Err("native save did not apply the requested preview/compression options".into()); + } + let args = json!({"name":"perf.vectorcraft","dataBase64":data}); + let mut opened = vectorcraft_engine::Session::new(); + let start = Instant::now(); + opened.execute("document.open", &args).map_err(|e| e.to_string())?; + let open_ms = start.elapsed().as_secs_f64() * 1000.0; + if opened.doc().map_err(|e| e.to_string())?.doc.artboards.len() != doc.artboards.len() { + return Err("native round trip changed the artboard count".into()); + } + if run > 0 { + saves.push(save_ms); + opens.push(open_ms); + } + } + saves.sort_by(f64::total_cmp); + opens.sort_by(f64::total_cmp); + let save = saves.get(2).copied().ok_or("no save measurements")?; + let open = opens.get(2).copied().ok_or("no open measurements")?; + outln!(" native {label}: save {save:.2} ms, open {open:.2} ms, {size} bytes, PDF {has_pdf}, compressed {compressed}"); + } + Ok(()) +} + /// 1-minute load average (macOS / Linux), if available. #[cfg(not(windows))] fn load_average() -> Option { @@ -116,7 +171,8 @@ fn edit_drags(n: usize) -> Result<(f64, f64), String> { let view = vectorcraft_engine::ViewInfo { zoom: 8.0, ..Default::default() }; let err = |e: vectorcraft_engine::EngineError| e.to_string(); let mut drag = |down: Point| -> Result { - let ev = |kind, y: f64| PointerEvent { kind, pos: down + Vec2::new(0.0, y), mods: Mods::default(), pressure: 1.0 }; + let ev = + |kind, y: f64| PointerEvent { kind, pos: down + Vec2::new(0.0, y), mods: Mods::default(), backquote: false, pressure: 1.0, pen: None }; s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 400]]})).map_err(err)?; s.select_tool("directSelection", view).map_err(err)?; let undo = s.doc().map_err(err)?.history.undo.len(); @@ -186,6 +242,48 @@ fn budget_row(name: &str, ms: f64, budget: f64, ok: bool) -> String { format!(" {name:<42} {ms:>8.2} ms {budget:>7.0} ms {}", if ok { "ok" } else { "OVER" }) } +/// Tracked rows for pointing at things in an n-path document: what hovering, clicking, marquee +/// selection and snapping cost when nothing narrows the search. +fn pointing(n: usize, rows: &mut Vec<(String, f64)>) -> Result<(), String> { + use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind}; + let err = |e: vectorcraft_engine::EngineError| e.to_string(); + let mut s = vectorcraft_engine::Session::new(); + s.add_document(synthetic(n)?, None); + let view = vectorcraft_engine::ViewInfo { zoom: 1.0, ..Default::default() }; + s.select_tool("selection", view).map_err(err)?; + // Off the art (nothing under the pointer), the case every hover over empty canvas pays. + let off = Point::new(-200.0, -200.0); + let hover = |s: &mut vectorcraft_engine::Session| { + let _ = s.pointer(&PointerEvent::new(PointerKind::Move, off.x, off.y), view); + let _ = s.cursor(off, Mods::default(), view); + }; + rows.push((format!("hover over empty canvas ({n} paths)"), median_ms(5, || hover(&mut s)))); + s.execute("select.all", &json!({})).map_err(err)?; + rows.push((format!("hover over empty canvas, all selected ({n} paths)"), median_ms(5, || hover(&mut s)))); + let doc = s.doc().map_err(err)?.doc.clone(); + rows.push((format!("hit test, a miss ({n} paths)"), median_ms(5, || drop(hit::hit_test(&doc, off, hit::HitOptions::default()))))); + let r = Rect::new(600.0, 450.0, 1000.0, 750.0); + rows.push((format!("marquee 400×300 ({n} paths)"), median_ms(5, || drop(hit::marquee(&doc, r, None, false))))); + let view_rect = Rect::new(0.0, 0.0, 1600.0, 1200.0); + rows.push(( + format!("smart guide targets in view ({n} paths)"), + median_ms(5, || drop(vectorcraft_engine::tools::guides::Targets::collect(&doc, &[], Some(view_rect)))), + )); + // Adding one more object to a selection of half the document: the command a shift-click ends + // in, without the pointer handling and hit test before it. + let ids: Vec = doc.layers[0].children().map(|c| c.iter().map(|n| n.id.0).collect()).unwrap_or_default(); + s.execute("select.set", &json!({"ids": ids[..ids.len() / 2]})).map_err(err)?; + let mut k = ids.len() / 2; + rows.push(( + format!("select.toggle in a {}-object selection", ids.len() / 2), + median_ms(5, || { + k += 1; + let _ = s.execute("select.toggle", &json!({"id": ids[k % ids.len()]})); + }), + )); + Ok(()) +} + /// `--deep`: tracked rows (no budget yet) for work the budgets above don't reach: editing a whole /// selection, live effects, every Pathfinder operation, typing in a long story, and memory, with /// the peak so far where `rss_mb` reads one. @@ -215,7 +313,14 @@ fn deep(n: usize) -> Result<(), String> { let first = s.doc().map_err(err)?.selection.objects.first().copied(); let at = first.and_then(|id| s.doc().ok()?.doc.node(id)?.geometric_bounds()).map(|b| b.center()); if let Some(down) = at { - let ev = |kind, dx: f64| PointerEvent { kind, pos: down + Vec2::new(dx, 0.0), mods: Mods::default(), pressure: 1.0 }; + let ev = |kind, dx: f64| PointerEvent { + kind, + pos: down + Vec2::new(dx, 0.0), + mods: Mods::default(), + backquote: false, + pressure: 1.0, + pen: None, + }; s.select_tool("selection", view).map_err(err)?; s.pointer(&ev(PointerKind::Down, 0.0), view).map_err(err)?; let mut dx = 0.0; @@ -274,6 +379,8 @@ fn deep(n: usize) -> Result<(), String> { }), )); note("after typing"); + pointing(n, &mut rows)?; + note("after pointing"); // Four embedded 24 MP photos drawn at fit page by three renderers, as the app's canvas, render // worker and a panel each draw them. { @@ -341,19 +448,36 @@ fn deep(n: usize) -> Result<(), String> { } pub fn run(args: &[String]) -> Result<(), String> { - if crate::help_requested(args, &["--paths"]) { + if crate::help_requested(args, &["--paths", "--artboards"]) { return crate::help(); } let mut n = 50_000usize; let mut want_deep = false; + let mut want_native = false; + let mut artboards = None::; let mut it = args.iter(); while let Some(a) = it.next() { match a.as_str() { "--deep" => want_deep = true, + "--native-io" => want_native = true, + "--artboards" => { + artboards = + Some(it.next().and_then(|v| v.parse().ok()).filter(|n| (1..=4).contains(n)).ok_or("--artboards needs a number from 1 to 4")?) + } "--paths" => n = it.next().and_then(|v| v.parse().ok()).ok_or("--paths needs a number")?, other => return Err(format!("unknown perf option `{other}`")), } } + if want_native && n > 50_000 { + return Err("--native-io allows at most 50000 paths".into()); + } + if want_native && want_deep { + return Err("--native-io and --deep are separate measurement modes".into()); + } + if artboards.is_some() && !want_native { + return Err("--artboards requires --native-io".into()); + } + let artboards = artboards.unwrap_or(1); let cores = std::thread::available_parallelism().map_or(1, |c| c.get()); // The figure is the 1-minute load average, or on Windows the cores busy over one second. #[cfg(not(windows))] @@ -366,8 +490,20 @@ pub fn run(args: &[String]) -> Result<(), String> { outln!("WARNING: the machine is busy; wall-clock timings below are not trustworthy."); } let t = Instant::now(); - let doc = synthetic(n)?; + let mut doc = synthetic(n)?; outln!(" (built in {:.0} ms)", t.elapsed().as_secs_f64() * 1000.0); + if want_native { + let first = doc.artboards.first().cloned().ok_or("synthetic document has no artboard")?; + // Overlapping artboards intentionally repeat the same paths on every PDF page. + for index in 1..artboards { + let mut page = first.clone(); + page.id = first.id.checked_add(index as u32).ok_or("artboard id overflow")?; + page.name = format!("Perf {}", index + 1); + doc.artboards.push(page); + } + outln!(" application native I/O: {artboards} overlapping artboard(s), one warmup + five samples; medians; no disk I/O"); + return native_io(&doc); + } let mut rows: Vec<(&str, f64, f64)> = vec![]; let opts = RenderOptions::default(); @@ -461,6 +597,24 @@ pub fn run(args: &[String]) -> Result<(), String> { mod tests { use super::*; + #[test] + fn native_io_exercises_the_application_save_and_open_commands() { + native_io(&synthetic(3).unwrap()).unwrap(); + } + + #[test] + fn native_io_rejects_conflicting_modes_and_excessive_workloads() { + for (args, expected) in [ + (vec!["--native-io", "--deep"], "separate measurement modes"), + (vec!["--native-io", "--paths", "50001"], "at most 50000"), + (vec!["--native-io", "--artboards", "5"], "1 to 4"), + (vec!["--artboards", "1"], "requires --native-io"), + (vec!["--artboards", "2"], "requires --native-io"), + ] { + assert!(run(&args.into_iter().map(str::to_owned).collect::>()).unwrap_err().contains(expected)); + } + } + #[test] fn busy_share_leaves_out_idle_time() { // In one second four processors log 40,000,000 ticks of 100 ns of kernel and user time, diff --git a/apps/vectorcraft-cli/tests/it/cli.rs b/apps/vectorcraft-cli/tests/it/cli.rs index 9caf4bc92f..05a5cc5fc6 100644 --- a/apps/vectorcraft-cli/tests/it/cli.rs +++ b/apps/vectorcraft-cli/tests/it/cli.rs @@ -283,6 +283,22 @@ fn mcp_headless_over_stdio() { assert_eq!(replies[3]["result"]["content"][0]["type"], "image"); } +/// `--safe-mode mcp` serves a headless session without plug-ins: it refuses `--connect`, and by +/// default it does not connect to an app listening on the default address, which loads its own +/// plug-ins. +#[test] +fn safe_mode_mcp_does_not_connect_to_a_running_app() { + let out = Command::new(BIN).args(["--safe-mode", "mcp", "--connect", "127.0.0.1:9"]).env("VECTORCRAFT_NO_PREFS", "1").output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success() && err.contains("--safe-mode runs a headless session"), "{err}"); + // Something listening on the default address, as a running app does; a running app or another + // program already holding it serves as well. + let _app = std::net::TcpListener::bind(vectorcraft_mcp::DEFAULT_ADDR); + let out = Command::new(BIN).args(["--safe-mode", "mcp"]).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success() && err.contains("MCP server on stdio (headless)"), "{err}"); +} + /// `mcp --automation-read-root` / `--automation-write-root` (#832): the flags are checked before the /// server starts, and the process then reads and writes only inside its roots. #[test] diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index 1423b78b42..c60357b5f8 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -105,6 +105,38 @@ fn images_open_at_their_pixel_size() { assert_eq!(&std::fs::read(&png).unwrap()[16..24], [0, 0, 0, 6, 0, 0, 0, 4], "IHDR 6×4"); } +#[test] +fn raster_exports_use_document_resolution_unless_overridden() { + let source = tmp("resolution.vectorcraft"); + ok(&["run", "--cmd", "file.new", "--params", r#"{"width":72,"height":36,"rasterEffectsPpi":300}"#, "--export", &source]); + for (flags, width, height) in [(vec![], 300u32, 150u32), (vec!["--scale", "1"], 72, 36), (vec!["--ppi", "150", "--scale", "2"], 150, 75)] { + for mode in ["run", "convert"] { + for format in ["png", "psd"] { + let path = tmp(&format!("resolution-{mode}-{width}.{format}")); + let mut args = if mode == "run" { vec!["run", "--in", &source, "--export", &path] } else { vec!["convert", &source, &path] }; + args.extend_from_slice(&flags); + ok(&args); + let bytes = std::fs::read(&path).unwrap(); + let dimensions = if format == "png" { &bytes[16..24] } else { &bytes[14..22] }; + let expected = + if format == "png" { [width.to_be_bytes(), height.to_be_bytes()] } else { [height.to_be_bytes(), width.to_be_bytes()] }; + assert_eq!(dimensions, expected.concat(), "{args:?}"); + } + } + } +} + +#[test] +fn raster_export_rejects_invalid_ppi() { + for ppi in ["0", "-150", "NaN", "inf", "high"] { + for args in [vec!["run", "--export", "unused.png", "--ppi", ppi], vec!["convert", "unused.svg", "unused.png", "--ppi", ppi]] { + let out = Command::new(BIN).args(&args).output().unwrap(); + assert!(!out.status.success(), "{args:?}"); + assert!(String::from_utf8_lossy(&out.stderr).contains("positive finite number"), "{args:?}: {out:?}"); + } + } +} + #[test] fn help_lists_readable_formats() { let out = ok(&["--help"]); diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 8decb13d85..6e4dbd7f00 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -14,8 +14,10 @@ name = "vectorcraft-web" path = "src/main.rs" [dependencies] -vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] } +vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] } vectorcraft-ui-egui = { workspace = true } +# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } vectorcraft-format = { workspace = true } vectorcraft-text = { workspace = true } egui = { workspace = true } diff --git a/apps/vectorcraft-web/index.html b/apps/vectorcraft-web/index.html index 42eaaf74e0..2ccfc271b0 100644 --- a/apps/vectorcraft-web/index.html +++ b/apps/vectorcraft-web/index.html @@ -9,6 +9,13 @@ VectorCraft + + + + + + + ", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + ] { + let doc = roxmltree::Document::parse(styled).unwrap(); + assert_eq!(filters_of(&doc, styled, usize::MAX, |_| false), (vec![], 1), "{styled}"); + } + // A style sheet for the shapes alone (as CSS export writes), applying the filter to them + // included, doesn't reach the filter. + for shapes in [ + "", + "", + // An identifier named currentColor takes no color. + "", + ] { + let doc = roxmltree::Document::parse(shapes).unwrap(); + assert_eq!(filters_of(&doc, shapes, usize::MAX, |_| false).0.len(), 1, "{shapes}"); + } +} + +#[test] +fn deeply_nested_filters_are_refused_before_they_are_parsed() { + let deep = format!("{}{}", "".repeat(20), "".repeat(20)); + assert!(check(&deep).is_err_and(|e| e.contains("nest at most 16 deep"))); + assert_eq!(with_id(&deep, "b"), None); + let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": deep }), visible: true }; + assert!(raster_effects(&[e]).is_empty(), "drawn without it"); + // Markup in comments, CDATA and attribute values doesn't count. + let quoted = + format!("", "<g>".repeat(20), "".repeat(20), "".repeat(20)); + assert_eq!(check("ed), Ok("a".into())); + let gt = format!("{}", "x>".repeat(20), "".repeat(3)); + assert_eq!(check(>), Ok("a".into())); +} + +#[test] +fn a_filter_replaces_the_pixels_with_its_result() { + let w = 20; + let mut data = blue_square(w, 5); + filter(json!({ "xml": RED_FLOOD })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0)); + assert_eq!(at(&data, w, 10, 10), [255, 0, 0, 255], "inside: the flood, cut to the source"); + assert_eq!(at(&data, w, 1, 1), [0; 4], "outside the source"); +} + +#[test] +fn lengths_are_in_points_times_scale() { + let w = 40; + let shift = r#""#; + let run = |px: f64, scale: f64| { + let n = (w as f64 / px) as usize; + let mut data = image(n, n, |x, y| { + let (x, y) = (x as f64 * px, y as f64 * px); + if (10.0..20.0).contains(&x) && (10.0..20.0).contains(&y) { [0, 0, 255, 255] } else { [0; 4] } + }); + filter(json!({ "xml": shift, "scale": scale })).apply(&mut data, n, n, &space(n, n, px, px)); + let column = |x: f64| at(&data, n, (x / px) as usize, (15.0 / px) as usize)[3]; + (column(9.5), column(21.0), column(23.5), column(25.0)) + }; + // The square spans 10..20 pt: moved by 4 pt, 14..24. + assert_eq!(run(1.0, 1.0), (0, 255, 255, 0)); + assert_eq!(run(0.5, 1.0), (0, 255, 255, 0), "the same in points at another zoom"); + // One unit of the filter is half a point: moved by 2 pt, 12..22. + assert_eq!(run(1.0, 0.5), (0, 255, 0, 0)); +} + +/// A user-space region is placed from the effect's origin. +#[test] +fn user_space_starts_at_the_origin() { + let w = 40; + // Flood the square, cut to the region x 0..20 of the filter's user space. + let half = r##""##; + let run = |origin: [f64; 2]| { + let mut data = image(w, w, |_, _| [0, 0, 255, 255]); + filter(json!({ "xml": half, "origin": origin })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0)); + (at(&data, w, 5, 20)[3], at(&data, w, 25, 20)[3]) + }; + assert_eq!(run([0.0, 0.0]), (255, 0)); + assert_eq!(run([20.0, 0.0]), (0, 255), "the region 20 pt to the right"); + let b = Rect::new(0.0, 0.0, 40.0, 40.0); + assert!((filter(json!({ "xml": half, "origin": [-10.0, 0.0] })).outset(b) - 10.0).abs() < 1e-9); +} + +#[test] +fn runs_no_finer_than_the_raster_effects_resolution() { + let w = 16; + // Columns one view pixel wide, alternately opaque and clear. + let stripes = image(w, w, |x, _| if x % 2 == 0 { [0, 0, 255, 255] } else { [0; 4] }); + let keep = r#""#; + let mut fine = stripes.clone(); + filter(json!({ "xml": keep })).apply(&mut fine, w, w, &space(w, w, 0.25, 0.25)); + assert_eq!(at(&fine, w, 4, 4)[3], 255); + assert_eq!(at(&fine, w, 5, 4)[3], 0, "at the view's resolution the stripes stay"); + let mut coarse = stripes.clone(); + filter(json!({ "xml": keep })).apply(&mut coarse, w, w, &space(w, w, 0.25, 1.0)); + let (a, b) = (at(&coarse, w, 4, 4)[3], at(&coarse, w, 5, 4)[3]); + assert!(a < 255 && b > 0, "four view pixels to a raster pixel: the stripes blend ({a}, {b})"); +} + +#[test] +fn draws_nothing_new_without_content_or_a_readable_filter() { + let w = 8; + let mut empty = vec![0; w * w * 4]; + filter(json!({ "xml": RED_FLOOD })).apply(&mut empty, w, w, &space(w, w, 1.0, 1.0)); + assert!(empty.iter().all(|v| *v == 0), "a flood cut to a source that draws nothing"); + // A filter that doesn't read the source draws on art that draws no pixels: the raster is its box. + let mut clear = vec![0; w * w * 4]; + filter(json!({ "xml": "" })).apply(&mut clear, w, w, &space(w, w, 1.0, 1.0)); + assert_eq!(at(&clear, w, 4, 4), [0, 255, 0, 255]); + let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": "" }), visible: true }; + assert!(raster_effects(&[e]).is_empty(), "not a filter: the object is drawn without it"); + let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": "" }), visible: true }; + assert!(raster_effects(&[e]).is_empty(), "a filter resvg can't draw: the object is drawn without it"); +} + +#[test] +fn outset_is_how_far_the_region_reaches() { + let b = Rect::new(0.0, 0.0, 100.0, 50.0); + assert!((filter(json!({ "xml": RED_FLOOD })).outset(b) - 10.0).abs() < 1e-9, "the default region: 10% of the width"); + let wide = r#""#; + assert!((filter(json!({ "xml": wide })).outset(b) - 50.0).abs() < 1e-9); + let user = r#""#; + assert!((filter(json!({ "xml": user, "scale": 2.0 })).outset(b) - 20.0).abs() < 1e-9, "user units times scale"); + let inside = r#""#; + assert_eq!(filter(json!({ "xml": inside })).outset(b), 0.0); + // User-space lengths in points: -30 pt is -40 user units. + let points = r#""#; + assert!((filter(json!({ "xml": points })).outset(b) - 40.0).abs() < 1e-9); + // In user space, a percentage is a share of the object's box; em, ex and a missing length + // take the default region's share of it. + let viewport = r#""#; + assert!((filter(json!({ "xml": viewport })).outset(b) - 50.0).abs() < 1e-9); + let far = r#""#; + assert!((filter(json!({ "xml": far })).outset(b) - 1900.0).abs() < 1e-9, "however far it reaches"); + let font = r#""#; + assert!((filter(json!({ "xml": font })).outset(b) - 10.0).abs() < 1e-9, "relative to the font"); + let default = r#""#; + assert!((filter(json!({ "xml": default })).outset(b) - 10.0).abs() < 1e-9); + // In the bounding box, a length with a unit is invalid: the default. + let unit = r#""#; + assert!((filter(json!({ "xml": unit })).outset(b) - 10.0).abs() < 1e-9); +} + +#[test] +fn a_filter_keeps_the_prefixes_an_ancestor_declares() { + let svg = r#""#; + let (found, skipped) = filters_in(svg); + assert_eq!((found.len(), skipped), (1, 0)); + assert_eq!( + found[0].1, r#""#, + "only the prefix it uses" + ); + // A declaration on the filter itself, with spaces around its `=`, is kept as it is. + let own = r#""#; + let (found, skipped) = filters_in(own); + assert_eq!((found.len(), skipped), (1, 0)); + assert_eq!(found[0].1, r#""#); + // The same declaration again on the filter, and text like one inside an attribute's value. + let again = r#""#; + let (found, skipped) = filters_in(again); + assert_eq!((found.len(), skipped), (2, 0), "{found:?}"); + assert!(found[1].1.starts_with(r#""#).unwrap(); + let b = primitive_forms(r#""#).unwrap(); + assert_eq!(a.len(), 1); + assert_ne!(a, b); + assert_eq!(primitive_forms(r#""#), Some(a), "the id doesn't count"); +} + +#[test] +fn costly_parameters_are_capped() { + for (xml, why) in [ + ("", "radius is at most 100"), + ("", "radius is at most 100"), + ("", "radius is at most 100"), + ("", "stdDeviation is at most 500"), + ("", "stdDeviation is at most 500"), + ( + "", + "kernelUnitLength is at most 100", + ), + ] { + let e = check(xml).expect_err(xml); + assert!(e.contains(why), "{xml}: {e}"); + } + assert_eq!(check(""), Ok("a".into())); + // usvg also reads attributes in the SVG, XLink and XML namespaces by their local names. + for prefixed in [ + "", + "", + ] { + assert!(check(prefixed).is_err(), "{prefixed}"); + } +} + +/// A filter is drawn and written rebuilt from its filter elements and their filter attributes: +/// no comments, text, descriptions, other attributes or prefixes. +#[test] +fn the_filter_is_drawn_and_written_from_its_filter_parts_alone() { + let xml = concat!( + "<script>T", + "", + "", + ); + let f = filter(json!({ "xml": xml })); + assert_eq!( + f.xml(), + "" + ); + // An image keeps how it is scaled, as a style declaration. + for image in [ + "", + "", + ] { + assert_eq!( + filter(json!({ "xml": image })).xml(), + "", + "{image}" + ); + } + // `currentColor` keeps the color it names. + let colored = filter(json!({ "xml": "" })); + assert_eq!(colored.xml(), ""); +} + +/// An image of a filter is a PNG, JPEG, GIF or WebP, by its bytes, within the pixel cap by its header. +#[test] +fn filter_images_are_small_raster_images() { + fn png(w: u32, h: u32) -> Vec { + let mut out = vec![]; + image::ImageEncoder::write_image( + image::codecs::png::PngEncoder::new(&mut out), + &vec![0; (w * h * 4) as usize], + w, + h, + image::ExtendedColorType::Rgba8, + ) + .unwrap(); + out + } + let raster_image = |data| raster_image_sized(data).map(|(kind, _)| kind); + assert!(matches!(raster_image(Arc::new(png(2, 2))), Some(usvg::ImageKind::PNG(_)))); + assert_eq!(raster_image_sized(Arc::new(png(3, 2))).map(|(_, n)| n), Some(6), "its pixel count"); + // A header that claims more pixels than the cap: the IHDR's width, with its CRC fixed. + let mut big = png(2, 2); + big[16..20].copy_from_slice(&5000u32.to_be_bytes()); + big[20..24].copy_from_slice(&5000u32.to_be_bytes()); + let crc = crc32(&big[12..29]); + big[29..33].copy_from_slice(&crc.to_be_bytes()); + assert!(raster_image(Arc::new(big)).is_none(), "past the pixel cap"); + assert!(raster_image(Arc::new(b"".to_vec())).is_none(), "SVG"); + assert!(raster_image(Arc::new(vec![0x1f, 0x8b, 8, 0, 0, 0, 0, 0])).is_none(), "compressed SVG"); +} + +/// A 2 × 2 PNG whose header claims `w` × `h` pixels (its IHDR rewritten, with the CRC fixed). +fn png_claiming(w: u32, h: u32) -> Vec { + let mut out = vec![]; + image::ImageEncoder::write_image(image::codecs::png::PngEncoder::new(&mut out), &[0; 16], 2, 2, image::ExtendedColorType::Rgba8).unwrap(); + out[16..20].copy_from_slice(&w.to_be_bytes()); + out[20..24].copy_from_slice(&h.to_be_bytes()); + let crc = crc32(&out[12..29]); + out[29..33].copy_from_slice(&crc.to_be_bytes()); + out +} + +/// A filter's images share the pixel cap: images that are each within it but pass it together +/// are refused. +#[test] +fn a_filters_images_share_the_pixel_cap() { + let img = |w: u32, h: u32| format!("", base64(&png_claiming(w, h))); + let half = img(4096, 2048); + let err = check(&format!("{half}{}", img(4096, 2049))).unwrap_err(); + assert!(err.contains("pixels in all"), "{err}"); + let err = check(&format!("{half}{half}{}", img(1, 1))).unwrap_err(); + assert!(err.contains("pixels in all"), "{err}"); + assert!(check(&format!("{half}{half}")).is_ok(), "two halves fill the cap exactly"); +} + +/// The image limit is for a filter's own images: the object it runs on is its source graphic +/// whatever its size. +#[test] +fn a_large_object_is_still_the_source_graphic() { + let w = 4097; + let mut d = blue_square(w, 0); + filter(json!({ "xml": RED_FLOOD })).apply(&mut d, w, w, &space(w, w, 1.0, 1.0)); + assert_eq!(at(&d, w, w / 2, w / 2), [255, 0, 0, 255]); +} + +fn crc32(bytes: &[u8]) -> u32 { + let mut c = !0u32; + for b in bytes { + c ^= u32::from(*b); + for _ in 0..8 { + c = if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; + } + } + !c +} + +/// A user-space region in percentages is written in user units, measured against the object's box. +#[test] +fn a_region_measured_against_the_box_is_written_out() { + let far = r#""#; + let f = filter(json!({ "xml": far, "origin": [10.0, 0.0] })); + assert_eq!( + f.written_xml(Rect::new(10.0, 0.0, 30.0, 10.0)).as_deref(), + Some(r#""#) + ); + let plain = filter(json!({ "xml": RED_FLOOD })); + assert_eq!(plain.written_xml(Rect::new(0.0, 0.0, 1.0, 1.0)).as_deref(), Some(plain.xml())); +} + +/// A filter at the size limit whose region is measured against the box still draws: written in +/// user units, the region can make the drawn form longer than the limit. +#[test] +fn a_filter_at_the_size_limit_draws_with_its_measured_region() { + let open = r#""#; + let xml = format!("{open}{}{close}", "a".repeat(SvgFilter::MAX_XML - open.len() - close.len())); + assert_eq!(xml.len(), SvgFilter::MAX_XML); + assert_eq!(check(&xml), Ok("r".into())); + let f = filter(json!({ "xml": xml })); + let drawn = f.drawn_xml(Rect::new(0.123456789, 0.123456789, 1000.987654321, 1000.987654321)).unwrap(); + assert!(drawn.len() > SvgFilter::MAX_XML, "the region written out is longer: {} bytes", drawn.len()); + assert!(with_id(&drawn, DRAWN_ID).is_some(), "the drawn form is read"); +} + +/// SVG output writes a filter live only when the form it writes, with its region and id, is one +/// SVG import reads back: at most [`SvgFilter::MAX_XML`] bytes. A filter at the limit whose region +/// is measured against the box, one at the limit whose id is a character long, and one whose +/// shadows make its SVG 1.1 form longer are left to be written as other pixel effects are. +#[test] +fn svg_output_writes_a_filter_only_in_a_form_import_reads() { + let at_limit = |open: &str, close: &str| { + let xml = format!("{open}{}{close}", "a".repeat(SvgFilter::MAX_XML - open.len() - close.len())); + assert_eq!((xml.len(), check(&xml).is_ok()), (SvgFilter::MAX_XML, true)); + filter(json!({ "xml": xml })) + }; + let measured = at_limit( + r#""#, + ); + let short_id = at_limit(r#""#); + let shadows = format!(r#"{}"#, "".repeat(12), "a".repeat(SvgFilter::MAX_XML - 400)); + assert!(check(&shadows).is_ok() && shadows.len() <= SvgFilter::MAX_XML); + for f in [measured, short_id, filter(json!({ "xml": shadows }))] { + assert!(!f.writes_as_svg11() && f.written_xml(Rect::new(0.0, 0.0, 10.0, 10.0)).is_none(), "{} bytes", f.xml().len()); + } + // Room for the id and the longest region: still written, and read back. + let open = r#""#; + let xml = format!("{open}{}{close}", "a".repeat(MAX_WRITTEN_XML - REGION_ROOM - open.len() - close.len())); + let f = filter(json!({ "xml": xml })); + assert!(f.writes_as_svg11()); + let id = format!("u_vc_unique_-filter-{}", usize::MAX); + let out = with_id(&f.written_xml(Rect::new(0.123456789, 0.123456789, 1000.987654321, 1000.987654321)).unwrap(), &id).unwrap(); + assert!(out.len() <= SvgFilter::MAX_XML && check(&out).is_ok(), "{} bytes", out.len()); + // The longest numbers a region can take still fit. + let far = f.written_xml(Rect::new(-f64::MIN_POSITIVE, -f64::MIN_POSITIVE, f64::MAX / 4.0, f64::MAX / 4.0)).unwrap(); + assert!(with_id(&far, &id).is_some_and(|out| out.len() <= SvgFilter::MAX_XML)); + for v in [-f64::MIN_POSITIVE, -5e-324, -2.225073858507201e-308, f64::MIN, -1.0 / 3.0] { + assert!(format!("{v}").len() <= MAX_NUMBER_TEXT, "{v:e}"); + } + assert_eq!(format!("{}", -f64::MIN_POSITIVE).len(), MAX_NUMBER_TEXT); +} + +/// Only a type selector naming a filter or one of its elements, or `*`, lets a style sheet reach +/// filters: class, id, attribute and pseudo-class names that contain "filter" or "fe" don't. +#[test] +fn style_sheets_reach_filters_only_through_their_type_selectors() { + let reaches = |sheet: &str| { + let svg = format!(""); + Styles::of(&roxmltree::Document::parse(&svg).unwrap()).reach_filters + }; + for sheet in + [".filter-button { color: red }", "#feature, .fe-icon { fill: blue }", "[data-filter] { fill: red }", "a:hover, rect.filter { stroke: red }"] + { + assert!(!reaches(sheet), "{sheet}"); + } + for sheet in + ["filter { x: 0 }", "FeFlood { flood-color: red }", "svg|feBlend { mode: multiply }", "* { color: red }", "g :is(feGaussianBlur) { x: 0 }"] + { + assert!(reaches(sheet), "{sheet}"); + } +} + +/// An attribute selector styles a filter whose elements carry that attribute, whatever its value +/// or namespace prefix; a filter without it is not affected. +#[test] +fn an_attribute_selector_styles_a_filter_with_that_attribute() { + let depends = |sheet: &str, filter: &str| { + let svg = format!("{filter}"); + let doc = roxmltree::Document::parse(&svg).unwrap(); + let f = doc.descendants().find(|n| n.tag_name().name() == "filter").unwrap(); + depends_on_styles(f, &Styles::of(&doc)) + }; + let tagged = r#""#; + let plain = r#""#; + for sheet in ["[data-tone] { flood-color: red }", "[data-tone=\"warm\"] { flood-color: red }", "[svg|data-tone ~= warm] { x: 0 }"] { + assert!(depends(sheet, tagged), "{sheet}"); + assert!(!depends(sheet, plain), "{sheet}"); + } +} + +#[test] +fn filters_of_reads_at_most_256_filters() { + let many = format!( + "{}", + (0..300).map(|i| format!("")).collect::() + ); + let doc = roxmltree::Document::parse(&many).unwrap(); + let (found, skipped) = filters_of(&doc, &many, usize::MAX, |_| false); + assert_eq!((found.len(), skipped), (MAX_FILTERS_READ, 300 - MAX_FILTERS_READ)); +} + +/// However large `scale` makes them, a morphology radius spans at most 32 pixels of the raster the +/// filter runs on, and a standard deviation at most 512. +#[test] +fn costly_lengths_are_clamped_in_pixels() { + let sp = space(10, 10, 0.5, 0.5); + let morph = filter(json!({ "xml": "", "scale": 1000.0 })); + let s = morph.resolution(&sp, 10.0); + assert!(100.0 * 1000.0 / 0.5 * s <= 32.0 + 1e-6, "{s}"); + let blur = filter(json!({ "xml": "", "scale": 1000.0 })); + let s = blur.resolution(&sp, 10.0); + assert!(500.0 * 1000.0 / 0.5 * s <= 512.0 + 1e-6, "{s}"); + // At a fine raster too (1200 ppi): the cap holds. + let fine = space(10, 10, 0.06, 0.06); + let s = morph.resolution(&fine, 10.0); + assert!(100.0 * 1000.0 / 0.06 * s <= 32.0 + 1e-6, "{s}"); + let small = filter(json!({ "xml": "" })); + assert_eq!(small.resolution(&sp, 10.0), 1.0, "a small radius runs at the raster's own pixels"); + // In the object's bounding box, a radius is a fraction of its box: half a 4096-pixel box. + let boxed = filter(json!({ "xml": "" })); + let s = boxed.resolution(&sp, 4096.0); + assert!(0.5 * 4096.0 * s <= 32.0 + 1e-6, "{s}"); +} + +/// A filter that `check` refuses is never drawn, whatever path put it in an effect. +#[test] +fn an_unchecked_filter_is_not_drawn() { + for xml in [ + "", + "", + "", + ] { + let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": xml }), visible: true }; + assert!(raster_effects(&[e]).is_empty(), "{xml}"); + } +} + +/// Scale Strokes & Effects scales the filter's lengths with the art: the points a unit measures. +#[test] +fn scaling_the_effect_scales_its_units() { + let mut e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": RED_FLOOD }), visible: true }; + crate::scale_effect(&mut e, 2.0); + assert_eq!(e.params["scale"], json!(2.0)); + crate::scale_effect(&mut e, 0.25); + assert_eq!(e.params["scale"], json!(0.5)); +} + +/// The form SVG output writes, for a filter that fills a 10 × 10 point box. +fn written(xml: &str) -> Option { + filter(json!({ "xml": xml })).written_xml(Rect::new(0.0, 0.0, 10.0, 10.0)) +} + +/// SVG 1.1 output writes an image's reference as `xlink:href`; the filter as it is drawn and +/// listed keeps `href`. +#[test] +fn an_image_is_written_with_an_xlink_reference() { + let data = format!("data:image/png;base64,{}", base64(&png_claiming(2, 2))); + let f = filter(json!({ "xml": format!(r#""#) })); + assert_eq!(f.xml(), format!(r#""#)); + let out = f.written_xml(Rect::new(0.0, 0.0, 10.0, 10.0)).unwrap(); + assert_eq!(out, format!(r#""#)); + assert!(f.writes_as_svg11()); + assert_eq!(check(&out), Ok("i".into()), "the written form reads back"); +} + +/// SVG 1.1 has no `feDropShadow`: it is written as the primitives Filter Effects gives as its +/// equivalent, with its defaults, input, result and subregion, and results no other primitive uses. +#[test] +fn a_drop_shadow_is_written_as_svg_1_1_primitives() { + assert_eq!( + written(r#""#).as_deref(), + Some(concat!( + r#""#, + r#""#, + )) + ); + // Its input, result, subregion, color space and flood; a name the filter uses is not taken. + let given = r#""#; + assert_eq!( + written(given).as_deref(), + Some(concat!( + r#""#, + r#""#, + r##""##, + r#""#, + r#""#, + )) + ); + // An implicit input, or a result no earlier primitive has, is the previous result, named. + for shadow in [r#""#, r#""#] { + let out = written(&format!(r#"{shadow}"#)).unwrap(); + assert!(out.starts_with(r##""#), "{out}"); + assert_eq!(check(&out), Ok("s".into()), "the written form reads back"); + } + // What SVG 1.1 can't hold leaves the filter to be written as other pixel effects are. + for xml in [ + r#""#, + r#""#, + ] { + let f = filter(json!({ "xml": xml })); + assert!(!f.writes_as_svg11() && f.written_xml(Rect::new(0.0, 0.0, 10.0, 10.0)).is_none(), "{xml}"); + } + // An offset that isn't a number is the shadow's default, which an `feOffset` doesn't share. + let out = written(r#""#).unwrap(); + assert!(out.contains(r#"{}"#, "".repeat(13)); + assert!(!filter(json!({ "xml": many })).writes_as_svg11()); +} + +/// Each input is written as the primitive it reads when drawn: a result name only usvg gives (to +/// a primitive without a `result`, here the shadow), and the inputs usvg draws as `SourceGraphic`. +#[test] +fn inputs_are_written_as_the_primitives_they_read() { + let xml = r#""#; + let out = written(xml).unwrap(); + assert_eq!( + out, + concat!( + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + ) + ); + assert_eq!(check(&out), Ok("s".into()), "the written form reads back"); +} + +/// Other values SVG 1.1 lacks: SVG 1.1 values that draw alike, or no SVG 1.1 form. +#[test] +fn values_svg_1_1_lacks_are_written_as_resvg_draws_them() { + // `lighter` (Filter Effects) is drawn as the default `over`, and a blur has no `edgeMode`. + assert_eq!( + written(r#""#) + .as_deref(), + Some(r#""#) + ); + assert_eq!( + written(r#""#).as_deref(), + Some(r#""#) + ); + // CSS colors as `#rrggbb`, a flood color's alpha in its opacity, a lighting color's dropped. + assert_eq!( + written(r#""#) + .as_deref(), + Some( + r##""## + ) + ); + // Image scaling as an SVG 1.1 keyword. + let data = format!("data:image/png;base64,{}", base64(&png_claiming(2, 2))); + for (given, kept) in + [("pixelated", "optimizeSpeed"), ("crisp-edges", "optimizeSpeed"), ("smooth", "optimizeQuality"), ("auto", "optimizeQuality")] + { + let out = written(&format!(r#""#)).unwrap(); + assert!(out.contains(&format!(r#"style="image-rendering:{kept}""#)), "{given}: {out}"); + } + // The blend modes SVG 1.1 lacks have no SVG 1.1 form. + for mode in LATER_BLEND_MODES { + let f = filter(json!({ "xml": format!(r#""#) })); + assert!(!f.writes_as_svg11(), "{mode}"); + } +} + +#[test] +fn base64_pads_as_rfc_4648_does() { + assert_eq!(base64(b""), ""); + assert_eq!(base64(b"f"), "Zg=="); + assert_eq!(base64(b"fo"), "Zm8="); + assert_eq!(base64(b"foo"), "Zm9v"); + assert_eq!(base64(b"foobar"), "Zm9vYmFy"); +} diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 3996794ace..90c215bf09 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -133,6 +133,15 @@ fn geometry_effects_are_deterministic() { } } +/// The effects that symbol art across 9-slice guides draws once around all its cells are raster +/// effects that do not reshape it. +#[test] +fn nine_slice_painted_effects_are_raster_effects() { + for id in vectorcraft_doc::PAINTED_EFFECTS { + assert!(is_raster(id) && !is_geometry(id), "{id}"); + } +} + #[test] fn open_paths_stay_open() { let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(50.0, 20.0), Point::new(100.0, 0.0)], false)); @@ -171,6 +180,24 @@ fn warp_zero_bend_is_identity_ish() { } } +/// `warp::bends` says a warp moves placed gradients exactly when the warp moves the outline: +/// Arc leaves the outline as it is under a bend of 0.0001 % and moves it above that, and the other +/// styles move it at any bend. +#[test] +fn warp_bends_when_the_warp_moves_the_outline() { + // A star: Fisheye moves nothing on the edge of the box, where an ellipse or a rectangle lies. + let oval = shapes::star(Point::new(51.7, 34.3), 40.9, 17.3, 5, 7.0); + for (s, _) in WARP_STYLES { + let id = format!("warp.{s}"); + let flat = run(&id, json!({"bend": 0}), &oval); + for bend in [0.0, 1e-5, -1e-5, 0.9e-4, -0.9e-4, 1.1e-4, -1.1e-4] { + let p = json!({ "bend": bend }); + let moved = run(&id, p.clone(), &oval) != flat; + assert_eq!(crate::warp::bends(&id, &p), moved, "{id} at {bend} %"); + } + } +} + #[test] fn warp_arc_bends_the_top_edge() { let out = run("warp.arc", json!({"bend": 50}), &square()); @@ -398,6 +425,140 @@ fn stacked_effects_on_art_stay_within_the_anchor_budget() { assert_eq!(reshaped, 10); } +/// A path that keeps its shape because its Transform effect would pass the budget keeps the +/// gradients that paint the art as a whole in place too, also with Scale Strokes & Effects on. +#[test] +fn art_past_the_budget_keeps_its_own_gradients_in_place() { + use std::sync::Arc; + + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + use vectorcraft_doc::{AppearanceItem, FillLayer, NodeId, color::Paint}; + let id = NodeId(9); + let stops = vec![GradientStop::new(0.0, vectorcraft_color::Color::BLACK), GradientStop::new(1.0, vectorcraft_color::Color::WHITE)]; + let geom = GradientGeom { start: (0.0, 50.0).into(), end: (100.0, 50.0).into(), aspect: 1.0, focal: None }; + let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) })); + let circle = || Arc::new(Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default())); + // The group's own fill, a gradient placed across the circle, after `carry` moves it. + let own_end = |carry: &crate::Carry| { + let mut ap = Appearance::default(); + ap.items.push(AppearanceItem::Fill(FillLayer::new(placed.clone()))); + carry.apply(&mut ap); + match ap.fill_paint() { + Paint::Gradient(g) => g.geom.map(|g| g.end.x), + _ => None, + } + }; + for params in [json!({"scaleH": 1000, "scaleV": 1000}), json!({"scaleH": 1000, "scaleV": 1000, "strokes": true})] { + let grow = fx("distort.transform", params.clone()); + let mut art = Node::group(id, vec![circle()]); + let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], Budget::EFFECTS); + let end = own_end(&carry).unwrap(); + assert!((end - 550.0).abs() < 1e-6, "{params}: within the budget the group's gradient grows with the circle: {end}"); + // No room beyond what the circle costs: scaled up, it would be drawn with more lines. + let mut art = Node::group(id, vec![circle()]); + let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], Budget { anchors: usize::MAX, lines: 0 }); + let b = art.geometric_bounds().unwrap(); + assert!(b.width() < 101.0 && b.height() < 101.0, "{params}: the circle keeps its shape: {b:?}"); + assert_eq!(own_end(&carry), Some(100.0), "{params}: the group's gradient stays where it was placed"); + // A group inside the art whose square took the effect moves its own gradient all the same. + let square = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default())); + let mut inner = Node::group(NodeId(2), vec![square]); + inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed.clone()))); + let mut art = Node::group(id, vec![circle(), Arc::new(inner)]); + let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], Budget { anchors: usize::MAX, lines: 0 }); + assert_eq!(own_end(&carry), Some(100.0), "{params}: the art's own gradient stays"); + let inner = &art.children().unwrap()[1]; + let Paint::Gradient(g) = inner.appearance.fill_paint() else { panic!("a gradient") }; + assert!((g.geom.unwrap().end.x - 550.0).abs() < 1e-6, "{params}: the inner group's gradient: {:?}", g.geom); + } +} + +/// A hidden path in a layer that keeps its shape past the budget does not hold the layer's +/// gradients in place: the layer's bounds leave it out, so the layer's own gradient moves with +/// the visible art under a Transform effect and Free Distort, as does the art's when the layer is +/// the art. +#[test] +fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move() { + use std::sync::Arc; + + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + use vectorcraft_doc::{AppearanceItem, FillLayer, LayerColor, NodeId, NodeKind, color::Paint}; + let stops = vec![GradientStop::new(0.0, vectorcraft_color::Color::BLACK), GradientStop::new(1.0, vectorcraft_color::Color::WHITE)]; + let geom = GradientGeom { start: (0.0, 50.0).into(), end: (100.0, 50.0).into(), aspect: 1.0, focal: None }; + let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) })); + let end = |ap: &Appearance| match ap.fill_paint() { + Paint::Gradient(g) => g.geom.map(|g| g.end.x), + _ => None, + }; + // A layer with a visible square and a hidden circle, both 0..100, and a gradient fill of its own. + let layer = || { + let square = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default())); + let mut circle = Node::path(NodeId(4), shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default()); + circle.visible = false; + let mut layer = Node::layer(NodeId(2), "Layer 1", LayerColor::Preset(0)); + if let NodeKind::Layer { children, .. } = &mut layer.kind { + *children = vec![square, Arc::new(circle)]; + } + layer.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed.clone()))); + layer + }; + // No room beyond what the paths cost: the square takes each effect, the circle would be drawn + // with more lines and keeps its shape. + let budget = Budget { anchors: usize::MAX, lines: 0 }; + // Each scales the art ten times about its center: 0..100 becomes -450..550. + let corners = json!({"corners": [[-4.5, -4.5], [5.5, -4.5], [5.5, 5.5], [-4.5, 5.5]]}); + for grow in [fx("distort.transform", json!({"scaleH": 1000, "scaleV": 1000})), fx("distort.freeDistort", corners)] { + let mut art = layer(); + let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], budget); + let circle = art.children().unwrap()[1].geometric_bounds().unwrap(); + assert!(circle.width() < 101.0, "{}: the hidden circle keeps its shape: {circle:?}", grow.id); + let square = art.children().unwrap()[0].geometric_bounds().unwrap(); + assert!((square.x1 - 550.0).abs() < 1e-6, "{}: the square takes the effect: {square:?}", grow.id); + let mut own = Appearance::clone(&art.appearance); + carry.apply(&mut own); + assert_eq!(end(&own), Some(550.0), "{}: the layer's gradient, as the art", grow.id); + let mut art = Node::group(NodeId(9), vec![Arc::new(layer())]); + crate::reshape::reshape_leaves_within(&mut art, &[&grow], budget); + assert_eq!(end(&art.children().unwrap()[0].appearance), Some(550.0), "{}: the layer's gradient, inside the art", grow.id); + } +} + +/// A freeform gradient whose points were edited (its vector still fitted to the bounds) moves its +/// points with a Transform effect and Free Distort, on a path, on a group inside the art and on the +/// art itself, as a placed gradient does. +#[test] +fn edited_freeform_points_follow_a_transform_effect_and_free_distort() { + use std::sync::Arc; + + use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint}; + use vectorcraft_doc::{AppearanceItem, FillLayer, NodeId, color::Paint}; + let mut ramp = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Gradient::default() }); + let pt = |x: f64, c| FreeformPoint::new(Point::new(x, 50.0), c); + ramp.set_freeform(Freeform { points: vec![pt(0.0, Color::BLACK), pt(100.0, Color::WHITE)], ..Default::default() }); + assert!(ramp.geom.is_none() && !ramp.is_placed()); + let freeform = Paint::Gradient(Box::new(ramp)); + let xs = |ap: &Appearance| match ap.fill_paint() { + Paint::Gradient(g) => g.freeform.as_ref().map(|f| f.points.iter().map(|p| p.at.x).collect::>()), + _ => None, + }; + let square = |ap: Appearance| Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap)); + // Each moves the art 30 pt right. + let corners = json!({"corners": [[0.3, 0.0], [1.3, 0.0], [1.3, 1.0], [0.3, 1.0]]}); + for e in [fx("distort.transform", json!({"moveH": 30})), fx("distort.freeDistort", corners)] { + let mut inner = Node::group(NodeId(2), vec![square(Appearance::default())]); + inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone()))); + let mut art = Node::group(NodeId(9), vec![square(Appearance::basic(freeform.clone(), Paint::None, 0.0)), Arc::new(inner)]); + art.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone()))); + let carry = crate::reshape::reshape_leaves_within(&mut art, &[&e], Budget::EFFECTS); + let members = art.children().unwrap(); + assert_eq!(xs(&members[0].appearance), Some(vec![30.0, 130.0]), "{}: the path's points", e.id); + assert_eq!(xs(&members[1].appearance), Some(vec![30.0, 130.0]), "{}: the inner group's points", e.id); + let mut own = Appearance::clone(&art.appearance); + carry.apply(&mut own); + assert_eq!(xs(&own), Some(vec![30.0, 130.0]), "{}: the art's own points", e.id); + } +} + /// #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] @@ -438,6 +599,93 @@ fn three_max_detail_roughens_stay_within_the_effect_budget() { assert_ne!(out, apply_geometry(&[rough], &rect, rect.bounds().unwrap()), "more than one Roughen applies"); } +#[test] +fn transform_copies_before_offset_path_evaluates_without_ram_spike() { + let effects = [ + fx("distort.transform", json!({"moveH": -0.66, "moveV": 0.66, "copies": 30})), + fx("path.offsetPath", json!({"offset": 10.0, "joins": "round"})), + ]; + let path = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); + let start = std::time::Instant::now(); + let out = apply_geometry(&effects, &path, path.bounds().unwrap()); + let elapsed = start.elapsed(); + assert!(elapsed < std::time::Duration::from_secs(2), "elapsed: {:?}", elapsed); + assert_eq!(out.subpaths.len(), 31); +} + +#[test] +fn reshape_leaves_within_optimizes_transform_before_terminal_offset_path() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Node, NodeId}; + + let id = NodeId(10); + let leaf = |x: f64| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 20.0)), Appearance::default())); + let mut art = Node::group(id, (0..5).map(|k| leaf(k as f64 * 30.0)).collect()); + let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 10})); + let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"})); + + let start = std::time::Instant::now(); + crate::reshape::reshape_leaves_within(&mut art, &[&transform, &offset], Budget::EFFECTS); + let elapsed = start.elapsed(); + assert!(elapsed < std::time::Duration::from_secs(2)); + + let children = art.children().unwrap(); + assert_eq!(children.len(), 5); + for c in children { + let (p, _) = crate::reshape::leaf_geometry(c).unwrap(); + // Base rectangle offset once, then copied 10 times -> 11 subpaths + assert_eq!(p.subpaths.len(), 11); + } +} + +#[test] +fn reshape_leaves_within_preserves_order_when_not_terminal_or_not_style_safe() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind}; + + let id = NodeId(11); + // 1. EvenOdd fill rule: preserving order causes Transform copies to union in Offset Path into 1 subpath. + let mut leaf = Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default()); + if let NodeKind::Path { rule, .. } = &mut leaf.kind { + *rule = FillRule::EvenOdd; + } + let mut art_evenodd = Node::group(id, vec![Arc::new(leaf)]); + let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 2})); + let offset = fx("path.offsetPath", json!({"offset": 4.0})); + crate::reshape::reshape_leaves_within(&mut art_evenodd, &[&transform, &offset], Budget::EFFECTS); + let p = art_evenodd.children().unwrap()[0].path_data().unwrap(); + assert_eq!(p.subpaths.len(), 1, "EvenOdd does not swap; copies union into 1 outer subpath"); + + // 2. Non-terminal Offset Path: followed by Round Corners, must preserve order. + let leaf_round = Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default())); + let mut art_round = Node::group(id, vec![leaf_round]); + let round_corners = fx("stylize.roundCorners", json!({"radius": 2.0})); + crate::reshape::reshape_leaves_within(&mut art_round, &[&transform, &offset, &round_corners], Budget::EFFECTS); + let p = art_round.children().unwrap()[0].path_data().unwrap(); + assert_eq!(p.subpaths.len(), 1, "Non-terminal Offset Path does not swap; copies union into 1 outer subpath"); + + // 3. Non-round join (e.g. miter): preserving order is required as corners differ (#4145). + let leaf_miter = Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default())); + let mut art_miter = Node::group(id, vec![leaf_miter]); + let offset_miter = fx("path.offsetPath", json!({"offset": 4.0, "joins": "miter"})); + crate::reshape::reshape_leaves_within(&mut art_miter, &[&transform, &offset_miter], Budget::EFFECTS); + let p = art_miter.children().unwrap()[0].path_data().unwrap(); + assert_eq!(p.subpaths.len(), 1, "Miter join does not swap; copies union into 1 outer subpath"); +} + +#[test] +fn consecutive_transforms_before_terminal_offset_path_all_move_after() { + let t1 = fx("distort.transform", json!({"moveH": 1.0, "moveV": 0.0, "copies": 2})); + let t2 = fx("distort.transform", json!({"moveH": 0.0, "moveV": 1.0, "copies": 3})); + let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"})); + + let opt = crate::geometry::optimize_geometry_effects(&[&t1, &t2, &offset], true); + assert_eq!(opt.len(), 3); + assert_eq!(opt[0].id, "path.offsetPath"); + assert_eq!(opt[1].id, "distort.transform"); + assert_eq!(opt[2].id, "distort.transform"); +} + #[test] fn transform_copies_stop_before_they_overflow() { let out = run("distort.transform", json!({"scaleH": 100000, "scaleV": 100000, "copies": 1000}), &square()); @@ -846,6 +1094,18 @@ fn round_corners_keeps_where_a_closed_path_starts() { assert_eq!(stylize::round_corners(&d, f64::INFINITY), stylize::round_corners(&d, 1e9)); } +#[test] +fn twist_turns_clockwise_for_positive_angles() { + // A positive angle turns clockwise, a negative one counterclockwise + // (https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). + // The document's y runs down, so clockwise on the page takes a point right of the center down. + let right = PathData::single(SubPath::polyline(&[Point::new(55.0, 50.0), Point::new(56.0, 50.0)], false)); + let bounds = Rect::new(0.0, 0.0, 100.0, 100.0); + let turned = |angle: f64| apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &right, bounds).subpaths[0].anchors[0].p; + assert!(turned(45.0).y > 50.5, "{:?}", turned(45.0)); + assert!(turned(-45.0).y < 49.5, "{:?}", turned(-45.0)); +} + #[test] fn twist_fixes_the_outer_circle_and_rotates_inside() { let out = run("distort.twist", json!({"angle": 0}), &square()); @@ -1104,10 +1364,10 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() { let instance = |name: &str| Arc::new(Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })); let mut d = Document::new(100.0, 100.0); // A 500 × 500 grid as a symbol's art, directly and inside a group; a symbol holding itself. - d.symbols.push(Symbol { name: "Grid".into(), art: repeat(grid(unit(), 500)) }); - d.symbols.push(Symbol { name: "Grouped".into(), art: Arc::new(Node::group(NodeId(0), vec![repeat(grid(unit(), 500))])) }); - d.symbols.push(Symbol { name: "Loop".into(), art: Arc::new(Node::group(NodeId(0), vec![unit(), instance("Loop")])) }); - d.symbols.push(Symbol { name: "Small".into(), art: repeat(grid(unit(), 3)) }); + d.symbols.push(Symbol { dynamic: false, name: "Grid".into(), art: repeat(grid(unit(), 500)) }); + d.symbols.push(Symbol { dynamic: false, name: "Grouped".into(), art: Arc::new(Node::group(NodeId(0), vec![repeat(grid(unit(), 500))])) }); + d.symbols.push(Symbol { dynamic: false, name: "Loop".into(), art: Arc::new(Node::group(NodeId(0), vec![unit(), instance("Loop")])) }); + d.symbols.push(Symbol { dynamic: false, name: "Small".into(), art: repeat(grid(unit(), 3)) }); // A 3 × 3 grid of an instance of each: each copy draws 250,000 instances, so one copy fits. for name in ["Grid", "Grouped"] { let outer = Node::new(NodeId(0), NodeKind::Repeat(grid(instance(name), 3))); @@ -1120,3 +1380,32 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() { let small = Node::new(NodeId(0), NodeKind::Repeat(RepeatSpec::mirror(vec![instance("Small")], 90.0, 5.0))); assert_eq!(expand_live(Some(&d), &small).len(), 2); } + +#[test] +fn a_distance_parameters_range_comes_from_its_documentation() { + assert_eq!(length_range("stylize.glowingEdges", "edgeWidth"), Some(1.0..=14.0)); + // A distance documented without a range, and unknown effects and parameters, have none. + assert_eq!(length_range("path.offsetPath", "offset"), None); + assert_eq!(length_range("stylize.glowingEdges", "edgeBrightness"), None); + assert_eq!(length_range("no.such", "edgeWidth"), None); +} + +#[test] +fn color_halftones_radius_is_in_raster_pixels_not_a_distance() { + // Pixels of the Document Raster Effects resolution, as public documentation gives it (#3260): + // no unit setting changes it, so it isn't a distance in points. + assert_eq!(raster_px_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0)); + assert!(!is_length("pixelate.colorHalftone", "maxRadius", false)); + assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), None); + assert_eq!(raster_px_range("pixelate.colorHalftone", "channel1"), None); + assert_eq!(raster_px_range("stylize.glowingEdges", "edgeWidth"), None); + // The effect applies the range's floor to a radius below it. + assert_eq!( + crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 1})), + crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 4})) + ); + // Scale Strokes & Effects scales it with the object, as it does distances. + let mut e = crate::new_effect("pixelate.colorHalftone", &json!({"maxRadius": 10})).unwrap(); + crate::scale_effect(&mut e, 2.0); + assert_eq!((e.params["maxRadius"].as_f64(), e.params["channel1"].as_f64()), (Some(20.0), Some(108.0))); +} diff --git a/crates/effects/src/tests/transformfx.rs b/crates/effects/src/tests/transformfx.rs index a5fdd674cc..84368b6f64 100644 --- a/crates/effects/src/tests/transformfx.rs +++ b/crates/effects/src/tests/transformfx.rs @@ -3,11 +3,11 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Dash, Effect, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Appearance, AppearanceItem, Dash, Document, 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}; +use crate::{bake_document, expand_outlined, has_transform_art, has_transform_options, reshape}; fn transform(params: Value) -> Effect { Effect { id: "distort.transform".into(), params, visible: true } @@ -157,3 +157,273 @@ fn stroke_scaling_across_copies_stays_finite() { } } } + +/// A 100 pt square at the origin with a solid gray fill and a 2 pt black stroke (dashed 4/2) that +/// carries the Transform effect `params` itself. +fn stroke_with_effect(params: Value) -> Node { + let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5)); + let mut n = + Node::path(NodeId(10), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(gray, 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 }); + s.effects.push(transform(params)); + } + n +} + +/// A 100 pt square at the origin filled with pattern "p" placed at the identity, the fill carrying +/// the Transform effect `params` itself. +fn fill_with_effect(params: Value) -> Node { + let mut n = patterned(json!({})); + n.appearance.effects.clear(); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.effects.push(transform(params)); + } + n +} + +/// The paths under `n` that a stroke paints. +fn stroked_leaves(n: &Node) -> Vec<&Node> { + leaves(n).into_iter().filter(|p| p.appearance.stroke().is_some()).collect() +} + +/// The paths under `n` that a pattern fills. +fn pattern_leaves(n: &Node) -> Vec<&Node> { + leaves(n).into_iter().filter(|p| matches!(p.appearance.fill_paint(), Paint::Pattern { .. })).collect() +} + +#[test] +fn a_strokes_own_transform_scales_its_weight_and_dashes_with_scale_strokes_and_effects() { + let n = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "strokes": true})); + assert!(has_transform_options(&n)); + let art = reshape(None, &n, None).unwrap(); + let paths = stroked_leaves(&art); + assert_eq!(paths.len(), 1); + let (w, dash) = stroke_of(paths[0]); + assert!(close(w, 4.0), "{w}"); + assert_eq!(dash, vec![8.0, 4.0]); + assert!(close(paths[0].geometric_bounds().unwrap().width(), 200.0)); + // The fill stays on the path as it was, below the stroke. + let all = leaves(&art); + assert_eq!(all.len(), 2); + assert!(all[0].appearance.stroke().is_none()); + assert_eq!(all[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)); + // Off, the stroke keeps its weight and dashes: the effect stays geometry alone. + let plain = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "strokes": false})); + assert!(!has_transform_art(&plain)); +} + +#[test] +fn each_copy_of_a_strokes_own_transform_scales_its_weight_once_more() { + let n = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "copies": 2, "strokes": true})); + let art = reshape(None, &n, None).unwrap(); + let widths: Vec = stroked_leaves(&art).iter().map(|p| stroke_of(p).0).collect(); + assert_eq!(widths, vec![2.0, 4.0, 8.0]); +} + +#[test] +fn a_fills_own_transform_with_scale_strokes_and_effects_scales_its_later_effects() { + let mut n = stroke_with_effect(json!({})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.effects.push(transform(json!({"scaleH": 300, "scaleV": 300, "strokes": true}))); + f.effects.push(Effect { id: "path.offsetPath".into(), params: json!({"offset": 5.0}), visible: true }); + } + let art = reshape(None, &n, None).unwrap(); + let fill = leaves(&art).into_iter().find(|p| p.appearance.stroke().is_none()).unwrap(); + let AppearanceItem::Fill(f) = &fill.appearance.items[0] else { panic!("not a fill") }; + // The Offset Path, scaled from 5 to 15, applies to the transformed fill's path. + assert!(f.effects.is_empty(), "{:?}", f.effects); + let w = fill.geometric_bounds().unwrap().width(); + assert!(close(w, 330.0), "{w}"); +} + +#[test] +fn a_later_transform_on_a_stroke_turns_its_copies_about_their_combined_center() { + for later in [json!({"rotate": 90}), json!({"rotate": 90, "strokes": true})] { + let mut n = stroke_with_effect(json!({"moveH": 200, "copies": 1, "strokes": true})); + if let Some(s) = n.appearance.stroke_mut() { + s.effects.push(transform(later.clone())); + } + let art = reshape(None, &n, None).unwrap(); + let paths = stroked_leaves(&art); + assert_eq!(paths.len(), 2, "{later}"); + // The copies span 0 to 300 by 0 to 100 before the turn; about the center (150, 50) both + // go to x 100 to 200, one above the other. + let boxes: Vec = paths.iter().map(|p| p.geometric_bounds().unwrap()).collect(); + for b in &boxes { + assert!(close(b.x0, 100.0) && close(b.x1, 200.0), "{later}: {boxes:?}"); + } + let top = boxes.iter().map(|b| b.y0).fold(f64::INFINITY, f64::min); + let bottom = boxes.iter().map(|b| b.y1).fold(f64::NEG_INFINITY, f64::max); + assert!(close(top, -100.0) && close(bottom, 200.0), "{later}: {boxes:?}"); + for p in &paths { + assert!(p.appearance.stroke().unwrap().effects.is_empty(), "{later}"); + } + } +} + +#[test] +fn a_fills_own_transform_moves_each_copys_pattern_with_transform_patterns() { + let n = fill_with_effect(json!({"moveH": 30, "copies": 2, "patterns": true})); + assert!(has_transform_options(&n)); + let art = reshape(None, &n, None).unwrap(); + let xs: Vec = pattern_leaves(&art).iter().map(|p| pattern_xf(p).as_coeffs()[4]).collect(); + assert_eq!(xs, vec![0.0, 30.0, 60.0]); + // Off, the pattern stays put. + assert!(!has_transform_art(&fill_with_effect(json!({"moveH": 30, "copies": 2})))); +} + +#[test] +fn a_strokes_own_transform_with_transform_objects_off_keeps_its_geometry() { + let n = stroke_with_effect(json!({"scaleH": 50, "scaleV": 50, "moveH": 40, "copies": 3, "objects": false, "strokes": true})); + let art = reshape(None, &n, None).unwrap(); + let paths = stroked_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)); + let n = fill_with_effect(json!({"rotate": 45, "objects": false, "patterns": true})); + let art = reshape(None, &n, None).unwrap(); + let paths = pattern_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 a_strokes_own_transform_draws_bakes_expands_and_measures_alike() { + let n = stroke_with_effect(json!({"scaleH": 200, "scaleV": 200, "copies": 1, "strokes": true})); + let drawn = reshape(None, &n, None).unwrap(); + let widths = |art: &Node| stroked_leaves(art).iter().map(|p| stroke_of(p).0).collect::>(); + assert_eq!(widths(&drawn), vec![2.0, 4.0]); + // Expand Appearance. + assert_eq!(widths(&expand_outlined(None, &n, None).unwrap()), widths(&drawn)); + // Export. + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, n.clone()).unwrap(); + let baked = bake_document(&d).unwrap(); + assert_eq!(widths(baked.node(NodeId(10)).unwrap()), widths(&drawn)); + // Use Preview Bounds: the copy's 4 pt stroke (on -50..150) reaches 2 pt past it. + let symbols = d.symbol_boxes(); + let b = crate::preview::visual_bounds(&symbols, &n).unwrap(); + assert!(close(b.width(), 204.0), "{b:?}"); + assert_eq!(Some(b), drawn.visual_bounds_with(&symbols)); +} + +/// Three strokes, each with three max-detail Roughens (#3578: nearly one effect budget on their +/// own) before its own Transform effect: their paths keep to one effect budget together, not one +/// each. +#[test] +fn strokes_with_their_own_transform_keep_to_one_effect_budget() { + use crate::geometry::Budget; + let rough = Effect { id: "distort.roughen".into(), params: json!({"size": 10000, "relative": false, "detail": 100}), visible: true }; + let mut n = Node::path( + NodeId(11), + shapes::rectangle(Rect::new(0.0, 0.0, 1000.0, 1000.0)), + Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0), + ); + let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).cloned() else { + panic!("no stroke") + }; + n.appearance.items.retain(|i| !matches!(i, AppearanceItem::Stroke(_))); + for _ in 0..3 { + let mut s = s.clone(); + s.effects = vec![rough.clone(); 3]; + s.effects.push(transform(json!({"scaleH": 50, "scaleV": 50, "strokes": true}))); + n.appearance.items.push(AppearanceItem::Stroke(s)); + } + let art = reshape(None, &n, None).unwrap(); + let paths = stroked_leaves(&art); + assert_eq!(paths.len(), 3); + let cost = + paths.iter().filter_map(|p| crate::reshape::leaf_geometry(p)).fold(Budget { anchors: 0, lines: 0 }, |c, (g, _)| c.plus(Budget::of(&g))); + assert!(Budget::EFFECTS.fits(cost) && cost.lines > crate::MAX_EFFECT_LINES / 2, "{cost:?}"); +} + +/// A path of 600,000 anchors with a fill below a stroke whose own Transform effect makes five +/// copies: the fill's path counts toward the effect budget, so the stroke's copies stop where the +/// whole art would pass it. +#[test] +fn a_fill_below_a_strokes_own_transform_counts_toward_the_effect_budget() { + use crate::geometry::Budget; + use vectorcraft_geom::{PathData, Point, SubPath}; + let points: Vec = (0..600_000).map(|i| Point::new(f64::from(i) * 1.0e-4, f64::from(i % 2))).collect(); + let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5)); + let mut n = Node::path(NodeId(12), PathData::single(SubPath::polyline(&points, false)), Appearance::basic(gray, Paint::solid(Color::BLACK), 1.0)); + if let Some(s) = n.appearance.stroke_mut() { + s.effects.push(transform(json!({"moveH": 100, "copies": 5, "strokes": true}))); + } + let art = reshape(None, &n, None).unwrap(); + let cost = leaves(&art) + .iter() + .filter_map(|p| crate::reshape::leaf_geometry(p)) + .fold(Budget { anchors: 0, lines: 0 }, |c, (g, _)| c.plus(Budget::of(&g))); + assert_eq!(stroked_leaves(&art).len(), 2, "{cost:?}"); + assert!(Budget::EFFECTS.fits(cost), "{cost:?}"); +} + +/// A path of 600,000 anchors with a stroke whose own Transform effect makes two copies, below a +/// fill: the stroke's copies leave room for the fill painted after them. +#[test] +fn a_strokes_own_transform_leaves_room_for_a_fill_above_it() { + use crate::geometry::Budget; + use vectorcraft_geom::{PathData, Point, SubPath}; + let points: Vec = (0..600_000).map(|i| Point::new(f64::from(i) * 1.0e-4, f64::from(i % 2))).collect(); + let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5)); + let mut n = Node::path(NodeId(13), PathData::single(SubPath::polyline(&points, false)), Appearance::basic(gray, Paint::solid(Color::BLACK), 1.0)); + if let Some(s) = n.appearance.stroke_mut() { + s.effects.push(transform(json!({"moveH": 100, "copies": 2, "strokes": true}))); + } + n.appearance.items.reverse(); + assert!(matches!(n.appearance.items.first(), Some(AppearanceItem::Stroke(_)))); + let art = reshape(None, &n, None).unwrap(); + let cost = leaves(&art) + .iter() + .filter_map(|p| crate::reshape::leaf_geometry(p)) + .fold(Budget { anchors: 0, lines: 0 }, |c, (g, _)| c.plus(Budget::of(&g))); + assert_eq!(stroked_leaves(&art).len(), 2, "{cost:?}"); + assert!(Budget::EFFECTS.fits(cost), "{cost:?}"); +} + +/// A 100 pt square at the origin painted with `fill` and a 1 pt white stroke, with the Transform +/// effect `params`. +fn filled_and_stroked(fill: Paint, params: Value) -> Node { + let mut n = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(fill, Paint::solid(Color::WHITE), 1.0)); + n.appearance.effects.push(transform(params)); + n +} + +#[test] +fn copies_with_a_fill_and_a_stroke_are_drawn_one_above_another() { + // Black fill, white stroke, each copy scaled and turned (#5920): each copy is an object of its + // own above the one before, so its fill covers the strokes of the copies below. + let params = json!({"scaleH": 97, "scaleV": 97, "rotate": 10, "copies": 25}); + let n = filled_and_stroked(Paint::solid(Color::BLACK), params.clone()); + assert!(has_transform_art(&n)); + let art = reshape(None, &n, None).unwrap(); + let paths = leaves(&art); + assert_eq!(paths.len(), 26, "the original and 25 copies"); + for p in &paths { + assert!(matches!(p.kind, NodeKind::Path { .. }), "one shape each, not one path of every copy"); + assert!(!p.appearance.fill_paint().is_none() && p.appearance.stroke().is_some()); + } + // The original is at the bottom, the smallest copy on top. + assert_eq!(paths[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)); + let top = paths[25].geometric_bounds().unwrap(); + assert!(top.width() < 100.0 && top.height() < 100.0, "{top:?}"); + // Drawn as Expand Appearance makes it. + assert_eq!(leaves(&expand_outlined(None, &n, None).unwrap()).len(), 26); + + // One opaque stroke, or one nonzero fill, paints the copies alike as one path: no art. + assert!(!has_transform_art(&filled_and_stroked(Paint::None, params.clone()))); + let mut fill_only = filled_and_stroked(Paint::solid(Color::BLACK), params.clone()); + fill_only.appearance.items.retain(AppearanceItem::is_fill); + assert!(!has_transform_art(&fill_only)); + // A partly transparent fill paints where copies overlap twice. + if let Some(AppearanceItem::Fill(f)) = fill_only.appearance.items.first_mut() { + f.opacity = 0.5; + } + assert!(has_transform_art(&fill_only)); + // No copies: nothing to stack. + assert!(!has_transform_art(&filled_and_stroked(Paint::solid(Color::BLACK), json!({"rotate": 10})))); +} diff --git a/crates/effects/src/warp.rs b/crates/effects/src/warp.rs index fb0279ede6..84f196a8b4 100644 --- a/crates/effects/src/warp.rs +++ b/crates/effects/src/warp.rs @@ -32,3 +32,14 @@ pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value, max: usize) - let piece = b.width().hypot(b.height()) / 24.0; map_nonlinear_within(path, piece, max, f) } + +/// Does warp effect `id` with params `p` move any point? Every style leaves the box as it is with +/// no bend and no distortion, and Arc (`warp.arc`) takes a bend under 0.0001 % as none: the +/// threshold must match the one in [`warp_point`]'s Arc case (`warp_bends_when_the_warp_moves_the_outline` +/// tests both sides of it). +pub(crate) fn bends(id: &str, p: &Value) -> bool { + let share = |key: &str, default: f64| num(p, key, default).clamp(-100.0, 100.0) / 100.0; + let bend = share("bend", 50.0); + let bent = if id == "warp.arc" { bend.abs() >= 1e-6 } else { bend != 0.0 }; + bent || share("horizontal", 0.0) != 0.0 || share("vertical", 0.0) != 0.0 +} diff --git a/crates/effects/tests/envelope_ink.rs b/crates/effects/tests/envelope_ink.rs new file mode 100644 index 0000000000..a95906cc1b --- /dev/null +++ b/crates/effects/tests/envelope_ink.rs @@ -0,0 +1,29 @@ +//! Live evaluation without an engine session makes envelopes measure type by its glyph outlines. +//! One test in its own process, so nothing else has registered the measure before the evaluation. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::Arc; + +use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Point, Rect}; + +/// The largest distance between the edges of `a` and `b`. +fn off(a: Rect, b: Rect) -> f64 { + [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs())) +} + +#[test] +fn live_evaluation_measures_type_in_envelopes_by_its_glyphs() { + let t = TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { size: 48.0, ..Default::default() }); + let n = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone())))); + let laid = n.geometric_bounds().unwrap(); + let ink = t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap()); + assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}"); + let before = vectorcraft_doc::live::envelope_content_bounds(std::slice::from_ref(&n)).unwrap(); + assert!(off(before, laid) < 1e-6, "with nothing registered, type keeps its laid-out box: {before:?} vs {laid:?}"); + + let _ = vectorcraft_effects::expand_live(None, &n); + let after = vectorcraft_doc::live::envelope_content_bounds(&[n]).unwrap(); + assert!(off(after, ink) < 1e-6, "after live evaluation, type is measured by its glyphs: {after:?} vs {ink:?}"); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f495697ceb..0ebcb71c50 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -9,10 +9,14 @@ description = "VectorCraft engine: sessions, history, selection, the command reg workspace = true [features] -default = ["bundled-fonts"] +default = ["bundled-fonts", "heif"] # The fonts vectorcraft-text bundles (see its `bundled-fonts`). Embedders that supply every font at # run time (`vectorcraft_text::FontDb::add_font`) build with `default-features = false`. bundled-fonts = ["vectorcraft-text/bundled-fonts"] +# HEIC and HEIF images open and place, decoded by heic-rs (an HEVC decoder). A build without this +# feature still recognizes the files and refuses them with a message. The apps list it beside +# `bundled-fonts`. +heif = ["dep:heic-rs", "dep:rayon"] [dependencies] # Which paths stored in documents may be opened. @@ -36,9 +40,15 @@ vectorcraft-plugins = { workspace = true } vectorcraft-affinity = { workspace = true } vectorcraft-scriptcheck = { workspace = true } image = { workspace = true } +hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] } +# Pure Rust, no unsafe; pinned at the version photocraft-heif uses. +heic-rs = { version = "=0.1.4", default-features = false, features = ["std"], optional = true } flate2 = { workspace = true } +chrono = { workspace = true } # The XML parts of Word documents placed as type (place/docx.rs). roxmltree = "0.21" +# The compound file that holds a Word 97-2003 document placed as type (place/doc.rs). +cfb = "0.15" kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } @@ -50,6 +60,11 @@ log = { workspace = true } [target.'cfg(unix)'.dependencies] rustix = { workspace = true, features = ["std", "process"] } +# The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true } +rayon = { version = "1.12", optional = true } + [dev-dependencies] vectorcraft-affinity = { workspace = true, features = ["synth"] } crc32fast = { workspace = true } @@ -57,6 +72,10 @@ vectorcraft-testkit = { workspace = true } proptest = { workspace = true } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } +# How many times an open reads a PDF. +vectorcraft-pdf = { workspace = true, features = ["read-count"] } wat = { workspace = true } # Zstandard streams for the Illustrator editing data fuzz tests. ruzstd = { workspace = true } +# The JavaScript parser's lexer, compared with the script checker's on the same scripts. +vectorcraft-js = { workspace = true } diff --git a/crates/engine/examples/anchor_bench.rs b/crates/engine/examples/anchor_bench.rs new file mode 100644 index 0000000000..281464c0b7 --- /dev/null +++ b/crates/engine/examples/anchor_bench.rs @@ -0,0 +1,336 @@ +//! `cargo run --release -p vectorcraft-engine --example anchor_bench` prints the wall time of the +//! engine steps of editing anchors with Direct Selection, on four synthetic documents: one closed path of +//! 50,000 anchors, 2,000 closed paths of 50 anchors each, one open path of 200,000 anchors, and the closed +//! path of 50,000 anchors filled and with a dashed stroke. +//! `ITERS` sets the runs per step (default 7); each row is the median in ms. +// 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::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Dash, Document, Node, NodeId}; +use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind}; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::{Affine, Anchor, PathData, Point, SubPath, Vec2}; +use vectorcraft_render::{RenderOptions, Renderer}; + +/// Anchors are 10 pt apart and their handles 3 pt long, along the path. +const STEP: f64 = 10.0; +const HANDLE: f64 = 3.0; + +/// A test document: its paths, an anchor to hover, click and drag, a point on a segment, and a +/// marquee from an empty point over about 10,000 anchors. +struct Shape { + name: &'static str, + doc: Document, + ids: Vec, + anchor: (NodeId, usize), + segment: Point, + marquee: (Point, Point), +} + +/// A closed path of `n` smooth anchors around `center`. +fn circle(center: Point, n: usize) -> PathData { + let r = n as f64 * STEP / std::f64::consts::TAU; + let anchors = (0..n) + .map(|i| { + let t = i as f64 / n as f64 * std::f64::consts::TAU; + let p = center + Vec2::new(r * t.cos(), r * t.sin()); + Anchor::smooth(p, p + Vec2::new(-t.sin(), t.cos()) * HANDLE) + }) + .collect(); + PathData::single(SubPath::new(anchors, true)) +} + +fn add(doc: &mut Document, path: PathData) -> NodeId { + let l = doc.layers.first().map(|l| l.id); + let id = doc.alloc_id(); + doc.insert(l, usize::MAX, Node::path(id, path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap(); + id +} + +fn one_outline() -> Shape { + let n = 50_000; + let mut doc = Document::new(1600.0, 1200.0); + let id = add(&mut doc, circle(Point::ZERO, n)); + let r = n as f64 * STEP / std::f64::consts::TAU; + let a = 72f64.to_radians(); + let mid = (n / 2) as f64 / n as f64 * std::f64::consts::TAU; + let next = (n / 2 + 1) as f64 / n as f64 * std::f64::consts::TAU; + let segment = Point::new(r * (mid.cos() + next.cos()) / 2.0, r * (mid.sin() + next.sin()) / 2.0); + Shape { + name: "one closed path, 50,000 anchors", + doc, + ids: vec![id], + anchor: (id, n / 2), + segment, + marquee: (Point::new(r + 50.0, -5.0), Point::new(r * a.cos() - 1.0, r * a.sin() + 1.0)), + } +} + +/// [`one_outline`] filled, with a 1 pt stroke of 6 pt dashes and 4 pt gaps. +fn dashed_outline() -> Shape { + let mut shape = one_outline(); + let mut look = Appearance::basic(Paint::solid(Color::rgb(0.8, 0.2, 0.2)), Paint::solid(Color::BLACK), 1.0); + for item in &mut look.items { + if let AppearanceItem::Stroke(st) = item { + st.dash = Some(Dash { pattern: vec![6.0, 4.0], offset: 0.0, align_corners: false }); + } + } + shape.doc.node_mut(shape.ids[0]).unwrap().appearance = look.into(); + shape.name = "one closed path, 50,000 anchors, filled, dashed stroke"; + shape +} + +fn many_paths() -> Shape { + let mut doc = Document::new(1600.0, 1200.0); + let ids: Vec = + (0..2000).map(|i| add(&mut doc, circle(Point::new((i % 50) as f64 * 200.0 + 100.0, (i / 50) as f64 * 200.0 + 100.0), 50))).collect(); + let r = 50.0 * STEP / std::f64::consts::TAU; + // Path 1,025 (row 20, column 25), its anchors 0 and 1. + let c = Point::new(25.0 * 200.0 + 100.0, 20.0 * 200.0 + 100.0); + let t = std::f64::consts::TAU / 50.0; + let segment = c + Vec2::new(r * (1.0 + t.cos()) / 2.0, r * t.sin() / 2.0); + Shape { + name: "2,000 closed paths, 50 anchors each", + doc, + anchor: (ids[1025], 0), + ids, + segment, + marquee: (Point::ZERO, Point::new(10_000.0, 800.0)), + } +} + +fn long_open_path() -> Shape { + let n = 200_000; + let mut doc = Document::new(1600.0, 1200.0); + let anchors = (0..n) + .map(|i| { + let p = Point::new(i as f64 * STEP, 0.0); + Anchor::smooth(p, p + Vec2::new(HANDLE, 0.0)) + }) + .collect(); + let id = add(&mut doc, PathData::single(SubPath::new(anchors, false))); + Shape { + name: "one open path, 200,000 anchors", + doc, + ids: vec![id], + anchor: (id, n / 2), + segment: Point::new((n / 2) as f64 * STEP + STEP / 2.0, 0.0), + marquee: (Point::new(-5.0, -20.0), Point::new(99_995.0, 30.0)), + } +} + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(mut ms: Vec) -> f64 { + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +fn time(mut f: impl FnMut()) -> f64 { + median( + (0..iters()) + .map(|_| { + let t = Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 + }) + .collect(), + ) +} + +fn ev(kind: PointerKind, p: Point) -> PointerEvent { + PointerEvent::new(kind, p.x, p.y) +} + +fn exec(s: &mut Session, cmd: &str, p: Value) { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")); +} + +fn anchor_at(s: &Session, (id, ai): (NodeId, usize)) -> Anchor { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[ai] +} + +/// The anchors selected: those direct-selected, and every anchor of a path selected whole. +fn selected_anchors(s: &Session) -> usize { + let st = s.doc().unwrap(); + let count = |id: &NodeId| st.doc.node(*id).and_then(|n| n.path_data()).map_or(0, |pd| pd.anchors().count()); + st.selection.objects.iter().map(|id| st.selection.partial(*id).map_or_else(|| count(id), |set| set.len())).sum() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn row(name: &str, ms: f64) { + println!(" {name:<58} {ms:>10.3} ms"); +} + +/// Select `count` anchors: the first ones of the first path, or the first anchors of as many +/// paths as needed. +fn select_count(s: &mut Session, shape: &Shape, count: usize) { + exec(s, "select.none", json!({})); + let mut left = count; + for id in &shape.ids { + if left == 0 { + break; + } + let n = s.doc().unwrap().doc.node(*id).unwrap().path_data().unwrap().subpaths[0].anchors.len(); + let take = left.min(n); + let refs: Vec<[usize; 2]> = (0..take).map(|i| [0, i]).collect(); + exec(s, "select.anchors", json!({"id": id.0, "anchors": refs, "mode": "add"})); + left -= take; + } +} + +fn bench(shape: Shape) { + println!("{}", shape.name); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + let mut s = Session::new(); + s.add_document(shape.doc.clone(), None); + s.select_tool("directSelection", view).unwrap(); + let a = anchor_at(&s, shape.anchor).p; + let none = Mods::default(); + { + let doc = s.doc().unwrap().doc.clone(); + let opt = vectorcraft_doc::hit::HitOptions { tol: 3.0, clip_outlines: true, ..Default::default() }; + row("hit test at an anchor", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, a, opt))))); + row("hit test at a segment", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, shape.segment, opt))))); + row("hit test beside the path", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, shape.segment + Vec2::new(0.0, 40.0), opt))))); + } + + // Hover with nothing selected, then with one anchor of the path selected. + for selected in [false, true] { + if selected { + exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"})); + } + let what = if selected { "one anchor selected" } else { "nothing selected" }; + row(&format!("hover over an anchor, {what}"), time(|| drop(s.pointer(&ev(PointerKind::Move, a), view).unwrap()))); + row(&format!("cursor over an anchor, {what}"), time(|| _ = black_box(s.cursor(a, none, view)))); + row(&format!("hover over a segment, {what}"), time(|| drop(s.pointer(&ev(PointerKind::Move, shape.segment), view).unwrap()))); + row(&format!("cursor over a segment, {what}"), time(|| _ = black_box(s.cursor(shape.segment, none, view)))); + } + + // A click that selects one anchor. + exec(&mut s, "select.none", json!({})); + row( + "click that selects one anchor", + time(|| { + s.pointer(&ev(PointerKind::Down, a), view).unwrap(); + s.pointer(&ev(PointerKind::Up, a), view).unwrap(); + }), + ); + assert_eq!(selected_anchors(&s), 1, "the click selects one anchor"); + + // One anchor dragged: each pointer move, then the release. + let undo = undo_len(&s); + s.pointer(&ev(PointerKind::Down, a), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, a + Vec2::new(0.0, 20.0)), view).unwrap(); + let mut y = 20.0; + row( + "anchor drag, one pointer move", + time(|| { + y += 1.0; + s.pointer(&ev(PointerKind::Drag, a + Vec2::new(0.0, y)), view).unwrap(); + }), + ); + let t = Instant::now(); + s.pointer(&ev(PointerKind::Up, a + Vec2::new(0.0, y)), view).unwrap(); + row("anchor drag, release (commit)", t.elapsed().as_secs_f64() * 1000.0); + assert_eq!(undo_len(&s), undo + 1, "the anchor drag records one step"); + exec(&mut s, "edit.undo", json!({})); + + // The selected anchor's outgoing handle dragged. + exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"})); + let h = anchor_at(&s, shape.anchor).h_out; + let undo = undo_len(&s); + s.pointer(&ev(PointerKind::Down, h), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, h + Vec2::new(0.0, 20.0)), view).unwrap(); + let mut y = 20.0; + row( + "handle drag, one pointer move", + time(|| { + y += 1.0; + s.pointer(&ev(PointerKind::Drag, h + Vec2::new(0.0, y)), view).unwrap(); + }), + ); + let t = Instant::now(); + s.pointer(&ev(PointerKind::Up, h + Vec2::new(0.0, y)), view).unwrap(); + row("handle drag, release (commit)", t.elapsed().as_secs_f64() * 1000.0); + assert_eq!(undo_len(&s), undo + 1, "the handle drag records one step"); + assert_eq!(anchor_at(&s, shape.anchor).p, a, "the handle drag leaves the anchor in place"); + exec(&mut s, "edit.undo", json!({})); + + // A marquee over about 10,000 anchors. + let (m0, m1) = shape.marquee; + let ms = time(|| { + exec(&mut s, "select.none", json!({})); + s.pointer(&ev(PointerKind::Down, m0), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, m0.lerp(m1, 0.5)), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, m1), view).unwrap(); + s.pointer(&ev(PointerKind::Up, m1), view).unwrap(); + }); + row(&format!("marquee over {} anchors (press to release)", selected_anchors(&s)), ms); + + // Select All with Direct Selection. + row("Select All", time(|| exec(&mut s, "select.all", json!({})))); + row("tool overlays, everything selected", time(|| drop(s.overlays(view)))); + + // Nudges of 1, 1,000 and every anchor, and Undo and Redo of each. + let total: usize = shape.ids.iter().map(|id| s.doc().unwrap().doc.node(*id).unwrap().path_data().unwrap().subpaths[0].anchors.len()).sum(); + for count in [1, 1000, total] { + select_count(&mut s, &shape, count); + row(&format!("nudge of {count} anchors"), time(|| exec(&mut s, "path.moveAnchors", json!({"dx": 1, "dy": 0})))); + row(&format!("undo of a nudge of {count} anchors"), time(|| exec(&mut s, "edit.undo", json!({})))); + row(&format!("redo of a nudge of {count} anchors"), time(|| exec(&mut s, "edit.redo", json!({})))); + } + + // The render of the document after one anchor moves (the renderer warm). + exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"})); + let opts = RenderOptions::default(); + let mut r = Renderer::new(); + let at = Affine::translate(Vec2::new(800.0 - a.x, 600.0 - a.y)); + r.render(&s.doc().unwrap().doc, 1600, 1200, at, &opts); + let ms = median( + (0..iters()) + .map(|_| { + exec(&mut s, "path.moveAnchors", json!({"dx": 0, "dy": 1})); + let doc = s.doc().unwrap().doc.clone(); + let t = Instant::now(); + drop(r.render(&doc, 1600, 1200, at, &opts)); + t.elapsed().as_secs_f64() * 1000.0 + }) + .collect(), + ); + row("render 1600x1200 around the anchor after it moves", ms); + let doc = s.doc().unwrap().doc.clone(); + row("render 1600x1200 around the anchor, nothing changed", time(|| drop(r.render(&doc, 1600, 1200, at, &opts)))); + + // Delete of one anchor, undone after each run. + let ms = median( + (0..iters()) + .map(|_| { + exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"})); + let t = Instant::now(); + exec(&mut s, "edit.clear", json!({})); + let ms = t.elapsed().as_secs_f64() * 1000.0; + exec(&mut s, "edit.undo", json!({})); + ms + }) + .collect(), + ); + row("Delete of one anchor", ms); +} + +fn main() { + bench(one_outline()); + bench(many_paths()); + bench(long_open_path()); + bench(dashed_outline()); +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 6b658da0d6..6ef4918e16 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -1,5 +1,7 @@ //! The command registry. Ids follow Illustrator's menu structure. +pub mod actionset; +mod addons; pub(crate) mod appearance; mod assets; mod attributes; @@ -10,6 +12,8 @@ pub mod clipboard; mod colorcmds; pub mod colormgmt; pub mod colortheme; +pub mod compositefonts; +mod compoundshape; pub(crate) mod create; mod css; mod cut; @@ -31,6 +35,7 @@ mod fonts; pub(crate) mod freeform; pub mod globaledit; pub(crate) mod gradient; +pub mod gradpresets; pub(crate) mod graph; mod halftone; pub mod help; @@ -59,6 +64,7 @@ pub mod params; mod path; pub(crate) mod pathops; mod patterncmds; +pub mod patternlib; pub mod pdfcmds; pub mod perspgrid; pub mod place; @@ -79,11 +85,14 @@ pub(crate) mod slices; mod stroke; mod style; pub mod stylelib; +mod svgfilter; mod swatch; pub mod swatchlib; +pub(crate) mod symboledit; pub mod symbollib; pub(crate) mod tabs; mod textedit; +pub use textedit::effective_kerning; pub mod textstyles; pub(crate) mod textwrap; pub(crate) mod threads; @@ -162,9 +171,20 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) } } -/// Objects are selected, or the Artboard tool is chosen (Copy and Cut take its artboard). -pub fn has_selection_or_artboard_tool(s: &Session) -> std::result::Result<(), String> { - if s.tool_id() == "artboard" { has_doc(s) } else { has_selection(s) } +/// A path is selected, or inside a selected group or compound path: Object › Path's items that +/// work on paths (not on text, images or other objects alone). +pub fn has_selected_path(s: &Session) -> std::result::Result<(), String> { + has_selection(s)?; + let st = s.active().ok_or("no document open")?; + // Stops at the first path: menus ask this every frame, and a selected group can hold many. + fn holds_path(n: &vectorcraft_doc::Node) -> bool { + matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: false, .. }) || n.children().is_some_and(|c| c.iter().any(|c| holds_path(c))) + } + if st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).any(holds_path) { Ok(()) } else { Err("select a path".into()) } +} +/// Objects or ruler guides are selected, or the Artboard tool is chosen (what Copy and Cut take). +pub fn has_selection_guides_or_artboard_tool(s: &Session) -> std::result::Result<(), String> { + if s.tool_id() == "artboard" { has_doc(s) } else { has_selection_or_guides(s) } } /// Objects or ruler guides are selected (what Delete and the arrow keys act on). pub fn has_selection_or_guides(s: &Session) -> std::result::Result<(), String> { @@ -179,20 +199,26 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.selection.len() < 2 { Err("select at least two objects".into()) } else { Ok(()) } } -/// A document is open and it is not in isolation mode: Object › Lock's and Object › Hide's items, -/// Unlock All and Show All are off in isolation mode. Pattern editing mode and opacity mask -/// editing isolate their art too, and do not count as isolation mode here while their own layer -/// is the isolated one. An object isolated inside them counts. -pub fn outside_isolation(s: &Session) -> std::result::Result<(), String> { - let st = s.active().ok_or("no document open")?; - let editing_layer = |l| st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == l) || st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == l); - if st.isolation.is_some_and(|l| !editing_layer(l)) { Err("exit isolation mode first".into()) } else { Ok(()) } +/// The isolated group, layer or object in isolation mode. Pattern editing mode, opacity mask +/// editing and symbol editing mode isolate their own layer, which does not count here; an object +/// isolated inside them counts. +pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option { + st.isolation.filter(|l| { + !st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l) + && !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l) + && !st.doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l) + }) } -/// Objects are selected ([`has_selection`]) and the document is not in isolation mode -/// ([`outside_isolation`]). -pub fn has_selection_outside_isolation(s: &Session) -> std::result::Result<(), String> { - outside_isolation(s)?; - has_selection(s) +/// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at +/// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items. +pub fn has_selected_member(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + let Some(root) = ordinary_isolation(st) else { return has_selection(s) }; + if st.selection.objects.iter().any(|id| inside_isolation(&st.doc, root, *id)) { Ok(()) } else { Err("nothing selected".into()) } +} +/// Whether `id` lies inside the isolated object `root` (the root itself does not). +pub(crate) fn inside_isolation(d: &vectorcraft_doc::Document, root: vectorcraft_doc::NodeId, id: vectorcraft_doc::NodeId) -> bool { + id != root && d.ancestry(id).is_some_and(|a| a.contains(&root)) } pub fn can_undo(s: &Session) -> std::result::Result<(), String> { s.active().filter(|d| !d.history.undo.is_empty()).map(|_| ()).ok_or_else(|| "nothing to undo".into()) @@ -242,6 +268,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(style::specs()); v.extend(swatch::specs()); v.extend(gradient::specs()); + v.extend(gradpresets::specs()); v.extend(opacitymask::specs()); v.extend(layer::specs()); v.extend(layerpanel::specs()); @@ -249,6 +276,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(xform::specs()); v.extend(effectcmd::specs()); v.extend(pathops::specs()); + v.extend(compoundshape::specs()); v.extend(typecmd::specs()); v.extend(menucmds::specs()); v.extend(live::specs()); @@ -259,6 +287,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(inline::specs()); v.extend(textstyles::specs()); v.extend(fonts::specs()); + v.extend(compositefonts::specs()); v.extend(fontfiles::specs()); v.extend(help::specs()); v.extend(threads::specs()); @@ -292,6 +321,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(expand::specs()); v.extend(attributes::specs()); v.extend(interactivity::specs()); + v.extend(svgfilter::specs()); v.extend(newart::specs()); v.extend(colortheme::specs()); v.extend(fileio::pdf::specs()); @@ -319,13 +349,23 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(halftone::specs()); v.extend(perspgrid::specs()); v.extend(shortcutset::specs()); + v.extend(actionset::specs()); v.extend(importmatches::specs()); + v.extend(addons::specs()); v }) } +/// The command `id`: a built-in one, or a command an installed plug-in adds +/// ([`plugin::command_specs`]). pub fn find_command(id: &str) -> Option<&'static CommandSpec> { - command_specs().iter().find(|c| c.id == id) + command_specs().iter().find(|c| c.id == id).or_else(|| plugin::find_spec(id)) +} + +/// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in +/// ([`plugin::run_command`]), which needs the command's id. +pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result { + if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) } } // ---------- param helpers ---------- @@ -378,11 +418,34 @@ pub(crate) fn check_switches(p: &Value, keys: &[&str], cmd: &str) -> Result<()> pub(crate) fn str_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> { p.get(key).and_then(Value::as_str) } +/// The string `p` gives for `key`, or `None` when `p` leaves it out or gives null. Any other +/// value, such as `5`, is an error: "`{key}` must be a string". +pub(crate) fn text_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(v)) => Ok(Some(v)), + Some(_) => Err(bad(cmd, format!("`{key}` must be a string"))), + } +} pub(crate) fn id_param(p: &Value, key: &str) -> Option { p.get(key).and_then(Value::as_u64).map(NodeId) } -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 object ids `p` gives for `key`, or `None` when `p` leaves it out or gives null. A value that +/// is not an array, or an entry that is not a non-negative integer, is an error with the message +/// [`checked_ids_param`] gives, so no entry is dropped. Whether each id names an object is left to +/// the caller. +pub(crate) fn ids_param(p: &Value, key: &str, cmd: &str) -> Result>> { + let values = match p.get(key) { + None | Some(Value::Null) => return Ok(None), + Some(Value::Array(a)) => a, + Some(_) => return Err(bad(cmd, format!("{key} must be an array of non-negative integer object ids"))), + }; + values.iter().enumerate().map(|(index, value)| id_entry(value, key, index, cmd)).collect::>>().map(Some) +} +/// Entry `index` (from 0) of the `key` list as an object id: anything but a non-negative integer is +/// an error naming the key, the entry and its value. +fn id_entry(value: &Value, key: &str, index: usize, cmd: &str) -> Result { + value.as_u64().map(NodeId).ok_or_else(|| bad(cmd, format!("`{key}` entry {index} is {value}, not a non-negative integer object id"))) } /// 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, @@ -408,7 +471,7 @@ pub(crate) fn index(v: u64) -> usize { pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str) -> Result> { let values = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(command, format!("{key} must be an array of non-negative integer object ids")))?; - values.iter().map(|value| checked_id(s, value, command)).collect() + values.iter().enumerate().map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_id(s, value, command))).collect() } /// The objects a command acts on: `ids` when given (every one checked, and those inside another @@ -460,9 +523,10 @@ pub fn matrix_param(p: &Value, key: &str) -> Option { } /// A colour from `"#rrggbb"`, a colour key (`"cmyk 0 100 100 0"`, `"lab 55 60 40"`), `[r,g,b]` (0..1), /// `{"c":..,"m":..,"y":..,"k":..}` (percent when any component is above 1, else 0..1), `{"gray":..}` or `{"l":..,"a":..,"b":..}` (CIE Lab: L 0..100, a and b about -/// −128..127). +/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`). pub fn color_value(v: &Value) -> Option { match v { + Value::String(s) if hex_with_alpha(s) => None, // A hex, or a colour key ("cmyk 0 100 100 0", as Recolor Artwork lists colours). Value::String(s) => Color::from_hex(s).or_else(|| vectorcraft_color::recolor::ColorKey::parse(s).map(|k| k.color())), Value::Array(a) if a.len() >= 3 => Some(Color::rgb(a[0].as_f64()? as f32, a[1].as_f64()? as f32, a[2].as_f64()? as f32)), @@ -488,24 +552,82 @@ pub fn color_value(v: &Value) -> Option { } } -/// Objects a command targets: explicit `ids` param or the selection. -pub(crate) fn targets(s: &Session, p: &Value) -> Result> { - // Objects given are used as given: a value that isn't an object id fails rather than the - // command acting on the selection instead (#785). - let object_id = |v: &Value| v.as_u64().map(NodeId).ok_or_else(|| EngineError::Other(format!("object ids are non-negative integers, not {v}"))); +/// Is `s` a hex color with an alpha part: eight or four hex digits, with or without the `#`? +/// [`Color::from_hex`] reads `#rrggbbaa` as `#rrggbb`, without the alpha. +pub(crate) fn hex_with_alpha(s: &str) -> bool { + let s = s.trim(); + let h = s.strip_prefix('#').unwrap_or(s); + matches!(h.len(), 4 | 8) && h.chars().all(|c| c.is_ascii_hexdigit()) +} + +/// The color `p` gives for `key`, read by [`color_value`]: `None` when `p` leaves it out or gives +/// null. Any other value that is not a color is an error: "bad color {v}". +pub(crate) fn color_param(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key).filter(|v| !v.is_null()) { + None => Ok(None), + Some(v) => color_value(v).map(Some).ok_or_else(|| bad(cmd, format!("bad color {v}"))), + } +} + +/// `v` as an object id: an error unless it is a non-negative integer. +fn object_id(v: &Value) -> Result { + v.as_u64().map(NodeId).ok_or_else(|| EngineError::Other(format!("object ids are non-negative integers, not {v}"))) +} + +/// The error for `id` given as step reference `r`, which only a batch resolves. +fn unresolved_reference(r: &str) -> EngineError { + EngineError::Other(format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")) +} + +/// The objects `p` names for a command whose `id` can only be an object id: its `ids`, else its +/// `id` as `ids` of one. A value that isn't an object id is an error, never the selection (#785). +/// `None` when `p` gives neither (or gives them as `null`). The ids are not looked up in the +/// document. +pub(crate) fn named_ids(p: &Value) -> Result>> { match p.get("ids").filter(|v| !v.is_null()) { - Some(Value::Array(a)) => return a.iter().map(object_id).collect(), + Some(Value::Array(a)) => return a.iter().map(object_id).collect::>>().map(Some), Some(v) => return Err(EngineError::Other(format!("`ids` must be an array of object ids, not {v}"))), None => {} } + Ok(named_id(p)?.map(|id| vec![id])) +} + +/// The object `p`'s `id` names, for a command whose `id` can only be an object id: a value that +/// isn't an object id is an error, never the selection (#785). `None` when `p` leaves `id` out (or +/// gives it as `null`). The id is not looked up in the document. +pub(crate) fn named_id(p: &Value) -> Result> { match p.get("id").filter(|v| !v.is_null()) { - Some(v @ Value::Number(_)) => Ok(vec![object_id(v)?]), - // A step reference a batch couldn't resolve (other strings are other ids, such as an - // effect's). - Some(Value::String(r)) if r.starts_with('$') => { - Err(EngineError::Other(format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve"))) + None => Ok(None), + Some(Value::String(r)) if r.starts_with('$') => Err(unresolved_reference(r)), + Some(v) => object_id(v).map(Some), + } +} + +/// The object `p` gives as `key`, for a command that acts on the selection (or makes something new) +/// without it: `None` when `p` leaves it out or gives null. Any other value that isn't an object id +/// (`"abc"`, `"5"`, `true`, `{}`, `-1`, `2.5`) is an error under `cmd` that names `key`, never the +/// selection. The id is not looked up in the document. +pub(crate) fn object_param(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(r)) if key == "id" && r.starts_with('$') => { + Err(bad(cmd, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve"))) + } + Some(v) => v.as_u64().map(|id| Some(NodeId(id))).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number"))), + } +} + +/// Objects a command targets: its `ids`, else its `id` as `ids` of one ([`named_ids`]), else the +/// selection. An `ids` or `id` that isn't an object id is an error, never the selection. The +/// selection is refused while an object of a dynamic symbol instance's art is selected, as by +/// [`edit::selected_roots`]. +pub(crate) fn targets(s: &Session, p: &Value) -> Result> { + match named_ids(p)? { + Some(ids) => Ok(ids), + None => { + edit::refuse_symbol_part(s)?; + Ok(s.doc()?.selection.objects.clone()) } - _ => Ok(s.doc()?.selection.objects.clone()), } } @@ -514,26 +636,30 @@ pub(crate) fn ok() -> Result { } /// Leaves whose appearance a paint command changes: groups and layers expand to their contents, -/// and compound paths own their children's appearance, so a member stands for its compound path -/// (#3692), which is listed once. +/// and compound paths and compound shapes own their members' appearance, so a member stands for +/// its compound path (#3692) or compound shape, which is listed once. pub(crate) fn leaf_targets(s: &Session, ids: &[NodeId]) -> Result> { use vectorcraft_doc::NodeKind; let d = &s.doc()?.doc; - let compound = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + let owns = |n: &vectorcraft_doc::Node| matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape(); + let compound = |id: NodeId| d.parent_of(id).filter(|p| d.node(*p).is_some_and(owns)); let mut out = vec![]; for id in ids { let Some(n) = d.node(*id) else { continue }; match &n.kind { - NodeKind::Group { .. } | NodeKind::Layer { .. } => n.walk(&mut |c| { - if !c.is_container() || matches!(c.kind, NodeKind::Compound { .. }) { + NodeKind::Group { .. } | NodeKind::Layer { .. } if !n.is_compound_shape() => n.walk(&mut |c| { + if !c.is_container() || owns(c) { out.push(c.id) } }), _ => out.push(compound(*id).unwrap_or(*id)), } } - let comp: Vec = out.iter().filter(|id| matches!(d.node(**id).map(|n| &n.kind), Some(NodeKind::Compound { .. }))).copied().collect(); - out.retain(|id| !comp.iter().any(|c| d.parent_of(*id) == Some(*c))); + let comp: std::collections::HashSet = out.iter().filter(|id| d.node(**id).is_some_and(owns)).copied().collect(); + if !comp.is_empty() { + // A compound shape's members lie at any depth in it. + out.retain(|id| !d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).any(|a| comp.contains(a)))); + } let mut seen = std::collections::HashSet::new(); out.retain(|id| seen.insert(*id)); Ok(out) @@ -552,8 +678,29 @@ pub(crate) fn unique_name(base: &str, taken: impl Fn(&str) -> bool) -> String { (2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| base.to_string()) } +/// [`unique_name`] for names given one after another (an import): `next` keeps, per base (in +/// any case), the number after the last one tried, so a run of one name doesn't count up from 2 +/// again for each copy. Names only become taken meanwhile, so the result is the same. +pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap, taken: impl Fn(&str) -> bool) -> String { + if !taken(base) { + return base.to_string(); + } + let i = next.entry(base.to_lowercase()).or_insert(2); + loop { + let n = format!("{base} {i}"); + *i += 1; + if !taken(&n) { + return n; + } + } +} + +/// The most presets one presets file imports: each is looked up among the saved ones. +pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; + pub(crate) use edit::{settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; +pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; pub(crate) use vectorcraft_doc::range::parse_range; /// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see @@ -581,6 +728,9 @@ pub use opacitymask::TransparencyInfo; /// Eyedropper Options (`Prefs::eyedropper`). pub use xform::{AppearanceAttrs, EyedropperAttrs, EyedropperOptions, FillAttrs, StrokeAttrs}; +/// The shape modes of the selected compound-shape members (the Pathfinder panel lights theirs). +pub use compoundshape::selected_member_modes; + /// Pathfinder Options (`Prefs::pathfinder`). pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions}; @@ -593,12 +743,28 @@ pub use flatten::FlattenOptions; /// A built-in or saved flattener preset ([`crate::Prefs::flattener_presets`]). pub use flatten::FlattenerPreset; +/// A saved Gradient panel preset ([`crate::Prefs::gradient_presets`]) and a row of the Presets list. +pub use gradpresets::{GradientPreset, GradientPresetEntry}; + +/// A saved Image Trace preset ([`crate::Prefs::trace_presets`]), and a change to the saved presets. +pub use buildcmds::{TracePreset, TracePresetChange}; + +/// An Image Trace made off the UI thread, and what it traced (#3098). +pub use buildcmds::{TraceRun, Traced}; + +/// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them). +pub(crate) use buildcmds::TracePresetChanges; + /// 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; +/// Whether Reset Transformation changes a symbol instance (the Symbols panel menu and the +/// Control bar enable it when it changes one). +pub use brushsym::reset_transformation_changes; + /// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`. /// They run as before but the command palette leaves them out (it lists the command once). pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")]; diff --git a/crates/engine/src/cmd/actionset.rs b/crates/engine/src/cmd/actionset.rs new file mode 100644 index 0000000000..b6a9118380 --- /dev/null +++ b/crates/engine/src/cmd/actionset.rs @@ -0,0 +1,560 @@ +//! Action sets another app saves as text (`.aia` files that start `/version`), read into their +//! actions and steps without changing anything (`actionSet.read`). +//! +//! The text is a set of fields and blocks. A slash name followed by a value sets a field, and a +//! slash name followed by `{` opens a block that `}` closes. A value is a decimal number, text in +//! parentheses, a byte count and hexadecimal bytes in square brackets (`[ 5 48656c6c6f ]`, UTF-8 +//! text, which can run over several words), or a byte count and hexadecimal bytes in angle brackets +//! (`< 3 0a0b0c >`, raw bytes). The set's `/version` comes first, and its `/name` is hexadecimal +//! text. Each action is an `/action-N` block with a hexadecimal `/name`; each step is an `/event-N` +//! block inside one, with its `/internalName` in parentheses, the `/localizedName` it is shown with +//! as hexadecimal text, and `/isOn` 0 when it is left out of playback; each value a step was +//! recorded with is a `/parameter-N` block inside it, which is counted, and whose hexadecimal +//! `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount` +//! and a step's `/parameterCount` give how many actions, steps and recorded values follow. +//! The layout follows the README of Inventsable's Redesigning-Illustrator-Actions-in-Scripting +//! (https://github.com/Inventsable/Redesigning-Illustrator-Actions-in-Scripting), the forum post +//! "Made a two-way aia to json converter" +//! (https://community.adobe.com/t5/illustrator-discussions/made-a-two-way-aia-to-json-converter/m-p/13751909), +//! sttk3's article on names as UTF-8 hexadecimal +//! (https://sttk3.com/blog/tips/illustrator/dynamic-generate-action.html), and the MIT-licensed +//! reader in zachshallbetter/adobe-mcp (https://github.com/zachshallbetter/adobe-mcp). The raw form +//! follows the forum thread "Creating a dynamic action" +//! (https://community.adobe.com/questions-652/creating-a-dynamic-action-to-use-with-app-doscript-method-814406). + +use serde_json::{Value, json}; + +use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, text_param}; + +/// The most bytes of a file read. +const MAX_BYTES: usize = 8 << 20; +/// The most bytes taken in: [`MAX_BYTES`] after a byte order mark, and one more that shows the text +/// goes on. +const READ_LIMIT: usize = MAX_BYTES + 4; +/// The most blocks open at once. +const MAX_DEPTH: usize = 16; +/// The most actions read. +const MAX_ACTIONS: usize = 1000; +/// The most steps read in one action. +const MAX_STEPS: usize = 10_000; +/// The most steps read in the set: a small text can hold hundreds of thousands of empty steps, and +/// the answer holds an object for each. +const MAX_SET_STEPS: usize = 100_000; +/// The longest name kept (bytes). +const MAX_NAME: usize = 1024; +/// The most tokens listed as unread. +const MAX_UNREAD: usize = 1000; +/// The longest unread token shown (characters). +const UNREAD_SHOWN: usize = 80; + +/// The extensions of action sets other apps save. +pub const EXTS: &[&str] = &["aia"]; + +pub fn specs() -> Vec { + vec![cmd!( + query "actionSet.read", + "Read Action Set File", + [], + None, + "{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error", + always, + read + )] +} + +/// A step of an action: an `/event-N` block. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AiaStep { + /// Its `/internalName`. + pub name: String, + /// Its `/localizedName`, if it has one. + pub label: Option, + /// Its `/isOn`, if it has one. + pub on: Option, + /// How many `/parameter-N` blocks it has. + pub params: usize, + /// Its `/parameterCount`, if it has one. + pub declared: Option, + /// The line its block opens on (from 1). + pub line: usize, +} + +/// An action: an `/action-N` block. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AiaAction { + pub name: String, + pub steps: Vec, + /// Its `/eventCount`, if it has one. + pub declared: Option, +} + +/// An action set read from text. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AiaSet { + pub version: i64, + /// The set's `/name`, if it has one. + pub name: Option, + pub actions: Vec, + /// Its `/actionCount`, if it has one. + pub declared: Option, + /// The tokens that weren't read, with their lines. + pub unread: Vec<(usize, String)>, + /// A cap stopped the reading or cut a name, the text ends inside a block or a value or after a + /// field's name, its counts differ from the actions, steps and recorded values read (a negative + /// count, one too large for an `i64` and one that isn't a number always differ), or a hexadecimal + /// name, label or recorded `/value` isn't as many bytes as its count says. + pub truncated: bool, + /// How many steps were read in all the actions. + steps: usize, +} + +/// A token of the text. +enum Token { + /// A slash name. + Name(Vec), + /// An integer; `None` when it doesn't fit an `i64`. + Int(Option), + /// Text in parentheses, a backslash taking the next byte as it is. + Text(Vec), + /// The bytes of `[ count hex… ]`; `None` when the hexadecimal digits don't make whole bytes or + /// as many bytes as the count says. + Hex(Option>), + /// `< count hex… >`. + Raw, + Open, + Close, + /// Anything else, as written. + Other(Vec), +} + +/// The tokens of `text`, each with its line. +struct Tokens<'a> { + text: &'a [u8], + at: usize, + line: usize, + /// The text ended inside a value in parentheses, square brackets or angle brackets. + unclosed: bool, +} + +impl<'a> Tokens<'a> { + /// Past one byte, counting a line at LF, at CR alone, and once for CRLF. + fn step(&mut self) -> Option { + let b = *self.text.get(self.at)?; + if b == b'\n' || b == b'\r' && self.text.get(self.at + 1) != Some(&b'\n') { + self.line += 1; + } + self.at += 1; + Some(b) + } + + /// The bytes up to `end` (not taken in); `None` when the text ends first. + fn until(&mut self, end: u8) -> Option<&'a [u8]> { + let (text, start) = (self.text, self.at); + while text.get(self.at).is_some_and(|&b| b != end) { + self.step(); + } + let inside = text.get(start..self.at)?; + text.get(self.at)?; + self.at += 1; + Some(inside) + } + + fn next_token(&mut self) -> Option<(usize, Token)> { + while self.text.get(self.at).is_some_and(|&b| b.is_ascii_whitespace() || b == 0) { + self.step(); + } + let line = self.line; + let b = *self.text.get(self.at)?; + let ends = |b: u8| b.is_ascii_whitespace() || b == 0 || b"{}[]()<>/".contains(&b); + let token = match b { + b'{' | b'}' => { + self.at += 1; + if b == b'{' { Token::Open } else { Token::Close } + } + b'(' => { + self.at += 1; + let (mut text, mut depth) = (vec![], 0usize); + self.unclosed = true; + while let Some(c) = self.step() { + match c { + b'\\' => text.extend(self.step()), + b'(' => { + depth += 1; + text.push(c); + } + b')' if depth == 0 => { + self.unclosed = false; + break; + } + b')' => { + depth -= 1; + text.push(c); + } + _ => text.push(c), + } + } + Token::Text(text) + } + b'[' | b'<' => { + self.at += 1; + let close = if b == b'[' { b']' } else { b'>' }; + let inside = self.until(close); + self.unclosed = inside.is_none(); + let inside = inside.unwrap_or_default().to_vec(); + if b == b'<' { + Token::Raw + } else { + // The first word is the byte count; the bytes follow in one or more words. + let mut words = inside.split(|c| c.is_ascii_whitespace()).filter(|w| !w.is_empty()); + let count = words.next().and_then(|w| std::str::from_utf8(w).ok()).and_then(|w| w.parse::().ok()); + let digits: Vec = words.flatten().copied().collect(); + Token::Hex(hex_bytes(&digits).filter(|b| Some(b.len()) == count)) + } + } + b'/' => { + self.at += 1; + let start = self.at; + while self.text.get(self.at).is_some_and(|&c| !ends(c)) { + self.at += 1; + } + Token::Name(self.text.get(start..self.at).unwrap_or_default().to_vec()) + } + _ => { + let start = self.at; + while self.text.get(self.at).is_some_and(|&c| !ends(c)) { + self.at += 1; + } + // Always past at least one byte. + self.at = self.at.max(start + 1); + let word = self.text.get(start..self.at).unwrap_or_default(); + let number = word.strip_prefix(b"-").or_else(|| word.strip_prefix(b"+")).unwrap_or(word); + if !number.is_empty() && number.iter().all(u8::is_ascii_digit) { + Token::Int(std::str::from_utf8(word).ok().and_then(|s| s.parse().ok())) + } else { + Token::Other(word.to_vec()) + } + } + }; + Some((line, token)) + } +} + +/// The bytes hexadecimal `digits` stand for, two digits a byte. +fn hex_bytes(digits: &[u8]) -> Option> { + let nibble = |c: u8| (c as char).to_digit(16).and_then(|d| u8::try_from(d).ok()); + if !digits.len().is_multiple_of(2) { + return None; + } + digits.chunks(2).map(|pair| Some((nibble(*pair.first()?)? << 4) | nibble(*pair.get(1)?)?)).collect() +} + +/// What a block is. +enum Kind { + Action, + Step, + Param, + /// A block that isn't read, or one past a cap. + Other, +} + +/// `name` ends with `-` and a number after `prefix`, as `/action-1` does. +fn numbered(name: &[u8], prefix: &[u8]) -> bool { + name.strip_prefix(prefix).is_some_and(|n| !n.is_empty() && n.iter().all(u8::is_ascii_digit)) +} + +/// A name as text: at most [`MAX_NAME`] bytes, read as UTF-8 with replacement characters. +fn name_text(name: &[u8], set: &mut AiaSet) -> String { + if name.len() > MAX_NAME { + set.truncated = true; + } + let mut s = String::from_utf8_lossy(name.get(..MAX_NAME).unwrap_or(name)).into_owned(); + // A character cut at the limit reads as one replacement character. + if name.len() > MAX_NAME && s.ends_with('\u{FFFD}') { + s.pop(); + } + s +} + +/// How the unread list shows a value in square brackets that isn't as many bytes as its count says. +const BAD_HEX: &str = "[ … ] (not the hexadecimal bytes its count says)"; + +/// List a token that isn't read. +fn unread(set: &mut AiaSet, line: usize, text: impl AsRef<[u8]>) { + if set.unread.len() < MAX_UNREAD { + let text: String = String::from_utf8_lossy(text.as_ref()).chars().take(UNREAD_SHOWN).collect(); + set.unread.push((line, text)); + } +} + +/// What the block `name` that opens on `line` inside the blocks `stack` is: a new action, step or +/// recorded value of `set`, or a block that isn't read (listed when it is out of place). +fn open_block(set: &mut AiaSet, stack: &[Kind], name: &[u8], line: usize) -> Kind { + match stack.last() { + _ if stack.len() >= MAX_DEPTH => { + set.truncated = true; + Kind::Other + } + None if numbered(name, b"action-") => { + if set.actions.len() < MAX_ACTIONS { + set.actions.push(AiaAction::default()); + Kind::Action + } else { + set.truncated = true; + Kind::Other + } + } + Some(Kind::Action) if numbered(name, b"event-") => match set.actions.last_mut() { + Some(a) if a.steps.len() < MAX_STEPS && set.steps < MAX_SET_STEPS => { + a.steps.push(AiaStep { line, ..AiaStep::default() }); + set.steps += 1; + Kind::Step + } + _ => { + set.truncated = true; + Kind::Other + } + }, + Some(Kind::Step) if numbered(name, b"parameter-") => { + if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) { + s.params += 1; + } + Kind::Param + } + Some(Kind::Param | Kind::Other) => Kind::Other, + _ => { + unread(set, line, format!("/{} {{", String::from_utf8_lossy(name))); + Kind::Other + } + } +} + +/// Set the field `name` of the block `kind` (the set when `None`) to the hexadecimal text `bytes` +/// on `line`: the set's or an action's `/name`, or a step's `/localizedName`. +fn set_hex(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, bytes: Option>, line: usize) { + let Some(bytes) = bytes else { + set.truncated = true; + unread(set, line, BAD_HEX); + return; + }; + match (kind, name) { + (None, Some(b"name")) => set.name = Some(name_text(&bytes, set)), + (Some(Kind::Action), Some(b"name")) => { + let text = name_text(&bytes, set); + if let Some(a) = set.actions.last_mut() { + a.name = text; + } + } + (Some(Kind::Step), Some(b"localizedName")) => { + let text = name_text(&bytes, set); + if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) { + s.label = Some(text); + } + } + (_, Some(_)) => {} + (_, None) => unread(set, line, "[ … ]"), + } +} + +/// Mark `set` truncated when the hexadecimal `/value` on `line` isn't as many bytes as its count +/// says. +fn check_value(set: &mut AiaSet, bytes: Option>, line: usize) { + if bytes.is_none() { + set.truncated = true; + unread(set, line, BAD_HEX); + } +} + +/// Mark `set` truncated when the field `name` of the block `kind` (the set when `None`) is a count +/// (the set's `/actionCount`, an action's `/eventCount` or a step's `/parameterCount`) whose value is +/// not a number that fits an `i64`. +fn bad_count(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>) { + if matches!((kind, name), (None, Some(b"actionCount")) | (Some(Kind::Action), Some(b"eventCount")) | (Some(Kind::Step), Some(b"parameterCount"))) + { + set.truncated = true; + } +} + +/// Set the field `name` of the block `kind` (the set when `None`) to the integer `value` on `line`: +/// the set's `/actionCount`, an action's `/eventCount`, a step's `/parameterCount`, or a step's +/// `/isOn`. A count too large for an `i64` marks the set truncated. +fn set_int(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, value: Option, line: usize) { + if value.is_none() { + bad_count(set, kind, name); + } + match (kind, name) { + (None, Some(b"actionCount")) => set.declared = value, + (Some(Kind::Action), Some(b"eventCount")) => { + if let Some(a) = set.actions.last_mut() { + a.declared = value; + } + } + (Some(Kind::Step), Some(b"parameterCount")) => { + if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) { + s.declared = value; + } + } + (Some(Kind::Step), Some(b"isOn")) => { + if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) { + s.on = value; + } + } + (_, Some(_)) => {} + (_, None) => unread(set, line, value.map_or_else(|| "(a number too large)".to_string(), |v| v.to_string())), + } +} + +/// Read an action set saved as text. An error when the text isn't one: it doesn't start with +/// `/version` and an integer. +pub fn read_aia(bytes: &[u8]) -> std::result::Result { + let mut set = AiaSet::default(); + let text = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes); + let text = match text.get(..MAX_BYTES) { + Some(head) if text.len() > MAX_BYTES => { + set.truncated = true; + head + } + _ => text, + }; + let mut tokens = Tokens { text, at: 0, line: 1, unclosed: false }; + match (tokens.next_token(), tokens.next_token()) { + (Some((_, Token::Name(n))), Some((_, Token::Int(Some(v))))) if n == b"version" => set.version = v, + _ => return Err("not an action set: the text doesn't start with /version and a number".into()), + } + let mut stack: Vec = vec![]; + // A slash name waiting for its value or its `{`: (line, name). + let mut pending: Option<(usize, Vec)> = None; + while let Some((line, token)) = tokens.next_token() { + let in_step = matches!(stack.last(), Some(Kind::Step)); + let field = |pending: &mut Option<(usize, Vec)>| pending.take().map(|(_, n)| n); + match token { + Token::Name(name) => { + if let Some((l, n)) = pending.replace((line, name)) { + bad_count(&mut set, stack.last(), Some(&n)); + unread(&mut set, l, [b"/".as_slice(), &n].concat()); + } + } + Token::Open => { + let (l, name) = pending.take().unwrap_or((line, vec![])); + bad_count(&mut set, stack.last(), Some(&name)); + let kind = open_block(&mut set, &stack, &name, l); + stack.push(kind); + } + Token::Close => { + if let Some((l, n)) = pending.take() { + bad_count(&mut set, stack.last(), Some(&n)); + unread(&mut set, l, [b"/".as_slice(), &n].concat()); + } + if stack.pop().is_none() { + unread(&mut set, line, "}"); + } + } + Token::Hex(bytes) if matches!(stack.last(), Some(Kind::Param)) => { + if field(&mut pending).as_deref() == Some(b"value".as_slice()) { + check_value(&mut set, bytes, line); + } + } + // The other values inside a recorded value, or a block that isn't read. + _ if matches!(stack.last(), Some(Kind::Param | Kind::Other)) => { + pending = None; + } + Token::Hex(bytes) => { + let name = field(&mut pending); + bad_count(&mut set, stack.last(), name.as_deref()); + set_hex(&mut set, stack.last(), name.as_deref(), bytes, line); + } + Token::Text(t) => { + let name = field(&mut pending); + bad_count(&mut set, stack.last(), name.as_deref()); + match name { + Some(n) if in_step && n == b"internalName" => { + let name = name_text(&t, &mut set); + if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) { + s.name = name; + } + } + Some(_) => {} + None => unread(&mut set, line, [b"(".as_slice(), &t, b")"].concat()), + } + } + Token::Int(v) => { + let name = field(&mut pending); + set_int(&mut set, stack.last(), name.as_deref(), v, line); + } + Token::Raw => { + let name = field(&mut pending); + bad_count(&mut set, stack.last(), name.as_deref()); + if name.is_none() { + unread(&mut set, line, "< … >"); + } + } + Token::Other(word) => { + // A real number, or another word as a field's value. + let name = field(&mut pending); + bad_count(&mut set, stack.last(), name.as_deref()); + if name.is_none() { + unread(&mut set, line, word); + } + } + } + } + // The text ends after a field's name, before its value. + if let Some((l, n)) = pending { + set.truncated = true; + unread(&mut set, l, [b"/".as_slice(), &n].concat()); + } + // An unclosed value is the last token: it takes the rest of the text. + if tokens.unclosed { + set.truncated = true; + unread(&mut set, tokens.line, "a value not closed at the end"); + } + if !stack.is_empty() { + set.truncated = true; + unread(&mut set, tokens.line, format!("blocks left open at the end: {}", stack.len())); + } + // Not as many actions, steps or recorded values as the counts give; a negative count never matches. + let differs = |declared: Option, read: usize| declared.is_some_and(|d| !usize::try_from(d).is_ok_and(|d| d == read)); + let step_differs = |a: &AiaAction| a.steps.iter().any(|s| differs(s.declared, s.params)); + if differs(set.declared, set.actions.len()) || set.actions.iter().any(|a| differs(a.declared, a.steps.len()) || step_differs(a)) { + set.truncated = true; + unread(&mut set, tokens.line, "not as many actions, steps or recorded values as the counts give"); + } + Ok(set) +} + +fn read(_: &mut Session, p: &Value) -> Result { + const C: &str = "actionSet.read"; + let (path, data, b64) = (text_param(p, "path", C)?, text_param(p, "data", C)?, text_param(p, "dataBase64", C)?); + let name = text_param(p, "name", C)?; + let bytes: std::borrow::Cow<[u8]> = match (path, data, b64) { + (Some(path), None, None) => super::fileio::read_file_head(path, READ_LIMIT)?.into(), + (None, Some(text), None) => text.as_bytes().get(..READ_LIMIT).unwrap_or(text.as_bytes()).into(), + (None, None, Some(b64)) => super::scripts::decode_head(b64, READ_LIMIT).ok_or_else(|| bad(C, "bad dataBase64"))?.into(), + _ => return Err(bad(C, "give exactly one of `path`, `data` and `dataBase64`")), + }; + let set = read_aia(&bytes).map_err(EngineError::Other)?; + let file = name.or(path).unwrap_or_default(); + let stem = std::path::Path::new(file).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let name = set.name.clone().filter(|n| !n.trim().is_empty()).unwrap_or(stem); + let actions: Vec = set + .actions + .iter() + .map(|a| { + let steps: Vec = a + .steps + .iter() + .map(|s| { + let label = s.label.clone().filter(|l| !l.trim().is_empty()); + json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "line": s.line }) + }) + .collect(); + json!({ "name": a.name, "steps": steps }) + }) + .collect(); + Ok(json!({ + "set": name, + "version": set.version, + "actions": actions, + "unread": set.unread.iter().map(|(line, text)| json!({ "line": line, "text": text })).collect::>(), + "truncated": set.truncated, + })) +} diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs new file mode 100644 index 0000000000..324d7bde58 --- /dev/null +++ b/crates/engine/src/cmd/addons.rs @@ -0,0 +1,30 @@ +//! VectorCraft's built-in add-ons: extra tools beyond the standard menus, each a module of its own +//! with commands under `addon..*` (see `docs/mcp.md`). + +mod arrange; +mod cleanup; +mod color; +mod contour; +mod document; +mod pathtools; +mod pen; +mod select; +mod shapes; +mod typetools; + +use super::CommandSpec; + +/// The commands of every built-in add-on. +pub fn specs() -> Vec { + let mut v = arrange::specs(); + v.extend(cleanup::specs()); + v.extend(color::specs()); + v.extend(contour::specs()); + v.extend(document::specs()); + v.extend(pathtools::specs()); + v.extend(pen::specs()); + v.extend(select::specs()); + v.extend(shapes::specs()); + v.extend(typetools::specs()); + v +} diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs new file mode 100644 index 0000000000..735d721335 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -0,0 +1,535 @@ +//! Arrange Tools (`addon.arrange.*`), a built-in add-on: Arrange in Grid lays the selected objects +//! out in rows and columns, a row or a column; Swap Objects swaps the places (and sizes) of two; +//! Replace with Top Object puts a copy of the topmost selected object in place of each of the +//! others; and Set Size of Each gives every selected object an exact width and height. Places and +//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the +//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random +//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in +//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection +//! (a view command) are the UI's. + +#[cfg(test)] +mod tests; + +use std::collections::HashMap; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::recolor::Rng; +use vectorcraft_doc::{Node, NodeId, OrientedBox}; +use vectorcraft_geom::{Affine, Point, Rect}; +use vectorcraft_render::effects; + +use super::super::edit::selected_roots; +use super::super::menucmds::whole_or; +use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns}; +use super::super::typecmd::refresh_bounds_of; +use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_multi, has_selection, number_or, switch_or}; +use crate::{EngineError, Result, Session}; + +/// The largest gap, width or height (pt) the commands take. +const LIMIT: f64 = 1e6; +/// The smallest width or height (pt) Set Size of Each takes. +const LEAST: f64 = 0.001; +/// The most columns Arrange in Grid takes. +const MAX_COLUMNS: u64 = 10_000; +/// The most objects Group Overlapping Objects and Sort Objects look at. +const MAX_OBJECTS: usize = 20_000; +/// The attributes Sort Objects sorts by and gives (`addon.arrange.sort`). +pub const SORT_KEYS: [&str; 7] = ["width", "height", "area", "x", "y", "opacity", "stacking"]; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.arrange.grid", + "Arrange in Grid", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{layout?: \"grid\" (rows and columns) | \"row\" (one row) | \"column\" (one column), columns?: 1..10000 (grid; default ⌈√count⌉; never more than the count), gapX?: pt −1000000..1000000 (10), gapY?: pt −1000000..1000000 (gapX), centerOnArtboard?: false (true: the grid is centred on the artboard under the selection's centre, else the first; false: it starts at the selection's top-left)} lay the selected objects (the top-level ones) out in their stacking order from the back, left to right and top to bottom, as one undo step. Each cell is as wide as the widest object in its column and as tall as the tallest in its row, each object is centred in its cell, and everything is measured by visual bounds (strokes and effects as drawn) → {count}", + has_selection, + grid + ), + cmd!( + "addon.arrange.swap", + "Swap Objects", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected", + exactly_two, + swap + ), + cmd!( + "addon.arrange.replace", + "Replace with Top Object", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}", + has_multi, + replace + ), + cmd!( + "addon.arrange.size", + "Set Size of Each", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}", + has_selection, + size + ), + cmd!( + "addon.arrange.groupOverlapping", + "Group Overlapping Objects", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{} group the selected objects (the top-level ones, at most 20000) wherever their visual bounds overlap or touch, chains included (when A overlaps B and B overlaps C, all three go in one group), as one undo step. Only objects in the same layer or group are grouped together, objects that overlap nothing stay as they are, and each new group goes where its frontmost member was in the stacking order; the new groups and the objects left alone stay selected → {groups: [id…], grouped (how many objects went into groups)}", + has_multi, + group_overlapping + ), + cmd!( + "addon.arrange.randomizeOpacity", + "Randomize Opacity", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it → {count}", + has_selection, + randomize_opacity + ), + cmd!( + "addon.arrange.sort", + "Sort Objects", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. A run that changes nothing makes no step → {count}", + has_multi, + sort + ), + ] +} + +/// Exactly two objects are selected (Swap Objects). +fn exactly_two(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + let n = selected_roots(s).map_err(|e| e.to_string())?.len(); + if n == 2 { Ok(()) } else { Err("select exactly two objects".into()) } +} + +/// Number param `key` (`default` when left out) within `lo..=hi`. +fn number_in(p: &Value, key: &str, default: f64, (lo, hi): (f64, f64), cmd: &str) -> Result { + let v = number_or(p, key, default, cmd)?; + if (lo..=hi).contains(&v) { Ok(v) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } +} + +/// Whole-number param `key` within `lo..=hi`, `None` when left out. +pub(super) fn whole_in(p: &Value, key: &str, (lo, hi): (u64, u64), cmd: &str) -> Result> { + let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) }; + let n = v.as_u64().ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number")))?; + if (lo..=hi).contains(&n) { Ok(Some(n)) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } +} + +/// A width or height param of Set Size of Each, `None` when left out. +fn size_param(p: &Value, key: &str, cmd: &str) -> Result> { + p.get(key).filter(|v| !v.is_null()).map(|_| number_in(p, key, 0.0, (LEAST, LIMIT), cmd)).transpose() +} + +/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes` +/// and, when given, a width and height. +fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value { + let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes }); + if let Some((w, h)) = size { + q["width"] = json!(w); + q["height"] = json!(h); + } + q +} + +/// Transform each object of `xfs` by its own transform as undo step `label`, strokes and effects +/// scaling with Scale Strokes & Effects `strokes`, pattern tiles as Transform Pattern Tiles says. +/// When every transform is (within rounding) the identity, nothing changes. +fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, Affine)]) -> Result<()> { + let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9); + if xfs.iter().all(|(_, xf)| still(xf)) { + return Ok(()); + } + let p = json!({ "strokes": strokes }); + let ids: Vec = xfs.iter().map(|(id, _)| *id).collect(); + let mut sc = scaling(s, &p); + sc.patterns = transform_patterns(s, &p, &ids)?; + s.edit(label, |d, _| { + for (id, xf) in xfs { + if let Some(n) = d.node_mut(*id) { + transform_node(n, *xf, sc, true); + } + } + Ok(()) + }) +} + +/// The box of object `id` as `object.setBounds` measures it. +fn box_of(s: &Session, id: NodeId) -> Result { + s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into())) +} + +fn grid(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.grid"; + let layout = choice(p, C, "layout", &["grid", "row", "column"])?.unwrap_or("grid"); + let columns = whole_in(p, "columns", (1, MAX_COLUMNS), C)?; + let gap_x = number_in(p, "gapX", 10.0, (-LIMIT, LIMIT), C)?; + let gap_y = number_in(p, "gapY", gap_x, (-LIMIT, LIMIT), C)?; + let center = switch_or(p, "centerOnArtboard", false, C)?; + let roots = selected_roots(s)?; + let d = &s.doc()?.doc; + let items: Vec<(NodeId, Rect)> = roots.iter().filter_map(|id| Some((*id, effects::preview::bounds_of(d, &[*id], true)?))).collect(); + let Some(all) = items.iter().map(|(_, b)| *b).reduce(|a, b| a.union(b)) else { return Ok(json!({ "count": 0 })) }; + let n = items.len(); + let cols = match layout { + "row" => n, + "column" => 1, + _ => columns.map_or_else(|| (n as f64).sqrt().ceil() as usize, |c| usize::try_from(c).unwrap_or(n)), + } + .clamp(1, n); + let mut widths = vec![0.0_f64; cols]; + let mut heights = vec![0.0_f64; n.div_ceil(cols)]; + for (i, (_, b)) in items.iter().enumerate() { + if let Some(w) = widths.get_mut(i % cols) { + *w = w.max(b.width()); + } + if let Some(h) = heights.get_mut(i / cols) { + *h = h.max(b.height()); + } + } + let total = |sizes: &[f64], gap: f64| sizes.iter().sum::() + gap * sizes.len().saturating_sub(1) as f64; + let origin = if center { + let board = d.artboards.get(d.artboard_at(all.center()).unwrap_or(0)).map_or(all, |a| a.rect); + Point::new(board.center().x - total(&widths, gap_x) / 2.0, board.center().y - total(&heights, gap_y) / 2.0) + } else { + Point::new(all.x0, all.y0) + }; + // The middle of each column (row): the sizes and gaps before it, and half its own size. + let middles = |sizes: &[f64], gap: f64, from: f64| -> Vec { + sizes + .iter() + .scan(from, |at, size| { + let mid = *at + size / 2.0; + *at += size + gap; + Some(mid) + }) + .collect() + }; + let (xs, ys) = (middles(&widths, gap_x, origin.x), middles(&heights, gap_y, origin.y)); + let xfs: Vec<(NodeId, Affine)> = items + .iter() + .enumerate() + .filter_map(|(i, (id, b))| Some((*id, Affine::translate(Point::new(*xs.get(i % cols)?, *ys.get(i / cols)?) - b.center())))) + .collect(); + transform_each(s, "Arrange in Grid", false, &xfs)?; + Ok(json!({ "count": n })) +} + +fn swap(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.swap"; + let size = switch_or(p, "size", false, C)?; + let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let roots = selected_roots(s)?; + let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) }; + let (ba, bb) = (box_of(s, a)?, box_of(s, b)?); + let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes); + let xfs = [(a, object_bounds_transform(s, &to(&bb), a)?), (b, object_bounds_transform(s, &to(&ba), b)?)]; + transform_each(s, "Swap Objects", strokes, &xfs)?; + Ok(json!({})) +} + +fn replace(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.replace"; + let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep"); + let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let keep = switch_or(p, "keep", false, C)?; + let roots = selected_roots(s)?; + let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else { + return Err(bad(C, "select at least two objects")); + }; + let tb = box_of(s, top)?; + let (tw, th) = (tb.rect.width(), tb.rect.height()); + let mut xfs = Vec::with_capacity(others.len()); + for &id in others { + let Some(b) = s.transform_box(&[id]) else { continue }; + let (w, h) = (b.rect.width(), b.rect.height()); + let size = match fit { + "bounds" => Some((w, h)), + // The smaller of the two scales that fit; a side the copy doesn't have doesn't count. + "proportional" => { + [(w, tw), (h, th)].into_iter().filter(|(_, t)| *t > 1e-9).map(|(v, t)| v / t).reduce(f64::min).map(|k| (tw * k, th * k)) + } + _ => None, + }; + xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes), top)?)); + } + let p = json!({ "strokes": strokes }); + let mut sc = scaling(s, &p); + sc.patterns = transform_patterns(s, &p, &[top])?; + let ids = s.edit("Replace with Top Object", |d, sel| { + let Some(n) = d.node(top).cloned() else { return Ok(vec![]) }; + let mut items = Vec::with_capacity(xfs.len()); + for (id, xf) in &xfs { + let mut c = d.reid(&n); + transform_node(&mut c, *xf, sc, true); + items.push((*id, vec![c])); + } + let out: Vec = items.iter().flat_map(|(_, c)| c.iter().map(|n| n.id)).collect(); + d.insert_beside(items, !keep)?; + refresh_bounds_of(d, &out); + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) +} + +fn size(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.size"; + let width = size_param(p, "width", C)?; + let height = size_param(p, "height", C)?; + if width.is_none() && height.is_none() { + return Err(bad(C, "give `width` or `height`")); + } + let proportional = switch_or(p, "proportional", false, C)?; + let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4); + let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) }); + if let Some(w) = width { + q["width"] = json!(w); + } + if let Some(h) = height { + q["height"] = json!(h); + } + let mut xfs = vec![]; + for id in selected_roots(s)? { + if s.transform_box(&[id]).is_some() { + xfs.push((id, object_bounds_transform(s, &q, id)?)); + } + } + transform_each(s, "Set Size of Each", strokes, &xfs)?; + Ok(json!({ "count": xfs.len() })) +} + +/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch, +/// chains included, among items of the same key (parent). A sweep along x: only the rects still +/// open where each one starts are compared with it. +fn overlapping(items: &[(K, Rect)]) -> Vec> { + fn root(up: &mut [usize], mut i: usize) -> usize { + while up[i] != i { + up[i] = up[up[i]]; + i = up[i]; + } + i + } + let mut up: Vec = (0..items.len()).collect(); + let mut order: Vec = (0..items.len()).collect(); + order.sort_by(|a, b| items[*a].1.x0.total_cmp(&items[*b].1.x0)); + let mut open: Vec = vec![]; + for i in order { + let (key, r) = (&items[i].0, items[i].1); + open.retain(|&j| items[j].1.x1 >= r.x0); + for &j in &open { + let (k, o) = (&items[j].0, items[j].1); + if k == key && o.y0 <= r.y1 && r.y0 <= o.y1 { + let (a, b) = (root(&mut up, i), root(&mut up, j)); + up[a] = b; + } + } + open.push(i); + } + let mut sets: Vec> = vec![vec![]; items.len()]; + for i in 0..items.len() { + let r = root(&mut up, i); + sets[r].push(i); + } + sets.retain(|s| s.len() > 1); + sets.sort_by_key(|s| s.first().copied()); + sets +} + +fn group_overlapping(s: &mut Session, _: &Value) -> Result { + const C: &str = "addon.arrange.groupOverlapping"; + let roots = selected_roots(s)?; + if roots.len() > MAX_OBJECTS { + return Err(bad(C, "too many objects selected (at most 20000)")); + } + let d = &s.doc()?.doc; + let items: Vec<(NodeId, (Option, Rect))> = + roots.iter().filter_map(|id| Some((*id, (d.parent_of(*id), effects::preview::bounds_of(d, &[*id], true)?)))).collect(); + let keyed: Vec<(Option, Rect)> = items.iter().map(|(_, k)| *k).collect(); + let sets: Vec> = overlapping(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect(); + if sets.is_empty() { + return Ok(json!({ "groups": [], "grouped": 0 })); + } + let grouped: std::collections::HashSet = sets.iter().flatten().copied().collect(); + let groups = s.edit("Group Overlapping Objects", |d, sel| { + // Every group at once: the members behind each front one go, then each front one is + // replaced by its group (one pass over the tree each, however many groups). + let (mut places, mut behind, mut groups) = (vec![], vec![], vec![]); + for set in &sets { + let Some((&front, rest)) = set.split_last() else { continue }; + let children: Vec> = set.iter().filter_map(|id| d.node(*id).cloned().map(Arc::new)).collect(); + let gid = d.alloc_id(); + places.push((front, vec![Node::group(gid, children)])); + behind.extend_from_slice(rest); + groups.push(gid); + } + d.remove_many(&behind)?; + d.insert_beside(places, true)?; + sel.set(groups.iter().copied().chain(roots.iter().copied().filter(|id| !grouped.contains(id)))); + Ok(groups) + })?; + Ok(json!({ "groups": groups.iter().map(|i| i.0).collect::>(), "grouped": grouped.len() })) +} + +fn randomize_opacity(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.randomizeOpacity"; + let min = number_in(p, "min", 30.0, (0.0, 100.0), C)?; + let max = number_in(p, "max", 100.0, (0.0, 100.0), C)?; + if min > max { + return Err(bad(C, "`min` is greater than `max`")); + } + let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); + let ids = checked_ids_or_selection(s, p, C)?; + if ids.is_empty() { + return Ok(json!({ "count": 0 })); + } + let (lo, hi) = ((min / 100.0) as f32, (max / 100.0) as f32); + s.edit("Randomize Opacity", |d, _| { + for id in &ids { + let o = rng.range(lo, hi); + if let Some(n) = d.node_mut(*id) { + n.opacity = o; + } + } + Ok(()) + })?; + Ok(json!({ "count": ids.len() })) +} + +/// An object Sort Objects sorts: its layer or group, its place in it, its box as +/// `object.setBounds` measures it and its opacity (%). +struct Sorted { + id: NodeId, + parent: Option, + slot: usize, + b: OrientedBox, + opacity: f64, +} + +/// Attribute `key` (one of [`SORT_KEYS`]) of `o`, the `i`th of the objects in stacking order. +fn attribute(key: &str, o: &Sorted, i: usize) -> f64 { + let r = o.b.rect; + // The top-left corner where `object.setBounds` places it (reference point 0). + let corner = o.b.to_doc() * Point::new(r.x0, r.y0); + match key { + "width" => r.width(), + "height" => r.height(), + "area" => r.width() * r.height(), + "x" => corner.x, + "y" => corner.y, + "opacity" => o.opacity, + _ => i as f64, + } +} + +fn sort(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.sort"; + let by = choice(p, C, "by", &SORT_KEYS)?.unwrap_or("area"); + let apply = choice(p, C, "apply", &SORT_KEYS)?.unwrap_or("stacking"); + let order = choice(p, C, "order", &["ascending", "descending", "random"])?.unwrap_or("ascending"); + let distribute = switch_or(p, "distribute", false, C)?; + let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); + let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let ids = checked_ids_or_selection(s, p, C)?; + if ids.len() > MAX_OBJECTS { + return Err(bad(C, "too many objects selected (at most 20000)")); + } + let d = &s.doc()?.doc; + // The objects in stacking order, from the back (their index paths, found in one walk). + let paths = d.index_paths(ids.iter().copied()); + let mut placed: Vec<(&Vec, NodeId)> = ids.iter().filter_map(|id| Some((paths.get(id)?, *id))).collect(); + placed.sort_by(|a, b| a.0.cmp(b.0)); + let items: Vec = placed + .into_iter() + .filter_map(|(path, id)| { + let (&slot, up) = path.split_last()?; + let parent = if up.is_empty() { None } else { Some(d.node_at(up)?.id) }; + Some(Sorted { id, parent, slot, b: s.transform_box(&[id])?, opacity: f64::from(d.node(id)?.opacity) * 100.0 }) + }) + .collect(); + let keys: Vec = items.iter().enumerate().map(|(i, o)| attribute(by, o, i)).collect(); + // The objects in sorted order; equal keys keep their stacking order. + let mut rank: Vec = (0..items.len()).collect(); + match order { + "random" => rng.shuffle(&mut rank), + "descending" => rank.sort_by(|a, b| keys[*b].total_cmp(&keys[*a])), + _ => rank.sort_by(|a, b| keys[*a].total_cmp(&keys[*b])), + } + let count = json!({ "count": items.len() }); + if apply == "stacking" { + // Each layer or group's objects take its objects' places, from the back, in sorted order. + let mut groups: HashMap, Vec> = HashMap::new(); + for o in rank.iter().filter_map(|i| items.get(*i)) { + groups.entry(o.parent).or_default().push(o.slot); + } + if groups.values().all(|slots| slots.is_sorted()) { + return Ok(count); + } + s.edit("Sort Objects", |d, _| { + for (parent, from) in groups { + let ch = d.children_mut(parent)?; + let nodes: Vec> = from.iter().filter_map(|i| ch.get(*i).cloned()).collect(); + let mut to = from; + to.sort_unstable(); + for (slot, n) in to.into_iter().zip(nodes) { + if let Some(c) = ch.get_mut(slot) { + *c = n; + } + } + } + Ok(()) + })?; + return Ok(count); + } + // The values the objects get, smallest first: theirs, or evenly from the smallest to the largest. + let mut values: Vec = items.iter().enumerate().map(|(i, o)| attribute(apply, o, i)).collect(); + values.sort_by(f64::total_cmp); + if let (true, Some(&lo), Some(&hi)) = (distribute && values.len() > 1, values.first(), values.last()) { + let steps = (values.len() - 1) as f64; + values = (0..values.len()).map(|j| lo + (hi - lo) * j as f64 / steps).collect(); + } + let wanted: Vec<(&Sorted, f64)> = rank.iter().filter_map(|i| items.get(*i)).zip(values).collect(); + if apply == "opacity" { + if wanted.iter().all(|(o, v)| (o.opacity - v).abs() < 1e-6) { + return Ok(count); + } + s.edit("Sort Objects", |d, _| { + for (o, v) in &wanted { + if let Some(n) = d.node_mut(o.id) { + n.opacity = (v / 100.0) as f32; + } + } + Ok(()) + })?; + return Ok(count); + } + let mut xfs = Vec::with_capacity(wanted.len()); + for (o, v) in wanted { + let q = match apply { + "x" => json!({ "x": v, "reference": 0 }), + "y" => json!({ "y": v, "reference": 0 }), + "width" => json!({ "width": v, "strokes": strokes }), + "height" => json!({ "height": v, "strokes": strokes }), + // An area: both sides in proportion; an object without one keeps its size. + _ => { + let (w, h) = (o.b.rect.width(), o.b.rect.height()); + let k = if w * h > 1e-12 { (v / (w * h)).sqrt() } else { 1.0 }; + json!({ "width": w * k, "height": h * k, "strokes": strokes }) + } + }; + xfs.push((o.id, object_bounds_transform(s, &q, o.id)?)); + } + transform_each(s, "Sort Objects", strokes, &xfs)?; + Ok(count) +} diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs new file mode 100644 index 0000000000..85191935b2 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -0,0 +1,564 @@ +//! Arrange Tools' commands: the geometry each one leaves, one undo step each, when they are off, +//! and bad params refused without a change. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::Rect; + +use crate::Session; + +/// A new document whose new art has no stroke, so visual and geometric bounds agree. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap() +} + +fn near(a: Rect, b: (f64, f64, f64, f64)) -> bool { + [(a.x0, b.0), (a.y0, b.1), (a.width(), b.2), (a.height(), b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-6) +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// Each of `bad` is refused and leaves the document as it was. +fn refuses(s: &mut Session, cmd: &str, bad: &[Value]) { + let (before, n) = (s.doc().unwrap().doc.clone(), steps(s)); + for p in bad { + assert!(s.execute(cmd, p).is_err(), "{cmd} {p}"); + } + assert_eq!(steps(s), n, "{cmd}"); + assert!(*s.doc().unwrap().doc == *before, "{cmd} changed the document"); +} + +fn enabled(s: &Session, cmd: &str) -> bool { + s.commands().into_iter().find(|c| c.id == cmd).unwrap().enabled +} + +#[test] +fn grid_lays_objects_out_in_rows_and_columns_from_the_back() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 20.0, 10.0); + let b = rect(&mut s, 300.0, 50.0, 40.0, 30.0); + let c = rect(&mut s, 10.0, 200.0, 10.0, 10.0); + let d = rect(&mut s, 50.0, 5.0, 30.0, 20.0); + select(&mut s, &[d, c, b, a]); + let n = steps(&s); + // Four objects: two columns. The grid starts at the selection's top-left (10, 5). + let r = s.execute("addon.arrange.grid", &json!({"gapX": 5, "gapY": 2})).unwrap(); + assert_eq!(r["count"], json!(4)); + assert_eq!(steps(&s), n + 1, "one undo step"); + // Columns 20 and 40 wide (the widest in each), rows 30 and 20 tall; each object centred. + assert!(near(bounds(&s, a), (10.0, 15.0, 20.0, 10.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (35.0, 5.0, 40.0, 30.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (15.0, 42.0, 10.0, 10.0)), "{:?}", bounds(&s, c)); + assert!(near(bounds(&s, d), (40.0, 37.0, 30.0, 20.0)), "{:?}", bounds(&s, d)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(near(bounds(&s, a), (100.0, 100.0, 20.0, 10.0))); +} + +#[test] +fn grid_lays_out_a_row_or_a_column_and_centres_on_the_artboard() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 100.0, 100.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("addon.arrange.grid", &json!({"layout": "row"})).unwrap(); + assert!(near(bounds(&s, b), (30.0, 0.0, 20.0, 20.0)), "gapX defaults to 10"); + s.execute("addon.arrange.grid", &json!({"layout": "column", "gapX": 4})).unwrap(); + assert!(near(bounds(&s, b), (0.0, 24.0, 20.0, 20.0)), "gapY follows gapX"); + // 20 × 44 centred on the 400 × 300 artboard. + s.execute("addon.arrange.grid", &json!({"layout": "column", "gapY": 4, "centerOnArtboard": true})).unwrap(); + assert!(near(bounds(&s, a), (190.0, 128.0, 20.0, 20.0)), "{:?}", bounds(&s, a)); + // In place already: no step. + let n = steps(&s); + s.execute("addon.arrange.grid", &json!({"layout": "column", "gapY": 4, "centerOnArtboard": true})).unwrap(); + assert_eq!(steps(&s), n); + // More columns than objects: one row. + s.execute("addon.arrange.grid", &json!({"columns": 50, "gapX": 0})).unwrap(); + assert!(near(bounds(&s, b), (210.0, 128.0, 20.0, 20.0)), "{:?}", bounds(&s, b)); +} + +#[test] +fn grid_measures_visual_bounds() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + s.execute("addon.arrange.grid", &json!({"layout": "row", "gapX": 0})).unwrap(); + // Visual boxes 24 wide, touching. + assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b)); +} + +#[test] +fn swap_trades_places_and_optionally_sizes() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + let c = rect(&mut s, 200.0, 200.0, 5.0, 5.0); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.swap")); + select(&mut s, &[a, b, c]); + assert!(!enabled(&s, "addon.arrange.swap")); + refuses(&mut s, "addon.arrange.swap", &[json!({})]); + select(&mut s, &[a, b]); + assert!(enabled(&s, "addon.arrange.swap")); + let n = steps(&s); + s.execute("addon.arrange.swap", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1); + // Centres (10, 5) and (120, 120) swap; sizes stay. + assert!(near(bounds(&s, a), (110.0, 115.0, 20.0, 10.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (-10.0, -15.0, 40.0, 40.0)), "{:?}", bounds(&s, b)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.swap", &json!({"size": true})).unwrap(); + assert!(near(bounds(&s, a), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (0.0, 0.0, 20.0, 10.0)), "{:?}", bounds(&s, b)); +} + +#[test] +fn swap_with_sizes_scales_strokes_as_asked() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 2})).unwrap(); + let weight = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width(); + s.execute("addon.arrange.swap", &json!({"size": true})).unwrap(); + assert_eq!((weight(&s, a), weight(&s, b)), (2.0, 2.0), "off by default (the preference)"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.swap", &json!({"size": true, "scaleStrokes": true})).unwrap(); + assert!((weight(&s, a) - 4.0).abs() < 1e-9 && (weight(&s, b) - 1.0).abs() < 1e-9, "{} {}", weight(&s, a), weight(&s, b)); +} + +#[test] +fn replace_puts_a_copy_of_the_top_object_in_each_place() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + let top = rect(&mut s, 200.0, 200.0, 10.0, 5.0); + select(&mut s, &[top]); + assert!(!enabled(&s, "addon.arrange.replace")); + refuses(&mut s, "addon.arrange.replace", &[json!({})]); + select(&mut s, &[a, b, top]); + let n = steps(&s); + let r = s.execute("addon.arrange.replace", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(ids.len(), 2); + let st = s.doc().unwrap(); + assert!(st.doc.node(a).is_none() && st.doc.node(b).is_none(), "replaced objects deleted"); + assert!(st.doc.node(top).is_some(), "the top object stays"); + assert_eq!(st.selection.objects, ids, "the copies are selected"); + // Kept size, centred on (10, 20) and (120, 120); each in its object's place (bottom, then middle). + assert!(near(bounds(&s, ids[0]), (5.0, 17.5, 10.0, 5.0)), "{:?}", bounds(&s, ids[0])); + assert!(near(bounds(&s, ids[1]), (115.0, 117.5, 10.0, 5.0)), "{:?}", bounds(&s, ids[1])); + let layer = &s.doc().unwrap().doc.layers[0]; + let order: Vec = layer.children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(order, [ids[0], ids[1], top]); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(a).is_some()); +} + +#[test] +fn replace_fits_the_copies_and_can_keep_the_originals() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0); + let top = rect(&mut s, 200.0, 200.0, 10.0, 5.0); + select(&mut s, &[a, top]); + let r = s.execute("addon.arrange.replace", &json!({"fit": "bounds", "keep": true})).unwrap(); + let copy = NodeId(r["ids"][0].as_u64().unwrap()); + assert!(near(bounds(&s, copy), (0.0, 0.0, 20.0, 40.0)), "{:?}", bounds(&s, copy)); + let order: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(order, [a, copy, top], "kept: the copy goes right above it"); + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[a, top]); + let r = s.execute("addon.arrange.replace", &json!({"fit": "proportional"})).unwrap(); + let copy = NodeId(r["ids"][0].as_u64().unwrap()); + // 10 × 5 into 20 × 40: twice as large, centred on (10, 20). + assert!(near(bounds(&s, copy), (0.0, 15.0, 20.0, 10.0)), "{:?}", bounds(&s, copy)); +} + +#[test] +fn size_gives_each_object_a_width_and_height() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + select(&mut s, &[a, b]); + let n = steps(&s); + s.execute("addon.arrange.size", &json!({"width": 30})).unwrap(); + assert_eq!(steps(&s), n + 1); + // About each centre; the height stays. + assert!(near(bounds(&s, a), (-5.0, 0.0, 30.0, 10.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (105.0, 100.0, 30.0, 40.0)), "{:?}", bounds(&s, b)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.size", &json!({"width": 40, "proportional": true, "reference": 0})).unwrap(); + assert!(near(bounds(&s, a), (0.0, 0.0, 40.0, 20.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, b)); + s.execute("addon.arrange.size", &json!({"width": 10, "height": 12, "proportional": true, "reference": 8})).unwrap(); + assert!(near(bounds(&s, a), (30.0, 8.0, 10.0, 12.0)), "both given: both set, {:?}", bounds(&s, a)); +} + +#[test] +fn bad_params_are_refused() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + select(&mut s, &[a, b]); + refuses( + &mut s, + "addon.arrange.grid", + &[ + json!({"layout": "spiral"}), + json!({"columns": 0}), + json!({"columns": 1.5}), + json!({"columns": 1e12}), + json!({"gapX": 1e308}), + json!({"gapY": "10"}), + json!({"centerOnArtboard": "yes"}), + ], + ); + refuses(&mut s, "addon.arrange.swap", &[json!({"size": 1}), json!({"scaleStrokes": "no"})]); + refuses(&mut s, "addon.arrange.replace", &[json!({"fit": "stretch"}), json!({"keep": 0})]); + refuses( + &mut s, + "addon.arrange.size", + &[ + json!({}), + json!({"width": 0}), + json!({"height": -5}), + json!({"width": 1e308}), + json!({"width": "10"}), + json!({"width": 10, "reference": 9}), + json!({"width": 10, "proportional": "yes"}), + ], + ); +} + +#[test] +fn off_without_a_selection() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 20.0, 10.0); + s.execute("select.none", &json!({})).unwrap(); + for c in [ + "addon.arrange.grid", + "addon.arrange.swap", + "addon.arrange.replace", + "addon.arrange.size", + "addon.arrange.groupOverlapping", + "addon.arrange.randomizeOpacity", + "addon.arrange.sort", + ] { + assert!(!enabled(&s, c), "{c}"); + } + assert!(!enabled(&Session::new(), "addon.arrange.swap")); +} + +fn ids_of(v: &Value) -> Vec { + v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +fn children(s: &Session, id: NodeId) -> Vec { + s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn group_overlapping_groups_chains_and_leaves_loners() { + let mut s = session(); + // a–b–c a chain (c only touches b), d alone, e over f. + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0); + let e = rect(&mut s, 100.0, 100.0, 30.0, 30.0); + let c = rect(&mut s, 35.0, 0.0, 10.0, 20.0); + let f = rect(&mut s, 110.0, 110.0, 5.0, 5.0); + select(&mut s, &[a, b, c, d, e, f]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupOverlapping", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(r["grouped"], json!(5)); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 2); + assert_eq!(children(&s, groups[0]), [a, b, c], "members keep their stacking order"); + assert_eq!(children(&s, groups[1]), [e, f]); + // Each group where its frontmost member was: a d [abc] [ef] → d, group(abc) above it, then (ef). + let layer: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(layer, [d, groups[0], groups[1]]); + let sel = &s.doc().unwrap().selection.objects; + assert!(sel.contains(&groups[0]) && sel.contains(&groups[1]) && sel.contains(&d) && sel.len() == 3, "{sel:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 6); +} + +#[test] +fn group_overlapping_keeps_layers_apart_and_measures_visual_bounds() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let gap = rect(&mut s, 22.0, 0.0, 20.0, 20.0); + s.execute("layer.new", &json!({})).unwrap(); + let other = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + select(&mut s, &[a, gap, other]); + // 2 pt apart: nothing overlaps within a layer, and a and `other` are in different layers. + let n = steps(&s); + let r = s.execute("addon.arrange.groupOverlapping", &json!({})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "no groups, no step"); + // A 4 pt stroke reaches 2 pt out: the two in the first layer now touch. + select(&mut s, &[a, gap]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + select(&mut s, &[a, gap, other]); + let r = s.execute("addon.arrange.groupOverlapping", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [a, gap]); + let doc = &s.doc().unwrap().doc; + assert_ne!(doc.layer_of(other), doc.layer_of(a), "left in its own layer"); +} + +#[test] +fn group_overlapping_is_off_with_one_object_and_scales_to_many() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.groupOverlapping")); + // A long row of pairs: each pair overlaps, neighbouring pairs don't. + let rects: Vec<(usize, Rect)> = + (0..4000).map(|i| (0, Rect::new(i as f64 * 10.0, 0.0, i as f64 * 10.0 + if i % 2 == 0 { 12.0 } else { 3.0 }, 5.0))).collect(); + let sets = super::overlapping(&rects); + assert_eq!(sets.len(), 2000); + assert!(sets.iter().all(|s| s.len() == 2 && s[1] == s[0] + 1)); +} + +fn opacity(s: &Session, id: NodeId) -> f32 { + s.doc().unwrap().doc.node(id).unwrap().opacity +} + +#[test] +fn randomize_opacity_gives_each_object_its_own_opacity_within_the_range() { + let mut s = session(); + let ids: Vec = (0..20).map(|i| rect(&mut s, i as f64 * 10.0, 0.0, 5.0, 5.0)).collect(); + select(&mut s, &ids); + let n = steps(&s); + let r = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 7})).unwrap(); + assert_eq!(r["count"], json!(20)); + assert_eq!(steps(&s), n + 1, "one undo step"); + let first: Vec = ids.iter().map(|id| opacity(&s, *id)).collect(); + assert!(first.iter().all(|o| (0.3..=0.6).contains(o)), "{first:?}"); + assert!(first.windows(2).any(|w| w[0] != w[1]), "each its own: {first:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(ids.iter().all(|id| opacity(&s, *id) == 1.0), "undone"); + // The same seed repeats them; another seed doesn't. + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 7})).unwrap(); + assert_eq!(ids.iter().map(|id| opacity(&s, *id)).collect::>(), first); + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 30, "max": 60, "seed": 8})).unwrap(); + assert_ne!(ids.iter().map(|id| opacity(&s, *id)).collect::>(), first); + // Defaults 30 to 100; min = max gives every object that opacity. + s.execute("addon.arrange.randomizeOpacity", &json!({})).unwrap(); + assert!(ids.iter().all(|id| (0.3..=1.0).contains(&opacity(&s, *id)))); + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 45, "max": 45})).unwrap(); + assert!(ids.iter().all(|id| opacity(&s, *id) == 0.45)); +} + +#[test] +fn randomize_opacity_takes_ids_and_leaves_the_rest() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 5.0, 5.0); + let b = rect(&mut s, 10.0, 0.0, 5.0, 5.0); + select(&mut s, &[a, b]); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let c = rect(&mut s, 20.0, 0.0, 5.0, 5.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(!enabled(&s, "addon.arrange.randomizeOpacity")); + s.execute("addon.arrange.randomizeOpacity", &json!({"ids": [c.0], "min": 10, "max": 10})).unwrap(); + assert_eq!((opacity(&s, a), opacity(&s, b), opacity(&s, c)), (1.0, 1.0, 0.1)); + // A group takes one opacity of its own; the objects inside keep theirs. + select(&mut s, &[g]); + s.execute("addon.arrange.randomizeOpacity", &json!({"min": 20, "max": 20})).unwrap(); + assert_eq!((opacity(&s, g), opacity(&s, a), opacity(&s, b)), (0.2, 1.0, 1.0)); +} + +#[test] +fn randomize_opacity_refuses_bad_params() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + select(&mut s, &[a]); + refuses( + &mut s, + "addon.arrange.randomizeOpacity", + &[ + json!({"min": -1}), + json!({"max": 101}), + json!({"min": 80, "max": 20}), + json!({"min": 1e308}), + json!({"max": "50"}), + json!({"seed": -1}), + json!({"seed": 1.5}), + json!({"seed": "x"}), + json!({"ids": [999_999]}), + json!({"ids": "x"}), + ], + ); + let e = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 80, "max": 20})).unwrap_err().to_string(); + assert!(e.contains("`min` is greater than `max`"), "{e}"); +} + +fn layer_order(s: &Session) -> Vec { + s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +/// Three squares: `a` 30 wide at x 0, `b` 10 wide at x 100, `c` 20 wide at x 200, all selected. +fn squares(s: &mut Session) -> (NodeId, NodeId, NodeId) { + let a = rect(s, 0.0, 0.0, 30.0, 30.0); + let b = rect(s, 100.0, 0.0, 10.0, 10.0); + let c = rect(s, 200.0, 0.0, 20.0, 20.0); + select(s, &[a, b, c]); + (a, b, c) +} + +#[test] +fn sort_by_area_lines_objects_up_along_x() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + let n = steps(&s); + let r = s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x"})).unwrap(); + assert_eq!(r["count"], json!(3)); + assert_eq!(steps(&s), n + 1, "one undo step"); + // Smallest first: b, c, a take the left edges 0, 100, 200; y stays. + assert!(near(bounds(&s, b), (0.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (100.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, c)); + assert!(near(bounds(&s, a), (200.0, 0.0, 30.0, 30.0)), "{:?}", bounds(&s, a)); + // Large to small: a, c, b. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x", "order": "descending"})).unwrap(); + assert_eq!((bounds(&s, a).x0, bounds(&s, c).x0, bounds(&s, b).x0), (0.0, 100.0, 200.0)); + // Already in order: no step. + let n = steps(&s); + s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "x", "order": "descending"})).unwrap(); + assert_eq!(steps(&s), n); +} + +#[test] +fn sort_distributes_values_evenly() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 10.0, 50.0, 10.0, 50.0); + let c = rect(&mut s, 200.0, 0.0, 10.0, 20.0); + select(&mut s, &[a, b, c]); + // Left edges 0, 10, 200 step evenly: 0, 100, 200. + s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "x", "distribute": true})).unwrap(); + assert_eq!((bounds(&s, a).x0, bounds(&s, b).x0, bounds(&s, c).x0), (0.0, 100.0, 200.0)); + // Heights that step evenly with x (10 to 50), each about its centre. + s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "height", "distribute": true})).unwrap(); + assert!(near(bounds(&s, a), (0.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (100.0, 60.0, 10.0, 30.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (200.0, -15.0, 10.0, 50.0)), "{:?}", bounds(&s, c)); +} + +#[test] +fn sort_restacks_within_each_layer() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + // Largest at the back. + s.execute("addon.arrange.sort", &json!({"by": "area", "apply": "stacking", "order": "descending"})).unwrap(); + assert_eq!(layer_order(&s), [a, c, b]); + s.execute("addon.arrange.sort", &json!({})).unwrap(); + assert_eq!(layer_order(&s), [b, c, a], "by area, small to large, into the stacking order by default"); + // An object in another layer keeps its layer; the others trade places among themselves. + s.execute("layer.new", &json!({})).unwrap(); + let big = rect(&mut s, 0.0, 100.0, 50.0, 50.0); + select(&mut s, &[a, b, c, big]); + s.execute("addon.arrange.sort", &json!({"order": "descending"})).unwrap(); + assert_eq!(layer_order(&s), [a, c, b]); + let doc = &s.doc().unwrap().doc; + assert_ne!(doc.layer_of(big), doc.layer_of(a), "left in its own layer"); +} + +#[test] +fn sort_by_stacking_and_opacity() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + // Back to front a, b, c; reversed: c, b, a take the left edges 0, 100, 200. + s.execute("addon.arrange.sort", &json!({"by": "stacking", "apply": "x", "order": "descending"})).unwrap(); + assert_eq!((bounds(&s, c).x0, bounds(&s, b).x0, bounds(&s, a).x0), (0.0, 100.0, 200.0)); + for (id, o) in [(a, 20), (b, 80), (c, 50)] { + s.execute("object.setProps", &json!({"ids": [id.0], "opacity": o})).unwrap(); + } + select(&mut s, &[a, b, c]); + let opacity = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().opacity; + // By x, large to small: a (x 200) gets the least opacity, then b, then c. + s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "opacity", "order": "descending"})).unwrap(); + assert_eq!((opacity(&s, a), opacity(&s, b), opacity(&s, c)), (0.2, 0.5, 0.8)); + // By opacity into the stacking order, large to small: the most opaque at the back. + s.execute("addon.arrange.sort", &json!({"by": "opacity", "order": "descending"})).unwrap(); + assert_eq!(layer_order(&s), [c, b, a]); +} + +#[test] +fn sort_by_area_into_areas_scales_in_proportion() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + // Areas 900, 100, 400 by x: a (x 0) 100, b 500, c 900. + s.execute("addon.arrange.sort", &json!({"by": "x", "apply": "area", "distribute": true})).unwrap(); + let side = |s: &Session, id| bounds(s, id).width(); + assert!((side(&s, a) - 10.0).abs() < 1e-6 && (side(&s, b) - 500f64.sqrt()).abs() < 1e-6 && (side(&s, c) - 30.0).abs() < 1e-6); + assert!((bounds(&s, b).height() - 500f64.sqrt()).abs() < 1e-6, "in proportion"); +} + +#[test] +fn sort_in_random_order_repeats_with_a_seed() { + let mut s = session(); + let ids: Vec = (0..12).map(|i| rect(&mut s, i as f64 * 10.0, 0.0, 5.0, 5.0)).collect(); + select(&mut s, &ids); + s.execute("addon.arrange.sort", &json!({"order": "random", "seed": 5})).unwrap(); + let first = layer_order(&s); + assert_ne!(first, ids, "shuffled"); + let mut sorted = first.clone(); + sorted.sort_by_key(|i| i.0); + assert_eq!(sorted, ids, "the same objects"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layer_order(&s), ids); + s.execute("addon.arrange.sort", &json!({"order": "random", "seed": 5})).unwrap(); + assert_eq!(layer_order(&s), first, "the same seed, the same order"); +} + +#[test] +fn sort_takes_ids_and_refuses_bad_params() { + let mut s = session(); + let (a, b, c) = squares(&mut s); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.sort")); + s.execute("addon.arrange.sort", &json!({"ids": [b.0, a.0], "apply": "x"})).unwrap(); + assert_eq!((bounds(&s, b).x0, bounds(&s, a).x0, bounds(&s, c).x0), (0.0, 100.0, 200.0), "c is left alone"); + select(&mut s, &[a, b, c]); + refuses( + &mut s, + "addon.arrange.sort", + &[ + json!({"by": "color"}), + json!({"apply": 3}), + json!({"order": "up"}), + json!({"distribute": "yes"}), + json!({"seed": -1}), + json!({"seed": 0.5}), + json!({"scaleStrokes": 1}), + json!({"ids": "x"}), + json!({"ids": [999_999]}), + ], + ); +} diff --git a/crates/engine/src/cmd/addons/cleanup.rs b/crates/engine/src/cmd/addons/cleanup.rs new file mode 100644 index 0000000000..cba512cd18 --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup.rs @@ -0,0 +1,378 @@ +//! Artwork Cleanup (`addon.cleanup.*`), a built-in add-on: Simplify Anchors (Keep Shape), the +//! Document Health Check (check, show and fix the issues it finds), Deep Ungroup and Rejoin Path +//! Pieces, and its text tools ([`text`]). Its panel and its submenu, Object › Plug-ins › Artwork +//! Cleanup, are the UI's. + +mod checks; +#[cfg(test)] +mod tests; +mod text; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{PathData, SubPath}; +use vectorcraft_pathops::addons as po; + +use self::checks::{Kind, MAX_OBJECTS, Outcome, Scope, set_path}; +use super::super::edit::selected_roots; +use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, number_or, switch_or, text_param}; +use crate::{EngineError, Result, Session}; + +/// Simplify Anchors' tolerance by default. +const TOLERANCE: f64 = 20.0; +/// Rejoin Path Pieces' gap by default, and the widest (pt). +const GAP: f64 = 0.1; +const MAX_GAP: f64 = 6.0; +/// Most anchors Simplify Anchors takes at once. +const MAX_ANCHORS: usize = 2_000_000; +/// Most rounds of fixes `addon.cleanup.fix` runs. +const FIX_ROUNDS: usize = 3; +/// Most ids a finding lists (its count counts them all). +const MAX_LISTED: usize = 1000; + +pub fn specs() -> Vec { + let mut v = vec![ + cmd!( + "addon.cleanup.simplify", + "Simplify Anchors (Keep Shape)…", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay, and locked and hidden paths are left out → {ids, before, after} anchor counts", + has_selection, + simplify + ), + cmd!( + query "addon.cleanup.check", + "Health Check", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{scope?: \"selection\"|\"document\" (default: the selection, or the document while nothing is selected), kinds?: [kind…] (default: all: emptyText, strayPoints (paths of one anchor), unpainted, zeroOpacity, duplicateObjects (a path stacked on an identical one, or type on the same type within 1 pt), offArtboard, duplicateAnchors (neighbours within 0.01 pt), tinyHandles (under 0.01 pt), collinearAnchors (corners on a straight run, turning less than sine 0.005), nearPoints (anchors within 0.01 pt of other paths' anchors), nearlyClosed (ends within 0.01 pt), filledOpenPaths (filled, unstroked open paths), needlessClipGroups (an unpainted clip that clips nothing, hides everything, or is a rectangle round all its art), needlessCompounds (one path or none), needlessGroups (one member or none, nothing of their own), emptyArtboards (the document only))} find issues without changing anything; locked and hidden objects are left out → {scope, total, findings: [{kind, label, count, ids (the objects, at most 1000), artboards (indexes)}]} for the kinds found", + has_doc, + check + ), + cmd!( + query "addon.cleanup.show", + "Show Issue", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{kind: kind (see addon.cleanup.check), scope?: \"selection\"|\"document\"} select the objects with that issue → {kind, count, ids, artboards}", + has_doc, + show + ), + cmd!( + "addon.cleanup.fix", + "Fix All Issues", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents → {scope, total, fixed: {kind: count}}", + has_doc, + fix + ), + cmd!( + "addon.cleanup.deepUngroup", + "Deep Ungroup…", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in; locked and hidden groups stay whole, and locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}", + has_selection, + deep_ungroup + ), + cmd!( + "addon.cleanup.rejoin", + "Rejoin Path Pieces…", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{gap?: pt 0..6 (0.1), ids?: [id…] (default: the selection)} weld the open paths under the objects whose ends lie within the gap of each other back into paths: an end joins one other end, the one the path turns least to go on into, pieces may run either way, and a chain whose ends meet closes; each path takes the place and paint of its topmost piece, as one undo step → {ids, joined (paths made), removed (pieces merged into them)}", + has_selection, + rejoin + ), + ]; + v.extend(text::specs()); + v +} + +/// The paths (not guides) under `roots`, compound path members included; locked and hidden +/// paths, and those in locked or hidden groups, stay out. +fn paths_under(d: &Document, roots: &[NodeId]) -> Vec { + let mut out = vec![]; + for n in roots.iter().filter_map(|id| d.node(*id)) { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::Path { guide: false, .. }) { + out.push(c.id); + } + }); + } + let editable = d.editable(); + out.retain(|id| editable(*id)); + out +} + +fn simplify(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.simplify"; + let tolerance = number_or(p, "tolerance", TOLERANCE, C)?; + if !(1.0..=100.0).contains(&tolerance) { + return Err(bad(C, "`tolerance` must be from 1 to 100")); + } + let protect = switch_or(p, "protectCorners", false, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let ids = paths_under(d, &roots); + let paths: Vec<(NodeId, &PathData)> = ids.iter().filter_map(|id| Some((*id, d.node(*id)?.path_data()?))).collect(); + let before: usize = paths.iter().map(|(_, p)| p.anchor_count()).sum(); + if before > MAX_ANCHORS { + return Err(EngineError::Other("Simplify Anchors: the paths have too many anchors to simplify at once".into())); + } + let changed: Vec<(NodeId, PathData)> = paths + .iter() + .filter_map(|(id, path)| { + let np = po::simplify_keep_shape(path, tolerance * po::PT_PER_TOLERANCE, protect); + (np != **path).then_some((*id, np)) + }) + .collect(); + let removed: usize = changed.iter().filter_map(|(id, np)| Some(d.node(*id)?.path_data()?.anchor_count().saturating_sub(np.anchor_count()))).sum(); + let after = before.saturating_sub(removed); + // When no anchor can go, the document and its undo history stay as they are. + if !changed.is_empty() { + s.edit("Simplify Anchors (Keep Shape)", |d, sel| { + for (id, np) in changed { + // The anchors left are new ones: the path is selected whole. + sel.anchors.remove(&id); + sel.segments.remove(&id); + set_path(d, id, np); + } + Ok(()) + })?; + } + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "before": before, "after": after })) +} + +/// The scope a check, show or fix request names (by default the selection, or the document while +/// nothing is selected) and its name. +fn scope_of(s: &Session, p: &Value, cmd: &str) -> Result<(Scope, &'static str)> { + let roots = selected_roots(s)?; + match text_param(p, "scope", cmd)? { + Some("document") => Ok((Scope::Document, "document")), + None if roots.is_empty() => Ok((Scope::Document, "document")), + Some("selection") if roots.is_empty() => Err(bad(cmd, "nothing selected")), + Some("selection") | None => Ok((Scope::Objects(roots), "selection")), + Some(other) => Err(bad(cmd, format!("`scope` must be \"selection\" or \"document\", not {other:?}"))), + } +} + +/// The kinds a request names (all by default), in the order Fix runs them. +fn kinds_of(p: &Value, cmd: &str) -> Result> { + let given: Vec = match p.get("kinds") { + None | Some(Value::Null) => return Ok(Kind::ALL.to_vec()), + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().and_then(Kind::parse).ok_or_else(|| bad(cmd, format!("unknown issue kind {v}")))).collect::>()? + } + Some(_) => return Err(bad(cmd, "`kinds` must be a list of issue kinds")), + }; + Ok(Kind::ALL.into_iter().filter(|k| given.contains(k)).collect()) +} + +/// Kind `kind`'s fix run on a copy of the active document: what Fix would change. +fn dry_run(s: &Session, kind: Kind, scope: &Scope) -> Result { + let st = s.doc()?; + let (mut d, mut sel, mut scope) = ((*st.doc).clone(), st.selection.clone(), scope.clone()); + kind.fix(&mut d, &mut sel, &mut scope) +} + +fn finding(kind: Kind, o: &Outcome) -> Value { + let ids: Vec = o.ids.iter().take(MAX_LISTED).map(|i| i.0).collect(); + json!({ "kind": kind.id(), "label": kind.label(), "count": o.count, "ids": ids, "artboards": o.artboards }) +} + +fn check(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.check"; + let (scope, name) = scope_of(s, p, C)?; + let mut findings = vec![]; + let mut total = 0; + for kind in kinds_of(p, C)? { + let o = dry_run(s, kind, &scope)?; + if o.count > 0 { + total += o.count; + findings.push(finding(kind, &o)); + } + } + Ok(json!({ "scope": name, "total": total, "findings": findings })) +} + +fn show(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.show"; + let id = text_param(p, "kind", C)?.ok_or_else(|| bad(C, "missing `kind`"))?; + let kind = Kind::parse(id).ok_or_else(|| bad(C, format!("unknown issue kind {id:?}")))?; + let (scope, _) = scope_of(s, p, C)?; + let o = dry_run(s, kind, &scope)?; + if o.count == 0 { + return Err(EngineError::Other("None of these issues are left: check again".into())); + } + // Artboards are no objects to select: the selection stays as it is for them. + let ids = o.ids.clone(); + if !ids.is_empty() { + s.select(|_, sel| sel.set(ids))?; + } + Ok(finding(kind, &o)) +} + +fn fix(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.fix"; + let (mut scope, name) = scope_of(s, p, C)?; + let kinds = kinds_of(p, C)?; + // Fixed on a copy, kind after kind (what one leaves, the next cleans up), then kept as one step. + let st = s.doc()?; + let (mut d, mut sel) = ((*st.doc).clone(), st.selection.clone()); + let mut fixed = Map::new(); + let mut total = 0; + // A fix can leave issues for a kind that ran before it (groups unwrapped side by side may hold + // duplicates): the kinds run again, a few rounds at most, until a round finds nothing. + for _ in 0..FIX_ROUNDS { + let before = total; + for &kind in &kinds { + let o = kind.fix(&mut d, &mut sel, &mut scope)?; + if o.count > 0 { + total += o.count; + let n = fixed.get(kind.id()).and_then(Value::as_u64).unwrap_or(0); + fixed.insert(kind.id().into(), json!(n + o.count as u64)); + } + } + if total == before { + break; + } + } + // With nothing to fix, the document and its undo history stay as they are. + if total > 0 { + sel.prune(&d); + s.edit("Fix Issues", |doc, selection| { + *doc = d; + *selection = sel; + Ok(()) + })?; + } + Ok(json!({ "scope": name, "total": total, "fixed": fixed })) +} + +/// Is `n` a group Deep Ungroup takes apart (a clipping group only with `clips`)? +fn ungroupable(n: &Node, clips: bool) -> bool { + matches!(n.kind, NodeKind::Group { clip, .. } if clips || !clip) +} + +/// `n` with every level of grouping Deep Ungroup takes apart removed, into `out`; `count` counts +/// the groups. Members take on the opacity of the groups they were in, and a clipping path +/// becomes a plain path. A locked or hidden group stays whole. +fn flatten(n: Node, clips: bool, out: &mut Vec, count: &mut usize) { + if !ungroupable(&n, clips) || n.locked || !n.visible { + out.push(n); + return; + } + let NodeKind::Group { children, clip } = &n.kind else { return }; + *count += 1; + for (k, c) in children.iter().enumerate() { + let mut c = (**c).clone(); + if *clip + && k == 0 + && let NodeKind::Path { clipping, .. } = &mut c.kind + { + *clipping = false; + } + c.opacity *= n.opacity; + flatten(c, clips, out, count); + } +} + +fn deep_ungroup(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.deepUngroup"; + let clips = switch_or(p, "includeClipGroups", false, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + // Locked and hidden objects, and those in locked or hidden groups, stay as they are. + let roots: Vec = { + let editable = d.editable(); + roots.into_iter().filter(|id| editable(*id)).collect() + }; + let (mut items, mut selected, mut count) = (vec![], vec![], 0); + for id in &roots { + match d.node(*id).filter(|n| ungroupable(n, clips)) { + Some(n) => { + let mut out = vec![]; + flatten(n.clone(), clips, &mut out, &mut count); + selected.extend(out.iter().map(|n| n.id)); + items.push((*id, out)); + } + None => selected.push(*id), + } + } + // With no group to take apart, the document, the selection and the undo history stay as they + // are, and the reply lists the selection. + if items.is_empty() { + selected = s.doc()?.selection.objects.to_vec(); + } else { + selected = s.edit("Deep Ungroup", move |d, sel| { + d.insert_beside(items, true)?; + // Members that are locked or hidden themselves keep that, and are not selected. + let editable = d.editable(); + selected.retain(|id| editable(*id)); + sel.set(selected.iter().copied()); + Ok(selected) + })?; + } + Ok(json!({ "ids": selected.iter().map(|i| i.0).collect::>(), "ungrouped": count })) +} + +/// The open single-subpath paths under `roots` that Rejoin Path Pieces takes, in paint order +/// (compound path members, clipping paths and guides stay out). +fn pieces(d: &Document, roots: &[NodeId]) -> Vec<(NodeId, SubPath)> { + fn visit(n: &Node, out: &mut Vec<(NodeId, SubPath)>) { + match &n.kind { + NodeKind::Path { path, guide: false, clipping: false, .. } => { + if let [sp] = path.subpaths.as_slice() + && !sp.closed + { + out.push((n.id, sp.clone())); + } + } + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, out)), + _ => {} + } + } + let mut out = vec![]; + roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out)); + let editable = d.editable(); + out.retain(|(id, _)| editable(*id)); + out +} + +fn rejoin(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.rejoin"; + let gap = number_or(p, "gap", GAP, C)?; + if !(0.0..=MAX_GAP).contains(&gap) { + return Err(bad(C, "`gap` must be from 0 to 6 pt")); + } + let roots = checked_ids_or_selection(s, p, C)?; + let found = pieces(&s.doc()?.doc, &roots); + if found.len() > MAX_OBJECTS { + return Err(EngineError::Other("Rejoin Path Pieces: too many paths to rejoin at once".into())); + } + let subpaths: Vec = found.iter().map(|(_, sp)| sp.clone()).collect(); + // Each chain becomes its topmost piece (the last in paint order); the others go. + let (mut kept, mut gone) = (vec![], vec![]); + for j in po::rejoin(&subpaths, gap) { + let ids: Vec = j.members.iter().filter_map(|&m| found.get(m).map(|f| f.0)).collect(); + let Some(&top) = j.members.iter().max().and_then(|&m| found.get(m).map(|f| &f.0)) else { continue }; + gone.extend(ids.into_iter().filter(|id| *id != top)); + kept.push((top, j.path)); + } + if !kept.is_empty() { + let ids: Vec = kept.iter().map(|k| k.0).collect(); + s.edit("Rejoin Path Pieces", |d, sel| { + for (id, sp) in &kept { + set_path(d, *id, PathData::single(sp.clone())); + } + d.remove_many(&gone)?; + sel.set(ids); + Ok(()) + })?; + } + let ids: Vec = kept.iter().map(|k| k.0.0).collect(); + Ok(json!({ "ids": ids, "joined": kept.len(), "removed": gone.len() })) +} diff --git a/crates/engine/src/cmd/addons/cleanup/checks.rs b/crates/engine/src/cmd/addons/cleanup/checks.rs new file mode 100644 index 0000000000..4b03f0e433 --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup/checks.rs @@ -0,0 +1,490 @@ +//! Document Health Check: the kinds of issue Artwork Cleanup looks for, and how each is fixed. A +//! check runs a kind's fix on a copy of the document, so what a check finds is what Fix changes. + +use std::collections::{HashMap, HashSet}; + +use vectorcraft_color::BlendMode; +use vectorcraft_doc::appearance::AppearanceItem; +use vectorcraft_doc::{Appearance, Document, Knockout, Node, NodeExtras, NodeId, NodeKind, Selection, SymbolBoxes}; +use vectorcraft_geom::{PathData, Point, Rect}; +use vectorcraft_pathops::addons as po; + +use super::super::super::edit::outermost; +use super::super::super::layer::empty_artboards; +use crate::Result; + +/// Sine of the turn below which an anchor on a straight run is collinear. +const COLLINEAR: f64 = 0.005; +/// Distance (pt) within which anchors coincide, handles are tiny and path ends meet. +const NEAR: f64 = 0.01; +/// Most objects a check looks at; the rest of a larger document is left as it is. +pub(super) const MAX_OBJECTS: usize = 250_000; +/// Most anchors Near Anchors compares. +const MAX_ANCHORS: usize = 1_000_000; +/// Most rounds of unwrapping nested groups. +const MAX_PASSES: usize = 64; + +/// One kind of issue. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Kind { + EmptyText, + StrayPoints, + Unpainted, + ZeroOpacity, + DuplicateObjects, + OffArtboard, + DuplicateAnchors, + TinyHandles, + CollinearAnchors, + NearPoints, + NearlyClosed, + FilledOpenPaths, + NeedlessClipGroups, + NeedlessCompounds, + NeedlessGroups, + EmptyArtboards, +} + +impl Kind { + /// Every kind, in the order Fix runs them (removing art first can leave groups to unwrap). + pub(super) const ALL: [Kind; 16] = [ + Kind::EmptyText, + Kind::StrayPoints, + Kind::Unpainted, + Kind::ZeroOpacity, + Kind::DuplicateObjects, + Kind::OffArtboard, + Kind::DuplicateAnchors, + Kind::TinyHandles, + Kind::CollinearAnchors, + Kind::NearPoints, + Kind::NearlyClosed, + Kind::FilledOpenPaths, + Kind::NeedlessClipGroups, + Kind::NeedlessCompounds, + Kind::NeedlessGroups, + Kind::EmptyArtboards, + ]; + + /// (id, label) of the kind. + fn names(self) -> (&'static str, &'static str) { + match self { + Kind::EmptyText => ("emptyText", "Empty Text"), + Kind::StrayPoints => ("strayPoints", "Stray Points"), + Kind::Unpainted => ("unpainted", "Unpainted Objects"), + Kind::ZeroOpacity => ("zeroOpacity", "Zero-Opacity Objects"), + Kind::DuplicateObjects => ("duplicateObjects", "Duplicate Objects"), + Kind::OffArtboard => ("offArtboard", "Off-Artboard Art"), + Kind::DuplicateAnchors => ("duplicateAnchors", "Duplicate Anchors"), + Kind::TinyHandles => ("tinyHandles", "Tiny Handles"), + Kind::CollinearAnchors => ("collinearAnchors", "Collinear Anchors"), + Kind::NearPoints => ("nearPoints", "Nearly Coincident Anchors"), + Kind::NearlyClosed => ("nearlyClosed", "Nearly Closed Paths"), + Kind::FilledOpenPaths => ("filledOpenPaths", "Filled Open Paths"), + Kind::NeedlessClipGroups => ("needlessClipGroups", "Needless Clipping Groups"), + Kind::NeedlessCompounds => ("needlessCompounds", "Needless Compound Paths"), + Kind::NeedlessGroups => ("needlessGroups", "Needless Groups"), + Kind::EmptyArtboards => ("emptyArtboards", "Empty Artboards"), + } + } + + pub(super) fn id(self) -> &'static str { + self.names().0 + } + + pub(super) fn label(self) -> &'static str { + self.names().1 + } + + pub(super) fn parse(id: &str) -> Option { + Kind::ALL.into_iter().find(|k| k.id() == id) + } + + /// Fix this kind of issue in `scope` of `d` → what changed. + pub(super) fn fix(self, d: &mut Document, sel: &mut Selection, scope: &mut Scope) -> Result { + match self { + Kind::DuplicateAnchors => reshape(d, scope, |_, p| p.subpaths.iter_mut().map(|sp| po::merge_duplicate_anchors(sp, NEAR)).sum()), + Kind::TinyHandles => reshape(d, scope, |_, p| p.subpaths.iter_mut().map(|sp| po::retract_tiny_handles(sp, NEAR)).sum()), + Kind::CollinearAnchors => reshape(d, scope, |_, p| p.subpaths.iter_mut().map(|sp| po::remove_collinear_anchors(sp, COLLINEAR)).sum()), + Kind::NearlyClosed => reshape(d, scope, |_, p| p.subpaths.iter_mut().map(|sp| usize::from(po::close_nearly_closed(sp, NEAR))).sum()), + Kind::FilledOpenPaths => reshape(d, scope, close_filled), + Kind::NearPoints => near_points(d, scope), + Kind::EmptyArtboards => artboards(d, sel, scope), + _ => restructure(d, scope, self), + } + } + + /// What replaces object `n` (at `place`) when it is this kind of issue: nothing to remove it, + /// its members to unwrap it. `None` when it isn't one. + fn replacement(self, cx: &Context, n: &Node, place: Place) -> Option> { + let removable = !place.clips && !is_guide_or_clip(n); + let gone = |is: bool| is.then(Vec::new); + match self { + Kind::EmptyText => gone(removable && matches!(&n.kind, NodeKind::Text(t) if t.plain_text().trim().is_empty())), + Kind::StrayPoints => gone(removable && matches!(&n.kind, NodeKind::Path { path, .. } if path.anchor_count() <= 1)), + Kind::Unpainted => gone(removable && !place.in_compound && is_shape(n) && !is_painted(&n.appearance)), + Kind::ZeroOpacity => gone(removable && !place.in_compound && n.opacity <= 0.0), + Kind::DuplicateObjects => gone(removable && duplicates_the_one_below(cx.d, n)), + Kind::OffArtboard => gone(place.top && removable && off_artboards(cx, n)), + Kind::NeedlessGroups => needless_group(n), + Kind::NeedlessCompounds => needless_compound(n), + Kind::NeedlessClipGroups => needless_clip_group(cx, n), + _ => None, + } + } +} + +/// What a fix changed (or a check found): how many issues, the objects they are on and the +/// artboards (by index) they are. +#[derive(Clone, Debug, Default)] +pub(super) struct Outcome { + pub count: usize, + pub ids: Vec, + pub artboards: Vec, +} + +/// What a check looks at: the whole document, or the objects given and what is inside them. +#[derive(Clone, Debug)] +pub(super) enum Scope { + Document, + Objects(Vec), +} + +/// Where an object sits. +#[derive(Clone, Copy, Default)] +struct Place { + /// A member of a compound path. + in_compound: bool, + /// The clipping path of its group or layer. + clips: bool, + /// A top-level object of the scope (on a layer, or given). + top: bool, +} + +/// The document a pass looks at, with its symbols measured once. +struct Context<'a> { + d: &'a Document, + symbols: SymbolBoxes<'a>, +} + +/// The visible, unlocked objects in `scope` with where they sit, in paint order: groups, layers, +/// clip groups and compound paths are looked into; live and generated art (blends, envelopes, +/// graphs, symbols…) is taken as it is. +fn objects<'a>(d: &'a Document, scope: &Scope) -> Vec<(&'a Node, Place)> { + let mut out = vec![]; + let top = Place { top: true, ..Place::default() }; + match scope { + Scope::Document => d.layers.iter().for_each(|l| visit(l, top, &mut out)), + Scope::Objects(ids) => { + ids.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, Place { clips: is_clipping_path(d, n.id), ..top }, &mut out)) + } + } + let editable = d.editable(); + out.retain(|(n, _)| editable(n.id)); + out +} + +fn visit<'a>(n: &'a Node, place: Place, out: &mut Vec<(&'a Node, Place)>) { + if !n.visible || n.locked || out.len() >= MAX_OBJECTS { + return; + } + let inner = |clip: bool, i: usize, top: bool| Place { clips: clip && i == 0, top, in_compound: false }; + match &n.kind { + // A layer's objects are top-level ones. + NodeKind::Layer { children, clip, .. } => children.iter().enumerate().for_each(|(i, c)| visit(c, inner(*clip, i, true), out)), + NodeKind::Group { children, clip } if !is_generated(n) => { + out.push((n, place)); + children.iter().enumerate().for_each(|(i, c)| visit(c, inner(*clip, i, false), out)); + } + NodeKind::Compound { children, .. } => { + out.push((n, place)); + children.iter().for_each(|c| visit(c, Place { in_compound: true, ..Place::default() }, out)); + } + _ => out.push((n, place)), + } +} + +/// Is `id` the clipping path of its group or layer? +fn is_clipping_path(d: &Document, id: NodeId) -> bool { + d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(Node::clips)) +} + +/// A group that stands for live or generated art: its members aren't loose art to clean. +fn is_generated(n: &Node) -> bool { + let e = n.extras(); + e.graph.is_some() || e.shaper.is_some() || e.dimension.is_some() || e.objects_on_path.is_some() || e.live_paint_gaps.is_some() || e.compound_shape +} + +fn is_guide_or_clip(n: &Node) -> bool { + matches!(n.kind, NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. }) +} + +fn is_shape(n: &Node) -> bool { + matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) +} + +fn is_painted(a: &Appearance) -> bool { + a.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(), + AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.width > 0.0, + }) +} + +/// A container with nothing of its own to show: full opacity, normal blending, no fill, stroke, +/// effect, mask, knockout or anything else attached. +fn is_plain(n: &Node) -> bool { + n.opacity >= 1.0 + && n.blend == BlendMode::Normal + && n.appearance.items.is_empty() + && n.appearance.effects.is_empty() + && !n.isolate + && n.knockout == Knockout::Neutral + && *n.extras() == NodeExtras::default() +} + +/// Is `n` a plain path or type object (full opacity, normal blending) that doubles the object just +/// below it? +fn duplicates_the_one_below(d: &Document, n: &Node) -> bool { + if n.opacity < 1.0 || n.blend != BlendMode::Normal { + return false; + } + let below = d.position(n.id).and_then(|(parent, i, _)| d.children(parent)?.get(i.checked_sub(1)?).cloned()); + below.is_some_and(|b| { + b.visible + && same_art(&b.kind, &n.kind) + && b.appearance == n.appearance + && b.opacity == n.opacity + && b.blend == n.blend + && b.extras() == n.extras() + }) +} + +/// Distance (pt) within which doubled type counts as stacked: text set twice from a PDF or an old +/// file, or for a fake bold, is often a fraction of a point off. +const DOUBLED_TYPE: f64 = 1.0; + +/// The same path, or the same type (text, styles, size and turn) within [`DOUBLED_TYPE`] of it. +fn same_art(a: &NodeKind, b: &NodeKind) -> bool { + match (a, b) { + (NodeKind::Path { .. }, NodeKind::Path { .. }) => a == b, + (NodeKind::Text(a), NodeKind::Text(b)) => { + let ([a0, a1, a2, a3, ax, ay], [b0, b1, b2, b3, bx, by]) = (a.xf.as_coeffs(), b.xf.as_coeffs()); + [a0, a1, a2, a3] == [b0, b1, b2, b3] && (ax - bx).hypot(ay - by) <= DOUBLED_TYPE && { + // `b` placed on `a`, with `a`'s layout caches (they are in document space). + let mut moved = (**b).clone(); + moved.xf = a.xf; + moved.cached_bounds = a.cached_bounds; + moved.cached_baselines.clone_from(&a.cached_baselines); + **a == moved + } + } + _ => false, + } +} + +fn inside(a: Rect, b: Rect) -> bool { + a.x0 >= b.x0 && a.y0 >= b.y0 && a.x1 <= b.x1 && a.y1 <= b.y1 +} + +fn meets(a: Rect, b: Rect) -> bool { + a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1 +} + +/// Does `n` lie wholly off every artboard (a document without artboards has none off them)? +fn off_artboards(cx: &Context, n: &Node) -> bool { + let Some(b) = n.visual_bounds_with(&cx.symbols) else { return false }; + // As Delete Empty Artboards measures: a millionth of a point covers rounding at the edges. + !cx.d.artboards.is_empty() && !cx.d.artboards.iter().any(|a| meets(a.rect.inflate(1e-6, 1e-6), b)) +} + +/// A plain group of one member or none: its member, or nothing. +fn needless_group(n: &Node) -> Option> { + let NodeKind::Group { children, clip: false } = &n.kind else { return None }; + (children.len() <= 1 && is_plain(n)).then(|| children.iter().map(|c| (**c).clone()).collect()) +} + +/// A compound path of one path or none: that path, painted as the compound was, or nothing. +fn needless_compound(n: &Node) -> Option> { + let NodeKind::Compound { children, rule } = &n.kind else { return None }; + let mut path = match children.as_slice() { + [] => return Some(vec![]), + [one] => (**one).clone(), + _ => return None, + }; + let NodeKind::Path { rule: r, .. } = &mut path.kind else { return None }; + *r = *rule; + path.appearance = n.appearance.clone(); + path.opacity = n.opacity; + path.blend = n.blend; + path.extras = n.extras.clone(); + Some(vec![path]) +} + +/// A plain clip group whose unpainted clipping path changes nothing: it clips nothing or lies wholly +/// away from its art (nothing shows: nothing is left), or it is a rectangle around all its art (its +/// art is left). +fn needless_clip_group(cx: &Context, n: &Node) -> Option> { + let NodeKind::Group { children, clip: true } = &n.kind else { return None }; + if !is_plain(n) { + return None; + } + let Some((clip, art)) = children.split_first() else { return Some(vec![]) }; + let paint = clip.clip_paint(); + if paint.fill.is_some() || paint.stroke.is_some() { + return None; + } + let clip_box = clip.geometric_bounds()?; + let art_box = art.iter().filter_map(|a| a.visual_bounds_with(&cx.symbols)).reduce(|a, b| a.union(b)); + match art_box { + None => Some(vec![]), + Some(b) if !meets(clip_box, b) => Some(vec![]), + Some(b) if is_rectangle(clip) && inside(b, clip_box.inflate(1e-6, 1e-6)) => Some(art.iter().map(|a| (**a).clone()).collect()), + _ => None, + } +} + +/// Is `n` a path drawing a square-to-the-page rectangle: four corners on its bounds, no curves? +fn is_rectangle(n: &Node) -> bool { + let NodeKind::Path { path, .. } = &n.kind else { return false }; + let (Some(b), [sp]) = (path.bounds(), path.subpaths.as_slice()) else { return false }; + let corner = |p: Point| ((p.x - b.x0).abs() < 1e-6 || (p.x - b.x1).abs() < 1e-6) && ((p.y - b.y0).abs() < 1e-6 || (p.y - b.y1).abs() < 1e-6); + sp.closed && sp.anchors.len() == 4 && sp.anchors.iter().all(|a| !a.has_in() && !a.has_out() && corner(a.p)) +} + +/// Replace the objects with this kind of issue (the outermost ones each round, until none is +/// left) by what [`Kind::replacement`] gives. +fn restructure(d: &mut Document, scope: &mut Scope, kind: Kind) -> Result { + let mut out = Outcome::default(); + for _ in 0..MAX_PASSES { + let found: Vec<(NodeId, Vec)> = { + let d: &Document = d; + let cx = Context { d, symbols: d.symbol_boxes() }; + let all: Vec<(NodeId, Vec)> = + objects(d, scope).into_iter().filter_map(|(n, pl)| Some((n.id, kind.replacement(&cx, n, pl)?))).collect(); + let keep: HashSet = outermost(d, all.iter().map(|(id, _)| *id).collect()).into_iter().collect(); + all.into_iter().filter(|(id, _)| keep.contains(id)).collect() + }; + if found.is_empty() { + break; + } + if let Scope::Objects(roots) = scope { + for (id, nodes) in &found { + if let Some(at) = roots.iter().position(|r| r == id) { + roots.splice(at..=at, nodes.iter().map(|n| n.id)); + } + } + } + out.ids.extend(found.iter().map(|(id, _)| *id)); + d.insert_beside(found, true)?; + } + out.count = out.ids.len(); + Ok(out) +} + +/// Run `f` on a copy of each path in scope (not guides), and keep the copies it changed: `f` +/// returns how many issues it fixed. +fn reshape(d: &mut Document, scope: &Scope, f: impl Fn(&Node, &mut PathData) -> usize) -> Result { + let changed: Vec<(NodeId, PathData, usize)> = objects(d, scope) + .into_iter() + .filter_map(|(n, _)| { + let NodeKind::Path { path, guide: false, .. } = &n.kind else { return None }; + let mut p = path.clone(); + let k = f(n, &mut p); + (k > 0).then_some((n.id, p, k)) + }) + .collect(); + let mut out = Outcome::default(); + for (id, p, k) in changed { + set_path(d, id, p); + out.count += k; + out.ids.push(id); + } + Ok(out) +} + +/// Give path `id` the geometry `p` (it stops being a live shape). +pub(super) fn set_path(d: &mut Document, id: NodeId, p: PathData) { + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *path = p; + *live = None; + } +} + +/// Filled Open Paths: close the open subpaths of a path with a fill and no stroke. +fn close_filled(n: &Node, p: &mut PathData) -> usize { + let items = &n.appearance.items; + let filled = items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none())); + let stroked = items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() && s.width > 0.0)); + if !filled || stroked { + return 0; + } + let mut count = 0; + for sp in p.subpaths.iter_mut().filter(|sp| !sp.closed && sp.anchors.len() >= 2) { + sp.closed = true; + count += 1; + } + count +} + +/// Nearly Coincident Anchors: anchors of the paths in scope within [`NEAR`] of one another (but +/// not neighbours on one path, which Duplicate Anchors merges) move onto the first of them. +fn near_points(d: &mut Document, scope: &Scope) -> Result { + // Each anchor: (path, subpath, anchor, its subpath's length and closedness). + let mut refs: Vec<(NodeId, usize, usize, usize, bool)> = vec![]; + let mut points: Vec = vec![]; + for (n, _) in objects(d, scope) { + let NodeKind::Path { path, guide: false, .. } = &n.kind else { continue }; + for (si, sp) in path.subpaths.iter().enumerate() { + for (ai, a) in sp.anchors.iter().enumerate().take(MAX_ANCHORS.saturating_sub(points.len())) { + refs.push((n.id, si, ai, sp.anchors.len(), sp.closed)); + points.push(a.p); + } + } + } + let neighbours = |i: usize, j: usize| { + let (Some(a), Some(b)) = (refs.get(i), refs.get(j)) else { return false }; + let gap = a.2.abs_diff(b.2); + a.0 == b.0 && a.1 == b.1 && (gap == 1 || (a.4 && gap + 1 == a.3)) + }; + let mut moves: HashMap> = HashMap::new(); + let mut count = 0; + for group in po::near_point_groups(&points, NEAR, neighbours) { + let Some(&to) = group.first().and_then(|&i| points.get(i)) else { continue }; + for &i in &group { + if let (Some(&(id, si, ai, ..)), Some(&p)) = (refs.get(i), points.get(i)) + && p != to + { + moves.entry(id).or_default().push((si, ai, to)); + count += 1; + } + } + } + let mut ids: Vec = moves.keys().copied().collect(); + ids.sort_unstable(); + for id in &ids { + let Some(mut p) = d.node(*id).and_then(Node::path_data).cloned() else { continue }; + for &(si, ai, to) in moves.get(id).into_iter().flatten() { + if let Some(a) = p.anchor_mut(si, ai) { + a.translate(to - a.p); + } + } + set_path(d, *id, p); + } + Ok(Outcome { count, ids, artboards: vec![] }) +} + +/// Empty Artboards: the artboards with no art on them (as Delete Empty Artboards finds them), +/// deleted with their guides. Only a check of the whole document looks at artboards. +fn artboards(d: &mut Document, sel: &mut Selection, scope: &Scope) -> Result { + let Scope::Document = scope else { return Ok(Outcome::default()) }; + let empty = empty_artboards(d); + // The last first, so the others keep their places. + for &i in empty.iter().rev() { + if i < d.artboards.len() { + let id = d.artboards.remove(i).id; + d.retire_artboard_id(id); + d.retain_guides(sel, |_, g| g.artboard != Some(id)); + } + } + Ok(Outcome { count: empty.len(), ids: vec![], artboards: empty }) +} diff --git a/crates/engine/src/cmd/addons/cleanup/tests.rs b/crates/engine/src/cmd/addons/cleanup/tests.rs new file mode 100644 index 0000000000..b20eb0d59b --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup/tests.rs @@ -0,0 +1,477 @@ +//! Artwork Cleanup's commands: Simplify Anchors (Keep Shape), the health check's kinds found and +//! fixed one by one, Fix as one undo step, scopes, Show, Deep Ungroup and Rejoin Path Pieces. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind}; +use vectorcraft_geom::{FillRule, Rect}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()) +} + +/// A path through `pts` (anchors as `{x, y, out?}` objects). +fn path(s: &mut Session, anchors: Value, closed: bool) -> NodeId { + id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()) +} + +fn line(s: &mut Session, pts: &[(f64, f64)]) -> NodeId { + path(s, pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(), false) +} + +fn node(s: &Session, id: NodeId) -> Option { + s.doc().unwrap().doc.node(id).cloned() +} + +fn change(s: &mut Session, id: NodeId, f: impl FnOnce(&mut Node)) { + s.edit("t", |d, _| { + f(d.node_mut(id).unwrap()); + Ok(()) + }) + .unwrap(); +} + +/// Put `id` inside a new container that `kind` makes of its members. +fn wrap(s: &mut Session, id: NodeId, kind: fn(Vec>) -> NodeKind) -> NodeId { + s.edit("t", |d, _| { + let w = d.alloc_id(); + Ok(d.wrap(&[id], |c| Node::new(w, kind(c)))?) + }) + .unwrap() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); +} + +fn anchors(s: &Session, id: NodeId) -> usize { + node(s, id).unwrap().path_data().unwrap().anchor_count() +} + +/// How many issues of `kind` a check of `scope` finds. +fn found(s: &mut Session, kind: &str, scope: &str) -> usize { + let r = s.execute("addon.cleanup.check", &json!({"kinds": [kind], "scope": scope})).unwrap(); + r["findings"].as_array().unwrap().iter().find(|f| f["kind"] == kind).map_or(0, |f| f["count"].as_u64().unwrap() as usize) +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +#[test] +fn simplify_keeps_the_shape_with_fewer_anchors_in_one_step() { + let mut s = session(); + let e = id_of(&s.execute("shape.ellipse", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + assert_eq!(anchors(&s, e), 16); + let bounds = node(&s, e).unwrap().geometric_bounds().unwrap(); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap(); + assert_eq!((r["before"].as_u64(), r["after"].as_u64()), (Some(16), Some(anchors(&s, e) as u64))); + assert!(anchors(&s, e) <= 8, "{r}"); + let now = node(&s, e).unwrap().geometric_bounds().unwrap(); + for (a, b) in [(bounds.x0, now.x0), (bounds.y0, now.y0), (bounds.x1, now.x1), (bounds.y1, now.y1)] { + assert!((a - b).abs() < 0.4, "{bounds:?} → {now:?}"); + } + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(anchors(&s, e), 16); + // A rectangle's corners stay; the anchors on its sides go. + let r = rect(&mut s, 200.0, 50.0, 100.0, 60.0); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + assert_eq!(anchors(&s, r), 8); + s.execute("addon.cleanup.simplify", &json!({"protectCorners": true})).unwrap(); + assert_eq!(anchors(&s, r), 4); + // Nothing left to remove: no undo step. + let steps = undo_steps(&s); + s.execute("addon.cleanup.simplify", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps); + for bad in [json!({"tolerance": 0}), json!({"tolerance": 101}), json!({"tolerance": "20"}), json!({"protectCorners": 1})] { + assert!(s.execute("addon.cleanup.simplify", &bad).is_err(), "{bad}"); + } +} + +#[test] +fn simplify_leaves_locked_and_hidden_paths_alone() { + let mut s = session(); + let mut ids = vec![]; + for x in [20.0, 140.0, 260.0] { + ids.push(id_of(&s.execute("shape.ellipse", &json!({"x": x, "y": 50, "width": 100, "height": 100})).unwrap())); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + } + select(&mut s, &ids); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + change(&mut s, ids[1], |n| n.locked = true); + change(&mut s, ids[2], |n| n.visible = false); + select(&mut s, &[g]); + let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap(); + assert_eq!(r["ids"], json!([ids[0].0])); + assert_eq!(r["before"], 16); + assert!(anchors(&s, ids[0]) < 16); + assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16)); + // Named by `ids`, or in a locked group, a path stays too, with no undo step. + let steps = undo_steps(&s); + s.execute("addon.cleanup.simplify", &json!({"ids": [ids[1].0, ids[2].0]})).unwrap(); + assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16)); + assert_eq!(undo_steps(&s), steps); + change(&mut s, ids[1], |n| n.locked = false); + change(&mut s, g, |n| n.locked = true); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap(); + assert_eq!((r["before"].as_u64(), r["after"].as_u64()), (Some(0), Some(0))); + assert_eq!(anchors(&s, ids[1]), 16); + assert_eq!(undo_steps(&s), steps); +} + +/// Each kind: what makes the issue in a fresh document (beside a clean rectangle). +fn make_issue(s: &mut Session, kind: &str) { + match kind { + "emptyText" => { + s.execute("text.create", &json!({"x": 20, "y": 20, "text": " "})).unwrap(); + } + "strayPoints" => { + path(s, json!([{"x": 30, "y": 30}]), false); + } + "unpainted" => { + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + change(s, id, |n| n.appearance = Appearance::default().into()); + } + "zeroOpacity" => { + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + change(s, id, |n| n.opacity = 0.0); + } + "duplicateObjects" => { + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + s.edit("t", |d, _| { + let mut copy = d.node(id).unwrap().clone(); + copy.id = d.alloc_id(); + let (parent, i, _) = d.position(id).unwrap(); + Ok(d.insert(parent, i + 1, copy)?) + }) + .unwrap(); + } + "offArtboard" => { + rect(s, -500.0, -500.0, 30.0, 30.0); + } + "duplicateAnchors" => { + line(s, &[(10.0, 150.0), (50.0, 150.0), (50.005, 150.0), (50.0, 190.0)]); + } + "tinyHandles" => { + path(s, json!([{"x": 10, "y": 150, "out": [10.004, 150]}, {"x": 60, "y": 190}]), false); + } + "collinearAnchors" => { + line(s, &[(10.0, 150.0), (30.0, 150.0), (50.0, 150.0), (50.0, 190.0)]); + } + "nearPoints" => { + line(s, &[(10.0, 150.0), (50.0, 150.0)]); + line(s, &[(50.005, 150.0), (90.0, 190.0)]); + } + "nearlyClosed" => { + line(s, &[(10.0, 150.0), (50.0, 150.0), (50.0, 190.0), (10.005, 150.0)]); + } + "filledOpenPaths" => { + let id = line(s, &[(10.0, 150.0), (50.0, 150.0), (50.0, 190.0)]); + change(s, id, |n| n.appearance = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 1.0).into()); + } + "needlessClipGroups" => { + let inner = rect(s, 30.0, 160.0, 20.0, 20.0); + let clip = rect(s, 20.0, 150.0, 50.0, 50.0); + select(s, &[inner, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + } + "needlessCompounds" => { + // A compound path holds the paint of its paths. + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + let look = node(s, id).unwrap().appearance; + let compound = wrap(s, id, |children| NodeKind::Compound { children, rule: FillRule::NonZero }); + change(s, compound, |n| n.appearance = look); + } + "needlessGroups" => { + let id = rect(s, 20.0, 150.0, 30.0, 30.0); + wrap(s, id, |children| NodeKind::Group { children, clip: false }); + } + "emptyArtboards" => { + s.edit("t", |d, _| { + let mut a = d.artboards[0].clone(); + a.id = d.next_artboard_id(); + a.rect = Rect::new(1000.0, 1000.0, 1100.0, 1100.0); + d.artboards.push(a); + Ok(()) + }) + .unwrap(); + } + _ => panic!("no setup for {kind}"), + } +} + +const KINDS: [&str; 16] = [ + "emptyText", + "strayPoints", + "unpainted", + "zeroOpacity", + "duplicateObjects", + "offArtboard", + "duplicateAnchors", + "tinyHandles", + "collinearAnchors", + "nearPoints", + "nearlyClosed", + "filledOpenPaths", + "needlessClipGroups", + "needlessCompounds", + "needlessGroups", + "emptyArtboards", +]; + +#[test] +fn each_check_finds_and_fixes_its_issue_and_leaves_clean_art_alone() { + let mut clean = session(); + let r = rect(&mut clean, 200.0, 20.0, 80.0, 60.0); + let before = node(&clean, r).unwrap(); + assert_eq!(clean.execute("addon.cleanup.check", &json!({})).unwrap()["total"], 0, "clean art has no issues"); + assert_eq!(clean.execute("addon.cleanup.fix", &json!({"scope": "document"})).unwrap()["total"], 0); + assert_eq!(node(&clean, r).unwrap(), before); + for kind in KINDS { + let mut s = session(); + let r = rect(&mut s, 200.0, 20.0, 80.0, 60.0); + make_issue(&mut s, kind); + select(&mut s, &[]); + assert!(found(&mut s, kind, "document") > 0, "{kind} not found"); + let fixed = s.execute("addon.cleanup.fix", &json!({"kinds": [kind], "scope": "document"})).unwrap(); + assert!(fixed["fixed"][kind].as_u64().unwrap() > 0, "{kind}: {fixed}"); + assert_eq!(found(&mut s, kind, "document"), 0, "{kind} still found after Fix"); + assert_eq!(s.execute("addon.cleanup.check", &json!({})).unwrap()["total"], 0, "{kind} left other issues"); + assert_eq!(node(&s, r).unwrap(), before, "{kind} changed the clean rectangle"); + } +} + +/// The pixel at (100, 100) of the document drawn on white. +fn pixel(s: &Session) -> [u8; 4] { + let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 400, 300, vectorcraft_geom::Affine::IDENTITY, &opts).pixel(100, 100) +} + +/// A clipping path hides the art outside it: empty type that clips a group, and type off every +/// artboard that clips a layer, stay, and the art stays hidden. +#[test] +fn clipping_type_stays_with_the_art_it_hides() { + const WHITE: [u8; 4] = [255, 255, 255, 255]; + let mut s = session(); + let art = rect(&mut s, 50.0, 50.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let t = id_of(&s.execute("text.create", &json!({"x": 60, "y": 80, "text": " ", "size": 40})).unwrap()); + select(&mut s, &[art, t]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + select(&mut s, &[]); + assert_eq!(pixel(&s), WHITE); + assert_eq!(found(&mut s, "emptyText", "document"), 0); + assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "document"})).unwrap()["total"], 0); + select(&mut s, &[t]); + assert_eq!(found(&mut s, "emptyText", "selection"), 0, "the clipping path selected"); + assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "selection"})).unwrap()["total"], 0); + assert!(node(&s, t).is_some()); + assert_eq!(pixel(&s), WHITE); + + let mut s = session(); + rect(&mut s, 50.0, 50.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let t = id_of(&s.execute("text.create", &json!({"x": -300, "y": -300, "text": "Clip", "size": 40})).unwrap()); + s.execute("layer.clippingMask.toggle", &json!({})).unwrap(); + select(&mut s, &[]); + assert_eq!(pixel(&s), WHITE); + assert_eq!(found(&mut s, "offArtboard", "document"), 0); + assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "document"})).unwrap()["total"], 0); + select(&mut s, &[t]); + assert_eq!(found(&mut s, "offArtboard", "selection"), 0, "the clipping path selected"); + assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "selection"})).unwrap()["total"], 0); + assert!(node(&s, t).is_some()); + assert_eq!(pixel(&s), WHITE); +} + +/// Type set twice in the same place (from a PDF, or for a fake bold) is a duplicate within a point: +/// Show selects the upper copy and Fix removes it. Other text, or the same text further off, stays. +#[test] +fn doubled_type_within_a_point_is_a_duplicate() { + let mut s = session(); + let text = |s: &mut Session, x: f64, text: &str| id_of(&s.execute("text.create", &json!({"x": x, "y": 100, "text": text})).unwrap()); + let base = text(&mut s, 20.0, "Total"); + let doubled = text(&mut s, 20.4, "Total"); + let other = text(&mut s, 20.0, "Subtotal"); + let far = text(&mut s, 23.0, "Subtotal"); + assert_eq!(found(&mut s, "duplicateObjects", "document"), 1); + let shown = s.execute("addon.cleanup.show", &json!({"kind": "duplicateObjects", "scope": "document"})).unwrap(); + assert_eq!(shown["ids"], json!([doubled.0])); + s.execute("addon.cleanup.fix", &json!({"kinds": ["duplicateObjects"], "scope": "document"})).unwrap(); + assert!(node(&s, doubled).is_none()); + for id in [base, other, far] { + assert!(node(&s, id).is_some(), "{id:?} stays"); + } +} + +#[test] +fn fix_all_is_one_undo_step() { + let mut s = session(); + for kind in KINDS { + make_issue(&mut s, kind); + } + select(&mut s, &[]); + let total = s.execute("addon.cleanup.check", &json!({})).unwrap()["total"].as_u64().unwrap(); + assert!(total >= 16, "{total}"); + let (steps, doc) = (undo_steps(&s), s.doc().unwrap().doc.clone()); + let r = s.execute("addon.cleanup.fix", &json!({})).unwrap(); + assert_eq!(r["scope"], "document"); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(s.execute("addon.cleanup.check", &json!({})).unwrap()["total"], 0); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, doc.layers); + assert_eq!(s.doc().unwrap().doc.artboards.len(), doc.artboards.len()); +} + +#[test] +fn the_scope_is_the_selection_or_the_document() { + let mut s = session(); + let a = path(&mut s, json!([{"x": 30, "y": 30}]), false); + let b = path(&mut s, json!([{"x": 60, "y": 30}]), false); + select(&mut s, &[a]); + let r = s.execute("addon.cleanup.check", &json!({"kinds": ["strayPoints"]})).unwrap(); + assert_eq!((r["scope"].as_str(), r["total"].as_u64()), (Some("selection"), Some(1))); + assert_eq!(found(&mut s, "strayPoints", "document"), 2); + s.execute("addon.cleanup.fix", &json!({"kinds": ["strayPoints"]})).unwrap(); + assert!(node(&s, a).is_none() && node(&s, b).is_some(), "only the selection is fixed"); + // Nothing selected: the document. + let r = s.execute("addon.cleanup.check", &json!({})).unwrap(); + assert_eq!((r["scope"].as_str(), r["total"].as_u64()), (Some("document"), Some(1))); + assert!(s.execute("addon.cleanup.check", &json!({"scope": "selection"})).is_err(), "nothing selected"); + for bad in [json!({"scope": "page"}), json!({"kinds": ["nope"]}), json!({"kinds": "strayPoints"}), json!({"kinds": [1]})] { + assert!(s.execute("addon.cleanup.check", &bad).is_err(), "{bad}"); + assert!(s.execute("addon.cleanup.fix", &bad).is_err(), "{bad}"); + } +} + +#[test] +fn show_selects_the_objects_with_the_issue() { + let mut s = session(); + rect(&mut s, 200.0, 20.0, 80.0, 60.0); + let stray = path(&mut s, json!([{"x": 30, "y": 30}]), false); + select(&mut s, &[]); + let r = s.execute("addon.cleanup.show", &json!({"kind": "strayPoints"})).unwrap(); + assert_eq!(r["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects, [stray]); + assert!(s.execute("addon.cleanup.show", &json!({"kind": "emptyText", "scope": "document"})).is_err(), "no such issue"); + assert!(s.execute("addon.cleanup.show", &json!({})).is_err() && s.execute("addon.cleanup.show", &json!({"kind": "x"})).is_err()); +} + +#[test] +fn deep_ungroup_takes_apart_every_level_but_clipping_groups() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0); + let c = rect(&mut s, 70.0, 10.0, 20.0, 20.0); + select(&mut s, &[b, c]); + let inner = id_of(&s.execute("object.group", &json!({})).unwrap()); + change(&mut s, inner, |n| n.opacity = 0.5); + let clipped = rect(&mut s, 100.0, 10.0, 10.0, 10.0); + let clip = rect(&mut s, 95.0, 5.0, 30.0, 30.0); + select(&mut s, &[clipped, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let clip_group = s.doc().unwrap().selection.objects[0]; + select(&mut s, &[a, inner, clip_group]); + let outer = id_of(&s.execute("object.group", &json!({})).unwrap()); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.deepUngroup", &json!({})).unwrap(); + assert_eq!(r["ungrouped"], 2); + assert_eq!(undo_steps(&s), steps + 1); + let d = &s.doc().unwrap().doc; + let layer: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(layer, [a, b, c, clip_group]); + assert!(d.node(outer).is_none() && d.node(inner).is_none()); + assert_eq!(d.node(b).unwrap().opacity, 0.5, "members keep their groups' opacity"); + assert_eq!(s.doc().unwrap().selection.objects.len(), 4); + // Asked to, clipping groups come apart too, their clipping paths kept as plain paths. + select(&mut s, &[clip_group]); + s.execute("addon.cleanup.deepUngroup", &json!({"includeClipGroups": true})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(clip_group).is_none()); + assert!(matches!(d.node(clip).unwrap().kind, NodeKind::Path { clipping: false, .. })); +} + +#[test] +fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0); + let c = rect(&mut s, 70.0, 10.0, 20.0, 20.0); + let e = rect(&mut s, 100.0, 10.0, 20.0, 20.0); + select(&mut s, &[b]); + let hidden = id_of(&s.execute("object.group", &json!({})).unwrap()); + select(&mut s, &[c]); + let locked = id_of(&s.execute("object.group", &json!({})).unwrap()); + change(&mut s, hidden, |n| n.visible = false); + change(&mut s, locked, |n| n.locked = true); + change(&mut s, e, |n| n.locked = true); + s.edit("t", |d, _| { + let w = d.alloc_id(); + Ok(d.wrap(&[a, hidden, locked, e], |ch| Node::group(w, ch))?) + }) + .unwrap(); + let outer = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id; + select(&mut s, &[outer]); + let r = s.execute("addon.cleanup.deepUngroup", &json!({})).unwrap(); + assert_eq!(r["ungrouped"], 1); + assert_eq!(r["ids"], json!([a.0])); + let d = &s.doc().unwrap().doc; + let layer: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(layer, [a, hidden, locked, e], "the hidden and locked groups stay whole"); + assert!(!d.node(hidden).unwrap().visible && d.node(b).unwrap().visible); + assert!(d.node(locked).unwrap().locked && d.node(e).unwrap().locked); + assert_eq!(s.doc().unwrap().selection.objects, [a]); + // Named by `ids`, a locked group stays as it is, with no undo step. + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0]})).unwrap(); + assert_eq!(r["ungrouped"], 0); + assert!(node(&s, locked).is_some()); + assert_eq!(undo_steps(&s), steps); + // With nothing ungrouped, the selection stays and the reply lists it. + assert_eq!(r["ids"], json!([a.0])); + let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0); + select(&mut s, &[a]); + let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [f.0]})).unwrap(); + assert_eq!((r["ids"].clone(), r["ungrouped"].clone()), (json!([a.0]), json!(0))); + assert_eq!(s.doc().unwrap().selection.objects, [a]); +} + +#[test] +fn rejoin_joins_pieces_within_the_gap_only() { + let mut s = session(); + let a = line(&mut s, &[(10.0, 10.0), (50.0, 10.0)]); + let b = line(&mut s, &[(50.05, 10.0), (90.0, 50.0)]); + let far = line(&mut s, &[(92.0, 50.0), (120.0, 50.0)]); + select(&mut s, &[a, b, far]); + let r = s.execute("addon.cleanup.rejoin", &json!({})).unwrap(); + assert_eq!((r["joined"].as_u64(), r["removed"].as_u64()), (Some(1), Some(1))); + // The topmost piece takes the joined path. + assert!(node(&s, a).is_none()); + assert_eq!(anchors(&s, b), 3); + assert_eq!(anchors(&s, far), 2, "beyond the gap"); + select(&mut s, &[b, far]); + let r = s.execute("addon.cleanup.rejoin", &json!({"gap": 3})).unwrap(); + assert_eq!(r["joined"], 1); + assert_eq!(anchors(&s, far), 4); + for bad in [json!({"gap": -1}), json!({"gap": 7}), json!({"gap": "1"})] { + assert!(s.execute("addon.cleanup.rejoin", &bad).is_err(), "{bad}"); + } +} diff --git a/crates/engine/src/cmd/addons/cleanup/text.rs b/crates/engine/src/cmd/addons/cleanup/text.rs new file mode 100644 index 0000000000..73b21356b0 --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup/text.rs @@ -0,0 +1,1011 @@ +//! Artwork Cleanup's text tools: Break Text into Lines / Paragraphs / Words / Glyphs, Combine Point +//! Text, Join Point Text, Split Text at Cursor, Remove Line / Paragraph Breaks, Set Alignment, Keep Position, Reset +//! Text Transform and Replace Missing Fonts. Each is one undo step. Pieces keep their characters' +//! styles and stay where the layout drew them: each is moved so the glyph of its first character +//! lands where it was. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{CharStyle, Document, Justify, Node, NodeId, NodeKind, ParaStyle, RubySpan, TextKind, TextObject}; +use vectorcraft_geom::{Affine, Point, Vec2}; +use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit}; + +use crate::cmd::fonts::{edit_symbol_texts, symbol_texts}; +use crate::cmd::textedit::{editing_range, editing_story}; +use crate::cmd::typecmd::refresh_bounds; +use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; +use crate::{EngineError, Result, Session}; + +/// Most text objects one command takes. +const MAX_TEXTS: usize = 10_000; +/// Most pieces Break Text and Split Text at Cursor make at once. +const MAX_PIECES: usize = 20_000; +/// Most breaks Remove Line / Paragraph Breaks removes at once. +const MAX_BREAKS: usize = 200_000; +/// Most pieces Combine Point Text tries to join, counted over every try: past it, what it joined +/// so far is the result. +const MAX_JOIN_TRIES: usize = 200_000; +/// How far (pt) a glyph Combine Point Text sets may land from where it was. +const TOLERANCE: f64 = 0.01; +/// Combine Point Text: pieces whose baselines are within this many ems of each other share a line +/// (the difference becomes baseline shift); a gap wider than `MAX_GAP` ems, or an overlap of more +/// than `MAX_OVERLAP`, starts another object. +const SAME_LINE: f64 = 0.4; +const MAX_GAP: f64 = 10.0; +const MAX_OVERLAP: f64 = 1.0; +/// Tracking Combine Point Text may give a character (thousandths of an em). +const TRACKING: std::ops::RangeInclusive = -1000.0..=10000.0; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.cleanup.breakText", + "Break Text", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{by?: \"lines\"|\"paragraphs\"|\"words\"|\"glyphs\" (lines), ids?: [id…] (default: the selection)} each horizontal point or area type object becomes point type objects, one per line, paragraph, word or glyph, each where its characters were and with their character styles, as one undo step; spaces between pieces go, a paragraph's lines stay lines (a wrapped line ends in a line break), justified lines close up, and a paragraph broken out whole keeps its bullet (not its number; other pieces have no list markers). Type on a path, vertical type, threaded type and area type whose text doesn't fit stay as they are → {ids (the pieces, selected), skipped}", + has_selection, + break_text + ), + cmd!( + "addon.cleanup.combineText", + "Combine Point Text", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{ids?: [id…] (default: the selection)} merge one-line horizontal point type into as few objects as it can, every glyph staying where it was: pieces turned and sheared alike whose baselines line up (within 0.4 em; the difference becomes baseline shift) join left to right, a space goes between pieces at least half a space apart, and tracking on the character before each piece keeps the spacing; each object keeps its character styles, and the leftmost piece of each run its place and paint, as one undo step → {ids (the objects made, selected), combined (pieces merged into them)}", + has_selection, + combine_text + ), + cmd!( + "addon.cleanup.joinText", + "Join Point Text", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{ids?: [id…] (default: the selection)} join one-line horizontal point type into one point type object, as one undo step: pieces turned and sheared like the top-left one are read as lines (baselines within 0.4 em of each other), top to bottom, each line's pieces left to right with a space between them; each line becomes a paragraph, left aligned, and keeps the distance between baselines as its leading. The text keeps its character styles; the object takes the top-left piece's place and paint, and the other pieces go → {id (selected), joined (pieces merged into it), lines}", + has_selection, + join_text + ), + cmd!( + "addon.cleanup.removeBreaks", + "Remove Breaks", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}", + has_selection, + remove_breaks + ), + cmd!( + "addon.cleanup.splitText", + "Split Text at Cursor", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{} while a Type tool edits horizontal point or area type: the text before the selected characters, they and the text after become point type objects of their own (at a cursor: before and after it), each where its characters were, as one undo step; spaces at the ends of each piece go, and editing ends with the pieces selected → {ids}", + editing_text, + split_text + ), + cmd!( + "addon.cleanup.alignInPlace", + "Set Alignment, Keep Position", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{align: \"left\"|\"center\"|\"right\", ids?: [id…] (default: the selection)} align every paragraph of each horizontal point type object so, moving the object so its longest line stays where it is (one line: the text doesn't move), as one undo step → {ids (the objects changed)}", + has_selection, + align_in_place + ), + cmd!( + "addon.cleanup.resetTextTransform", + "Reset Text Transform", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{scale?: bool (false: the horizontal scale stays; true: it goes too, the object's and every character's), ids?: [id…] (default: the selection)} take the rotation, shear and reflection off each point type object, its size and the centre of its text staying, as one undo step → {ids (the objects changed)}", + has_selection, + reset_transform + ), + cmd!( + "addon.cleanup.replaceFonts", + "Replace Missing Fonts…", + ["Object", "Plug-ins", "Artwork Cleanup"], + None, + "{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in the art of its symbols included) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}", + has_doc, + replace_fonts + ), + ] +} + +/// Enabled while a Type tool edits text. +fn editing_text(s: &Session) -> std::result::Result<(), String> { + match s.tool_options().get("editing") { + Some(v) if !v.is_null() => Ok(()), + _ => Err("Click in type with a Type tool to split it".into()), + } +} + +/// The type objects under `roots` (inside groups and layers, not live art) that can be edited. +fn texts_under(d: &Document, roots: &[NodeId]) -> Result> { + fn visit(n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::Text(_) => out.push(n.id), + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, out)), + _ => {} + } + } + let mut out = vec![]; + roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out)); + let editable = d.editable(); + out.retain(|id| editable(*id)); + out.dedup(); + if out.len() > MAX_TEXTS { + return Err(EngineError::Other("Too many type objects to change at once".into())); + } + Ok(out) +} + +fn text_of(d: &Document, id: NodeId) -> Option<&TextObject> { + match &d.node(id)?.kind { + NodeKind::Text(t) => Some(t), + _ => None, + } +} + +fn layout(t: &TextObject) -> TextLayout { + vectorcraft_text::layout(FontDb::global(), t) +} + +/// Where the layout draws the character at `byte` (the one it starts in): its glyph's pen position. +fn glyph_at(lay: &TextLayout, byte: usize) -> Option { + let start = lay.glyphs.iter().filter(|g| g.len > 0 && g.byte <= byte).map(|g| g.byte).max()?; + lay.glyphs.iter().find(|g| g.len > 0 && g.byte == start).map(|g| g.origin) +} + +/// The pen position of the glyph that starts at `byte`, if one does. +fn glyph_starting(lay: &TextLayout, byte: usize) -> Option { + lay.glyphs.iter().find(|g| g.len > 0 && g.byte == byte).map(|g| g.origin) +} + +/// The first glyph of line `l`, in text order. +fn line_start(lay: &TextLayout, l: usize) -> Option { + let line = lay.lines.get(l)?; + let g = lay.glyphs.get(line.glyph_start..line.glyph_end)?.iter().filter(|g| g.len > 0).min_by_key(|g| g.byte)?; + Some(g.origin) +} + +/// `a..b` of `text` without the white space at its ends; None when nothing else is left. +fn trimmed(text: &str, a: usize, b: usize) -> Option<(usize, usize)> { + let s = text.get(a..b)?; + let start = a + (s.len() - s.trim_start().len()); + let end = a + s.trim_end().len(); + (start < end).then_some((start, end)) +} + +/// Paragraph alignment as point type keeps it: justified lines align to their side. +fn point_justify(j: Justify) -> Justify { + match j { + Justify::JustifyLeft | Justify::JustifyAll => Justify::Left, + Justify::JustifyCenter => Justify::Center, + Justify::JustifyRight => Justify::Right, + j => j, + } +} + +#[derive(Clone, Copy, PartialEq)] +enum By { + Lines, + Paragraphs, + Words, + Glyphs, +} + +/// A type object being cut into point type pieces: its text as drawn (Shrink Text to Fit's sizes +/// taken in) and its layout. +struct Source { + t: TextObject, + lay: TextLayout, + text: String, +} + +impl Source { + /// Horizontal point or area type that isn't threaded and whose text all fits; None otherwise. + fn of(d: &Document, id: NodeId) -> Option { + let t = text_of(d, id)?; + if t.vertical || matches!(t.kind, TextKind::OnPath { .. }) || d.text_threads.iter().any(|th| th.contains(&id)) { + return None; + } + let lay = layout(t); + // Text left out of a frame would be lost with it. + if lay.overflow { + return None; + } + let t = if (lay.fit_scale - 1.0).abs() > 1e-9 { vectorcraft_text::scaled(t, lay.fit_scale) } else { t.clone() }; + Some(Self { text: t.plain_text(), t, lay }) + } + + /// The byte ranges of the pieces `by` cuts the text into. + fn ranges(&self, by: By) -> Vec<(usize, usize)> { + let text = &self.text; + match by { + By::Paragraphs => { + let mut out = vec![]; + let mut a = 0; + for (i, _) in text.match_indices('\n') { + out.push((a, i)); + a = i + 1; + } + out.push((a, text.len())); + out + } + By::Lines => self.lay.lines.iter().map(|l| (l.start, l.end)).collect(), + By::Words => { + let mut out = vec![]; + for l in &self.lay.lines { + let Some(s) = text.get(l.start..l.end) else { continue }; + let mut word: Option = None; + for (i, c) in s.char_indices() { + match (c.is_whitespace(), word) { + (true, Some(w)) => { + out.push((l.start + w, l.start + i)); + word = None; + } + (false, None) => word = Some(i), + _ => {} + } + } + if let Some(w) = word { + out.push((l.start + w, l.end)); + } + } + out + } + By::Glyphs => { + // One piece per cluster (a ligature's characters stay together). + let mut clusters = std::collections::BTreeMap::new(); + for g in self.lay.glyphs.iter().filter(|g| g.len > 0) { + let end = clusters.entry(g.byte).or_insert(g.byte + g.len); + *end = (*end).max(g.byte + g.len); + } + clusters.into_iter().collect() + } + } + } + + /// Point type holding bytes `a..b` (white space at its ends left out) where they were drawn. + /// Lines the layout wrapped end in a forced line break; `lists` keeps bulleted paragraphs' + /// bullets where the piece starts its paragraph. + fn piece(&self, (a, b): (usize, usize), lists: bool) -> Option { + let (a, b) = trimmed(&self.text, a, b)?; + let mut p = TextObject::point(Point::ZERO, "", CharStyle::default()); + p.runs = edit::slice_runs(&self.t.runs, a, b); + p.xf = self.t.xf; + p.optical_margin = self.t.optical_margin; + p.system_layout = self.t.system_layout; + p.fractional_widths = self.t.fractional_widths; + p.ruby = + self.t.ruby.iter().filter(|r| a <= r.start && r.end <= b).map(|r| RubySpan { start: r.start - a, end: r.end - a, ..r.clone() }).collect(); + // The paragraphs it holds, with their styles; the first keeps its bullet only from its start. + let starts_para = self.text.get(..a).is_some_and(|s| s.rsplit('\n').next().is_some_and(|line| line.trim().is_empty())); + let styles = self.t.paragraph_styles(); + let mut paras: Vec = styles.get(self.t.paragraphs_in(a, b))?.to_vec(); + for (i, para) in paras.iter_mut().enumerate() { + para.justify = point_justify(para.justify); + if !(lists && (i > 0 || starts_para) && para.list.as_ref().is_some_and(|l| l.number.is_none())) { + para.list = None; + } + } + p.set_paragraph_styles(paras); + // Lines the layout wrapped end in a forced line break, in place of the spaces they ended in. + let mut wraps = vec![]; + for next in self.lay.lines.iter().skip(1).filter(|l| a < l.start && l.start < b) { + let content = self.text.get(..next.start)?.trim_end_matches([' ', '\t']); + // A line that ends in a break of its own keeps it. + if !content.ends_with(['\n', '\u{2028}']) { + wraps.push((content.len().max(a) - a, next.start - a)); + } + } + for &(s, e) in wraps.iter().rev() { + edit::replace_range(&mut p.runs, s, e, "\u{2028}"); + p.ruby_after_replace(s, e, '\u{2028}'.len_utf8()); + } + self.place(&mut p, a)?; + Some(p) + } + + /// Move `p` (cut from byte `a`) so the glyph of its first character lands where it was drawn. + /// A piece of several lines that starts inside a left-aligned line takes a first-line indent, + /// so its later lines stay where they were too. + fn place(&self, p: &mut TextObject, a: usize) -> Option<()> { + let lay = layout(p); + let mut shift: Vec2 = glyph_at(&self.lay, a)? - glyph_at(&lay, 0)?; + let first = self.lay.lines.iter().rposition(|l| l.start <= a); + if let (Some(now), Some(was)) = (line_start(&lay, 1), first.and_then(|l| line_start(&self.lay, l + 1))) { + let off = was.x - (now.x + shift.x); + let left = match p.para.justify { + Justify::Left => true, + Justify::Auto => lay.lines.first().is_some_and(|l| !l.rtl), + _ => false, + }; + if left && off.abs() > 1e-6 { + p.edit_paras(Some(0..1), |para| para.first_line_indent -= off); + shift.x += off; + } + } + p.xf = self.t.xf * Affine::translate(shift); + Some(()) + } +} + +/// Put each object of `items` (id, the node, its pieces) out of the document, its pieces in its +/// place, as one undo step labelled `label`, the pieces selected → their ids. +fn replace_with_pieces(s: &mut Session, label: &str, items: Vec<(NodeId, Node, Vec)>) -> Result> { + s.edit(label, |d, sel| { + let (mut made, mut places) = (vec![], vec![]); + for (id, mut node, pieces) in items { + // A light template: the pieces take its paint and attributes, not its text. + node.kind = NodeKind::Text(Box::new(TextObject::point(Point::ZERO, "", CharStyle::default()))); + let nodes: Vec = pieces + .into_iter() + .map(|mut t| { + refresh_bounds(&mut t); + let mut n = d.reid(&node); + n.kind = NodeKind::Text(Box::new(t)); + n + }) + .collect(); + made.extend(nodes.iter().map(|n| n.id)); + places.push((id, nodes)); + } + d.insert_beside(places, true)?; + sel.set(made.iter().copied()); + Ok(made.iter().map(|i| i.0).collect()) + }) +} + +fn ids_json(ids: &[NodeId]) -> Vec { + ids.iter().map(|i| i.0).collect() +} + +fn break_text(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.breakText"; + let by = match text_param(p, "by", C)?.unwrap_or("lines") { + "lines" => By::Lines, + "paragraphs" => By::Paragraphs, + "words" => By::Words, + "glyphs" => By::Glyphs, + other => return Err(bad(C, format!("`by` must be lines, paragraphs, words or glyphs, not {other:?}"))), + }; + let d = &s.doc()?.doc; + let (mut items, mut skipped, mut count) = (vec![], vec![], 0); + for id in texts_under(d, &checked_ids_or_selection(s, p, C)?)? { + let (Some(src), Some(node)) = (Source::of(d, id), d.node(id)) else { + skipped.push(id); + continue; + }; + let ranges = src.ranges(by); + count += ranges.len(); + if count > MAX_PIECES { + return Err(EngineError::Other("Too many pieces to make at once".into())); + } + let pieces: Vec = ranges.into_iter().filter_map(|r| src.piece(r, by == By::Paragraphs)).collect(); + if pieces.is_empty() { + skipped.push(id); + } else { + items.push((id, node.clone(), pieces)); + } + } + if items.is_empty() { + return Err(EngineError::Other("Select horizontal point or area type whose text fits".into())); + } + let ids = replace_with_pieces(s, "Break Text", items)?; + Ok(json!({ "ids": ids, "skipped": ids_json(&skipped) })) +} + +fn split_text(s: &mut Session, _: &Value) -> Result { + let Some((id, a, b)) = editing_range(s)? else { + return Err(EngineError::Other("Click in type with a Type tool to split it".into())); + }; + let d = &s.doc()?.doc; + let (Some(src), Some(node)) = (Source::of(d, id), d.node(id).filter(|_| d.is_editable(id))) else { + return Err(EngineError::Other("Select horizontal point or area type whose text fits".into())); + }; + let text = &src.text; + let (a, b) = (edit::floor_char(text, a.min(b)), edit::floor_char(text, a.max(b))); + let cuts: Vec<(usize, usize)> = if a == b { vec![(0, a), (a, text.len())] } else { vec![(0, a), (a, b), (b, text.len())] }; + let pieces: Vec = cuts.into_iter().filter_map(|r| src.piece(r, true)).collect(); + if pieces.len() < 2 { + return Err(EngineError::Other("Nothing to split at the cursor".into())); + } + let node = node.clone(); + let ids = replace_with_pieces(s, "Split Text at Cursor", vec![(id, node, pieces)])?; + // The text edited is gone: the pieces stay selected. + s.set_tool_option("stopEditing", &Value::Bool(true)); + Ok(json!({ "ids": ids })) +} + +/// One piece of point type Combine Point Text takes: its text with its object's scale taken into +/// its characters, and where it starts and ends along its line in the frame of its turn and shear. +struct Piece { + id: NodeId, + t: TextObject, + /// The object's turn and shear (`xf` without its move). + turn: [f64; 4], + /// Where its first character's glyph starts on its baseline, in that frame. + at: Point, + /// Where its last glyph ends along the line, in that frame. + end: f64, + /// Its first character's size. + size: f64, + /// Each character's pen position from the first's (byte, x), as it lays out alone. + pens: Vec<(usize, f64)>, +} + +impl Piece { + fn of(d: &Document, id: NodeId) -> Option<(Self, &Node)> { + let node = d.node(id)?; + let NodeKind::Text(t) = &node.kind else { return None }; + let text = t.plain_text(); + if t.vertical || !matches!(t.kind, TextKind::Point) || text.trim().is_empty() || text.contains(['\n', '\u{2028}']) { + return None; + } + let mut t = (**t).clone(); + t.scale_text_attributes(); + t.style_scale()?; + let lay = layout(&t); + let line = lay.lines.first().filter(|l| !l.rtl && lay.lines.len() == 1)?; + let first = glyph_at(&lay, 0)?; + // The first glyph of each cluster (a mark drawn over it shares its byte). + let mut seen = std::collections::HashSet::new(); + let pens = lay.glyphs.iter().filter(|g| g.len > 0 && seen.insert(g.byte)).map(|g| (g.byte, g.origin.x - first.x)).collect(); + let end = lay.glyphs.iter().map(|g| g.origin.x + g.advance).fold(first.x, f64::max) - first.x; + let [a, b, c, dd, _, _] = t.xf.as_coeffs(); + let turn = Affine::new([a, b, c, dd, 0.0, 0.0]); + let at = turn.inverse() * (t.xf * Point::new(first.x, line.baseline)); + let size = t.runs.first()?.style.size; + if !(at.x.is_finite() && at.y.is_finite() && size > 0.0) { + return None; + } + Some((Self { id, t, turn: [a, b, c, dd], at, end: at.x + end, size, pens }, node)) + } + + /// Whether `o` is turned and sheared alike. + fn turned_like(&self, o: &Piece) -> bool { + self.turn.iter().zip(&o.turn).all(|(x, y)| (x - y).abs() <= 1e-6 * x.abs().max(y.abs()).max(1.0)) + } +} + +/// Whether two objects look alike apart from their text (paint, opacity, blending, effects). +fn same_look(a: &Node, b: &Node) -> bool { + a.appearance == b.appearance + && a.opacity == b.opacity + && a.blend == b.blend + && a.isolate == b.isolate + && a.knockout == b.knockout + && a.extras == b.extras +} + +/// How wide a space of `style` is. +fn space_width(style: &CharStyle) -> f64 { + let probe = TextObject::point(Point::ZERO, " ", CharStyle { tracking: 0.0, ..style.clone() }); + layout(&probe).glyphs.first().map_or(style.size * 0.25, |g| g.advance) +} + +/// `chain` (pieces left to right on one line) as one point type object whose glyphs land where +/// theirs were, or the index of the first piece that can't join the ones before it so. +fn merge(chain: &[&Piece]) -> std::result::Result { + let Some(first) = chain.first() else { return Err(0) }; + let mut runs = vec![]; + // Each piece's first byte, and the byte range of the character before it (whose tracking sets + // the gap). + let (mut starts, mut before) = (vec![], vec![]); + let mut text = String::new(); + for (k, p) in chain.iter().enumerate() { + if let Some(prev) = k.checked_sub(1).and_then(|i| chain.get(i)) { + let starts_blank = p.t.plain_text().starts_with(char::is_whitespace); + let last = prev.t.runs.iter().rev().find(|r| !r.text.is_empty()).map(|r| r.style.clone()).unwrap_or_default(); + if !text.ends_with(char::is_whitespace) && !starts_blank && p.at.x - prev.end >= 0.5 * space_width(&last) { + runs.push(vectorcraft_doc::TextRun::new(" ", last)); + text.push(' '); + } + let c = text.chars().next_back().map_or(1, char::len_utf8); + before.push((text.len() - c, text.len())); + } + starts.push(text.len()); + // Baselines a little apart: the difference is baseline shift (up is positive). + let shift = first.at.y - p.at.y; + for r in &p.t.runs { + let mut r = r.clone(); + r.style.baseline_shift += shift; + text.push_str(&r.text); + runs.push(r); + } + } + let mut m = first.t.clone(); + m.set_all_paras(ParaStyle { justify: Justify::Left, ..first.t.para.clone() }); + let [a, b, c, d] = first.turn; + let base = Affine::new([a, b, c, d, 0.0, 0.0]) * Affine::translate(first.at.to_vec2()); + m.xf = base; + m.runs = runs; + m.ruby.clear(); + // Tracking after the character before each piece, until each lands where it was. + let targets: Vec = chain.iter().map(|p| p.at.x - first.at.x).collect(); + let mut lay = layout(&m); + for _ in 0..4 { + // A piece whose first character joins the one before it (a ligature) can't keep its place. + let xs: Vec = match starts.iter().enumerate().map(|(k, b)| glyph_starting(&lay, *b).map(|g| g.x).ok_or(k)).collect() { + Ok(xs) => xs, + Err(k) => return Err(k.max(1)), + }; + let x0 = xs.first().copied().unwrap_or(0.0); + let off: Vec = targets.iter().zip(&xs).map(|(t, x)| t - (x - x0)).collect(); + if off.iter().all(|o| o.abs() <= TOLERANCE * 0.5) { + break; + } + // Moving piece k moves those after it as far. + for (k, w) in off.windows(2).enumerate() { + let (delta, Some(&(s, e))) = (w[1] - w[0], before.get(k)) else { continue }; + if delta.abs() > 1e-9 { + edit::style_range(&mut m.runs, s, e, |st| st.tracking += delta / st.size.max(1e-6) * 1000.0); + if !TRACKING.contains(&edit::style_at(&m.runs, s).tracking) { + return Err(k + 1); + } + } + } + lay = layout(&m); + } + // Every glyph where it was, within the tolerance; else the run ends before the piece that moved. + let x0 = glyph_starting(&lay, 0).map_or(0.0, |g| g.x); + for (k, p) in chain.iter().enumerate() { + let (Some(&start), Some(&target)) = (starts.get(k), targets.get(k)) else { return Err(k.max(1)) }; + let moved = p.pens.iter().any(|(byte, x)| glyph_starting(&lay, start + byte).is_none_or(|g| (g.x - x0 - target - x).abs() > TOLERANCE)); + if moved { + return Err(k.max(1)); + } + } + m.xf = base * Affine::translate((-x0, 0.0)); + Ok(m) +} + +fn combine_text(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.combineText"; + let d = &s.doc()?.doc; + let mut pieces: Vec<(Piece, &Node)> = + texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id)).collect(); + // Lines: pieces turned alike and looking alike, by baseline, then left to right. + pieces.sort_by(|x, y| x.0.at.y.total_cmp(&y.0.at.y).then(x.0.at.x.total_cmp(&y.0.at.x))); + let mut lines: Vec> = vec![]; + for (piece, node) in &pieces { + let fits = |l: &Vec<(&Piece, &Node)>| { + l.first() + .is_some_and(|(f, n)| f.turned_like(piece) && same_look(n, node) && (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size)) + }; + match lines.iter_mut().find(|l| fits(l)) { + Some(l) => l.push((piece, node)), + None => lines.push(vec![(piece, node)]), + } + } + // Runs along each line: a wide gap or an overlap starts another. + let mut chains: Vec> = vec![]; + for mut l in lines { + l.sort_by(|x, y| x.0.at.x.total_cmp(&y.0.at.x)); + let mut chain: Vec<&Piece> = vec![]; + for (piece, _) in l { + if let Some(prev) = chain.last() { + let gap = piece.at.x - prev.end; + if gap > MAX_GAP * prev.size || gap < -MAX_OVERLAP * prev.size { + chains.push(std::mem::take(&mut chain)); + } + } + chain.push(piece); + } + chains.push(chain); + } + // Each run as one object, or as several where a piece can't keep its place joined. + let mut made: Vec<(NodeId, TextObject, Vec)> = vec![]; + let mut tries = 0; + 'chains: for chain in chains { + let mut rest: &[&Piece] = &chain; + while rest.len() > 1 { + let mut upto = rest.len(); + while let Some(part) = rest.get(..upto) { + tries += part.len(); + if tries > MAX_JOIN_TRIES { + break 'chains; + } + match merge(part) { + Ok(m) => { + let gone = part.iter().skip(1).map(|p| p.id).collect(); + if let Some(first) = part.first() { + made.push((first.id, m, gone)); + } + break; + } + // A run of one stays as it is. + Err(k) if k <= 1 => { + upto = 1; + break; + } + Err(k) => upto = k, + } + } + rest = rest.get(upto.max(1)..).unwrap_or_default(); + } + } + if made.is_empty() { + return Err(EngineError::Other("Select two or more one-line point type objects on one baseline to combine".into())); + } + let combined: usize = made.iter().map(|m| m.2.len()).sum(); + let ids: Vec = made.iter().map(|m| m.0.0).collect(); + s.edit("Combine Point Text", |d, sel| { + let mut gone = vec![]; + for (id, mut t, others) in made { + refresh_bounds(&mut t); + if let Some(n) = d.node_mut(id) { + n.kind = NodeKind::Text(Box::new(t)); + } + gone.extend(others); + } + d.remove_many(&gone)?; + sel.set(ids.iter().map(|i| NodeId(*i))); + Ok(()) + })?; + Ok(json!({ "ids": ids, "combined": combined })) +} + +fn join_text(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.joinText"; + let d = &s.doc()?.doc; + let pieces: Vec = + texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id).map(|p| p.0)).collect(); + // The piece top-left on the page sets the turn; the others turned like it are read in that frame. + let on_page = |p: &Piece| Affine::new([p.turn[0], p.turn[1], p.turn[2], p.turn[3], 0.0, 0.0]) * p.at; + let first = pieces.iter().min_by(|x, y| { + let (a, b) = (on_page(x), on_page(y)); + a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x)) + }); + let mut kept: Vec<&Piece> = first.map(|f| pieces.iter().filter(|p| p.turned_like(f)).collect()).unwrap_or_default(); + kept.sort_by(|x, y| x.at.y.total_cmp(&y.at.y).then(x.at.x.total_cmp(&y.at.x))); + // Lines, top to bottom, by baseline; each line's pieces left to right. + let mut lines: Vec> = vec![]; + for piece in kept { + match lines.last_mut().filter(|l| l.first().is_some_and(|f| (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size))) { + Some(l) => l.push(piece), + None => lines.push(vec![piece]), + } + } + for line in &mut lines { + line.sort_by(|x, y| x.at.x.total_cmp(&y.at.x)); + } + let joined: usize = lines.iter().map(Vec::len).sum(); + let (Some(top), true) = (lines.first().and_then(|l| l.first()).copied(), joined >= 2) else { + return Err(EngineError::Other("Select two or more one-line point type objects to join".into())); + }; + let mut runs: Vec = vec![]; + let mut prev_y = None; + for line in &lines { + let y = line.first().map_or(top.at.y, |p| p.at.y); + // The line keeps the distance from the baseline above as its leading. + let leading = prev_y.map(|above| y - above).filter(|l: &f64| l.is_finite() && *l > 0.0); + prev_y = Some(y); + let last = |runs: &[vectorcraft_doc::TextRun]| runs.iter().rev().find(|r| !r.text.is_empty()).map(|r| r.style.clone()).unwrap_or_default(); + if !runs.is_empty() { + runs.push(vectorcraft_doc::TextRun::new("\n", last(&runs))); + } + let start = runs.len(); + for (k, piece) in line.iter().enumerate() { + let blank = runs.last().is_some_and(|r| r.text.ends_with(char::is_whitespace)) || piece.t.plain_text().starts_with(char::is_whitespace); + if k > 0 && !blank { + runs.push(vectorcraft_doc::TextRun::new(" ", last(&runs))); + } + runs.extend(piece.t.runs.iter().cloned()); + } + if let Some(l) = leading { + for r in runs.iter_mut().skip(start) { + r.style.leading = Some(l); + } + } + } + let mut m = top.t.clone(); + m.set_all_paras(ParaStyle { justify: Justify::Left, ..top.t.para.clone() }); + m.runs = runs; + edit::normalize(&mut m.runs); + m.ruby.clear(); + // The top-left piece's first glyph stays where it was. + let [a, b, c, dd] = top.turn; + let base = Affine::new([a, b, c, dd, 0.0, 0.0]) * Affine::translate(top.at.to_vec2()); + m.xf = base; + let x0 = glyph_starting(&layout(&m), 0).map_or(0.0, |g| g.x); + m.xf = base * Affine::translate((-x0, 0.0)); + refresh_bounds(&mut m); + let id = top.id; + let gone: Vec = lines.iter().flatten().map(|p| p.id).filter(|g| *g != id).collect(); + let count = lines.len(); + s.edit("Join Point Text", |d, sel| { + if let Some(n) = d.node_mut(id) { + n.kind = NodeKind::Text(Box::new(m)); + } + d.remove_many(&gone)?; + sel.set([id]); + Ok(()) + })?; + Ok(json!({ "id": id.0, "joined": joined, "lines": count })) +} + +/// The breaks `brk` in bytes `a..b` of `text`, each with whether it becomes a space (it is between +/// two words). +fn break_cuts(text: &str, a: usize, b: usize, brk: char) -> Vec<(usize, bool)> { + let (a, b) = (edit::floor_char(text, a), edit::floor_char(text, b)); + let Some(range) = text.get(a..b) else { return vec![] }; + let mut prev = text.get(..a).and_then(|s| s.chars().next_back()); + let mut cuts = vec![]; + for (i, c) in range.char_indices() { + let at = a + i; + if c != brk { + prev = Some(c); + continue; + } + // The next character left: past the breaks that go too. + let after = at + c.len_utf8(); + let next = text.get(after..).and_then(|rest| rest.char_indices().find(|(j, n)| *n != brk || after + j >= b).map(|(_, n)| n)); + let space = prev.is_some_and(|p| !p.is_whitespace()) && next.is_some_and(|n| !n.is_whitespace()); + if space { + prev = Some(' '); + } + cuts.push((at, space)); + } + cuts +} + +/// Remove the breaks `brk` at the bytes of `cuts` from `t`, each one that `cuts` marks becoming a +/// space → how many went. +fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize { + for &(at, space) in cuts.iter().rev() { + let insert = if space { " " } else { "" }; + let end = at + brk.len_utf8(); + t.splice_paras(at, end, insert); + edit::replace_range(&mut t.runs, at, end, insert); + t.ruby_after_replace(at, end, insert.len()); + } + cuts.len() +} + +/// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or +/// start of a frame between words of the frames on either side becomes a space. Each editable frame +/// comes with its own breaks, at its own bytes. +fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> { + let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect(); + let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect(); + // The breaks in story order, handed to the frames in one pass. + let mut cuts = break_cuts(&joined, 0, joined.len(), brk).into_iter().peekable(); + let mut out = vec![]; + let mut start = 0; + for (id, text) in texts { + let end = start + text.len(); + let mut own = vec![]; + while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) { + own.push((at - start, space)); + } + if d.is_editable(id) { + out.push((id, own)); + } + start = end; + } + out +} + +fn remove_breaks(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.removeBreaks"; + let (brk, label, none) = match text_param(p, "kind", C)? { + Some("line") => ('\u{2028}', "Remove Line Breaks", "No line breaks to remove"), + Some("paragraph") => ('\n', "Remove Paragraph Breaks", "No paragraph breaks to remove"), + Some(other) => return Err(bad(C, format!("`kind` must be \"line\" or \"paragraph\", not {other:?}"))), + None => return Err(bad(C, "missing `kind`")), + }; + // The characters a Type tool has selected (after Select All in threaded text, all the text of + // every frame of the story), else all the text of the selected type. + let editing = if p.get("ids").is_some() { None } else { editing_range(s)?.filter(|(_, a, b)| a != b) }; + let story = if editing.is_some() { editing_story(s) } else { vec![] }; + let d = &s.doc()?.doc; + // Each type object with the breaks that go from it. + let targets: Vec<(NodeId, Vec<(usize, bool)>)> = match editing { + Some(_) if !story.is_empty() => story_cuts(d, &story, brk), + Some((id, a, b)) => vec![(id, a.min(b), a.max(b))] + .into_iter() + .filter(|(id, ..)| d.is_editable(*id)) + .filter_map(|(id, a, b)| Some((id, break_cuts(&text_of(d, id)?.plain_text(), a, b, brk)))) + .collect(), + None => { + let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?; + // A threaded story whose frames are all among them is read as one text, once. + let named: std::collections::HashSet = ids.iter().copied().collect(); + let mut done = std::collections::HashSet::new(); + let mut out: Vec<(NodeId, Vec<(usize, bool)>)> = vec![]; + for &id in &ids { + if !done.insert(id) { + continue; + } + let story = crate::cmd::threads::story_of(d, id); + if !story.is_empty() && story.iter().all(|f| named.contains(f)) { + done.extend(story.iter().copied()); + out.extend(story_cuts(d, &story, brk)); + } else if let Some(t) = text_of(d, id) { + out.push((id, break_cuts(&t.plain_text(), 0, usize::MAX, brk))); + } + } + out + } + }; + let count: usize = targets.iter().map(|(_, cuts)| cuts.len()).sum(); + if count == 0 { + return Err(EngineError::Other(none.into())); + } + if count > MAX_BREAKS { + return Err(EngineError::Other("Too many breaks to remove at once".into())); + } + let (removed, ids) = s.edit(label, |d, _| { + let (mut removed, mut ids) = (0, vec![]); + for (id, cuts) in targets { + let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { continue }; + let n = apply_cuts(t, &cuts, brk); + if n > 0 { + refresh_bounds(t); + removed += n; + ids.push(id.0); + } + } + Ok((removed, ids)) + })?; + Ok(json!({ "ids": ids, "removed": removed })) +} + +/// Horizontal point type among the objects `p` names. +fn point_texts(s: &Session, p: &Value, cmd: &str) -> Result> { + let d = &s.doc()?.doc; + let ids: Vec = texts_under(d, &checked_ids_or_selection(s, p, cmd)?)? + .into_iter() + .filter(|id| text_of(d, *id).is_some_and(|t| matches!(t.kind, TextKind::Point))) + .collect(); + if ids.is_empty() { + return Err(EngineError::Other("Select point type".into())); + } + Ok(ids) +} + +/// Replace the type objects of `changed` as one undo step labelled `label` → their ids. +fn set_texts(s: &mut Session, label: &str, changed: Vec<(NodeId, TextObject)>, reset_angle: bool) -> Result { + let ids: Vec = changed.iter().map(|c| c.0.0).collect(); + s.edit(label, |d, _| { + for (id, mut t) in changed { + refresh_bounds(&mut t); + if let Some(n) = d.node_mut(id) { + n.kind = NodeKind::Text(Box::new(t)); + if reset_angle { + n.bbox_angle = 0.0; + } + } + } + Ok(()) + })?; + Ok(json!({ "ids": ids })) +} + +fn align_in_place(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.alignInPlace"; + let justify = match text_param(p, "align", C)? { + Some("left") => Justify::Left, + Some("center") => Justify::Center, + Some("right") => Justify::Right, + Some(other) => return Err(bad(C, format!("`align` must be \"left\", \"center\" or \"right\", not {other:?}"))), + None => return Err(bad(C, "missing `align`")), + }; + let ids = point_texts(s, p, C)?; + let d = &s.doc()?.doc; + let mut changed = vec![]; + for id in ids { + let Some(t) = text_of(d, id).filter(|t| !t.vertical && t.para_styles().any(|para| para.justify != justify)) else { continue }; + let was = layout(t); + // The longest line stays where it is. + let Some((i, line)) = was.lines.iter().enumerate().max_by(|a, b| (a.1.x1 - a.1.x0).total_cmp(&(b.1.x1 - b.1.x0))) else { continue }; + let mut n = t.clone(); + n.edit_paras(None, |para| para.justify = justify); + let Some(now) = layout(&n).lines.get(i).map(|l| l.x0) else { continue }; + n.xf *= Affine::translate((line.x0 - now, 0.0)); + changed.push((id, n)); + } + if changed.is_empty() { + return Err(EngineError::Other("The point type is aligned that way already".into())); + } + set_texts(s, "Set Alignment, Keep Position", changed, false) +} + +fn reset_transform(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.resetTextTransform"; + let scale = switch_or(p, "scale", false, C)?; + let ids = point_texts(s, p, C)?; + let d = &s.doc()?.doc; + let mut changed = vec![]; + for id in ids { + let Some(t) = text_of(d, id) else { continue }; + let [a, b, c, dd, _, _] = t.xf.as_coeffs(); + // The object's own axes: its width along its baseline, and its height square to it. + let (sx, det) = (a.hypot(b), a * dd - b * c); + if !(sx > 1e-12 && sx.is_finite() && det.is_finite() && det.abs() > 1e-12) { + continue; + } + let sy = det.abs() / sx; + let unscaled = |t: &TextObject| t.runs.iter().all(|r| r.style.h_scale == 100.0); + let upright = b.abs() <= 1e-9 * sx && c.abs() <= 1e-9 * sy && a > 0.0 && dd > 0.0; + if upright && (!scale || ((sx - sy).abs() <= 1e-9 * sy && unscaled(t))) { + continue; + } + let mut n = t.clone(); + let w = if scale { + n.runs.iter_mut().for_each(|r| r.style.h_scale = 100.0); + sy + } else { + sx + }; + // The centre of the text stays where it is. + let centre = t.xf * layout(t).bounds.center(); + let turn = Affine::scale_non_uniform(w, sy); + let now = turn * layout(&n).bounds.center(); + n.xf = Affine::translate(centre - now) * turn; + changed.push((id, n)); + } + if changed.is_empty() { + return Err(EngineError::Other("The point type has no transform to reset".into())); + } + set_texts(s, "Reset Text Transform", changed, true) +} + +fn replace_fonts(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.cleanup.replaceFonts"; + let default = CharStyle::default().font_family; + let wanted = text_param(p, "font", C)?.filter(|f| !f.trim().is_empty()).unwrap_or(&default); + let db = FontDb::global(); + // Any name of the family is stored as its own name, and a composite font as its own name. + let composite = db.composite_font(wanted).is_some(); + let family = db.stored_family(wanted, "Regular").ok_or_else(|| bad(C, "the replacement font is not available"))?; + let missing = |st: &CharStyle| db.resolve(&st.font_family, &st.font_style).is_none_or(|(_, m)| m == FontMatch::Missing); + let lacks = |t: &TextObject| t.runs.iter().any(|r| missing(&r.style)); + let d = &s.doc()?.doc; + let mut ids = vec![]; + for l in &d.layers { + l.walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && lacks(t) + { + ids.push(n.id); + } + }); + } + // The type in the symbols' art too, which exports name when its font is missing. + if ids.is_empty() && !symbol_texts(d, None).into_iter().any(|(t, _)| lacks(t)) { + return Err(EngineError::Other("No fonts are missing".into())); + } + let runs = s.edit("Replace Missing Fonts", |d, _| { + let mut runs = 0; + let mut replace = |t: &mut TextObject| { + for r in t.runs.iter_mut().filter(|r| missing(&r.style)) { + // The style the font has closest to the one the character had (a composite font's + // parts name their own styles: the character keeps its style). + if !composite { + r.style.font_style = db.face(&family, &r.style.font_style).map_or_else(|| r.style.font_style.clone(), |f| f.style.clone()); + } + r.style.font_family = family.clone(); + r.style.font_version = None; + r.style.font_axes.clear(); + runs += 1; + } + edit::normalize(&mut t.runs); + refresh_bounds(t); + }; + for id in &ids { + if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { + replace(t); + } + } + edit_symbol_texts(d, None, &|t, _| lacks(t), &mut replace); + Ok(runs) + })?; + Ok(json!({ "runs": runs, "font": family })) +} diff --git a/crates/engine/src/cmd/addons/cleanup/text/tests.rs b/crates/engine/src/cmd/addons/cleanup/text/tests.rs new file mode 100644 index 0000000000..c75446b106 --- /dev/null +++ b/crates/engine/src/cmd/addons/cleanup/text/tests.rs @@ -0,0 +1,363 @@ +//! Artwork Cleanup's text tools: pieces stay where their glyphs were drawn and keep their styles, +//! each command is one undo step and refuses cleanly when there is nothing to do. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Justify, NodeId, NodeKind, TextKind, TextObject}; +use vectorcraft_geom::Point; + +use crate::{EngineError, Session}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn text(s: &mut Session, p: Value) -> NodeId { + NodeId(s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap()) +} + +fn obj(s: &Session, id: NodeId) -> TextObject { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); +} + +fn ids(v: &Value) -> Vec { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +/// Each drawn character of `ids` (spaces left out) with where its glyph starts on the page, in +/// the order of the objects and their text. +fn glyphs(s: &Session, ids: &[NodeId]) -> Vec<(char, Point)> { + let mut out = vec![]; + for id in ids { + let t = obj(s, *id); + let text = t.plain_text(); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let mut gs: Vec<_> = lay.glyphs.iter().filter(|g| g.len > 0).collect(); + gs.sort_by_key(|g| g.byte); + gs.dedup_by_key(|g| g.byte); + for g in gs { + let c = text[g.byte..].chars().next().unwrap(); + if !c.is_whitespace() { + out.push((c, t.xf * g.origin)); + } + } + } + out +} + +fn assert_same_places(was: &[(char, Point)], now: &[(char, Point)]) { + assert_eq!(was.iter().map(|g| g.0).collect::(), now.iter().map(|g| g.0).collect::()); + for (a, b) in was.iter().zip(now) { + assert!((a.1 - b.1).hypot() < 0.02, "{:?} moved to {:?}", a, b); + } +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn doc_json(s: &Session) -> String { + serde_json::to_string(&s.doc().unwrap().doc.layers).unwrap() +} + +fn other(r: Result) -> String { + match r { + Err(EngineError::Other(m)) => m, + r => panic!("expected a refusal, got {r:?}"), + } +} + +#[test] +fn break_into_words_keeps_places_styles_and_is_one_step() { + let mut s = session(); + let id = text(&mut s, json!({"x": 40, "y": 100, "text": "Hello big World", "size": 24})); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 6, "end": 9, "size": 36, "tracking": 50})).unwrap(); + let rotated = text(&mut s, json!({"x": 300, "y": 200, "text": "Turned words", "size": 18, "rotation": 30})); + let was = glyphs(&s, &[id, rotated]); + let before = doc_json(&s); + let steps = undo_steps(&s); + select(&mut s, &[id, rotated]); + let r = s.execute("addon.cleanup.breakText", &json!({"by": "words"})).unwrap(); + let pieces = ids(&r); + assert_eq!(pieces.len(), 5); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(s.doc().unwrap().selection.objects.len(), 5, "the pieces are selected"); + let texts: Vec = pieces.iter().map(|p| obj(&s, *p).plain_text()).collect(); + assert_eq!(texts, ["Hello", "big", "World", "Turned", "words"]); + assert_same_places(&was, &glyphs(&s, &pieces)); + let big = obj(&s, pieces[1]); + assert!(matches!(big.kind, TextKind::Point)); + assert_eq!((big.runs[0].style.size, big.runs[0].style.tracking), (36.0, 50.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc_json(&s), before); +} + +#[test] +fn break_area_type_into_lines_paragraphs_and_glyphs() { + for (by, count) in [("lines", None), ("paragraphs", Some(2)), ("glyphs", None)] { + let mut s = session(); + let id = text( + &mut s, + json!({"x": 40, "y": 40, "text": "A paragraph long enough to wrap in its frame\nSecond one", "size": 14, "area": {"width": 140, "height": 200}}), + ); + let t = obj(&s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + assert!(lay.lines.len() >= 3, "the first paragraph wraps"); + let was = glyphs(&s, &[id]); + select(&mut s, &[id]); + let r = s.execute("addon.cleanup.breakText", &json!({"by": by})).unwrap(); + let pieces = ids(&r); + let want = count.unwrap_or(if by == "lines" { lay.lines.len() } else { was.len() }); + assert_eq!(pieces.len(), want, "{by}"); + assert_same_places(&was, &glyphs(&s, &pieces)); + if by == "paragraphs" { + // The wrapped lines end in line breaks. + assert!(obj(&s, pieces[0]).plain_text().contains('\u{2028}')); + } + } +} + +#[test] +fn break_text_refuses_what_it_cannot_break() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + assert!(other(s.execute("addon.cleanup.breakText", &json!({}))).contains("point or area type")); + let r = s.execute("addon.cleanup.breakText", &json!({"by": "sentences"})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}"); +} + +#[test] +fn combine_puts_glyph_pieces_back_together_where_they_were() { + let mut s = session(); + let id = text(&mut s, json!({"x": 50, "y": 120, "text": "Water Lily", "size": 30})); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 6, "end": 10, "fill": "#ff0000"})).unwrap(); + let was = glyphs(&s, &[id]); + select(&mut s, &[id]); + let pieces = ids(&s.execute("addon.cleanup.breakText", &json!({"by": "glyphs"})).unwrap()); + assert_eq!(pieces.len(), 9); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.combineText", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + let made = ids(&r); + assert_eq!((made.len(), r["combined"].as_u64()), (1, Some(8))); + let t = obj(&s, made[0]); + assert_eq!(t.plain_text(), "Water Lily", "a space goes back between the words"); + assert_same_places(&was, &glyphs(&s, &made)); + let red = t.runs.iter().find(|r| r.text.contains('L')).unwrap(); + assert_ne!(red.style.fill, t.runs[0].style.fill, "styles stay"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(pieces[1]).is_some(), "undo brings the pieces back"); +} + +#[test] +fn combine_joins_only_pieces_on_one_line_turned_alike() { + let mut s = session(); + let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20})); + let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20})); + let c = text(&mut s, json!({"x": 50, "y": 200, "text": "Below", "size": 20})); + let d = text(&mut s, json!({"x": 300, "y": 100, "text": "Turned", "size": 20, "rotation": 45})); + let was = glyphs(&s, &[a, b]); + select(&mut s, &[a, b, c, d]); + let r = s.execute("addon.cleanup.combineText", &json!({})).unwrap(); + assert_eq!(ids(&r), [a]); + assert_eq!(obj(&s, a).plain_text(), "Left Right"); + assert_same_places(&was, &glyphs(&s, &[a])); + let doc = &s.doc().unwrap().doc; + assert!(doc.node(b).is_none() && doc.node(c).is_some() && doc.node(d).is_some()); + select(&mut s, &[c, d]); + assert!(other(s.execute("addon.cleanup.combineText", &json!({}))).contains("combine")); +} + +/// Join Point Text makes one object of stacked one-line pieces: lines top to bottom as paragraphs, +/// pieces on a line left to right, each line's baseline where it was (its leading is the distance +/// from the line above), in one undo step. A piece turned unlike the top-left one stays. +#[test] +fn join_stacks_lines_into_one_object_with_their_spacing() { + let mut s = session(); + let a = text(&mut s, json!({"x": 50, "y": 100, "text": "First", "size": 20})); + let b = text(&mut s, json!({"x": 120, "y": 101, "text": "line", "size": 20})); + let c = text(&mut s, json!({"x": 50, "y": 130, "text": "Second", "size": 20})); + let d = text(&mut s, json!({"x": 50, "y": 166, "text": "Third", "size": 20})); + let turned = text(&mut s, json!({"x": 300, "y": 300, "text": "Turned", "size": 20, "rotation": 45})); + let was = glyphs(&s, &[a, c, d]); + select(&mut s, &[d, b, turned, c, a]); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.joinText", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!((r["id"].as_u64(), r["joined"].as_u64(), r["lines"].as_u64()), (Some(a.0), Some(4), Some(3))); + let t = obj(&s, a); + assert_eq!(t.plain_text(), "First line\nSecond\nThird"); + assert_eq!(t.runs.iter().filter(|r| r.text.contains("Third")).map(|r| r.style.leading).collect::>(), [Some(36.0)]); + // Each line's first glyph is where it was. + let now = glyphs(&s, &[a]); + for ch in ['F', 'S', 'T'] { + let (p, q) = (was.iter().find(|g| g.0 == ch).unwrap().1, now.iter().find(|g| g.0 == ch).unwrap().1); + assert!((p - q).hypot() < 0.05, "{ch}: {p:?} moved to {q:?}"); + } + let doc = &s.doc().unwrap().doc; + assert!(doc.node(b).is_none() && doc.node(c).is_none() && doc.node(d).is_none() && doc.node(turned).is_some()); + select(&mut s, &[turned]); + assert!(other(s.execute("addon.cleanup.joinText", &json!({}))).contains("join")); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(c).is_some(), "undo brings the pieces back"); +} + +#[test] +fn remove_line_and_paragraph_breaks() { + let mut s = session(); + let id = text(&mut s, json!({"x": 40, "y": 60, "text": "one\u{2028}two \u{2028}three\nfour\n\nfive", "size": 12})); + select(&mut s, &[id]); + let before = doc_json(&s); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "line"})).unwrap(); + assert_eq!(r["removed"], 2); + assert_eq!(obj(&s, id).plain_text(), "one two three\nfour\n\nfive"); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap(); + assert_eq!(r["removed"], 3); + let t = obj(&s, id); + assert_eq!((t.plain_text().as_str(), t.paragraph_count()), ("one two three four five", 1)); + assert_eq!(other(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "line"}))), "No line breaks to remove"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc_json(&s), before); + assert!(matches!(s.execute("addon.cleanup.removeBreaks", &json!({})), Err(EngineError::BadParams { .. }))); +} + +/// The Type tool editing `id` with bytes `anchor..caret` selected. +fn edit_text(s: &mut Session, id: NodeId, anchor: usize, caret: usize) { + s.select_tool("type", Default::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": id.0, "anchor": anchor, "caret": caret})); +} + +#[test] +fn remove_breaks_in_the_characters_a_type_tool_selected() { + let mut s = session(); + let id = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb\nc", "size": 12})); + select(&mut s, &[id]); + edit_text(&mut s, id, 0, 2); + s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap(); + assert_eq!(obj(&s, id).plain_text(), "a b\nc"); +} + +#[test] +fn split_at_the_cursor_and_around_a_selection() { + for (anchor, caret, want) in [(6, 6, &["Split", "here please"][..]), (6, 10, &["Split", "here", "please"][..])] { + let mut s = session(); + let id = text(&mut s, json!({"x": 40, "y": 60, "text": "Split here please", "size": 20, "justify": "center"})); + let was = glyphs(&s, &[id]); + select(&mut s, &[id]); + let r = s.execute("addon.cleanup.splitText", &json!({})); + assert!(matches!(&r, Err(EngineError::Disabled(_, why)) if why.contains("Type tool")), "{r:?}"); + edit_text(&mut s, id, anchor, caret); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.splitText", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + let pieces = ids(&r); + let texts: Vec = pieces.iter().map(|p| obj(&s, *p).plain_text()).collect(); + assert_eq!(texts, want); + assert_same_places(&was, &glyphs(&s, &pieces)); + assert!(s.tool_options()["editing"].is_null(), "editing ends"); + } +} + +#[test] +fn split_keeps_the_later_lines_of_a_wrapped_piece() { + let mut s = session(); + let id = text( + &mut s, + json!({"x": 40, "y": 40, "text": "First words then a long run of text that wraps in the frame", "size": 14, "area": {"width": 160, "height": 200}}), + ); + let was = glyphs(&s, &[id]); + select(&mut s, &[id]); + edit_text(&mut s, id, 6, 6); + let pieces = ids(&s.execute("addon.cleanup.splitText", &json!({})).unwrap()); + assert_eq!(pieces.len(), 2); + assert_same_places(&was, &glyphs(&s, &pieces)); +} + +#[test] +fn set_alignment_keeps_the_text_in_place() { + let mut s = session(); + let id = text(&mut s, json!({"x": 100, "y": 60, "text": "Stay put", "size": 20})); + let multi = text(&mut s, json!({"x": 100, "y": 160, "text": "Short\u{2028}The longest line", "size": 20})); + let was = glyphs(&s, &[id]); + let longest: Vec<_> = glyphs(&s, &[multi]).into_iter().skip(5).collect(); + select(&mut s, &[id, multi]); + for align in ["center", "right", "left"] { + s.execute("addon.cleanup.alignInPlace", &json!({"align": align})).unwrap(); + assert_same_places(&was, &glyphs(&s, &[id])); + assert_same_places(&longest, &glyphs(&s, &[multi]).into_iter().skip(5).collect::>()); + } + assert_eq!(obj(&s, id).para.justify, Justify::Left); + assert!(other(s.execute("addon.cleanup.alignInPlace", &json!({"align": "left"}))).contains("already")); + assert!(matches!(s.execute("addon.cleanup.alignInPlace", &json!({"align": "up"})), Err(EngineError::BadParams { .. }))); +} + +#[test] +fn reset_text_transform_takes_off_rotation_and_with_scale_the_horizontal_scale() { + let mut s = session(); + let id = text(&mut s, json!({"x": 100, "y": 100, "text": "Tilted", "size": 20, "rotation": 30})); + s.execute("text.setRangeStyle", &json!({"id": id.0, "hScale": 150})).unwrap(); + let centre = |s: &Session| { + let t = obj(s, id); + t.xf * vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).bounds.center() + }; + let was = centre(&s); + let size = obj(&s, id).effective_char_style(&obj(&s, id).runs[0].style).unwrap().size; + select(&mut s, &[id]); + s.execute("addon.cleanup.resetTextTransform", &json!({})).unwrap(); + let t = obj(&s, id); + let [_, b, c, _, _, _] = t.xf.as_coeffs(); + assert!(b.abs() < 1e-9 && c.abs() < 1e-9, "{:?}", t.xf); + assert!((centre(&s) - was).hypot() < 1e-6); + assert!((t.effective_char_style(&t.runs[0].style).unwrap().size - size).abs() < 1e-6, "the size stays"); + assert!(t.runs[0].style.h_scale > 100.0, "the horizontal scale stays"); + assert!(other(s.execute("addon.cleanup.resetTextTransform", &json!({}))).contains("no transform")); + s.execute("addon.cleanup.resetTextTransform", &json!({"scale": true})).unwrap(); + assert_eq!(obj(&s, id).runs[0].style.h_scale, 100.0); +} + +#[test] +fn replace_missing_fonts_with_the_default_or_a_chosen_font() { + let mut s = session(); + let gone = text(&mut s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family", "style": "Bold"})); + let kept = text(&mut s, json!({"x": 40, "y": 120, "text": "Fine", "size": 20})); + let fine = obj(&s, kept); + let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap(); + assert_eq!((r["runs"].as_u64(), r["font"].as_str()), (Some(1), Some("Source Sans 3"))); + let t = obj(&s, gone); + assert_eq!((t.runs[0].style.font_family.as_str(), t.runs[0].style.font_style.as_str()), ("Source Sans 3", "Bold")); + assert_eq!(obj(&s, kept), fine); + assert_eq!(other(s.execute("addon.cleanup.replaceFonts", &json!({}))), "No fonts are missing"); + let r = s.execute("addon.cleanup.replaceFonts", &json!({"font": "No Such Font Family"})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}"); +} + +#[test] +fn replace_missing_fonts_reaches_the_type_in_symbols() { + let mut s = session(); + let gone = text(&mut s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family"})); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [gone.0]})).unwrap(); + let family = |s: &Session| crate::cmd::fonts::symbol_texts(&s.doc().unwrap().doc, None)[0].0.runs[0].style.font_family.clone(); + assert_eq!(family(&s), "No Such Font Family"); + let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap(); + assert_eq!((r["runs"].as_u64(), r["font"].as_str()), (Some(1), Some("Source Sans 3")), "{r}"); + assert_eq!(family(&s), "Source Sans 3"); + assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None); + assert_eq!(other(s.execute("addon.cleanup.replaceFonts", &json!({}))), "No fonts are missing"); + // A symbol being edited: its type on the editing layer is replaced once. + let gone = text(&mut s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family"})); + s.execute("symbol.new", &json!({"name": "Mark 2", "ids": [gone.0]})).unwrap(); + s.execute("symbol.edit", &json!({"name": "Mark 2"})).unwrap(); + let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap(); + assert_eq!(r["runs"].as_u64(), Some(1), "{r}"); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None); +} diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs new file mode 100644 index 0000000000..cd30d29d15 --- /dev/null +++ b/crates/engine/src/cmd/addons/color.rs @@ -0,0 +1,272 @@ +//! Color Effects (`addon.color.*`), a built-in add-on: its live effects (Exposure, Desaturate, +//! Duotone and Invert Colors, in Effect › Color Effects) are the effects crate's; here, Apply as +//! Filter writes any colour adjustment into the colours themselves, Select by Color Kind selects the +//! objects that use spot colours, carry a live colour adjustment, or are images of a colour model, +//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest +//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend +//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply +//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its panel and its submenu, +//! Object › Plug-ins › Color Effects, are the UI's. + +pub mod legend; +mod nearest; +mod print_fixes; +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind}; +use vectorcraft_render::effects; + +use super::super::colorcmds::recolor_links; +use super::super::paint::{restore_unpainted_stroke, set_run_stroke}; +use super::super::select::walk_selectable; +use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, paint_targets, switch_or, text_param}; +use crate::{EngineError, Result, Session}; + +/// The kinds Select by Color Kind selects (`addon.color.select`). +pub const SELECT_KINDS: [&str; 5] = ["spotColors", "colorEffects", "rgbImages", "cmykImages", "grayImages"]; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.color.select", + "Select by Color Kind", + ["Object", "Plug-ins", "Color Effects"], + None, + "{kind: \"spotColors\" (objects painted with a spot colour swatch, solid or in a gradient's stops) | \"colorEffects\" (objects carrying a visible colour adjustment effect, on themselves or on a fill or stroke) | \"rgbImages\" | \"cmykImages\" | \"grayImages\" (embedded or linked images whose pixels are RGB, CMYK, or grayscale or 1-bit)} select those objects among the ones Select All reaches, inside groups too; locked and hidden ones are left out → {count}", + has_doc, + select + ), + cmd!( + "addon.color.filter", + "Apply as Filter", + ["Object", "Plug-ins", "Color Effects"], + None, + "{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step; their effects stay. Duotone links a colour to its one tone's swatch as the live effect does → {changed}", + has_selection, + filter + ), + cmd!( + "addon.color.printFixes", + "Print Ink Fixes", + ["Object", "Plug-ins", "Color Effects"], + None, + "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", + has_doc, + print_fixes::run + ), + cmd!( + query "addon.color.nearestSwatch", + "Find Nearest Swatch", + ["Object", "Plug-ins", "Color Effects"], + None, + "{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up, #rrggbbaa and #rgba refused; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}", + has_doc, + nearest::find + ), + cmd!( + "addon.color.applyNearestSwatch", + "Apply Nearest Swatch", + ["Object", "Plug-ins", "Color Effects"], + None, + "{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step: a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}", + has_selection, + nearest::apply + ), + cmd!( + "addon.color.fillToStroke", + "Apply Fill to Stroke", + ["Object", "Plug-ins", "Color Effects"], + None, + "{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's series marks and labels keep the paint when the graph is drawn again. skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}", + has_doc, + |s, p| copy_paint(s, p, true) + ), + cmd!( + "addon.color.strokeToFill", + "Apply Stroke to Fill", + ["Object", "Plug-ins", "Color Effects"], + None, + "{ids?|id?, skipNone?: bool} each target's top fill takes its own top stroke's paint, as addon.color.fillToStroke does the other way; the stroke itself is unchanged. The default fill takes the default stroke → {objects}", + has_doc, + |s, p| copy_paint(s, p, false) + ), + ] + .into_iter() + .chain(legend::specs()) + .collect() +} + +fn select(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.color.select"; + let kind = text_param(p, "kind", C)?.ok_or_else(|| bad(C, "missing `kind`"))?; + if !SELECT_KINDS.contains(&kind) { + return Err(bad(C, "`kind` must be spotColors, colorEffects, rgbImages, cmykImages or grayImages")); + } + let st = s.doc()?; + let mut ids: Vec = vec![]; + walk_selectable(&st.doc, st.isolation, |n| { + if is_of_kind(&st.doc, n, kind) { + ids.push(n.id); + // An object taken whole: what is inside it isn't taken again. + return false; + } + true + }); + s.select(|_, sel| sel.set(ids))?; + Ok(json!({ "count": s.doc()?.selection.objects.len() })) +} + +/// Is `n` an object of Select by Color Kind's `kind`? Containers count for colour effects only: +/// for the other kinds, the objects inside them are looked at one by one. +fn is_of_kind(d: &Document, n: &Node, kind: &str) -> bool { + match kind { + "colorEffects" => effects::has_adjustment(n), + "spotColors" if !n.is_container() => { + let mut spot = false; + vectorcraft_doc::swatches::node_colors(n, &mut |_, swatch| { + spot |= swatch.is_some_and(|name| d.swatch(name).is_some_and(|w| w.spot)); + }); + spot + } + _ => { + let NodeKind::Image(img) = &n.kind else { return false }; + let Some(blob) = d.images.get(&img.key) else { return false }; + let model = if blob.is_cmyk() { + "cmykImages" + } else if is_gray(&blob.bytes) { + "grayImages" + } else { + "rgbImages" + }; + model == kind + } + } +} + +/// Are the encoded image `bytes` grayscale or 1-bit? Reads only the header. +fn is_gray(bytes: &[u8]) -> bool { + use image::ImageDecoder as _; + let decoder = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok().and_then(|r| r.into_decoder().ok()); + decoder.is_some_and(|d| matches!(d.color_type(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16)) +} + +fn filter(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.color.filter"; + let id = text_param(p, "effect", C)?.ok_or_else(|| bad(C, "missing `effect`"))?; + if !effects::is_adjustment(id) { + return Err(bad(C, format!("`{id}` is not a colour adjustment"))); + } + let params = match p.get("params") { + None | Some(Value::Null) => json!({}), + Some(v @ Value::Object(_)) => v.clone(), + Some(_) => return Err(bad(C, "`params` must be an object")), + }; + let fx = effects::new_effect(id, ¶ms).ok_or_else(|| bad(C, format!("unknown effect `{id}`")))?; + let ids = checked_ids_or_selection(s, p, C)?; + // Settings that change nothing still make the pass, which then leaves every colour as it was. + let Some(map) = effects::color_map(&[fx]) else { return Ok(json!({ "changed": 0 })) }; + let mut given = p.clone(); + if let Some(o) = given.as_object_mut() { + o.insert("ids".into(), json!(ids.iter().map(|i| i.0).collect::>())); + } + let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…')); + let kinds = effects::addons::duotone::swatch_kinds(&s.doc()?.doc); + let swatches = |name: &str| kinds.get(name).copied(); + recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches)) +} + +/// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own +/// paints onto the other, so a mixed selection keeps each object's colour (#5530). Aimed and +/// undone like Swap Fill and Stroke; characters selected with the Type tool are the only ones that +/// change, as for `paint.setFill`. A graph's series marks and labels give the graph the paint in +/// the same undo step, as `paint.setFill` does, so drawing the graph again keeps it. When nothing +/// changes, the document and its undo history stay as they are. +fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result { + let (cmd, label) = + if to_stroke { ("addon.color.fillToStroke", "Apply Fill to Stroke") } else { ("addon.color.strokeToFill", "Apply Stroke to Fill") }; + let skip_none = switch_or(p, "skipNone", false, cmd)?; + // One text style: its stroke takes its fill, or the other way. + let copy_run = |st: &mut CharStyle| { + let from = if to_stroke { st.fill.clone() } else { st.stroke.clone() }; + if (skip_none && from.is_none()) || from == if to_stroke { st.stroke.clone() } else { st.fill.clone() } { + return; + } + if to_stroke { + set_run_stroke(st, from); + } else { + st.fill = from; + } + }; + if p.get("ids").is_none() + && p.get("id").is_none() + && let Some((id, a, b)) = super::super::textedit::editing_range(s)? + && a != b + { + // After Select All in threaded text, every frame's text takes it. + let story = super::super::textedit::editing_story(s); + let ranges: Vec<(NodeId, usize, usize)> = + if story.is_empty() { vec![(id, a, b)] } else { story.iter().map(|f| (*f, 0, usize::MAX)).collect() }; + let ids: Vec = ranges.iter().map(|(f, _, _)| *f).collect(); + let before = s.doc()?.doc.clone(); + let n = super::super::overprint::edit_counted(s, label, |d| { + for &(id, a, b) in &ranges { + let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; + vectorcraft_text::edit::style_range(&mut t.runs, a, b, copy_run); + super::super::typecmd::refresh_bounds(t); + } + Ok(super::super::appearance::count_changed(d, &before, &ids)) + })?; + return Ok(json!({"objects": n})); + } + // A graph's series group stands for its marks, as for `paint.setFill`. + let ids = super::super::graph::paint_targets(&s.doc()?.doc, &paint_targets(s, p)?); + let mut objects = 0; + if !ids.is_empty() { + let before = s.doc()?.doc.clone(); + super::super::overprint::edit_counted(s, label, |d| { + for id in &ids { + let Some(node) = d.node_mut(*id) else { continue }; + if let NodeKind::Text(t) = &mut node.kind { + for r in &mut t.runs { + copy_run(&mut r.style); + } + super::super::typecmd::refresh_bounds(t); + continue; + } + let ap = &mut node.appearance; + let (from, to) = if to_stroke { (ap.fill_paint(), ap.stroke_paint()) } else { (ap.stroke_paint(), ap.fill_paint()) }; + // A missing item reads as None: copying None onto it would add an item that + // changes nothing. + if (skip_none && from.is_none()) || from == to { + continue; + } + if to_stroke { + restore_unpainted_stroke(ap, None, &from); + ap.set_stroke(from); + } else { + ap.set_fill(from); + } + } + objects = super::super::appearance::count_changed(d, &before, &ids); + // The graph keeps the paint its series marks and labels now have. + let series = super::super::graph::capture_series_paints(d, &ids, !to_stroke); + let labels = super::super::graph::capture_label_styles(d, &ids, ©_run); + Ok(objects + usize::from(series || labels)) + })?; + } + // The defaults for new art change the same way, as Swap Fill and Stroke changes them. + let from = if to_stroke { s.paint.fill.clone() } else { s.paint.stroke.clone() }; + if !(skip_none && from.is_none()) { + if to_stroke { + if s.paint.stroke.is_none() && !from.is_none() && s.paint.stroke_width == 0.0 { + s.paint.stroke_width = 1.0; + } + s.paint.stroke = from; + } else { + s.paint.fill = from; + } + } + Ok(json!({"objects": objects})) +} diff --git a/crates/engine/src/cmd/addons/color/legend.rs b/crates/engine/src/cmd/addons/color/legend.rs new file mode 100644 index 0000000000..e2f38a7a17 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/legend.rs @@ -0,0 +1,183 @@ +//! Create Swatch Legend (`addon.color.swatchLegend`; Object › Plug-ins › Color Effects › Create +//! Swatch Legend…, #4919): a grid of chips on the artboard, one per colour swatch, each filled with +//! its swatch and labelled with the swatch's name and colour values, as one group made in one undo +//! step. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint, cms::Model}; +use vectorcraft_doc::{Appearance, AreaFit, Node, NodeKind, TextKind, TextObject}; +use vectorcraft_geom::{Point, Rect, shapes}; + +use super::super::super::{CommandSpec, bad, cmd, has_doc}; +use crate::{Result, Session}; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.color.swatchLegend", + "Create Swatch Legend", + ["Object", "Plug-ins", "Color Effects"], + None, + "{names?: [swatch name…] (default: every colour swatch of the document, in panel order), columns?: 1..50 (4), size?: chip side in pt 8..1000 (72), gap?: pt 0..1000 (12), values?: [hex|rgb|cmyk|lab|gray…] (each at most once; default: each swatch's own colour model; spot swatches also say spot), x?, y? (the legend's top-left; default: the first artboard's, inset by `gap`)} draw a legend of colour swatches: one square chip per swatch filled with it (linked to it), labelled inside with the swatch name and the values asked for, in black on light chips and white on dark ones, as one group in one undo step; the group is selected → {id, count} (#4919)", + has_doc, + legend + )] +} + +/// The command. +pub const COMMAND: &str = "addon.color.swatchLegend"; + +/// Most swatches one legend draws. +const MAX_CHIPS: usize = 2000; +const VALUES: [&str; 5] = ["hex", "rgb", "cmyk", "lab", "gray"]; + +fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive, cmd: &str) -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(default), + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && range.contains(n)) + .ok_or_else(|| bad(cmd, format!("`{key}` must be a number {}..{}", range.start(), range.end()))), + } +} + +/// The label lines of colour `c`: the values `values` names, else those of its own model. +fn value_lines(c: Color, values: &[String], spot: bool) -> Vec { + let own = match c.model() { + Model::Rgb => "rgb", + Model::Cmyk => "cmyk", + Model::Gray => "gray", + Model::Lab => "lab", + }; + let picked: Vec<&str> = if values.is_empty() { vec![own] } else { values.iter().map(String::as_str).collect() }; + let pct = |v: f32| (v * 100.0).round() as i32; + let mut lines: Vec = picked + .into_iter() + .map(|v| match v { + "hex" => c.to_hex().to_uppercase(), + "rgb" => { + let [r, g, b] = c.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as i32); + format!("R={r} G={g} B={b}") + } + "cmyk" => { + let [cy, m, y, k] = c.to_cmyk().map(|v| pct(v.clamp(0.0, 1.0))); + format!("C={cy} M={m} Y={y} K={k}") + } + "lab" => { + let l = c.to_lab(); + format!("L={} a={} b={}", l.l.round() as i32, l.a.round() as i32, l.b.round() as i32) + } + _ => { + // As Edit Colors › Convert to Grayscale and the Color panel convert it. + let k = match c.in_model(Model::Gray) { + Color::Gray { k } => k, + _ => 1.0 - c.to_lab().l / 100.0, + }; + format!("K={}%", pct(k.clamp(0.0, 1.0))) + } + }) + .collect(); + if spot { + lines.insert(0, "Spot".into()); + } + lines +} + +fn legend(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMAND; + let columns = number(p, "columns", 4.0, 1.0..=50.0, C)?; + if columns.fract() != 0.0 { + return Err(bad(C, "`columns` must be a whole number 1..50")); + } + let columns = columns as usize; + let size = number(p, "size", 72.0, 8.0..=1000.0, C)?; + let gap = number(p, "gap", 12.0, 0.0..=1000.0, C)?; + let values: Vec = match p.get("values") { + None | Some(Value::Null) => vec![], + Some(Value::Array(a)) => a + .iter() + .map(|v| { + v.as_str().filter(|v| VALUES.contains(v)).map(str::to_string).ok_or_else(|| bad(C, "`values` must name hex, rgb, cmyk, lab or gray")) + }) + .collect::>()?, + Some(_) => return Err(bad(C, "`values` must be a list")), + }; + // Each kind once: every value line goes into every chip, so repeats would only multiply them. + if values.iter().enumerate().any(|(i, v)| values[..i].contains(v)) { + return Err(bad(C, "`values` names a kind twice")); + } + let st = s.doc()?; + let doc = &st.doc; + let colour = |w: &&vectorcraft_color::Swatch| w.paint.color().is_some(); + let swatches: Vec = match p.get("names") { + None | Some(Value::Null) => doc.swatches_iter().filter(colour).cloned().collect(), + Some(Value::Array(a)) => { + let mut out = vec![]; + for n in a { + let n = n.as_str().ok_or_else(|| bad(C, "`names` must be a list of swatch names"))?; + let w = doc.swatches_iter().find(|w| w.name == n).ok_or_else(|| bad(C, format!("no swatch named `{n}`")))?; + if w.paint.color().is_none() { + return Err(bad(C, format!("`{n}` is not a colour swatch"))); + } + out.push(w.clone()); + } + out + } + Some(_) => return Err(bad(C, "`names` must be a list of swatch names")), + }; + if swatches.is_empty() { + return Err(bad(C, "there are no colour swatches to draw")); + } + if swatches.len() > MAX_CHIPS { + return Err(bad(C, format!("a legend draws at most {MAX_CHIPS} swatches"))); + } + let origin = doc.artboards.first().map_or(Point::ZERO, |a| a.rect.origin()); + let x0 = number(p, "x", origin.x + gap, -1e6..=1e6, C)?; + let y0 = number(p, "y", origin.y + gap, -1e6..=1e6, C)?; + let system_layout = doc.setup.system_layout; + let parent = st.target_parent()?; + let text_size = (size / 7.0).clamp(4.0, 12.0); + let pad = (size / 12.0).clamp(1.0, 8.0); + let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size })); + let count = swatches.len(); + // Each chip's fill links to its swatch, as paint.setFill {swatch} links art: editing a global or + // spot swatch then recolours the legend too. + let fills: Vec = + swatches.iter().map(|w| super::super::super::paint::swatch_solid(doc, &w.name, None).unwrap_or_else(|_| w.paint.clone())).collect(); + let gid = s.edit("Create Swatch Legend", |d, sel| { + let mut children = Vec::with_capacity(count * 2); + for (i, (w, fill)) in swatches.iter().zip(fills).enumerate() { + let Some(c) = w.paint.color() else { continue }; + let (col, row) = (i % columns, i / columns); + let (x, y) = (x0 + col as f64 * (size + gap), y0 + row as f64 * (size + gap)); + let mut chip = + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + size, y + size)), Appearance::basic(fill, Paint::None, 0.0)); + chip.name = Some(w.name.clone()); + children.push(std::sync::Arc::new(chip)); + let mut lines = vec![w.name.clone()]; + lines.extend(value_lines(c, &values, w.spot)); + let mut label_style = style.clone(); + label_style.fill = Paint::solid(if c.to_lab().l < 50.0 { Color::WHITE } else { Color::BLACK }); + label_style.stroke = Paint::None; + // Area type the size of the chip (less its inset) that shrinks text to fit, so a long + // name or value line stays on its chip. + let mut t = TextObject::point(Point::new(x + pad, y + pad), &lines.join("\n"), label_style); + let inner = (size - 2.0 * pad).max(1.0); + t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, inner, inner)) }; + t.area.fit = AreaFit::ShrinkText { min_percent: AreaFit::MIN_PERCENT }; + t.para = super::super::super::create::new_type_para(); + t.system_layout = system_layout; + super::super::super::typecmd::refresh_bounds(&mut t); + children.push(std::sync::Arc::new(Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))))); + } + let gid = d.alloc_id(); + let mut g = Node::new(gid, NodeKind::Group { children, clip: false }); + g.name = Some("Swatch Legend".into()); + d.insert(parent, usize::MAX, g)?; + sel.set([gid]); + Ok(gid) + })?; + Ok(json!({ "id": gid.0, "count": count })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/color/legend/tests.rs b/crates/engine/src/cmd/addons/color/legend/tests.rs new file mode 100644 index 0000000000..9a8fa57f21 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/legend/tests.rs @@ -0,0 +1,118 @@ +use serde_json::json; +use vectorcraft_color::Color; +use vectorcraft_doc::{Node, NodeId, NodeKind}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn group(s: &Session, id: u64) -> Node { + s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone() +} + +/// The text of each label in group `g`, in order. +fn labels(g: &Node) -> Vec<(String, Color)> { + g.children() + .unwrap() + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some((t.plain_text(), t.runs[0].style.fill.color().unwrap())), + _ => None, + }) + .collect() +} + +#[test] +fn a_legend_draws_a_labelled_chip_per_colour_swatch_in_one_undo_step() { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#101010"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Paper", "color": "#f8f4e8"})).unwrap(); + let colours = s.doc().unwrap().doc.swatches_iter().filter(|w| w.paint.color().is_some()).count(); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("addon.color.swatchLegend", &json!({"columns": 3, "size": 60, "gap": 10})).unwrap(); + assert_eq!(r["count"].as_u64().unwrap() as usize, colours); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(r["id"].as_u64().unwrap())], "the legend is selected"); + let g = group(&s, r["id"].as_u64().unwrap()); + assert_eq!(g.name.as_deref(), Some("Swatch Legend")); + let kids = g.children().unwrap(); + assert_eq!(kids.len(), 2 * colours, "a chip and a label each"); + // Chips fill with their swatch, three to a row, 70 pt apart. + let chips: Vec<&Node> = kids.iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| &**n).collect(); + let doc = &s.doc().unwrap().doc; + for (chip, w) in chips.iter().zip(doc.swatches_iter().filter(|w| w.paint.color().is_some())) { + assert_eq!(chip.appearance.fill_paint().color(), w.paint.color(), "{}", w.name); + assert_eq!(chip.name.as_deref(), Some(w.name.as_str())); + } + let b = |i: usize| chips[i].geometric_bounds().unwrap(); + assert!((b(1).x0 - b(0).x0 - 70.0).abs() < 1e-6 && (b(3).y0 - b(0).y0 - 70.0).abs() < 1e-6 && (b(3).x0 - b(0).x0).abs() < 1e-6); + assert!((b(0).width() - 60.0).abs() < 1e-6); + // Labels: the name, then the swatch's own values; white on the dark chip, black on the light. + let l = labels(&g); + let ink = l.iter().find(|(t, _)| t.starts_with("Ink")).unwrap(); + let paper = l.iter().find(|(t, _)| t.starts_with("Paper")).unwrap(); + assert!(ink.0.contains("R=16 G=16 B=16"), "{}", ink.0); + assert_eq!((ink.1, paper.1), (Color::WHITE, Color::BLACK)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(g.id).is_none()); +} + +#[test] +fn a_legend_takes_names_values_and_a_position() { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Signal", "color": "cmyk 0 100 100 0", "spot": true})).unwrap(); + let r = + s.execute("addon.color.swatchLegend", &json!({"names": ["Signal"], "values": ["hex", "cmyk", "lab", "gray"], "x": 100, "y": 50})).unwrap(); + assert_eq!(r["count"], 1); + let g = group(&s, r["id"].as_u64().unwrap()); + let (text, _) = labels(&g).remove(0); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines[0], "Signal"); + assert_eq!(lines[1], "Spot", "a spot swatch says so"); + assert!(lines[2].starts_with('#') && lines[3] == "C=0 M=100 Y=100 K=0" && lines[4].starts_with("L=") && lines[5].starts_with("K="), "{lines:?}"); + let chip = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Path { .. })).unwrap().geometric_bounds().unwrap(); + assert!((chip.x0 - 100.0).abs() < 1e-6 && (chip.y0 - 50.0).abs() < 1e-6); + // Refused, with nothing drawn. + let before = s.doc().unwrap().history.undo.len(); + for bad in [ + json!({"names": ["Nope"]}), + json!({"names": "Signal"}), + json!({"values": ["xyz"]}), + json!({"columns": 0}), + json!({"columns": 2.5}), + json!({"size": 2}), + json!({"gap": -1}), + json!({"x": f64::MAX}), + json!({"names": []}), + json!({"values": ["rgb", "rgb"]}), + ] { + assert!(s.execute("addon.color.swatchLegend", &bad).is_err(), "{bad}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), before); +} + +/// A chip of a global swatch is linked to it: editing the swatch recolours the chip. Each label is +/// area type inside its chip that shrinks a long name to fit (#4919 review). +#[test] +fn chips_stay_linked_and_labels_stay_on_their_chips() { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "A Rather Long Brand Colour Name", "color": "#2050a0", "global": true})).unwrap(); + let r = s + .execute("addon.color.swatchLegend", &json!({"names": ["A Rather Long Brand Colour Name"], "size": 40, "values": ["hex", "rgb", "cmyk"]})) + .unwrap(); + let id = r["id"].as_u64().unwrap(); + s.execute("swatch.edit", &json!({"name": "A Rather Long Brand Colour Name", "color": "#a02050"})).unwrap(); + let g = group(&s, id); + let kids = g.children().unwrap(); + let chip = kids.iter().find(|n| matches!(n.kind, NodeKind::Path { .. })).unwrap(); + assert_eq!(chip.appearance.fill_paint().color().map(|c| c.to_hex()), Some("#a02050".into()), "the edit reached the chip"); + let label = kids.iter().find(|n| matches!(n.kind, NodeKind::Text(_))).unwrap(); + let NodeKind::Text(t) = &label.kind else { panic!("not type") }; + assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) && matches!(t.area.fit, vectorcraft_doc::AreaFit::ShrinkText { .. })); + let (c, l) = (chip.geometric_bounds().unwrap(), label.geometric_bounds().unwrap()); + assert!(l.x0 >= c.x0 - 1e-6 && l.y0 >= c.y0 - 1e-6 && l.x1 <= c.x1 + 1e-6 && l.y1 <= c.y1 + 1e-6, "label {l:?} inside chip {c:?}"); +} diff --git a/crates/engine/src/cmd/addons/color/nearest.rs b/crates/engine/src/cmd/addons/color/nearest.rs new file mode 100644 index 0000000000..0236698be0 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/nearest.rs @@ -0,0 +1,198 @@ +//! Find Nearest Swatch (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`; Object › +//! Plug-ins › Color Effects › Find Nearest Swatch…): the swatches of a library, a colour book the +//! user loaded or the document closest to each colour of the selection (CIEDE2000), and the +//! colours replaced by them as one undo step (#4923). + +use serde_json::{Value, json}; +use vectorcraft_color::cms::{Lab, delta_e2000}; +use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::swatches::color_name; +use vectorcraft_doc::{Document, NodeId, NodeKind}; + +use super::super::super::colorcmds::recolor_links; +use super::super::super::menucmds::squash; +use super::super::super::swatchlib::{DOCUMENT_SWATCHES, library_swatches}; +use super::super::super::{bad, checked_ids_or_selection, color_value, index, switch_or, text_param}; +use super::super::arrange::whole_in; +use crate::{Result, Session}; + +const FIND: &str = "addon.color.nearestSwatch"; +const APPLY: &str = "addon.color.applyNearestSwatch"; +/// The most colours of the selection looked up. +const MAX_COLORS: usize = 100; + +/// The `library` param ([`DOCUMENT_SWATCHES`] when left out) and its colour swatches with their Lab +/// values. +fn candidates(s: &Session, p: &Value, cmd: &str) -> Result<(String, Vec<(Swatch, Lab)>)> { + let key = text_param(p, "library", cmd)?.unwrap_or(DOCUMENT_SWATCHES).to_string(); + let swatches = library_swatches(s, &key).ok_or_else(|| bad(cmd, format!("no swatch library `{key}` (see swatch.library.list)")))?; + let labs: Vec<(Swatch, Lab)> = swatches + .into_iter() + .filter(|w| !w.is_reserved()) + .filter_map(|w| { + let lab = w.paint.color()?.to_lab(); + Some((w, lab)) + }) + .collect(); + if labs.is_empty() { + return Err(bad(cmd, format!("`{key}` has no colours"))); + } + Ok((key, labs)) +} + +/// The `count` swatches of `among` closest to `c`, closest first, with their difference (ΔE 2000). +fn nearest(among: &[(Swatch, Lab)], c: Color, count: usize) -> Vec<(&Swatch, f32)> { + let lab = c.to_lab(); + let mut v: Vec<(&Swatch, f32)> = among.iter().map(|(w, l)| (w, delta_e2000(*l, lab))).collect(); + v.sort_by(|a, b| a.1.total_cmp(&b.1)); + v.truncate(count); + v +} + +/// The solid colours and gradient stops of the fills (`fill`) and strokes (`stroke`) of `ids`, of +/// everything inside them and of their type, once each and at most [`MAX_COLORS`]. +fn art_colors(d: &Document, ids: &[NodeId], fill: bool, stroke: bool) -> Vec { + let mut out: Vec = vec![]; + let mut add = |p: &Paint| { + let colors: Vec = match p { + Paint::Solid { color, .. } => vec![*color], + Paint::Gradient(g) => g.gradient.stops.iter().map(|s| s.color).collect(), + _ => vec![], + }; + for c in colors { + if out.len() < MAX_COLORS && !out.contains(&c) { + out.push(c); + } + } + }; + for n in ids.iter().filter_map(|id| d.node(*id)) { + n.walk(&mut |m| { + for it in &m.appearance.items { + if if it.is_fill() { fill } else { stroke } { + add(it.paint()); + } + } + if let NodeKind::Text(t) = &m.kind { + for r in &t.runs { + if fill { + add(&r.style.fill); + } + if stroke { + add(&r.style.stroke); + } + } + } + }); + } + out +} + +/// A swatch's name and values as the results give them. +fn described(w: &Swatch) -> Value { + let c = w.paint.color().unwrap_or_default(); + json!({ "name": w.name, "values": color_name(c), "hex": c.to_hex(), "spot": w.spot }) +} + +pub(super) fn find(s: &mut Session, p: &Value) -> Result { + let count = whole_in(p, "count", (1, 50), FIND)?.map_or(5, index); + let (fill, stroke) = (switch_or(p, "fill", true, FIND)?, switch_or(p, "stroke", true, FIND)?); + let colors = match p.get("color").filter(|v| !v.is_null()) { + Some(v) => vec![color_value(v).ok_or_else(|| bad(FIND, "`color` is not a colour"))?], + None => { + let ids = checked_ids_or_selection(s, p, FIND)?; + if ids.is_empty() { + return Err(bad(FIND, "select objects or give `color`")); + } + art_colors(&s.doc()?.doc, &ids, fill, stroke) + } + }; + let (library, among) = candidates(s, p, FIND)?; + let found: Vec = colors + .iter() + .map(|c| { + let matches: Vec = nearest(&among, *c, count) + .into_iter() + .map(|(w, de)| { + let mut m = described(w); + m["deltaE"] = json!((f64::from(de) * 100.0).round() / 100.0); + m + }) + .collect(); + json!({ "values": color_name(*c), "hex": c.to_hex(), "matches": matches }) + }) + .collect(); + Ok(json!({ "library": library, "colors": found })) +} + +pub(super) fn apply(s: &mut Session, p: &Value) -> Result { + let (fill, stroke) = (switch_or(p, "fill", true, APPLY)?, switch_or(p, "stroke", true, APPLY)?); + let ids = checked_ids_or_selection(s, p, APPLY)?; + if ids.is_empty() { + return Err(bad(APPLY, "nothing selected")); + } + let (library, among) = candidates(s, p, APPLY)?; + // The swatch each colour takes, once each. + let colors = art_colors(&s.doc()?.doc, &ids, fill, stroke); + let mut used: Vec<&Swatch> = vec![]; + for c in &colors { + if let Some((w, _)) = nearest(&among, *c, 1).first() + && !used.iter().any(|u| u.name == w.name) + { + used.push(w); + } + } + if used.is_empty() { + return Ok(json!({ "changed": 0, "swatches": [], "added": [] })); + } + let undo = s.doc()?.history.undo.len(); + // A library's swatches join the document's first, as Add to Swatches adds them, so spot and + // global colours stay linked to theirs. + let mut added = vec![]; + let mut names: Vec = used.iter().map(|w| w.name.clone()).collect(); + if library != DOCUMENT_SWATCHES { + let r = s.execute("swatch.library.add", &json!({ "library": library, "names": names }))?; + let listed = |k: &str| r.get(k).and_then(Value::as_array).cloned().unwrap_or_default(); + let in_doc: Vec = listed("added").iter().chain(&listed("existing")).filter_map(Value::as_str).map(str::to_string).collect(); + let d = &s.doc()?.doc; + // Each library swatch's copy: the document swatch with its paint among those added or kept. + names = used + .iter() + .map(|w| in_doc.iter().find(|n| d.swatch(n).is_some_and(|x| x.paint == w.paint)).cloned().unwrap_or_else(|| w.name.clone())) + .collect(); + added = listed("added"); + } + // Each used swatch's paint as art takes it: linked to a global or spot swatch. + let d = &s.doc()?.doc; + let paints: Vec<(Lab, Paint)> = used + .iter() + .zip(&names) + .filter_map(|(w, name)| { + let lab = w.paint.color()?.to_lab(); + let paint = d.swatch(name).filter(|x| x.global).and_then(|_| d.tint_paint(name, 1.0)).unwrap_or_else(|| w.paint.clone()); + Some((lab, paint)) + }) + .collect(); + // shortcut: a colour past the MAX_COLORS looked up takes the closest of the swatches those + // took; look up every colour if documents with more colours need their own matches. + let to = |c: Color| -> Option<&Paint> { + let lab = c.to_lab(); + paints.iter().min_by(|a, b| delta_e2000(a.0, lab).total_cmp(&delta_e2000(b.0, lab))).map(|(_, p)| p) + }; + let links = |c: &mut Color, link: &mut Option, tint: &mut f32| { + let Some(Paint::Solid { color, swatch, .. }) = to(*c) else { return false }; + if *c == *color && *link == *swatch { + return false; + } + (*c, *link, *tint) = (*color, swatch.clone(), 1.0); + true + }; + let given = json!({ + "ids": ids.iter().map(|i| i.0).collect::>(), "fill": fill, "stroke": stroke, "includeImages": false, "includePatterns": false, + }); + let r = recolor_links(s, &given, APPLY, "Apply Nearest Swatch", &|c| to(c).and_then(Paint::color).unwrap_or(c), &links)?; + squash(s, undo, "Apply Nearest Swatch"); + Ok(json!({ "changed": r["changed"], "swatches": names, "added": added })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/color/nearest/tests.rs b/crates/engine/src/cmd/addons/color/nearest/tests.rs new file mode 100644 index 0000000000..0436d19c89 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/nearest/tests.rs @@ -0,0 +1,115 @@ +//! Find Nearest Swatch. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::NodeId; + +use crate::Session; + +const FIND: &str = "addon.color.nearestSwatch"; +const APPLY: &str = "addon.color.applyNearestSwatch"; + +/// A document with a global swatch "Brand" and a selected rectangle filled `fill`, stroked `stroke`. +fn doc(fill: &str, stroke: Option<&str>) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#ff8000", "global": true})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": fill})).unwrap(); + match stroke { + Some(c) => s.execute("paint.setStroke", &json!({"color": c})).unwrap(), + None => s.execute("paint.setStroke", &json!({"none": true})).unwrap(), + }; + (s, id) +} + +fn paints(s: &Session, id: NodeId) -> (Paint, Paint) { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + (n.appearance.fill_paint(), n.appearance.items.iter().find(|i| !i.is_fill()).unwrap().paint().clone()) +} + +fn names(matches: &Value) -> Vec<&str> { + matches.as_array().unwrap().iter().map(|m| m["name"].as_str().unwrap()).collect() +} + +#[test] +fn the_closest_swatches_of_a_library_are_listed_closest_first() { + let (mut s, _) = doc("#ff6634", None); + let v = s.execute(FIND, &json!({"library": "web-safe-216", "count": 3})).unwrap(); + assert_eq!(v["library"], "web-safe-216"); + let colors = v["colors"].as_array().unwrap(); + assert_eq!(colors.len(), 1, "the fill; no stroke"); + assert_eq!((colors[0]["hex"].as_str(), colors[0]["values"].as_str()), (Some("#ff6634"), Some("R=255 G=102 B=52"))); + let m = &colors[0]["matches"]; + assert_eq!(names(m)[0], "#FF6633"); + let de: Vec = m.as_array().unwrap().iter().map(|x| x["deltaE"].as_f64().unwrap()).collect(); + assert_eq!(de.len(), 3); + assert!(de[0] < 1.0 && de.windows(2).all(|w| w[0] <= w[1]), "{de:?}"); + // A colour given is looked up instead of the selection's. + let v = s.execute(FIND, &json!({"library": "web-safe-216", "color": "#010203", "count": 1})).unwrap(); + assert_eq!(names(&v["colors"][0]["matches"]), ["#000000"]); +} + +#[test] +fn the_document_swatches_are_the_default_library() { + let (mut s, _) = doc("#ff8010", Some("#ff8010")); + let v = s.execute(FIND, &json!({})).unwrap(); + assert_eq!(v["library"], "document"); + assert_eq!(v["colors"].as_array().unwrap().len(), 1, "fill and stroke share a colour: looked up once"); + assert_eq!(names(&v["colors"][0]["matches"])[0], "Brand"); + assert!(!names(&v["colors"][0]["matches"]).contains(&"[Registration]")); +} + +#[test] +fn applying_links_each_colour_to_its_nearest_document_swatch_as_one_undo_step() { + let (mut s, id) = doc("#ff8010", Some("#ff8010")); + let undo = s.doc().unwrap().history.undo.len(); + let v = s.execute(APPLY, &json!({"stroke": false})).unwrap(); + assert_eq!((v["changed"].as_u64(), v["swatches"].clone(), v["added"].clone()), (Some(1), json!(["Brand"]), json!([]))); + let (fill, stroke) = paints(&s, id); + assert!(matches!(&fill, Paint::Solid { swatch: Some(n), color, .. } if n == "Brand" && color.to_hex() == "#ff8000"), "{fill:?}"); + assert_eq!(stroke.color().unwrap().to_hex(), "#ff8010", "strokes left alone"); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.history.undo.last().unwrap().label.as_str()), (undo + 1, "Apply Nearest Swatch")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(paints(&s, id).0.color().unwrap().to_hex(), "#ff8010"); +} + +#[test] +fn a_library_spot_colour_joins_the_document_and_stays_spot() { + let (mut s, id) = doc("#e01525", None); + // A colour book of one spot colour, loaded as a user would load one they own. + s.execute("swatch.new", &json!({"name": "Ink Red", "color": "#e01020", "spot": true})).unwrap(); + let data = s.execute("swatch.library.save", &json!({"names": ["Ink Red"]})).unwrap()["data"].as_str().unwrap().to_string(); + s.execute("swatch.delete", &json!({"names": ["Ink Red"]})).unwrap(); + let lib = s.execute("swatch.library.load", &json!({"data": data, "name": "Book.vcswatches"})).unwrap()["library"].as_str().unwrap().to_string(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let v = s.execute(APPLY, &json!({"library": lib})).unwrap(); + assert_eq!((v["swatches"].clone(), v["added"].clone()), (json!(["Ink Red"]), json!(["Ink Red"]))); + let d = &s.doc().unwrap().doc; + assert!(d.swatch("Ink Red").is_some_and(|w| w.spot && w.global)); + assert!(matches!(paints(&s, id).0, Paint::Solid { swatch: Some(n), .. } if n == "Ink Red")); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "adding and applying undo together"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Ink Red").is_none()); + assert_eq!(paints(&s, id).0, Paint::solid(Color::from_hex("#e01525").unwrap())); +} + +#[test] +fn bad_requests_are_refused() { + let (mut s, _) = doc("#ff8010", None); + for (p, why) in [ + (json!({"library": "nope"}), "no swatch library `nope`"), + (json!({"library": "spectrum-gradients"}), "has no colours"), + (json!({"count": 0}), "`count` must be from 1 to 50"), + (json!({"color": "zzz"}), "`color` is not a colour"), + (json!({"fill": "yes"}), "`fill` must be true or false"), + ] { + let e = s.execute(FIND, &p).unwrap_err().to_string(); + assert!(e.contains(why), "{p}: {e}"); + } + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute(FIND, &json!({})).unwrap_err().to_string().contains("select objects or give `color`")); + assert!(s.execute(APPLY, &json!({})).is_err(), "nothing selected"); +} diff --git a/crates/engine/src/cmd/addons/color/print_fixes.rs b/crates/engine/src/cmd/addons/color/print_fixes.rs new file mode 100644 index 0000000000..7a4cfee9c4 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/print_fixes.rs @@ -0,0 +1,170 @@ +//! Print Ink Fixes (`addon.color.printFixes`, Object › Plug-ins › Color Effects › Print Ink +//! Fixes…): a CMYK document's inks made ready for print in one undo step. Colours with more total +//! ink than the limit are scaled down to it, white fills and strokes stop overprinting, and black +//! ones start to, as Edit › Edit Colors › Overprint Black sets it. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_doc::overprint::{OverprintBlack, is_white}; +use vectorcraft_doc::{ColorMode, Node, NodeKind}; + +use super::super::super::colorcmds::{Recolor, Scope}; +use super::super::super::overprint::edit_counted; +use super::super::super::{bad, checked_ids_or_selection, number_or, switch_or, text_param}; +use crate::{Result, Session}; + +const C: &str = "addon.color.printFixes"; + +/// What `p` asks for. +struct Fixes { + /// Most total ink, 0..4 (0: off). + ink_limit: f32, + exclude_pure_black: bool, + remove_white_overprint: bool, + /// Overprint Black's least black, 0..1 (0: off). + overprint_black: f32, + text_only: bool, + fill: bool, + stroke: bool, +} + +/// The percentage `p` gives for `key` in 0..=`max`, as a fraction (0 when left out). +fn percent(p: &Value, key: &str, max: f64) -> Result { + let v = number_or(p, key, 0.0, C)?; + if !(0.0..=max).contains(&v) { + return Err(bad(C, format!("`{key}` must be 0..{max}"))); + } + Ok((v / 100.0) as f32) +} + +impl Fixes { + fn of(p: &Value) -> Result { + let f = Fixes { + ink_limit: percent(p, "inkLimit", 400.0)?, + exclude_pure_black: switch_or(p, "excludePureBlack", true, C)?, + remove_white_overprint: switch_or(p, "removeWhiteOverprint", false, C)?, + overprint_black: percent(p, "overprintBlack", 100.0)?, + text_only: switch_or(p, "textOnly", false, C)?, + fill: switch_or(p, "fill", true, C)?, + stroke: switch_or(p, "stroke", true, C)?, + }; + if f.ink_limit <= 0.0 && f.overprint_black <= 0.0 && !f.remove_white_overprint { + return Err(bad(C, "give `inkLimit`, `removeWhiteOverprint` or `overprintBlack`")); + } + Ok(f) + } + + /// `c` with its total ink scaled down to the limit: CMYK, and grey (black ink) unless + /// pure blacks are excluded, which CMYK with black ink only is too. + fn limit(&self, c: Color) -> Color { + const E: f32 = 0.005; + let max = self.ink_limit; + match c { + Color::Cmyk { c: cy, m, y, k } => { + let total = cy + m + y + k; + let pure_black = cy <= E && m <= E && y <= E; + if total <= max || (self.exclude_pure_black && pure_black) || !total.is_finite() { + return c; + } + let s = max / total; + Color::cmyk(cy * s, m * s, y * s, k * s) + } + Color::Gray { k } if k > max && !self.exclude_pure_black => Color::gray(max), + _ => c, + } + } + + /// Remove white overprint from `n`'s own fills and strokes and its characters': true when + /// that changed anything. + fn unset_white(&self, n: &mut Node) -> bool { + let mut changed = false; + let mut off = |aimed: bool, white: bool, flag: &mut bool| { + if aimed && white && *flag { + *flag = false; + changed = true; + } + }; + for it in &mut n.appearance.items { + let aimed = if it.is_fill() { self.fill } else { self.stroke }; + let white = is_white(it.paint()); + off(aimed, white, it.overprint_mut()); + } + if let NodeKind::Text(t) = &mut n.kind { + for r in &mut t.runs { + off(self.fill, is_white(&r.style.fill), &mut r.style.overprint_fill); + off(self.stroke, is_white(&r.style.stroke), &mut r.style.overprint_stroke); + } + } + changed + } + + /// The overprint fixes on `n` and everything inside it: (objects whose white overprint was + /// removed, objects set to overprint black). + fn overprint(&self, n: &mut Node, black: &OverprintBlack, spots: &[String]) -> (usize, usize) { + let white = usize::from(self.remove_white_overprint && self.unset_white(n)); + let blacks = self.overprint_black > 0.0 && (!self.text_only || matches!(n.kind, NodeKind::Text(_))); + let mut counts = (white, usize::from(blacks && black.apply(n, spots))); + for c in n.children_mut().into_iter().flatten() { + let (w, b) = self.overprint(Arc::make_mut(c), black, spots); + counts = (counts.0 + w, counts.1 + b); + } + counts + } +} + +pub(super) fn run(s: &mut Session, p: &Value) -> Result { + let fixes = Fixes::of(p)?; + let st = s.doc()?; + if st.doc.color_mode != ColorMode::Cmyk { + return Err(bad(C, "Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first")); + } + let layers = st.doc.layers.iter().map(|l| l.id).collect(); + let roots = checked_ids_or_selection(s, p, C)?; + // As Artwork Cleanup's: the selection, or the document while nothing is selected. + let ids = match text_param(p, "scope", C)? { + Some("document") => layers, + None if roots.is_empty() => layers, + Some("selection") if roots.is_empty() => return Err(bad(C, "nothing selected")), + Some("selection") | None => roots, + Some(other) => return Err(bad(C, format!("`scope` must be \"selection\" or \"document\", not {other:?}"))), + }; + let black = OverprintBlack { min_k: fixes.overprint_black, fill: fixes.fill, stroke: fixes.stroke, ..OverprintBlack::default() }; + let (mut ink, mut white, mut blacks) = (0, 0, 0); + let changed = edit_counted(s, "Print Ink Fixes", |d| { + if fixes.ink_limit > 0.0 { + let spots = d.spot_names(); + // Spot inks and Registration aren't process ink: they keep their colour and link. + let links = |c: &mut Color, link: &mut Option, _: &mut f32| { + if link.as_ref().is_some_and(|n| n == REGISTRATION || spots.contains(n)) { + return false; + } + let new = fixes.limit(*c); + if new == *c { + return false; + } + (*c, *link) = (new, None); + true + }; + let scope = Scope { fill: fixes.fill, stroke: fixes.stroke, images: false, patterns: false }; + ink = Recolor::with_links(scope, &|c| fixes.limit(c), &links).run(d, &ids); + } + if !fixes.remove_white_overprint && fixes.overprint_black <= 0.0 { + return Ok(ink); + } + let spots = d.spot_names(); + for id in &ids { + if let Some(n) = d.node_mut(*id) { + let (w, b) = fixes.overprint(n, &black, &spots); + (white, blacks) = (white + w, blacks + b); + } + } + Ok(ink + white + blacks) + })?; + Ok(json!({ "changed": changed, "inkLimited": ink, "whiteOverprintRemoved": white, "blackOverprinted": blacks })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/color/print_fixes/tests.rs b/crates/engine/src/cmd/addons/color/print_fixes/tests.rs new file mode 100644 index 0000000000..e4c1915879 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/print_fixes/tests.rs @@ -0,0 +1,129 @@ +//! Print Ink Fixes. + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_doc::NodeId; + +use crate::Session; + +const C: &str = "addon.color.printFixes"; + +/// A CMYK document with a rectangle per fill, each with overprint as given; nothing selected. +fn doc(fills: &[(Value, bool)]) -> (Session, Vec) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap(); + let ids = fills + .iter() + .enumerate() + .map(|(i, (fill, overprint))| { + let id = s.execute("shape.rectangle", &json!({"x": 10 + 30 * i, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({ "color": fill })).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("object.setOverprint", &json!({ "fill": overprint })).unwrap(); + NodeId(id) + }) + .collect(); + s.execute("select.none", &json!({})).unwrap(); + (s, ids) +} + +fn fill(s: &Session, id: NodeId) -> (Color, bool) { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let item = n.appearance.items.iter().find(|i| i.is_fill()).unwrap().clone(); + (item.paint().color().unwrap(), item.overprint()) +} + +fn cmyk(c: f64, m: f64, y: f64, k: f64) -> Value { + json!({"c": c, "m": m, "y": y, "k": k}) +} + +fn close(a: Color, b: [f32; 4]) -> bool { + let Color::Cmyk { c, m, y, k } = a else { return false }; + [c, m, y, k].iter().zip(b).all(|(x, y)| (x - y).abs() < 0.001) +} + +#[test] +fn the_ink_limit_scales_heavy_colours_down_to_it() { + let (mut s, ids) = doc(&[(cmyk(100.0, 100.0, 100.0, 100.0), false), (cmyk(40.0, 30.0, 20.0, 10.0), false), (cmyk(0.0, 0.0, 0.0, 80.0), false)]); + let undo = s.doc().unwrap().history.undo.len(); + // Nothing selected: the whole document. + let v = s.execute(C, &json!({"inkLimit": 300})).unwrap(); + assert_eq!((v["inkLimited"].clone(), v["changed"].clone()), (json!(1), json!(1))); + assert!(close(fill(&s, ids[0]).0, [0.75; 4]), "{:?}", fill(&s, ids[0])); + assert!(close(fill(&s, ids[1]).0, [0.4, 0.3, 0.2, 0.1]), "under the limit: as it was"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + // The selection only. + s.execute("select.set", &json!({"ids": [ids[1].0]})).unwrap(); + s.execute(C, &json!({"inkLimit": 50})).unwrap(); + assert!(close(fill(&s, ids[1]).0, [0.2, 0.15, 0.1, 0.05])); + assert!(close(fill(&s, ids[0]).0, [0.75; 4]), "left out"); + // Pure black keeps its ink unless it is included. + s.execute(C, &json!({"inkLimit": 50, "scope": "document"})).unwrap(); + assert!(close(fill(&s, ids[0]).0, [0.125; 4])); + assert!(close(fill(&s, ids[2]).0, [0.0, 0.0, 0.0, 0.8])); + s.execute(C, &json!({"inkLimit": 50, "scope": "document", "excludePureBlack": false})).unwrap(); + assert!(close(fill(&s, ids[2]).0, [0.0, 0.0, 0.0, 0.5])); +} + +#[test] +fn spot_and_registration_colours_keep_their_ink() { + let (mut s, ids) = doc(&[(cmyk(0.0, 0.0, 0.0, 0.0), false), (cmyk(0.0, 0.0, 0.0, 0.0), false)]); + s.execute("swatch.new", &json!({"name": "Heavy", "color": cmyk(100.0, 100.0, 100.0, 50.0), "spot": true})).unwrap(); + s.execute("select.set", &json!({"ids": [ids[0].0]})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Heavy"})).unwrap(); + s.execute("select.set", &json!({"ids": [ids[1].0]})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "[Registration]"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = [fill(&s, ids[0]), fill(&s, ids[1])]; + assert_eq!(s.execute(C, &json!({"inkLimit": 200})).unwrap()["changed"], 0); + assert_eq!([fill(&s, ids[0]), fill(&s, ids[1])], before); +} + +#[test] +fn white_overprint_goes_and_black_overprint_comes_at_the_threshold() { + let white = cmyk(0.0, 0.0, 0.0, 0.0); + let (mut s, ids) = + doc(&[(white.clone(), true), (cmyk(0.0, 0.0, 0.0, 95.0), false), (cmyk(0.0, 0.0, 0.0, 80.0), false), (cmyk(30.0, 0.0, 0.0, 100.0), false)]); + let undo = s.doc().unwrap().history.undo.len(); + let v = s.execute(C, &json!({"removeWhiteOverprint": true, "overprintBlack": 90})).unwrap(); + assert_eq!((v["whiteOverprintRemoved"].clone(), v["blackOverprinted"].clone()), (json!(1), json!(1)), "{v}"); + let overprints: Vec = ids.iter().map(|id| fill(&s, *id).1).collect(); + // White stops; 95 % black starts; 80 % is under the threshold; a rich black isn't pure black. + assert_eq!(overprints, [false, true, false, false]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(ids.iter().map(|id| fill(&s, *id).1).collect::>(), [true, false, false, false]); + // On type only: the rectangles stay. + let v = s.execute(C, &json!({"overprintBlack": 90, "textOnly": true})).unwrap(); + assert_eq!(v["changed"], 0); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed, no undo step"); + // Strokes only: the fills stay. + assert_eq!(s.execute(C, &json!({"overprintBlack": 90, "fill": false})).unwrap()["changed"], 0); +} + +#[test] +fn bad_requests_and_rgb_documents_are_refused() { + let (mut s, ids) = doc(&[(cmyk(100.0, 100.0, 100.0, 100.0), true)]); + for p in [ + json!({}), + json!({"inkLimit": 0}), + json!({"inkLimit": "300"}), + json!({"inkLimit": 401}), + json!({"inkLimit": -1}), + json!({"overprintBlack": 101}), + json!({"overprintBlack": true}), + json!({"removeWhiteOverprint": "yes"}), + json!({"inkLimit": 300, "fill": 1}), + json!({"inkLimit": 300, "scope": "page"}), + json!({"inkLimit": 300, "scope": "selection"}), + json!({"inkLimit": 300, "ids": [999_999]}), + ] { + assert!(s.execute(C, &p).is_err(), "{p}"); + } + assert!(close(fill(&s, ids[0]).0, [1.0; 4])); + let mut rgb = Session::new(); + rgb.execute("file.new", &json!({})).unwrap(); + rgb.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let e = rgb.execute(C, &json!({"inkLimit": 300})).unwrap_err().to_string(); + assert!(e.contains("CMYK"), "{e}"); +} diff --git a/crates/engine/src/cmd/addons/color/tests.rs b/crates/engine/src/cmd/addons/color/tests.rs new file mode 100644 index 0000000000..ed8137d6a9 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/tests.rs @@ -0,0 +1,316 @@ +//! Color Effects: its live effects through effect.apply, and Apply as Filter. + +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::Rect; + +use crate::Session; + +/// A document with a selected red rectangle, unstroked. +fn red_rect() -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + (s, id) +} + +fn fill_hex(s: &Session, id: NodeId) -> String { + s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color().unwrap().to_hex() +} + +fn pixel(s: &Session) -> [u8; 4] { + vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0, true).pixel(50, 50) +} + +#[test] +fn the_live_effects_draw_without_changing_the_colours() { + for (effect, params, drawn) in [ + ("addon.color.invert", json!({}), [0, 255, 255, 255]), + ("addon.color.desaturate", json!({}), [128, 128, 128, 255]), + ("addon.color.exposure", json!({"exposure": -20}), [0, 0, 0, 255]), + ] { + let (mut s, id) = red_rect(); + s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap(); + assert_eq!(fill_hex(&s, id), "#ff0000", "{effect}"); + assert_eq!(pixel(&s), drawn, "{effect}"); + } +} + +#[test] +fn a_filter_recolours_the_object_as_one_undo_step() { + let (mut s, id) = red_rect(); + let undo = s.doc().unwrap().history.undo.len(); + let v = s.execute("addon.color.filter", &json!({"effect": "addon.color.invert"})).unwrap(); + assert_eq!(v["changed"], 1); + assert_eq!(fill_hex(&s, id), "#00ffff"); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(n.appearance.effects.is_empty(), "no effect is added"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fill_hex(&s, id), "#ff0000"); +} + +#[test] +fn a_filter_takes_any_colour_adjustment_with_its_params() { + let (mut s, id) = red_rect(); + s.execute("addon.color.filter", &json!({"effect": "adjust.hueSaturation", "params": {"hue": 120}})).unwrap(); + assert_eq!(fill_hex(&s, id), "#00ff00"); + // Live effects already on the object stay live, on top of the new colours. + s.execute("effect.apply", &json!({"effect": "addon.color.invert"})).unwrap(); + s.execute("addon.color.filter", &json!({"effect": "addon.color.desaturate", "ids": [id.0]})).unwrap(); + assert_eq!(fill_hex(&s, id), "#808080"); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().appearance.effects.len(), 1); + // The stroke only: the fill stays. + s.execute("addon.color.filter", &json!({"effect": "addon.color.invert", "fill": false})).unwrap(); + assert_eq!(fill_hex(&s, id), "#808080"); +} + +#[test] +fn bad_requests_are_refused() { + let (mut s, id) = red_rect(); + let undo = s.doc().unwrap().history.undo.len(); + for p in [ + json!({}), + json!({"effect": 3}), + json!({"effect": "distort.roughen"}), + json!({"effect": "adjust.nothing"}), + json!({"effect": "addon.color.invert", "params": [1]}), + json!({"effect": "addon.color.invert", "ids": [999_999]}), + json!({"effect": "addon.color.invert", "ids": ["x"]}), + ] { + assert!(s.execute("addon.color.filter", &p).is_err(), "{p}"); + } + assert_eq!(fill_hex(&s, id), "#ff0000"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("addon.color.filter", &json!({"effect": "addon.color.invert"})).is_err(), "nothing selected"); +} + +/// An embedded image object of `blob`, selected. +fn image(s: &mut Session, key: &str, blob: vectorcraft_doc::ImageBlob, x: f64) -> NodeId { + s.edit("Place", |d, sel| { + d.images.insert(key.into(), blob); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: key.into(), + width: 4, + height: 4, + xf: vectorcraft_geom::Affine::translate((x, 0.0)) * vectorcraft_geom::Affine::scale(10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap() +} + +fn png(img: image::DynamicImage) -> vectorcraft_doc::ImageBlob { + let mut bytes = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + vectorcraft_doc::ImageBlob::png(bytes) +} + +fn selected(s: &Session) -> Vec { + s.doc().unwrap().selection.objects.clone() +} + +#[test] +fn select_by_color_kind_finds_spot_colours_effects_and_image_models() { + let (mut s, plain) = red_rect(); + // A spot colour, inside a group: the path is taken, not the group. + s.execute("swatch.new", &json!({"name": "Gold", "color": {"model": "cmyk", "c": 0.0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap(); + let spot = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"swatch": "Gold"})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + // A live colour adjustment. + let adjusted = NodeId(s.execute("shape.rectangle", &json!({"x": 140, "y": 20, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap()); + // Its own colour: setting the spot fill made it the default for new art too. + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("effect.apply", &json!({"effect": "addon.color.invert"})).unwrap(); + let rgb = image(&mut s, "rgb", png(image::DynamicImage::ImageRgb8(image::RgbImage::new(4, 4))), 0.0); + let gray = image(&mut s, "gray", png(image::DynamicImage::ImageLuma8(image::GrayImage::new(4, 4))), 50.0); + let inks = vectorcraft_doc::cmyk::Inks::new(4, 4, vec![0; 64]).unwrap(); + let cmyk = image(&mut s, "cmyk", vectorcraft_doc::ImageBlob::cmyk_tiff(&inks).unwrap(), 100.0); + for (kind, ids) in [ + ("spotColors", vec![spot]), + ("colorEffects", vec![adjusted]), + ("rgbImages", vec![rgb]), + ("grayImages", vec![gray]), + ("cmykImages", vec![cmyk]), + ] { + let v = s.execute("addon.color.select", &json!({"kind": kind})).unwrap(); + assert_eq!((selected(&s), v["count"].clone()), (ids.clone(), json!(ids.len())), "{kind}"); + } + // Locked objects are left out; none found selects nothing. + s.execute("select.set", &json!({"ids": [spot.0]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + assert_eq!(s.execute("addon.color.select", &json!({"kind": "spotColors"})).unwrap()["count"], 0); + assert!(!selected(&s).contains(&plain)); + assert!(s.execute("addon.color.select", &json!({"kind": "pantone"})).is_err()); + assert!(s.execute("addon.color.select", &json!({})).is_err()); +} + +/// Vector Halftone, the live effect. +const HALFTONE: &str = "addon.color.halftone"; + +/// The dots in group `g`: each path's geometry, ink and blend mode. +fn dots(g: &vectorcraft_doc::Node) -> Vec<(vectorcraft_geom::PathData, String, vectorcraft_color::BlendMode)> { + let ink = |c: &vectorcraft_doc::Node| c.appearance.fill_paint().color().unwrap().to_hex(); + g.children().unwrap().iter().map(|c| (c.path_data().unwrap().clone(), ink(c), c.blend)).collect() +} + +/// `format` as `document.export` writes the active document. +fn exported(s: &mut Session, format: &str) -> Vec { + let v = s.execute("document.export", &json!({"format": format})).unwrap(); + vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap() +} + +/// How many subpaths the path data of `svg` starts. +fn svg_moves(svg: &[u8]) -> usize { + let svg = String::from_utf8_lossy(svg); + svg.split(" d=\"").skip(1).map(|d| d.split('"').next().unwrap_or("").matches(['M', 'm']).count()).sum() +} + +#[test] +fn expand_appearance_gives_the_dots_object_vector_halftone_makes() { + for params in [ + json!({"frequency": 18}), + json!({"frequency": 12, "mode": "cmyk", "shape": "square", "angle": 15}), + json!({"shape": "line", "invert": true, "clip": false}), + json!({"shape": "ellipse", "color": "#336699", "angle": -30}), + ] { + let (mut live, id) = red_rect(); + live.execute("effect.apply", &json!({"effect": HALFTONE, "params": params})).unwrap(); + assert_eq!(fill_hex(&live, id), "#ff0000", "the effect leaves the object as it is"); + live.execute("effect.expandAppearance", &json!({})).unwrap(); + let expanded = live.doc().unwrap().doc.node(id).cloned().unwrap(); + assert!(expanded.appearance.effects.is_empty()); + let (mut made, _) = red_rect(); + let r = made.execute("object.vectorHalftone", ¶ms).unwrap(); + let g = made.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).cloned().unwrap(); + assert!(!dots(&g).is_empty(), "{params}"); + assert_eq!(dots(&expanded), dots(&g), "{params}"); + // Ids of their own. + let ids: std::collections::HashSet<_> = expanded.children().unwrap().iter().map(|c| c.id).chain([id]).collect(); + assert_eq!(ids.len(), expanded.children().unwrap().len() + 1); + } +} + +#[test] +fn exports_write_the_dots_as_paths() { + let (mut s, _) = red_rect(); + let plain: Vec = ["pdf", "eps", "ai"].map(|f| exported(&mut s, f).len()).to_vec(); + s.execute("effect.apply", &json!({"effect": HALFTONE, "params": {"frequency": 18}})).unwrap(); + // The exporters' copy of the document has the dots in the object's place. + let baked = vectorcraft_render::effects::bake_document(&s.doc().unwrap().doc).unwrap(); + let mut paths = 0; + baked.walk(|n| { + assert!(n.appearance.effects.iter().all(|e| e.id != HALFTONE)); + paths += n.path_data().map_or(0, |p| p.subpaths.len()); + }); + assert!(paths > 100, "{paths} subpaths"); + // SVG: path data of a subpath per dot. + let moves = svg_moves(&exported(&mut s, "svg")); + assert!(moves > 100, "{moves} subpaths"); + // PDF, EPS and AI: the dots' paths make each file larger. + for (f, plain) in ["pdf", "eps", "ai"].into_iter().zip(plain) { + let with = exported(&mut s, f).len(); + assert!(with > plain + 1000, "{f}: {with} bytes, {plain} without the effect"); + } +} + +#[test] +fn a_halftone_past_the_caps_leaves_the_object_as_it_is() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 9000, "height": 9000})).unwrap()["id"].as_u64().unwrap()); + s.execute("effect.apply", &json!({"effect": HALFTONE, "params": {"frequency": 300}})).unwrap(); + // Drawn as it is, exported and expanded without dots and without a panic. + pixel(&s); + assert!(svg_moves(&exported(&mut s, "svg")) < 5); + let r = s.execute("effect.expandAppearance", &json!({})); + assert!(!matches!(r, Err(crate::EngineError::Internal { .. })), "{r:?}"); + let n = s.doc().unwrap().doc.node(id).cloned().unwrap(); + assert!(n.children().is_none_or(|c| c.len() < 5), "no dots"); +} + +/// Duotone, the live effect. +const DUOTONE: &str = "addon.color.duotone"; + +/// A document with spot swatch "Ink" and a selected grey (50 %) rectangle, unstroked. +fn grey_rect() -> (Session, NodeId) { + let (mut s, id) = red_rect(); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0.0, "m": 0.6, "y": 1.0, "k": 0.0}, "spot": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": {"gray": 0.5}})).unwrap(); + (s, id) +} + +fn ink_tone(curve: &str) -> serde_json::Value { + json!({"tones": [{"color": {"model": "cmyk", "c": 0.0, "m": 0.6, "y": 1.0, "k": 0.0}, "swatch": "Ink", "curve": curve}]}) +} + +fn fill_paint(s: &Session, id: NodeId) -> vectorcraft_color::Paint { + s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().clone() +} + +#[test] +fn duotone_draws_a_tint_of_its_spot_tone_and_expands_to_it() { + let (mut s, id) = grey_rect(); + let grey = pixel(&s); + s.execute("effect.apply", &json!({"effect": DUOTONE, "params": ink_tone("0,0 100,100")})).unwrap(); + assert_eq!(fill_paint(&s, id).color().unwrap(), vectorcraft_color::Color::gray(0.5), "the colours stay"); + let drawn = pixel(&s); + assert!(drawn != grey && drawn[0] > drawn[2], "drawn in the ink: {drawn:?}"); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let vectorcraft_color::Paint::Solid { swatch, tint, .. } = fill_paint(&s, id) else { panic!("a solid fill") }; + assert_eq!(swatch.as_deref(), Some("Ink"), "linked to the spot swatch, so it separates on its plate"); + assert!((tint - 0.5).abs() < 0.01, "{tint}"); +} + +#[test] +fn duotone_as_a_filter_equals_the_live_effect_expanded() { + for params in [ + ink_tone("0,0 100,100"), + ink_tone("0,0 40,70 100,100"), + json!({"tones": [{"color": "#00ffff", "swatch": "Ink"}, {"color": {"model": "cmyk", "c": 0.0, "m": 0.0, "y": 0.0, "k": 1.0}, "curve": "0,0 100,40"}]}), + json!({"tones": [{"color": "#000000"}], "skipSpot": true}), + ] { + let (mut live, id) = grey_rect(); + live.execute("effect.apply", &json!({"effect": DUOTONE, "params": params})).unwrap(); + live.execute("effect.expandAppearance", &json!({})).unwrap(); + let (mut filtered, _) = grey_rect(); + let undo = filtered.doc().unwrap().history.undo.len(); + assert_eq!(filtered.execute("addon.color.filter", &json!({"effect": DUOTONE, "params": params})).unwrap()["changed"], 1); + assert_eq!(filtered.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert_eq!(fill_paint(&filtered, id), fill_paint(&live, id), "{params}"); + } + // The params round-trip: the effect keeps what it was given, and the filter reads the same. + let (mut s, id) = grey_rect(); + let params = ink_tone("0,0 40,70 100,100"); + s.execute("effect.apply", &json!({"effect": DUOTONE, "params": params})).unwrap(); + let kept = s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params.clone(); + assert_eq!(kept["tones"], params["tones"]); + s.execute("addon.color.filter", &json!({"effect": DUOTONE, "params": kept})).unwrap(); + let vectorcraft_color::Paint::Solid { swatch, tint, .. } = fill_paint(&s, id) else { panic!("a solid fill") }; + assert_eq!(swatch.as_deref(), Some("Ink")); + let fx = vectorcraft_render::effects::addons::duotone::tone_curve_points(Some(&json!("0,0 40,70 100,100"))); + let want = vectorcraft_render::effects::curve_at(&fx, 0.5); + assert!(want > 0.7 && (tint - want).abs() < 0.01, "the curve lifts the mid tone: {tint}, {want}"); +} + +#[test] +fn duotone_skips_spot_colours_when_asked() { + let (mut s, id) = grey_rect(); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + let spot = fill_paint(&s, id); + s.execute("addon.color.filter", &json!({"effect": DUOTONE, "params": {"tones": [{"color": "#000000"}], "skipSpot": true}})).unwrap(); + assert_eq!(fill_paint(&s, id), spot); + s.execute("addon.color.filter", &json!({"effect": DUOTONE, "params": {"tones": [{"color": "#000000"}]}})).unwrap(); + assert_ne!(fill_paint(&s, id), spot); +} diff --git a/crates/engine/src/cmd/addons/contour.rs b/crates/engine/src/cmd/addons/contour.rs new file mode 100644 index 0000000000..46df381edc --- /dev/null +++ b/crates/engine/src/cmd/addons/contour.rs @@ -0,0 +1,85 @@ +//! Contour (`addon.contour.*`), a built-in add-on: the Contour tool's command. A Contour is a copy of a selected shape that +//! carries a live Offset Path effect, so it grows or shrinks the shape without baking anything: its +//! fill, stroke and effect stay editable, and Expand Appearance bakes it into plain paths. The +//! original stays where it is. Running the command on an object that already carries an Offset +//! Path effect (a Contour made earlier) changes that effect instead of nesting another one. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; +use vectorcraft_render::effects; + +use super::super::edit::{copy_above, selected_roots}; +use super::super::pathops::{len_param, num_param}; +use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, str_param}; + +const C: &str = "addon.contour.set"; +/// The live effect that does the offsetting (the one Effect › Path › Offset Path applies). +const EFFECT: &str = "path.offsetPath"; +/// The largest offset, in points; Offset Path takes the same. +const MAX_OFFSET: f64 = 1e5; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.contour.set", + "Contour", + [], + None, + "{offset: pt (negative insets), corners?: \"sharp\"|\"round\"|\"square\" (default sharp; square cuts each corner off flat), miterLimit?: 1..500 (4; sharp corners only)} make a copy of each selected path or shape directly above it with a live Offset Path effect, or, for a selected object that already has one (a Contour), change that effect: nothing is baked (Expand Appearance bakes it) and the original is kept → {ids, created, updated}", + has_selection, + contour + )] +} + +/// The Offset Path join a Contour corner style stands for. +fn joins_for(corners: Option<&str>) -> Result<&'static str> { + match corners.map(str::to_ascii_lowercase).as_deref() { + None | Some("sharp") => Ok("miter"), + Some("round") => Ok("round"), + Some("square") => Ok("bevel"), + Some(other) => Err(bad(C, format!("`corners` must be sharp, round or square, not `{other}`"))), + } +} + +fn contour(s: &mut Session, p: &Value) -> Result { + let offset = len_param(p, "offset").ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?; + if offset.abs() > MAX_OFFSET { + return Err(bad(C, "offset out of range")); + } + let joins = joins_for(str_param(p, "corners"))?; + let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0); + let effect = effects::new_effect(EFFECT, &json!({"offset": offset, "joins": joins, "miterLimit": miter})) + .ok_or_else(|| EngineError::Other("Contour: the Offset Path effect is not available".into()))?; + let roots = selected_roots(s)?; + let (updated, created) = s.edit("Contour", |d, sel| { + // A shape that already carries Offset Path is a Contour: change it. Any other path or + // shape gets a Contour copy above it. Type, images and the rest are left alone. + let (mut again, mut fresh) = (vec![], vec![]); + for id in roots { + let Some(n) = d.node(id) else { continue }; + if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { + continue; + } + if n.appearance.effects.iter().any(|e| e.id == EFFECT) { + again.push(id); + } else { + fresh.push(id); + } + } + if again.is_empty() && fresh.is_empty() { + return Err(EngineError::Other("Contour: select paths or shapes".into())); + } + for id in &again { + if let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects.iter_mut().rev().find(|e| e.id == EFFECT)) { + e.params = effect.params.clone(); + } + } + let made = copy_above(d, &fresh, |_, _, copy| copy.appearance.effects.push(effect.clone()))?; + sel.set(again.iter().chain(made.iter()).copied()); + Ok((again, made)) + })?; + let list = |ids: &[NodeId]| ids.iter().map(|i| i.0).collect::>(); + Ok(json!({ "ids": list(&[updated.as_slice(), created.as_slice()].concat()), "created": list(&created), "updated": list(&updated) })) +} diff --git a/crates/engine/src/cmd/addons/contour/tests.rs b/crates/engine/src/cmd/addons/contour/tests.rs new file mode 100644 index 0000000000..900d110d58 --- /dev/null +++ b/crates/engine/src/cmd/addons/contour/tests.rs @@ -0,0 +1,371 @@ +//! Tests for `addon.contour.set`: a live Offset Path copy of a shape that stays editable until baked. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; +use vectorcraft_geom::Rect; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + let r = s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn ids_of(v: &Value, key: &str) -> Vec { + v[key].as_array().unwrap().iter().map(|x| NodeId(x.as_u64().unwrap())).collect() +} + +fn node(s: &Session, id: NodeId) -> vectorcraft_doc::Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn effects_of(s: &Session, id: NodeId) -> Vec<(String, Value)> { + node(s, id).appearance.effects.iter().map(|e| (e.id.clone(), e.params.clone())).collect() +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +fn node_count(s: &Session) -> usize { + s.doc().unwrap().doc.node_count() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +#[test] +fn contour_is_a_live_copy_above_the_original() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let before = bounds(&s, a); + let r = s.execute("addon.contour.set", &json!({"offset": 10})).unwrap(); + let (made, updated) = (ids_of(&r, "created"), ids_of(&r, "updated")); + assert_eq!((made.len(), updated.len()), (1, 0)); + // The original is untouched, the copy is above it and selected, and nothing is baked: the + // copy's own path is still the original's, with the effect on top. + assert!(effects_of(&s, a).is_empty()); + assert_eq!(bounds(&s, a), before); + assert_eq!(s.doc().unwrap().selection.objects, made); + let d = &s.doc().unwrap().doc; + assert!(d.index_path(made[0]).unwrap() > d.index_path(a).unwrap()); + assert_eq!(bounds(&s, made[0]), before); + let fx = effects_of(&s, made[0]); + assert_eq!(fx.len(), 1); + assert_eq!(fx[0].0, "path.offsetPath"); + assert_eq!(fx[0].1["offset"], json!(10.0)); + assert_eq!(fx[0].1["joins"], json!("miter")); +} + +#[test] +fn baking_a_contour_gives_the_grown_and_the_shrunk_shape() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + for (offset, want) in [(10.0, Rect::new(90.0, 90.0, 160.0, 150.0)), (-5.0, Rect::new(105.0, 105.0, 145.0, 135.0))] { + select(&mut s, &[a]); + s.execute("addon.contour.set", &json!({"offset": offset})).unwrap(); + let baked = ids_of(&s.execute("effect.expandAppearance", &json!({})).unwrap(), "ids"); + let b = bounds(&s, baked[0]); + // The default stroke widens the baked art by its weight; compare the fill's edges. + let fill = baked_fill_bounds(&s, baked[0]); + assert!((fill.x0 - want.x0).abs() < 1e-2 && (fill.y1 - want.y1).abs() < 1e-2, "{offset}: {fill:?} vs {want:?} ({b:?})"); + } +} + +/// The bounds of the fill path inside a baked object (a group of its fill and stroke), or of the +/// object itself when it is one path. +fn baked_fill_bounds(s: &Session, id: NodeId) -> Rect { + match &node(s, id).kind { + NodeKind::Group { children, .. } => children.iter().filter_map(|c| c.geometric_bounds()).next().unwrap(), + _ => bounds(s, id), + } +} + +#[test] +fn a_second_drag_changes_the_contour_instead_of_nesting_one() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 10})).unwrap(), "created"); + let count = node_count(&s); + // The Contour is selected: the next call edits it. + let r = s.execute("addon.contour.set", &json!({"offset": -4, "corners": "round"})).unwrap(); + assert_eq!(ids_of(&r, "updated"), made); + assert!(ids_of(&r, "created").is_empty()); + assert_eq!(node_count(&s), count, "no new object"); + let fx = effects_of(&s, made[0]); + assert_eq!(fx.len(), 1, "one Offset Path, not two"); + assert_eq!((fx[0].1["offset"].clone(), fx[0].1["joins"].clone()), (json!(-4.0), json!("round"))); + assert!(effects_of(&s, a).is_empty()); +} + +#[test] +fn corner_styles_choose_the_join() { + for (corners, joins) in [("sharp", "miter"), ("round", "round"), ("square", "bevel"), ("Round", "round")] { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 3, "corners": corners})).unwrap(), "created"); + assert_eq!(effects_of(&s, made[0])[0].1["joins"], json!(joins), "{corners}"); + } +} + +#[test] +fn contour_keeps_the_color_and_stroke_editable_on_the_copy() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 6})).unwrap(), "created"); + let original = node(&s, a).appearance.items.clone(); + assert_eq!(node(&s, made[0]).appearance.items, original, "the copy starts with the shape's own paint"); + // Recolouring the Contour (it is the selection) changes its fill only: the live effect stays + // and the original keeps its paint. + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + assert_ne!(node(&s, made[0]).appearance.items, original, "the copy took the new fill"); + assert_eq!(node(&s, a).appearance.items, original, "the original is untouched"); + assert_eq!(effects_of(&s, made[0]).len(), 1); +} + +#[test] +fn contour_is_one_undo_step() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let count = node_count(&s); + s.execute("addon.contour.set", &json!({"offset": 6})).unwrap(); + assert_eq!(node_count(&s), count + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node_count(&s), count); + assert!(effects_of(&s, a).is_empty()); +} + +#[test] +fn contour_refuses_what_it_cannot_offset() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let count = node_count(&s); + for params in [json!({}), json!({"offset": "abc"}), json!({"offset": 1e300}), json!({"offset": 5, "corners": "pointy"})] { + assert!(s.execute("addon.contour.set", ¶ms).is_err(), "{params}"); + } + // Nothing was added by the refused calls. + assert_eq!(node_count(&s), count); + // Type is not a path to offset. + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Hi"})).unwrap(); + let err = s.execute("addon.contour.set", &json!({"offset": 5})).unwrap_err().to_string(); + assert!(err.contains("select paths or shapes"), "{err}"); +} + +/// The border-with-a-gap recipe: two Contours of one shape (the gap, then the border), baked, then +/// the gap taken out of the border with Minus Front, leaves a ring between the two. +#[test] +fn border_with_a_gap_from_two_contours_and_minus_front() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + // Strip the default stroke so the areas are plain. + s.execute("paint.setStroke", &json!({"none": true})).ok(); + // The gap first (+8), then the border (+20) from the same shape: both land directly above it, + // the later one lower, so the gap ends up in front of the border. + select(&mut s, &[a]); + let gap = ids_of(&s.execute("addon.contour.set", &json!({"offset": 8})).unwrap(), "created")[0]; + select(&mut s, &[a]); + let border = ids_of(&s.execute("addon.contour.set", &json!({"offset": 20})).unwrap(), "created")[0]; + let d = &s.doc().unwrap().doc; + assert!(d.index_path(gap).unwrap() > d.index_path(border).unwrap(), "the gap is in front of the border"); + select(&mut s, &[border, gap]); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let both: Vec = s.doc().unwrap().selection.objects.to_vec(); + assert_eq!(both.len(), 2); + let ring = ids_of(&s.execute("object.pathfinder.minusFront", &json!({})).unwrap(), "ids"); + assert_eq!(ring.len(), 1); + // 90 x 80 outer minus 66 x 56 inner, with sharp corners. + let area = vectorcraft_pathops::area(&ring_path(&s, ring[0]).0, ring_path(&s, ring[0]).1); + assert!((area - (90.0 * 80.0 - 66.0 * 56.0)).abs() < 1.0, "{area}"); +} + +fn ring_path(s: &Session, id: NodeId) -> (vectorcraft_geom::PathData, vectorcraft_geom::FillRule) { + match &node(s, id).kind { + NodeKind::Path { path, rule, .. } => (path.clone(), *rule), + NodeKind::Compound { children, rule } => { + (vectorcraft_geom::PathData::new(children.iter().flat_map(|c| c.path_data().unwrap().subpaths.clone()).collect()), *rule) + } + NodeKind::Group { children, .. } => children.first().map(|c| ring_path(s, c.id)).unwrap(), + _ => panic!("not a path"), + } +} + +mod tool { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + + use super::*; + use crate::tooling::ViewInfo; + + fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..Default::default() } + } + + fn at(s: &mut Session, kind: PointerKind, x: f64, y: f64, mods: Mods) { + s.pointer(&PointerEvent::new(kind, x, y).with_mods(mods), view()).unwrap(); + } + + fn undo_depth(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() + } + + /// A 50 x 40 rectangle at (100, 100), selected, with the Contour tool active. + fn ready() -> (Session, NodeId) { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + select(&mut s, &[a]); + s.select_tool("contour", view()).unwrap(); + (s, a) + } + + fn offset_of(s: &Session, id: NodeId) -> f64 { + effects_of(s, id)[0].1["offset"].as_f64().unwrap() + } + + #[test] + fn dragging_out_previews_live_and_commits_one_undo_step() { + let (mut s, a) = ready(); + let (before, nodes) = (undo_depth(&s), node_count(&s)); + // Press on the right edge and pull 10 pt away from the shape. + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 160.0, 120.0, Mods::default()); + assert!(s.in_interaction(), "the Contour is previewed while the button is down"); + at(&mut s, PointerKind::Up, 160.0, 120.0, Mods::default()); + assert!(!s.in_interaction()); + assert_eq!(undo_depth(&s), before + 1); + assert_eq!(node_count(&s), nodes + 1); + assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("addon.contour.set")); + let made = s.doc().unwrap().selection.objects.clone(); + assert_eq!(made.len(), 1); + assert_ne!(made[0], a); + assert!((offset_of(&s, made[0]) - 10.0).abs() < 1e-6, "{}", offset_of(&s, made[0])); + assert!(effects_of(&s, a).is_empty(), "the original is kept as it was"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node_count(&s), nodes); + } + + #[test] + fn dragging_in_shrinks_and_a_second_drag_continues_from_where_the_contour_stands() { + let (mut s, _) = ready(); + // From inside, 5 pt toward the middle of the right edge's neighbourhood. + at(&mut s, PointerKind::Down, 145.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 140.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 140.0, 120.0, Mods::default()); + let contour = s.doc().unwrap().selection.objects[0]; + assert!((offset_of(&s, contour) + 5.0).abs() < 1e-6); + // The Contour is selected: pressing at the edge and pulling out 12 pt adds to its -5. + let nodes = node_count(&s); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 162.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 162.0, 120.0, Mods::default()); + assert_eq!(node_count(&s), nodes, "the same Contour changed, none was nested"); + assert_eq!(s.doc().unwrap().selection.objects, vec![contour]); + assert_eq!(effects_of(&s, contour).len(), 1); + assert!((offset_of(&s, contour) - 7.0).abs() < 1e-6, "{}", offset_of(&s, contour)); + } + + #[test] + fn escape_and_a_plain_click_change_nothing() { + let (mut s, _) = ready(); + let (before, nodes) = (undo_depth(&s), node_count(&s)); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 170.0, 120.0, Mods::default()); + assert!(s.in_interaction()); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + at(&mut s, PointerKind::Up, 170.0, 120.0, Mods::default()); + assert!(!s.in_interaction()); + assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes)); + // A click with no movement. + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 150.0, 120.0, Mods::default()); + assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes)); + } + + #[test] + fn shift_rounds_to_whole_points_and_the_corner_option_is_used() { + let (mut s, _) = ready(); + s.set_tool_option("corners", &json!("round")); + let shift = Mods { shift: true, ..Mods::default() }; + at(&mut s, PointerKind::Down, 150.0, 120.0, shift); + at(&mut s, PointerKind::Drag, 160.4, 120.0, shift); + at(&mut s, PointerKind::Up, 160.4, 120.0, shift); + let contour = s.doc().unwrap().selection.objects[0]; + assert_eq!(offset_of(&s, contour), 10.0); + assert_eq!(effects_of(&s, contour)[0].1["joins"], json!("round")); + } + + /// A Contour keeps its own corner style and miter limit when it is dragged again, whatever the + /// tool's options are by then (they said Sharp when the Contour was made Square). + #[test] + fn dragging_a_contour_again_keeps_its_corners_and_miter_limit() { + let (mut s, _) = ready(); + s.execute("addon.contour.set", &json!({"offset": 5, "corners": "square", "miterLimit": 7})).unwrap(); + let contour = s.doc().unwrap().selection.objects[0]; + s.set_tool_option("corners", &json!("sharp")); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 158.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 158.0, 120.0, Mods::default()); + let fx = effects_of(&s, contour); + assert_eq!(fx.len(), 1); + assert!((offset_of(&s, contour) - 13.0).abs() < 1e-6, "{}", offset_of(&s, contour)); + assert_eq!(fx[0].1["joins"], json!("bevel"), "{:?}", fx[0].1); + assert_eq!(fx[0].1["miterLimit"], json!(7.0), "{:?}", fx[0].1); + } + + /// A drag that never moves the distance (along the edge, or rounded back to nothing by Shift) + /// leaves no unchanged copy and no undo step. + #[test] + fn a_drag_along_the_edge_changes_nothing() { + let (mut s, _) = ready(); + let (before, nodes) = (undo_depth(&s), node_count(&s)); + let shift = Mods { shift: true, ..Mods::default() }; + for (mods, to) in [(Mods::default(), (150.0, 135.0)), (shift, (150.3, 120.0))] { + at(&mut s, PointerKind::Down, 150.0, 120.0, mods); + at(&mut s, PointerKind::Drag, to.0, to.1, mods); + at(&mut s, PointerKind::Up, to.0, to.1, mods); + assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes), "{to:?}"); + assert!(!s.in_interaction()); + } + } + + /// The outline a Contour was made from shows as a dashed guide over a solid halo (so it reads + /// over any fill); a shape that is not a Contour yet has none. + #[test] + fn a_selected_contour_shows_the_outline_it_was_made_from() { + use vectorcraft_tools::Overlay; + let (mut s, _) = ready(); + let paths = |s: &mut Session| -> Vec<(bool, f32)> { + s.overlays(view()) + .into_iter() + .filter_map(|o| match o { + Overlay::Path { dashed, width, .. } => Some((dashed, width)), + _ => None, + }) + .collect() + }; + assert!(paths(&mut s).is_empty(), "a plain shape has no guide"); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 160.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 160.0, 120.0, Mods::default()); + // The solid halo first, the dashes on top of it. + assert_eq!(paths(&mut s), [(false, 3.0), (true, 1.0)]); + } + + #[test] + fn nothing_selected_does_nothing() { + let mut s = session(); + rect(&mut s, 100.0, 100.0, 50.0, 40.0); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("contour", view()).unwrap(); + let before = undo_depth(&s); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 170.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 170.0, 120.0, Mods::default()); + assert_eq!(undo_depth(&s), before); + } +} diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs new file mode 100644 index 0000000000..fafdfc07dc --- /dev/null +++ b/crates/engine/src/cmd/addons/document.rs @@ -0,0 +1,241 @@ +//! Document Tools (`addon.document.*`), a built-in add-on: Save a Timestamped Copy writes a copy of +//! the document named with the date and time through File › Save a Copy's save; New Symbols from +//! Layers makes a symbol of each layer's art as New Symbol does; Export All Open Documents writes a +//! copy of every open document to one folder as Save a Copy does (#4920); Batch Trace Folder traces +//! each image of a folder and saves the results to another ([`batch_trace`], #4921). Its submenu +//! (Object › Plug-ins › Document Tools) is the UI's. + +mod batch_trace; +#[cfg(test)] +mod tests; + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolRegistration}; + +use super::super::brushsym::{instance_in_place, normalize, place_xf, store_symbol}; +use super::super::fileio::{self, SaveMode}; +use super::super::{CommandSpec, always, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or}; +use crate::{Result, Session}; + +/// The most numbers (`-2`, `-3`…) tried after a timestamped name that is taken. +const MAX_NUMBER: u32 = 999; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.document.saveTimestampedCopy", + "Save a Timestamped Copy", + ["Object", "Plug-ins", "Document Tools"], + None, + "{folder? (default: the document's own folder; needed for a document never saved), format?: vectorcraft|pdf|svg|svgz|ai|eps (default: the document's own, else vectorcraft), time?: Unix seconds (default: now)} write a copy of the document named _YYYY-MM-DD_HH-MM. (the date and time in UTC; -2, -3… added when that name is taken) as File › Save a Copy writes it: the document keeps its path, title and modified state, and no undo step is made. Off where there is no clock (the web) → {path, format, bytes, warnings}", + has_clock, + save_timestamped_copy + ), + cmd!( + "addon.document.exportAllOpen", + "Export All Open Documents", + ["Object", "Plug-ins", "Document Tools"], + None, + "{folder, format?: vectorcraft|pdf|svg|svgz|ai|eps (default: pdf)} write a copy of every open document, in tab order, to `folder` as File › Save a Copy writes it, each named after its document (.; -2, -3… added when that name is taken, so no file is replaced), one self-contained file each with all of its art (images embedded or included, every artboard; no remembered save options apply): every document keeps its path, title and modified state, and no undo step is made. A document that can't be written is listed in `failed` and the others are still written; the active document stays active → {files: [{title, path, warnings}], failed: [{title, error}], format}", + has_doc, + export_all_open + ), + cmd!( + "addon.document.batchTraceFolder", + "Batch Trace Folder", + ["Object", "Plug-ins", "Document Tools"], + None, + "{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as . (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Optional settings use their defaults only when omitted; null and values of the wrong type return an error before any image is opened. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)", + always, + batch_trace::batch_trace_folder + ), + cmd!( + "addon.document.symbolsFromLayers", + "New Symbols from Layers", + ["Object", "Plug-ins", "Document Tools"], + None, + "{layers?: [layer id…] (top-level layers; default: those highlighted in the Layers panel when two or more are, else every one), replace?: bool (false: the art stays; true: each layer's art is replaced by an instance of its symbol in the same place)} make one symbol of each layer's art as symbol.new makes one (registration in the centre), named after the layer (with a number added when a symbol has that name), as one undo step. Layers with no art are skipped, and with replace so are locked layers; with replace the instances are selected → {symbols: [name…], ids: [instance id…] (with replace), skipped: [{layer, name, reason: \"empty\"|\"locked\"}…]}", + has_doc, + symbols_from_layers + ), + ] +} + +/// A document is open and the time can be told. +fn has_clock(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + vectorcraft_doc::metadata::output_time().map(|_| ()).ok_or_else(|| "there is no clock here".into()) +} + +/// `.`, then `-2.`… in `folder`: the first that `taken` doesn't hold. +fn free_name(folder: &str, base: &str, ext: &str, taken: impl Fn(&str) -> bool) -> Option { + (1..=MAX_NUMBER) + .map(|i| { + let name = if i == 1 { format!("{base}.{ext}") } else { format!("{base}-{i}.{ext}") }; + std::path::Path::new(folder).join(name).to_string_lossy().into_owned() + }) + .find(|path| !taken(path)) +} + +fn save_timestamped_copy(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.document.saveTimestampedCopy"; + let st = s.doc()?; + let format = match str_param(p, "format") { + Some(f) => fileio::save_format(Some(f), None), + // A document opened from a format Save doesn't write (a picture, a drawing) copies as native. + None => fileio::save_format(Some(st.format), None).or_else(|_| fileio::save_format(None, None)), + } + .map_err(|e| bad(C, e))?; + let folder = match str_param(p, "folder").filter(|f| !f.trim().is_empty()) { + Some(f) => f.to_string(), + None => st + .path + .as_deref() + .and_then(|path| std::path::Path::new(path).parent()) + .map(|f| f.to_string_lossy().into_owned()) + .filter(|f| !f.is_empty()) + .ok_or_else(|| bad(C, "the document has never been saved: give `folder`"))?, + }; + let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&st.doc.title)); + let given = date_param(p, "time", C)?; + let t = clock_date(s, "time", given).ok_or_else(|| bad(C, "there is no clock here: give `time` (Unix seconds)"))?; + let [y, mo, d, h, mi, _] = vectorcraft_doc::metadata::civil(t); + let base = format!("{stem}_{y:04}-{mo:02}-{d:02}_{h:02}-{mi:02}"); + // Only whether something is there: the write itself goes through the automation roots. + let path = free_name(&folder, &base, format.extensions[0], |p| std::path::Path::new(p).exists()) + .ok_or_else(|| bad(C, "every numbered name for the copy is taken"))?; + fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id })) +} + +/// The save options of every copy, given in full so that no document's remembered options (linked +/// SVG images, a PDF page range, separate artboard files) apply: one self-contained file per +/// document with all of its art. Each format reads only the options it has, and `range` is left +/// out of SVG, where it would pick artboards over `useArtboards`. +fn copy_options(format: &str) -> Value { + match format { + "svg" | "svgz" => json!({ "images": "embed", "useArtboards": false }), + "pdf" => json!({ "range": "all" }), + "eps" => json!({ "includeLinkedFiles": true, "useArtboards": false }), + "ai" | "ait" => json!({ "range": "all", "includeLinked": true, "separateArtboards": false }), + _ => json!({ "includeLinked": true, "separateArtboards": false }), + } +} + +fn export_all_open(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.document.exportAllOpen"; + let format = fileio::save_format(Some(str_param(p, "format").unwrap_or("pdf")), None).map_err(|e| bad(C, e))?; + let folder = str_param(p, "folder").map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "give `folder`"))?.to_string(); + let ext = format.extensions.first().copied().ok_or_else(|| bad(C, "the format has no file extension"))?; + let (mut files, mut failed, mut written) = (vec![], vec![], Vec::::new()); + let active = s.active; + for i in 0..s.docs.len() { + // Each document in turn is the one Save a Copy writes; switching tabs this way leaves every + // document's tool and interaction alone, and the active one comes back below. + s.active = Some(i); + let Ok(st) = s.doc() else { continue }; + let title = st.doc.title.clone(); + let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&title)); + // Names the copies already took count as taken, as do files on disk. + let Some(path) = free_name(&folder, &stem, ext, |p| written.iter().any(|w| w == p) || std::path::Path::new(p).exists()) else { + failed.push(json!({ "title": title, "error": "every numbered name for the copy is taken" })); + continue; + }; + let options = copy_options(format.id); + match fileio::save_document(s, SaveMode::Copy, &json!({ "path": path, "format": format.id, "options": options })) { + Ok(r) => { + written.push(path.clone()); + // Any other file the save wrote is taken for the copies still to come. + for key in ["files", "linked"] { + for f in r.get(key).and_then(Value::as_array).into_iter().flatten() { + if let Some(f) = f.as_str().or_else(|| f.get("path").and_then(Value::as_str)) { + written.push(f.to_string()); + } + } + } + files.push(json!({ "title": title, "path": r.get("path").cloned().unwrap_or(json!(path)), "warnings": r.get("warnings").cloned().unwrap_or(json!([])) })); + } + Err(e) => failed.push(json!({ "title": title, "error": e.to_string() })), + } + } + s.active = active; + Ok(json!({ "files": files, "failed": failed, "format": format.id })) +} + +/// `n` with each layer in it, and itself, made a group of the same art and clipping (a symbol holds +/// no layers). +fn without_layers(n: &Node) -> Node { + let mut n = n.clone(); + if let NodeKind::Layer { children, clip, .. } = &n.kind { + n.kind = NodeKind::Group { children: children.clone(), clip: *clip }; + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| matches!(c.kind, NodeKind::Layer { .. })) { + *c = Arc::new(without_layers(c)); + } + } + n +} + +fn symbols_from_layers(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.document.symbolsFromLayers"; + let replace = switch_or(p, "replace", false, C)?; + let st = s.doc()?; + let d = &st.doc; + let layers: Vec = match p.get("layers").filter(|v| !v.is_null()) { + // The layers highlighted in the Layers panel when two or more are (one is mostly just the + // current layer), else every one. + None => { + let rows = st.highlighted_rows(); + let picked: Vec = d.layers.iter().map(|l| l.id).filter(|id| rows.contains(id)).collect(); + if picked.len() > 1 { picked } else { d.layers.iter().map(|l| l.id).collect() } + } + Some(_) => { + let ids = checked_ids_param(s, p, "layers", C)?; + if let Some(NodeId(id)) = ids.iter().find(|id| !d.layers.iter().any(|l| l.id == **id)) { + return Err(bad(C, format!("{id} is no top-level layer"))); + } + d.layers.iter().map(|l| l.id).filter(|id| ids.contains(id)).collect() + } + }; + // Each layer with art: its id and name, the art's roots, and the art ready for a symbol. + let (mut made, mut skipped) = (vec![], vec![]); + for layer in layers.iter().filter_map(|id| d.layers.iter().find(|l| l.id == *id)) { + let name = layer.display_name(); + let roots: Vec = layer.children().map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default(); + let art = match layer.children().map(Vec::as_slice).unwrap_or_default() { + [] => None, + [one] => Some(without_layers(one)), + many => Some(without_layers(&Node::group(NodeId(0), many.to_vec()))), + }; + let reason = if replace && layer.locked { Some("locked") } else { None }; + let ready = art.and_then(|mut art| { + crate::cmd::threads::keep_shown_text(d, &mut art); + normalize(art).ok() + }); + match (reason, ready) { + (None, Some(ready)) => made.push((name, roots, ready)), + (reason, _) => skipped.push(json!({ "layer": layer.id.0, "name": name, "reason": reason.unwrap_or("empty") })), + } + } + if made.is_empty() { + return Ok(json!({ "symbols": [], "ids": [], "skipped": skipped })); + } + let (names, ids) = s.edit("New Symbols from Layers", |d, sel| { + let (mut names, mut ids) = (vec![], vec![]); + for (name, roots, (art, size, center)) in &made { + let name = d.unique_symbol_name(name); + store_symbol(d, art, &name, *size); + if replace { + ids.push(instance_in_place(d, roots, &name, place_xf(*center, *size, SymbolRegistration::CENTER))?); + } + names.push(name); + } + if replace { + sel.set(ids.iter().copied()); + } + Ok((names, ids)) + })?; + Ok(json!({ "symbols": names, "ids": ids.iter().map(|i| i.0).collect::>(), "skipped": skipped })) +} diff --git a/crates/engine/src/cmd/addons/document/batch_trace.rs b/crates/engine/src/cmd/addons/document/batch_trace.rs new file mode 100644 index 0000000000..61e59fc54f --- /dev/null +++ b/crates/engine/src/cmd/addons/document/batch_trace.rs @@ -0,0 +1,146 @@ +//! Batch Trace Folder (`addon.document.batchTraceFolder`, #4921): each image in a folder is opened, +//! traced with a preset (and expanded when asked), saved into a destination folder under its own +//! name, and closed again, whether it traced or not. + +use serde_json::Value; +#[cfg(not(target_arch = "wasm32"))] +use serde_json::json; + +#[cfg(not(target_arch = "wasm32"))] +use super::super::super::fileio; +#[cfg(not(target_arch = "wasm32"))] +use super::super::super::str_param; +use super::super::super::{Result, Session, bad}; + +/// The command id. +pub(super) const ID: &str = "addon.document.batchTraceFolder"; + +#[cfg(target_arch = "wasm32")] +pub(super) fn batch_trace_folder(_: &mut Session, _: &Value) -> Result { + Err(bad(ID, "no file system here")) +} + +#[cfg(not(target_arch = "wasm32"))] +/// The image files a batch traces, by extension. +const IMAGE_EXTS: [&str; 10] = ["png", "jpg", "jpeg", "tif", "tiff", "bmp", "gif", "webp", "psd", "psb"]; +#[cfg(not(target_arch = "wasm32"))] +/// Caps on a batch (folders and MCP payloads are untrusted). +pub(super) const MAX_FILES: usize = 500; +#[cfg(not(target_arch = "wasm32"))] +const MAX_DEPTH: usize = 8; +#[cfg(not(target_arch = "wasm32"))] +const FORMATS: [&str; 5] = ["vectorcraft", "svg", "pdf", "ai", "eps"]; + +#[cfg(not(target_arch = "wasm32"))] +/// The image files in `folder` (and its subfolders with `deep`), sorted. +fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec) -> Result<()> { + if depth > MAX_DEPTH { + return Err(bad(ID, format!("folders deeper than {MAX_DEPTH} levels"))); + } + let max = MAX_FILES.saturating_mul(2); + let (entries, truncated) = fileio::list_dir(folder, max)?; + // The listing is cut before it is sorted, so a cut one could skip any image: refuse it. + if truncated { + return Err(bad(ID, format!("{folder}: more than {max} files and folders"))); + } + let mut subdirs = vec![]; + for e in entries { + let name = e.get("name").and_then(Value::as_str).unwrap_or(""); + if name.is_empty() || name.starts_with('.') { + continue; + } + let path = std::path::Path::new(folder).join(name).to_string_lossy().into_owned(); + match e.get("kind").and_then(Value::as_str) { + Some("file") if IMAGE_EXTS.contains(&fileio::extension(&path).as_str()) => out.push(path), + Some("folder") if deep => subdirs.push(path), + _ => {} + } + if out.len() > MAX_FILES { + return Err(bad(ID, format!("more than {MAX_FILES} images"))); + } + } + for d in subdirs { + images(&d, deep, depth + 1, out)?; + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result { + let folder = str_param(p, "folder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `folder`"))?; + let dest = str_param(p, "destinationFolder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `destinationFolder`"))?; + let format = match p.get("format") { + None => "vectorcraft", + Some(Value::String(value)) => value.as_str(), + Some(_) => return Err(bad(ID, "`format` must be a string")), + }; + let preset = match p.get("preset") { + None => "Default", + Some(Value::String(value)) => value.as_str(), + Some(_) => return Err(bad(ID, "`preset` must be a string")), + }; + let expand = match p.get("expand") { + None => false, + Some(Value::Bool(value)) => *value, + Some(_) => return Err(bad(ID, "`expand` must be true or false")), + }; + let include_subdirs = match p.get("includeSubdirs") { + None => false, + Some(Value::Bool(value)) => *value, + Some(_) => return Err(bad(ID, "`includeSubdirs` must be true or false")), + }; + if !FORMATS.contains(&format) { + return Err(bad(ID, format!("`format` must be one of {}", FORMATS.join(", ")))); + } + let preset = preset.to_string(); + let presets = s.execute("imageTrace.presets", &json!({}))?; + if !presets["presets"].as_array().into_iter().flatten().any(|q| q["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&preset))) { + return Err(bad(ID, format!("no tracing preset `{preset}` (see imageTrace.presets)"))); + } + let trace = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; + fileio::may_read(&folder)?; + fileio::may_write(&dest)?; + let mut files = vec![]; + images(&folder, include_subdirs, 0, &mut files)?; + files.sort(); + if files.is_empty() { + return Err(bad(ID, "no images in the folder")); + } + std::fs::create_dir_all(&dest).map_err(|e| bad(ID, format!("{dest}: {e}")))?; + let ext = fileio::save_format(Some(format), None).map_err(|e| bad(ID, e))?.extensions.first().copied().unwrap_or(format); + let active = s.active_index(); + let (mut traced, mut failed, mut taken) = (vec![], vec![], Vec::::new()); + for path in &files { + let opened_before = s.documents().len(); + let one = |s: &mut Session| -> Result { + s.execute("document.open", &json!({ "path": path }))?; + s.execute("select.all", &json!({}))?; + s.execute(trace, &json!({ "preset": preset }))?; + let stem = fileio::file_stem(path); + // Names this batch already took count as taken, as do files on disk. + let free = super::free_name(&dest, &stem, ext, |o| taken.iter().any(|t| t == o) || std::path::Path::new(o).exists()) + .ok_or_else(|| bad(ID, "every numbered name for the result is taken"))?; + s.execute("document.save", &json!({ "path": free, "format": format }))?; + Ok(free) + }; + let result = one(s); + // The image's document closes whatever happened, so a failure leaves no tab behind. + if s.documents().len() > opened_before + && let Some(i) = s.active_index() + { + // A just-opened image has no work to lose; if closing fails, one extra tab stays open. + let _ = s.execute("file.close", &json!({ "index": i })); + } + match result { + Ok(out) => { + taken.push(out.clone()); + traced.push(json!({ "path": path, "output": out })); + } + Err(e) => failed.push(json!({ "path": path, "error": e.to_string() })), + } + } + if let Some(i) = active.filter(|i| *i < s.documents().len()) { + s.set_active(i); + } + Ok(json!({ "traced": traced, "failed": failed, "format": format })) +} diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs new file mode 100644 index 0000000000..b0fbb41422 --- /dev/null +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -0,0 +1,381 @@ +//! Document Tools' commands: the timestamped copy's name and place with the document left as it +//! was, symbols made of layers, a folder of images traced, and bad params refused. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use crate::Session; + +/// 2026-10-05 14:03:00 UTC. +const TIME: i64 = 1_791_208_980; + +/// A new, empty folder of its own for test `name`. +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vc-addon-document-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + s +} + +fn stamp(s: &mut Session, p: Value) -> crate::Result { + s.execute("addon.document.saveTimestampedCopy", &p) +} + +#[test] +fn a_timestamped_copy_goes_next_to_the_document_which_stays_as_it_was() { + let dir = folder("next-to"); + let mut s = session(); + let own = dir.join("poster.vectorcraft"); + s.execute("document.save", &json!({"path": own})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let (steps, title) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.title.clone()); + let r = stamp(&mut s, json!({"time": TIME})).unwrap(); + let copy = dir.join("poster_2026-10-05_14-03.vectorcraft"); + assert_eq!(Path::new(r["path"].as_str().unwrap()), copy); + assert!(copy.is_file()); + let st = s.doc().unwrap(); + assert_eq!(st.path.as_deref().map(Path::new), Some(own.as_path()), "the document keeps its path"); + assert_eq!((st.history.undo.len(), &st.doc.title, st.is_dirty()), (steps, &title, true), "no step; still modified"); + // The copy holds the document as it is now: the ellipse too. + let mut other = Session::new(); + other.execute("document.open", &json!({"path": copy})).unwrap(); + assert_eq!(other.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + // The same minute again: numbered. + let r = stamp(&mut s, json!({"time": TIME})).unwrap(); + assert!(r["path"].as_str().unwrap().ends_with("poster_2026-10-05_14-03-2.vectorcraft"), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_unsaved_document_needs_a_folder_and_other_formats_take_their_extension() { + let dir = folder("unsaved"); + let mut s = session(); + let before = s.doc().unwrap().doc.clone(); + assert!(stamp(&mut s, json!({"time": TIME})).is_err(), "no folder to put it in"); + let r = stamp(&mut s, json!({"time": TIME, "folder": dir, "format": "svg"})).unwrap(); + let name = Path::new(r["path"].as_str().unwrap()).file_name().unwrap().to_string_lossy().into_owned(); + assert!(name.ends_with("_2026-10-05_14-03.svg") && dir.join(&name).is_file(), "{name}"); + let st = s.doc().unwrap(); + assert!(st.path.is_none() && *st.doc == *before, "the document is unchanged"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn bad_params_are_refused_and_writes_stay_inside_the_automation_roots() { + let dir = folder("bad"); + let mut s = session(); + for p in [ + json!({"folder": dir, "format": "png"}), + json!({"folder": dir, "format": "dxf"}), + json!({"folder": dir, "time": "now"}), + json!({"folder": dir, "time": 1.5}), + json!({"folder": dir.join("missing").join("deeper"), "time": TIME}), + ] { + assert!(stamp(&mut s, p.clone()).is_err(), "{p}"); + } + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing written"); + let allowed = dir.join("allowed"); + std::fs::create_dir_all(&allowed).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&dir], &[&allowed]).unwrap(); + let outside = crate::file_access::confine(roots.as_ref(), || stamp(&mut s, json!({"folder": dir, "time": TIME}))); + assert!(outside.is_err(), "outside the write root"); + let inside = crate::file_access::confine(roots.as_ref(), || stamp(&mut s, json!({"folder": allowed, "time": TIME}))); + assert!(inside.is_ok(), "{inside:?}"); + assert!(!enabled_without_document(), "off with no document"); + let _ = std::fs::remove_dir_all(&dir); +} + +fn enabled_without_document() -> bool { + Session::new().commands().into_iter().find(|c| c.id == "addon.document.saveTimestampedCopy").unwrap().enabled +} + +fn layer_ids(s: &Session) -> Vec { + s.doc().unwrap().doc.layers.iter().map(|l| l.id.0).collect() +} + +fn symbol_names(s: &Session) -> Vec { + s.doc().unwrap().doc.symbols.iter().map(|x| x.name.clone()).collect() +} + +/// A document of three layers: `Layer 1` with two rectangles, an empty one, and `Icons` with one +/// ellipse. +fn layered() -> Session { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + s.execute("layer.new", &json!({"name": "Icons"})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 0, "y": 100, "width": 40, "height": 20})).unwrap(); + s +} + +#[test] +fn a_symbol_is_made_of_each_layer_and_empty_layers_are_reported() { + let mut s = layered(); + let before = symbol_names(&s).len(); + let n = s.doc().unwrap().history.undo.len(); + let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), n + 1, "one undo step"); + let names: Vec = serde_json::from_value(r["symbols"].clone()).unwrap(); + assert_eq!(names.len(), 2, "{r}"); + assert!(names.contains(&"Icons".to_string())); + assert_eq!(symbol_names(&s).len(), before + 2); + assert_eq!(r["skipped"].as_array().unwrap().len(), 1, "the empty layer: {r}"); + assert_eq!(r["skipped"][0]["reason"], json!("empty")); + assert_eq!(r["ids"], json!([]), "without replace the art stays"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + // Again: the names are taken, so they get numbers. + let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap(); + assert!(r["symbols"].as_array().unwrap().contains(&json!("Icons 2")), "{r}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(symbol_names(&s).len(), before); +} + +#[test] +fn replace_puts_an_instance_where_the_layers_art_was() { + let mut s = layered(); + let first = layer_ids(&s)[0]; + let bounds = |s: &Session, id: NodeId| s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + let layer = NodeId(first); + let art = bounds(&s, layer); + let r = s.execute("addon.document.symbolsFromLayers", &json!({"layers": [first], "replace": true})).unwrap(); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1); + let inst = NodeId(ids[0].as_u64().unwrap()); + let st = s.doc().unwrap(); + let kids = st.doc.layers[0].children().unwrap(); + assert_eq!(kids.len(), 1); + assert!(matches!(&kids[0].kind, NodeKind::SymbolInstance { .. })); + assert_eq!(st.selection.objects, [inst]); + let now = bounds(&s, layer); + assert!((now.x0 - art.x0).abs() < 1e-6 && (now.y1 - art.y1).abs() < 1e-6 && (now.width() - art.width()).abs() < 1e-6, "{art:?} {now:?}"); + assert_eq!(s.doc().unwrap().doc.layers.len(), 3, "the other layers untouched"); +} + +#[test] +fn locked_layers_keep_their_art_and_bad_layers_are_refused() { + let mut s = layered(); + let ids = layer_ids(&s); + s.execute("layer.setProps", &json!({"id": ids[2], "locked": true})).unwrap(); + let r = s.execute("addon.document.symbolsFromLayers", &json!({"replace": true})).unwrap(); + let skipped: Vec<&str> = r["skipped"].as_array().unwrap().iter().map(|k| k["reason"].as_str().unwrap()).collect(); + assert_eq!(skipped, ["empty", "locked"]); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let rect = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0; + for p in [json!({"layers": [rect]}), json!({"layers": [u64::MAX]}), json!({"layers": "all"}), json!({"layers": [-1]}), json!({"replace": "yes"})] + { + assert!(s.execute("addon.document.symbolsFromLayers", &p).is_err(), "{p}"); + } + assert!(*s.doc().unwrap().doc == *before.0 && s.doc().unwrap().history.undo.len() == before.1); + // Only an empty layer: nothing made, no step. + let r = s.execute("addon.document.symbolsFromLayers", &json!({"layers": [ids[1]]})).unwrap(); + assert_eq!((r["symbols"].clone(), s.doc().unwrap().history.undo.len()), (json!([]), before.1)); +} + +#[test] +fn the_layers_highlighted_in_the_layers_panel_are_the_default() { + let mut s = layered(); + let ids = layer_ids(&s); + // One highlighted row is just the current layer: every layer. + s.execute("layer.setCurrent", &json!({"id": ids[0]})).unwrap(); + let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap(); + assert_eq!(r["symbols"].as_array().unwrap().len(), 2); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("layer.highlight", &json!({"ids": [ids[1], ids[2]]})).unwrap(); + let r = s.execute("addon.document.symbolsFromLayers", &json!({})).unwrap(); + assert_eq!((r["symbols"].clone(), r["skipped"].as_array().unwrap().len()), (json!(["Icons"]), 1)); +} + +/// #4920: Export All Open Documents writes an SVG of each open document; a folder that can't be +/// written lists every document in `failed`, and either way the active document stays active. +#[test] +fn export_all_open_documents_writes_each_and_reports_failures() { + let dir = std::env::temp_dir().join(format!("vc-export-all-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "name": "one"})).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100, "name": "two"})).unwrap(); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + let r = s.execute("addon.document.exportAllOpen", &json!({"folder": dir, "format": "svg"})).unwrap(); + assert_eq!(r["files"].as_array().unwrap().len(), 2, "{r}"); + assert!(dir.join("one.svg").exists() && dir.join("two.svg").exists()); + assert_eq!(s.active_index(), Some(0)); + assert!(s.documents().iter().all(|d| d.path.is_none()), "the documents stay unsaved"); + let missing = dir.join("missing").join("deeper"); + let r = s.execute("addon.document.exportAllOpen", &json!({"folder": missing, "format": "svg"})).unwrap(); + assert_eq!((r["files"].as_array().unwrap().len(), r["failed"].as_array().unwrap().len()), (0, 2), "{r}"); + assert_eq!(s.active_index(), Some(0)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// An SVG document last saved with linked images exports as one SVG with its images embedded: no +/// image file is written beside the copies (#4920 review). +#[test] +fn export_all_open_documents_writes_one_file_each() { + let dir = std::env::temp_dir().join(format!("vc-export-all-one-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("out")).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "name": "pic"})).unwrap(); + let mut png = vec![]; + image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + s.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + s.execute("document.save", &json!({"path": dir.join("pic.svg"), "format": "svg", "options": {"images": "link"}})).unwrap(); + let saved: Vec<_> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).filter(|e| e.path().is_file()).collect(); + assert!(saved.len() > 1, "the linked save wrote its image beside it: {saved:?}"); + let out = dir.join("out"); + let r = s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "svg"})).unwrap(); + let names: Vec = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["pic.svg"], "{r}"); + assert!(std::fs::read_to_string(out.join("pic.svg")).unwrap().contains("data:image/png;base64,"), "the image is embedded"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A PDF document last saved with a page range exports with every page, and an SVG document with +/// two artboards exports as one SVG holding the art of both (#4920 review). +#[test] +fn export_all_open_documents_keeps_every_page_and_artboard() { + let dir = std::env::temp_dir().join(format!("vc-export-all-pages-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("out")).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2, "name": "pages"})).unwrap(); + s.execute("document.save", &json!({"path": dir.join("pages.pdf"), "format": "pdf", "options": {"range": "1"}})).unwrap(); + let pages = |b: &[u8]| { + String::from_utf8_lossy(b).matches("/Type /Page\n").count() + + String::from_utf8_lossy(b).matches("/Type/Page/").count() + + String::from_utf8_lossy(b).matches("/Type /Page/").count() + + String::from_utf8_lossy(b).matches("/Type /Page ").count() + }; + let first = pages(&std::fs::read(dir.join("pages.pdf")).unwrap()); + let out = dir.join("out"); + s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "pdf"})).unwrap(); + let copy = pages(&std::fs::read(out.join("pages.pdf")).unwrap()); + assert!(copy > first, "the copy has every page: {first} saved, {copy} exported"); + // SVG: one file with the art on both artboards. + let a = s.doc().unwrap().doc.artboards[1].rect; + s.execute("shape.rectangle", &json!({"x": a.x0 + 10.0, "y": a.y0 + 10.0, "width": 20, "height": 20})).unwrap(); + s.execute("addon.document.exportAllOpen", &json!({"folder": out, "format": "svg"})).unwrap(); + let svgs: Vec = + std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".svg")).collect(); + assert_eq!(svgs, ["pages.svg"]); + let svg = std::fs::read_to_string(out.join("pages.svg")).unwrap(); + // Not the first artboard alone (its 100 × 100 box at the origin): the art's own bounds. + let view = svg.split("viewBox=\"").nth(1).and_then(|v| v.split('"').next()).unwrap(); + let w: f64 = view.split_whitespace().nth(2).unwrap().parse().unwrap(); + assert!(w > 19.0 && w < 30.0, "the SVG shows the art (the square on the second artboard), not the first artboard: viewBox {view}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A 24×24 white PNG with a dark (or red) square in it. +#[cfg(not(target_arch = "wasm32"))] +fn png(path: &Path, dark: bool) { + let mut img = image::RgbaImage::from_pixel(24, 24, image::Rgba([255, 255, 255, 255])); + for y in 6..18 { + for x in 6..18 { + img.put_pixel(x, y, if dark { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([200, 30, 30, 255]) }); + } + } + img.save(path).unwrap(); +} + +/// #4921: each image of the folder is traced and saved under its own name; a file that isn't an +/// image is left alone, one that can't be read is reported, and every document the batch opened +/// is closed again, the active one staying active. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn batch_trace_folder_traces_and_saves_each_image() { + const C: &str = "addon.document.batchTraceFolder"; + let dir = folder("batch-trace"); + let (src, out) = (dir.join("in"), dir.join("out")); + std::fs::create_dir_all(&src).unwrap(); + png(&src.join("logo.png"), true); + png(&src.join("mark.png"), false); + std::fs::write(src.join("notes.txt"), "not an image").unwrap(); + std::fs::write(src.join("broken.png"), b"not a png").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let docs = s.documents().len(); + let r = s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg", "expand": true})).unwrap(); + assert_eq!(r["traced"].as_array().unwrap().len(), 2, "{r}"); + assert_eq!(r["failed"].as_array().unwrap().len(), 1, "{r}"); + assert!(r["failed"][0]["path"].as_str().unwrap().ends_with("broken.png")); + let mut names: Vec = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names, ["logo.svg", "mark.svg"]); + let svg = std::fs::read_to_string(out.join("logo.svg")).unwrap(); + assert!(svg.contains(" Vec { + let mut v = vec![ + cmd!( + "addon.pathtools.erase", + "Anchor Eraser Brush", + [], + None, + "{points: [[x, y] | [x, y, pressure 0..1]…] (the brush's path, at most 100000 points), diameter?: pt 0.1..2500 (20; a point's pressure scales it), tolerance?: 1..100 (10; the outline may move up to tolerance × 0.02 pt), ignoreTolerance?: bool (false: every anchor under the brush that can go goes, its neighbours refitted), plain?: bool (false: true deletes them without refitting the handles beside them), ids?: [id…] (default: the selection)} remove the anchors of the paths under the objects that the brush passes over and that can go while the outline stays within the tolerance, as one undo step; open ends stay → {ids, removed}", + has_selection, + erase + ), + cmd!( + "addon.pathtools.extend", + "Extend Path", + [], + None, + "{id, subpath?: index (0), end: \"start\"|\"end\", length?: pt (negative shortens; never all of it), to?: [x, y] (instead of length: the length that brings the end nearest this point), mode?: \"straight\"|\"bezier\" (stretch the last segment's curve, no anchor added)|\"arc\" (along the circle the end curves on, at most half way round) (\"straight\")} lengthen an open path at an end the way it runs there, or shorten it back along itself, as one undo step; with Keep Shared Points Together on, anchors coincident with an end that moves go with it → {id, length (pt)}", + has_doc, + extend + ), + cmd!( + query "addon.pathtools.inspect", + "Measure & Inspect", + [], + None, + "{id, x, y, tolerance?: pt (3; how near an anchor counts as over it)} what the path reads at the point nearest (x, y): {subpath, closed, anchors, length, area (pt², an open subpath closed by a straight line), segment, t, point: [x, y], segmentLength, tangent (degrees counter-clockwise), radius (of curvature, null where straight), anchor?: {index, x, y, smooth, angle (at the anchor, null at an open end), in?: {length, angle}, out?: {length, angle}}}", + has_doc, + inspect + ), + cmd!( + "addon.pathtools.setAnchor", + "Set Anchor", + [], + None, + "{x?, y?: pt (on the page), inLength?, outLength?: pt (0 retracts), inAngle?, outAngle?: degrees counter-clockwise} move the selected anchors (with their handles) and set their handles, as one undo step: direct-selected anchors, or every anchor of a path selected whole; a smooth anchor's other handle turns with the one set; with Keep Shared Points Together on, anchors coincident with one that moves go with it → {anchors}", + has_selection, + set_anchor + ), + cmd!( + "addon.pathtools.smooth", + "Make Smooth", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{ratio?: 0.1..0.5 (0.3905: a square's corners make a circle)} make the selected anchors smooth: a lone handle is mirrored; without handles, both stand at right angles to the bisector of the angle at the anchor, ratio × the nearer neighbour's distance long; two handles are put in line; an open end without handles aims at its neighbour's handle. One undo step → {anchors (changed)}", + has_selection, + smooth + ), + cmd!( + "addon.pathtools.corner", + "Make Corner", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{retract?: bool (true: the handles go; false: they stay where they are and move apart)} make the selected anchors corners, as one undo step → {anchors (changed)}", + has_selection, + corner + ), + cmd!( + "addon.pathtools.equalize", + "Equalize Handles", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{} give each selected anchor's two handles their average length (a missing one is made opposite the other), as one undo step → {anchors (changed)}", + has_selection, + equalize + ), + cmd!( + "addon.pathtools.removeKeepShape", + "Remove Points, Keep Shape", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{} remove the direct-selected anchors, refitting the handles beside each so the outline keeps its shape as best it can, as one undo step; open ends stay → {removed}", + has_selection, + remove_keep_shape + ), + cmd!( + "addon.pathtools.addPoints", + "Add Points to Segments…", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{count?: 1..100 (1)} add count anchors to each selected segment (a segment between two selected anchors, or every segment of a path selected whole), splitting it into pieces of equal length; the shape doesn't change. One undo step → {added}", + has_selection, + add_points + ), + cmd!( + "addon.pathtools.close", + "Close Path", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{mode?: \"handles\" (keep the ends' handles)|\"straight\" (a straight closing segment)|\"smooth\" (the ends made smooth), ratio?: 0.1..0.5 (0.3905, for smooth)} close the open subpaths of the selected paths, as one undo step → {closed}", + has_selection, + close + ), + cmd!( + "addon.pathtools.crossings", + "Add Points at Crossings", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}", + has_selection, + crossings + ), + cmd!( + "addon.pathtools.slideAnchor", + "Slide Anchor Along Path", + [], + None, + "{id, subpath?: index (0), anchor: index, t: -0.98..0.98 (where to: positive, a curve parameter on the segment after the anchor; negative, back from the end of the one before)} move an anchor along its path, the segments beside it refitted so the outline stays, as one undo step; ends of open paths don't slide; with Keep Shared Points Together on, anchors coincident with it go with it → {id, strayed (pt)}", + has_doc, + slide_anchor + ), + cmd!( + "addon.pathtools.divideDashes", + "Divide into Dashes", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{dash?: pt 0.01..1000000 (10), gap?: pt 0..1000000 (0: the pieces touch), fit?: bool (false: exact lengths, the last piece of each run what is left; true: fit to corners and ends, every run between corners and ends holding whole dashes, all stretched or squeezed alike so it starts and ends on a dash), removeGaps?: bool (true: the gaps are left empty; false: they stay as pieces too)} cut the selected paths into separate open paths along the curve, each dash long with gap between them and keeping the path's appearance, as one undo step. Only the direct-selected segments (or those between two direct-selected anchors) are divided when there are any, the dash pattern running on across segments that follow one another; the rest of such a path stays, as pieces of its own. The pieces are selected; at most 100000 → {ids, dashes}", + has_selection, + divide_dashes + ), + cmd!( + "addon.pathtools.expandDashes", + "Expand Dashes into Paths", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{ids?: [id…] (default: the selection)} turn the dashed stroke of each path and compound path under the objects into separate open paths, one per dash, laid out as the stroke draws them (its dash pattern, offset and Align Dashes to Corners and Path Ends), each keeping the path's appearance with the dashes off, so the gaps are real gaps: a dash running all the way round a closed path stays closed, and with a round or projecting cap a dash of no length (a dot) becomes a path on its point. The top stroke's dashes are the ones expanded; its arrowheads go, and the path's fills stay on it, below its dashes. Paths without a dashed stroke stay as they are. One undo step; the dashes are selected; at most 100000 → {ids, dashes}", + has_selection, + expand_dashes + ), + ]; + v.extend(shape::specs()); + v.extend(corners::specs()); + v.extend(shared_edge::specs()); + v +} + +/// The editable paths (not guides) under `roots`, compound path members included. +fn paths_under(d: &Document, roots: &[NodeId]) -> Vec { + let editable = d.editable(); + let mut out = vec![]; + for n in roots.iter().filter_map(|id| d.node(*id)) { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::Path { guide: false, .. }) && editable(c.id) { + out.push(c.id); + } + }); + } + out +} + +/// Put `np` in path `id`'s place; its live shape goes (its anchors are edited). +fn set_path(d: &mut Document, id: NodeId, np: PathData) { + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *path = np; + *live = None; + } +} + +/// Error unless the paths together have at most [`MAX_ANCHORS`] anchors. +fn check_size<'a>(paths: impl IntoIterator, cmd: &str) -> Result<()> { + if paths.into_iter().map(PathData::anchor_count).sum::() > MAX_ANCHORS { + return Err(bad(cmd, "the paths have too many anchors to edit at once")); + } + Ok(()) +} + +// ---------- Anchor Eraser Brush ---------- + +/// The brush's points (with the radius each has), from `points`. +fn stroke(p: &Value, radius: f64, cmd: &str) -> Result> { + let list = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`points` must be a list of [x, y] points"))?; + if list.len() > MAX_STROKE_POINTS { + return Err(bad(cmd, "too many `points` (at most 100000)")); + } + list.iter() + .map(|v| { + let point = |[x, y]: [f64; 2], pressure: f64| (Point::new(x, y), (radius * pressure.clamp(0.0, 1.0)).max(MIN_RADIUS)); + finite_numbers::<2>(v) + .map(|xy| point(xy, 1.0)) + .or_else(|| finite_numbers::<3>(v).map(|[x, y, f]| point([x, y], f))) + .ok_or_else(|| bad(cmd, format!("bad point {v}: expected [x, y] or [x, y, pressure]"))) + }) + .collect() +} + +/// Does the brush, sweeping through `pts`, cover `q`? +fn under_brush(pts: &[(Point, f64)], q: Point) -> bool { + let hit = |(a, ra): (Point, f64), (b, rb): (Point, f64)| { + let ab = b - a; + let len2 = ab.hypot2(); + let t = if len2 > 0.0 { ((q - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + q.distance(a + ab * t) <= ra + (rb - ra) * t + }; + match pts { + [only] => hit(*only, *only), + _ => pts.windows(2).any(|w| matches!(w, [a, b] if hit(*a, *b))), + } +} + +/// The anchors of `sp` that go when the brush passes over those marked, removed without refitting +/// the handles beside them: open ends stay, and the subpath keeps two anchors (three closed). +fn delete_marked(sp: &SubPath, marked: &[bool]) -> SubPath { + let n = sp.anchors.len(); + let min = if sp.closed { 3 } else { 2 }; + let mut left = n.saturating_sub(min); + let mut out = sp.clone(); + let keep: Vec = (0..n) + .map(|i| { + let end = !sp.closed && (i == 0 || i + 1 == n); + let go = !end && left > 0 && marked.get(i).copied().unwrap_or(false); + left -= usize::from(go); + !go + }) + .collect(); + let mut it = keep.iter(); + out.anchors.retain(|_| it.next().copied().unwrap_or(true)); + out +} + +fn erase(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.erase"; + let diameter = number_or(p, "diameter", 20.0, C)?; + if !(0.1..=MAX_DIAMETER).contains(&diameter) { + return Err(bad(C, "`diameter` must be from 0.1 to 2500 pt")); + } + let tolerance = number_or(p, "tolerance", ERASE_TOLERANCE, C)?; + if !(1.0..=100.0).contains(&tolerance) { + return Err(bad(C, "`tolerance` must be from 1 to 100")); + } + let (ignore, plain) = (switch_or(p, "ignoreTolerance", false, C)?, switch_or(p, "plain", false, C)?); + let pts = stroke(p, diameter / 2.0, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let ids = paths_under(d, &roots); + let paths: Vec<(NodeId, &PathData)> = ids.iter().filter_map(|id| Some((*id, d.node(*id)?.path_data()?))).collect(); + check_size(paths.iter().map(|(_, p)| *p), C)?; + let tol = if ignore { f64::INFINITY } else { tolerance * po::PT_PER_TOLERANCE }; + let mut removed = 0; + let mut changed = vec![]; + for (id, path) in paths { + let subs: Vec = path + .subpaths + .iter() + .map(|sp| { + let marked: Vec = sp.anchors.iter().map(|a| !pts.is_empty() && under_brush(&pts, a.p)).collect(); + match marked.contains(&true) { + false => sp.clone(), + true if plain => delete_marked(sp, &marked), + true => po::simplify_anchors_keep_shape(sp, tol, &marked), + } + }) + .collect(); + let np = PathData::new(subs); + if np != *path { + removed += path.anchor_count().saturating_sub(np.anchor_count()); + changed.push((id, np)); + } + } + edit_whole(s, "Anchor Eraser Brush", changed)?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "removed": removed })) +} + +/// Replace paths with the new data given, as one step (none when there is nothing to change); each +/// is selected whole, as its anchors' indexes changed. +fn edit_whole(s: &mut Session, label: &str, changed: Vec<(NodeId, PathData)>) -> Result<()> { + if changed.is_empty() { + return Ok(()); + } + s.edit(label, |d, sel| { + for (id, np) in changed { + sel.anchors.remove(&id); + sel.segments.remove(&id); + set_path(d, id, np); + } + Ok(()) + }) +} + +// ---------- Extend Path ---------- + +/// The subpath a request names: (path id, subpath index, its data). +fn named_subpath(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, usize, SubPath)> { + let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), cmd)?; + let si = usize_opt(p, "subpath", cmd)?.unwrap_or(0); + let d = &s.doc()?.doc; + if !d.is_editable(id) { + return Err(bad(cmd, "the path is locked or hidden")); + } + let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(cmd, "`id` is not a path"))?; + let sp = path.subpaths.get(si).ok_or_else(|| bad(cmd, "no such subpath"))?; + Ok((id, si, sp.clone())) +} + +/// Put `new` in place of the subpath `old` (from [`named_subpath`]) as one step labelled `label` +/// (none when it is the same), with what Keep Shared Points Together moves too; the path's direct +/// selection goes. +fn set_subpath(s: &mut Session, label: &str, (id, si, old): (NodeId, usize, SubPath), new: SubPath) -> Result<()> { + if new == old { + return Ok(()); + } + let mut np = s.doc()?.doc.node(id).and_then(|n| n.path_data()).cloned().ok_or(EngineError::NoNode(id))?; + if let Some(slot) = np.subpaths.get_mut(si) { + *slot = new; + } + let shared = shared_edge::shared_points(s, [(id, &np)])?; + s.edit(label, |d, sel| { + sel.anchors.remove(&id); + sel.segments.remove(&id); + set_path(d, id, np); + shared_edge::move_shared(d, shared); + Ok(()) + }) +} + +fn extend(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.extend"; + let (id, si, sp) = named_subpath(s, p, C)?; + if sp.closed || sp.anchors.len() < 2 { + return Err(bad(C, "the subpath has no ends to extend (it is closed or a single point)")); + } + let at_start = match text_param(p, "end", C)? { + Some("start") => true, + Some("end") => false, + _ => return Err(bad(C, "`end` must be \"start\" or \"end\"")), + }; + let mode = match text_param(p, "mode", C)? { + None => pt::ExtendMode::Straight, + Some(m) => pt::ExtendMode::parse(m).ok_or_else(|| bad(C, "`mode` must be \"straight\", \"bezier\" or \"arc\""))?, + }; + let length = match (p.get("to").filter(|v| !v.is_null()), p.get("length").filter(|v| !v.is_null())) { + (Some(to), None) => { + let [x, y] = finite_numbers::<2>(to).ok_or_else(|| bad(C, "`to` must be [x, y]"))?; + pt::extend_length_to(&sp, at_start, Point::new(x, y), mode).ok_or_else(|| bad(C, "the path can't be extended"))? + } + (None, Some(_)) => number_or(p, "length", 0.0, C)?, + _ => return Err(bad(C, "give `length` or `to`")), + }; + if !length.is_finite() || length.abs() > MAX_EXTEND { + return Err(bad(C, "`length` must be a number of at most 1000000 pt either way")); + } + let new = pt::extend_open(&sp, at_start, length, mode).ok_or_else(|| bad(C, "the path is too short to shorten that much"))?; + set_subpath(s, "Extend Path", (id, si, sp), new)?; + Ok(json!({ "id": id.0, "length": length })) +} + +// ---------- Slide Anchor Along Path ---------- + +fn slide_anchor(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.slideAnchor"; + let (id, si, sp) = named_subpath(s, p, C)?; + let anchor = usize_opt(p, "anchor", C)?.ok_or_else(|| bad(C, "give `anchor`, the index of the anchor to slide"))?; + let t = number_or(p, "t", f64::NAN, C)?; + if t.is_nan() || t.abs() > pt::MAX_SLIDE { + return Err(bad(C, "`t` must be a number from -0.98 to 0.98")); + } + let (new, strayed) = + pt::slide_anchor(&sp, anchor, t).ok_or_else(|| bad(C, "that anchor can't slide: an end of an open path has nowhere to go"))?; + set_subpath(s, "Slide Anchor Along Path", (id, si, sp), new)?; + Ok(json!({ "id": id.0, "strayed": strayed })) +} + +// ---------- Measure & Inspect ---------- + +fn polar(h: Option<(f64, f64)>) -> Value { + h.map_or(Value::Null, |(length, angle)| json!({ "length": length, "angle": angle })) +} + +fn inspect(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.inspect"; + let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?; + let (x, y) = (number_or(p, "x", f64::NAN, C)?, number_or(p, "y", f64::NAN, C)?); + let tolerance = number_or(p, "tolerance", 3.0, C)?; + if !(x.is_finite() && y.is_finite() && tolerance >= 0.0 && tolerance.is_finite()) { + return Err(bad(C, "give `x` and `y` (and a `tolerance` of 0 or more)")); + } + let path = s.doc()?.doc.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(C, "`id` is not a path"))?; + let i = pt::inspect(path, Point::new(x, y), tolerance).ok_or_else(|| bad(C, "the path has no segments to measure"))?; + let anchor = i.anchor.map(|a| { + json!({ "index": a.index, "x": a.p.x, "y": a.p.y, "smooth": a.smooth, "angle": a.angle, "in": polar(a.handle_in), "out": polar(a.handle_out) }) + }); + Ok(json!({ + "subpath": i.subpath, "closed": i.closed, "anchors": i.anchors, "length": i.length, "area": i.area, + "segment": i.segment, "t": i.t, "point": [i.point.x, i.point.y], "segmentLength": i.segment_length, + "tangent": i.tangent, "radius": i.radius, "anchor": anchor, + })) +} + +// ---------- Anchor Inspector ---------- + +/// The anchors the Anchor Inspector acts on, per path: each path's direct-selected anchors, or +/// every anchor of a path selected whole (with `whole`), keyed by subpath. +type Picked = Vec<(NodeId, BTreeMap>)>; + +/// The selected anchors ([`Picked`]); `whole` counts the anchors of paths selected whole. +fn picked_anchors(s: &Session, whole: bool) -> Result { + let st = s.doc()?; + let (d, sel) = (&st.doc, &st.selection); + let roots = super::super::edit::selected_roots(s)?; + let mut out = vec![]; + for id in paths_under(d, &roots) { + let Some(path) = d.node(id).and_then(|n| n.path_data()) else { continue }; + let refs: Vec = match sel.anchors.get(&id).filter(|a| !a.is_empty()) { + Some(set) => set.iter().copied().collect(), + None if whole => path.anchors().map(|(si, ai, _)| (si, ai)).collect(), + None => continue, + }; + let mut by_sub: BTreeMap> = BTreeMap::new(); + for (si, ai) in refs.into_iter().filter(|(si, ai)| path.subpaths.get(*si).is_some_and(|sp| *ai < sp.anchors.len())) { + by_sub.entry(si).or_default().insert(ai); + } + if !by_sub.is_empty() { + out.push((id, by_sub)); + } + } + Ok(out) +} + +/// Edit each selected anchor ([`picked_anchors`]) in place with `f` (true when it changed one), as +/// one step labelled `label`; the selection stays. → how many anchors changed. +fn edit_anchors(s: &mut Session, label: &str, cmd: &str, f: impl Fn(&mut SubPath, usize) -> bool) -> Result { + let picked = picked_anchors(s, true)?; + if picked.is_empty() { + return Err(bad(cmd, "select paths or anchor points")); + } + let d = &s.doc()?.doc; + check_size(picked.iter().filter_map(|(id, _)| d.node(*id)?.path_data()), cmd)?; + let mut count = 0; + let mut changed = vec![]; + for (id, by_sub) in &picked { + let Some(mut np) = d.node(*id).and_then(|n| n.path_data()).cloned() else { continue }; + let before = count; + for (si, anchors) in by_sub { + let Some(sp) = np.subpaths.get_mut(*si) else { continue }; + count += anchors.iter().filter(|&&i| f(sp, i)).count(); + } + if count > before { + changed.push((*id, np)); + } + } + if !changed.is_empty() { + let shared = shared_edge::shared_points(s, changed.iter().map(|(id, np)| (*id, np)))?; + s.edit(label, |d, _| { + for (id, np) in changed { + set_path(d, id, np); + } + shared_edge::move_shared(d, shared); + Ok(()) + })?; + } + Ok(count) +} + +/// A smoothing `ratio` param (default [`pt::SMOOTH_RATIO`]). +pub(super) fn ratio(p: &Value, cmd: &str) -> Result { + let r = number_or(p, "ratio", pt::SMOOTH_RATIO, cmd)?; + let (lo, hi) = pt::SMOOTH_RATIO_RANGE; + if !(lo..=hi).contains(&r) { + return Err(bad(cmd, "`ratio` must be from 0.1 to 0.5")); + } + Ok(r) +} + +fn smooth(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.smooth"; + let r = ratio(p, C)?; + let n = edit_anchors(s, "Make Smooth", C, |sp, i| pt::auto_smooth(sp, i, r))?; + Ok(json!({ "anchors": n })) +} + +fn corner(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.corner"; + let retract = switch_or(p, "retract", true, C)?; + let n = edit_anchors(s, "Make Corner", C, |sp, i| pt::make_corner(sp, i, retract))?; + Ok(json!({ "anchors": n })) +} + +fn equalize(s: &mut Session, _: &Value) -> Result { + const C: &str = "addon.pathtools.equalize"; + let n = edit_anchors(s, "Equalize Handles", C, pt::equalize_handles)?; + Ok(json!({ "anchors": n })) +} + +/// A number param that is given, finite, and (with `range`) inside it. +fn given(p: &Value, key: &str, range: Option<(f64, f64)>, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => { + let x = v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?; + match range { + Some((lo, hi)) if !(lo..=hi).contains(&x) => Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))), + _ => Ok(Some(x)), + } + } + } +} + +fn set_anchor(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.setAnchor"; + const LIMIT: Option<(f64, f64)> = Some((-1e7, 1e7)); + let (x, y) = (given(p, "x", LIMIT, C)?, given(p, "y", LIMIT, C)?); + let lengths = [given(p, "inLength", Some((0.0, 1e7)), C)?, given(p, "outLength", Some((0.0, 1e7)), C)?]; + let angles = [given(p, "inAngle", LIMIT, C)?, given(p, "outAngle", LIMIT, C)?]; + if [x, y].iter().chain(&lengths).chain(&angles).all(Option::is_none) { + return Err(bad(C, "give x, y, or a handle's length or angle")); + } + let n = edit_anchors(s, "Set Anchor", C, |sp, i| { + let Some(a) = sp.anchors.get_mut(i) else { return false }; + let before = *a; + let to = Point::new(x.unwrap_or(a.p.x), y.unwrap_or(a.p.y)); + a.translate(to - a.p); + for (out, (len, ang)) in [false, true].into_iter().zip(lengths.into_iter().zip(angles)) { + if len.is_none() && ang.is_none() { + continue; + } + let h = if out { a.h_out } else { a.h_in }; + let (l0, a0) = pt::handle_polar(a.p, h).unwrap_or((0.0, if out { 0.0 } else { 180.0 })); + let (l, deg) = (len.unwrap_or(l0), ang.unwrap_or(a0)); + // A length alone keeps a smooth anchor's other handle where it is; an angle turns it too. + let other = if out { a.h_in } else { a.h_out }; + a.set_handle(out, pt::handle_at(a.p, l, deg), false); + if ang.is_none() { + if out { a.h_in = other } else { a.h_out = other } + } + } + *a != before + })?; + Ok(json!({ "anchors": n })) +} + +fn remove_keep_shape(s: &mut Session, _: &Value) -> Result { + const C: &str = "addon.pathtools.removeKeepShape"; + let picked = picked_anchors(s, false)?; + if picked.is_empty() { + return Err(bad(C, "direct-select the anchor points to remove")); + } + let d = &s.doc()?.doc; + check_size(picked.iter().filter_map(|(id, _)| d.node(*id)?.path_data()), C)?; + let mut removed = 0; + let mut changed = vec![]; + for (id, by_sub) in &picked { + let Some(mut np) = d.node(*id).and_then(|n| n.path_data()).cloned() else { continue }; + for (si, anchors) in by_sub { + let Some(sp) = np.subpaths.get_mut(*si) else { continue }; + // From the last back, so the indexes left stay right. + for &i in anchors.iter().rev() { + if let Some((out, _)) = po::remove_anchor_keep_shape(sp, i) { + *sp = out; + removed += 1; + } + } + } + if np != *d.node(*id).and_then(|n| n.path_data()).ok_or(EngineError::NoNode(*id))? { + changed.push((*id, np)); + } + } + edit_whole(s, "Remove Points, Keep Shape", changed)?; + Ok(json!({ "removed": removed })) +} + +/// The segments of subpath `si` (`sp`) picked: the direct-selected segments `segments` of its +/// path, else those between two of its selected `anchors`. +fn picked_segments(segments: Option<&BTreeSet<(usize, usize)>>, si: usize, sp: &SubPath, anchors: &BTreeSet) -> BTreeSet { + let n = sp.anchors.len().max(1); + match segments.filter(|set| !set.is_empty()) { + Some(set) => set.iter().filter(|(s, _)| *s == si).map(|(_, k)| *k).collect(), + None => (0..sp.segment_count()).filter(|k| anchors.contains(k) && anchors.contains(&((k + 1) % n))).collect(), + } +} + +fn add_points(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.addPoints"; + let count = number_or(p, "count", 1.0, C)?; + if !(1.0..=MAX_ADD as f64).contains(&count) || count.fract() != 0.0 { + return Err(bad(C, "`count` must be a whole number from 1 to 100")); + } + let picked = picked_anchors(s, true)?; + let st = s.doc()?; + let d = &st.doc; + check_size(picked.iter().filter_map(|(id, _)| d.node(*id)?.path_data()), C)?; + let mut added = 0; + let mut changed = vec![]; + for (id, by_sub) in &picked { + let Some(path) = d.node(*id).and_then(|n| n.path_data()) else { continue }; + let mut np = path.clone(); + for (si, sp) in np.subpaths.iter_mut().enumerate() { + let Some(anchors) = by_sub.get(&si) else { continue }; + let segs = picked_segments(st.selection.segments.get(id), si, sp, anchors); + let (out, marks) = pt::add_points(sp, Some(&segs), count as usize); + added += marks.len(); + *sp = out; + } + if np != *path { + changed.push((*id, np)); + } + } + if added == 0 { + return Err(bad(C, "select segments, or paths, to add points to")); + } + edit_whole(s, "Add Points to Segments", changed)?; + Ok(json!({ "added": added })) +} + +pub(super) fn close(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.close"; + let mode = match text_param(p, "mode", C)? { + None => pt::CloseMode::Handles, + Some(m) => pt::CloseMode::parse(m).ok_or_else(|| bad(C, "`mode` must be \"handles\", \"straight\" or \"smooth\""))?, + }; + let r = ratio(p, C)?; + let roots = super::super::edit::selected_roots(s)?; + let d = &s.doc()?.doc; + let mut closed = 0; + let mut changed = vec![]; + for id in paths_under(d, &roots) { + let Some(path) = d.node(id).and_then(|n| n.path_data()) else { continue }; + let mut np = path.clone(); + let n = np.subpaths.iter_mut().map(|sp| pt::close(sp, mode, r)).filter(|c| *c).count(); + if n > 0 { + closed += n; + changed.push((id, np)); + } + } + if changed.is_empty() { + return Err(bad(C, "select open paths to close")); + } + s.edit("Close Path", |d, _| { + for (id, np) in changed { + set_path(d, id, np); + } + Ok(()) + })?; + Ok(json!({ "closed": closed })) +} + +// ---------- Split / Add Points at Crossings ---------- + +fn crossings(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.crossings"; + let (cut, self_crossings) = (switch_or(p, "cut", false, C)?, switch_or(p, "selfCrossings", false, C)?); + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let ids = paths_under(d, &roots); + let paths: Vec<&PathData> = ids.iter().filter_map(|id| d.node(*id)?.path_data()).collect(); + if paths.len() != ids.len() { + return Err(EngineError::Other("Add Points at Crossings: a path went missing".into())); + } + let places = pt::crossings(&paths, self_crossings) + .ok_or_else(|| bad(C, "the paths are too many or too tangled to find where they cross (at most 10000 segments)"))?; + let mut count = 0; + // Each path that is crossed: its new subpaths, and the anchors at the crossings on each. + let mut changed: Vec<(NodeId, Vec, Vec>)> = vec![]; + for ((id, path), on) in ids.iter().zip(&paths).zip(places) { + if on.is_empty() { + continue; + } + let mut subs = vec![]; + let mut marks = vec![]; + for (si, sp) in path.subpaths.iter().enumerate() { + let here: Vec<(usize, f64)> = on.iter().filter(|(s, ..)| *s == si).map(|&(_, seg, t)| (seg, t)).collect(); + let (out, m) = pt::insert_at(sp, &here); + count += m.len(); + subs.push(out); + marks.push(m); + } + changed.push((*id, subs, marks)); + } + if changed.is_empty() { + return Ok(json!({ "ids": [], "crossings": 0 })); + } + let label = if cut { "Split at Crossings" } else { "Add Points at Crossings" }; + let out = s.edit(label, |d, sel| { + let mut all = vec![]; + let mut beside = Beside::replacing(d, &changed.iter().map(|(id, ..)| *id).collect::>()); + for (id, subs, marks) in changed { + sel.anchors.remove(&id); + sel.segments.remove(&id); + if !cut { + set_path(d, id, PathData::new(subs)); + all.push(id); + continue; + } + let pieces: Vec = subs.iter().zip(&marks).flat_map(|(sp, m)| sp.cut_at(m)).collect(); + // A path of one subpath becomes a path per piece; a compound shape's pieces stay its subpaths. + if subs.len() == 1 { + let made = replace_with_pieces(d, &mut beside, id, pieces.into_iter().map(PathData::single).collect())?; + for n in &made { + if !sel.contains(*n) { + sel.add(*n); + } + } + all.extend(made); + } else { + set_path(d, id, PathData::new(pieces)); + all.push(id); + } + } + beside.finish(d)?; + Ok(all) + })?; + Ok(json!({ "ids": out.iter().map(|i| i.0).collect::>(), "crossings": count })) +} + +// ---------- Divide into Dashes ---------- + +fn divide_dashes(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.divideDashes"; + let spec = pt::DashSpec { + dash: given(p, "dash", Some((0.01, 1e6)), C)?.unwrap_or(10.0), + gap: given(p, "gap", Some((0.0, 1e6)), C)?.unwrap_or(0.0), + fit: switch_or(p, "fit", false, C)?, + }; + let remove_gaps = switch_or(p, "removeGaps", true, C)?; + let picked = picked_anchors(s, true)?; + let st = s.doc()?; + let d = &st.doc; + check_size(picked.iter().filter_map(|(id, _)| d.node(*id)?.path_data()), C)?; + let (mut made, mut dashes) = (0, 0); + // Each path divided: what stays of it (the subpaths not divided, as one path) and its pieces. + let mut changed: Vec<(NodeId, Vec)> = vec![]; + for (id, by_sub) in &picked { + let Some(path) = d.node(*id).and_then(|n| n.path_data()) else { continue }; + let (mut kept, mut pieces) = (vec![], vec![]); + for (si, sp) in path.subpaths.iter().enumerate() { + let segs = by_sub.get(&si).map(|anchors| picked_segments(st.selection.segments.get(id), si, sp, anchors)).unwrap_or_default(); + if segs.is_empty() { + kept.push(sp.clone()); + continue; + } + let only = (segs.len() < sp.segment_count()).then_some(&segs); + let out = pt::divide_dashes(sp, only, spec, MAX_PIECES.saturating_sub(made)) + .ok_or_else(|| bad(C, "that makes too many pieces (at most 100000): make the dashes longer"))?; + made += out.len(); + for (piece, kind) in out.into_iter().filter(|(_, k)| !(remove_gaps && *k == pt::Piece::Gap)) { + dashes += usize::from(kind == pt::Piece::Dash); + pieces.push(PathData::single(piece)); + } + } + if !pieces.is_empty() { + changed.push((*id, (!kept.is_empty()).then(|| PathData::new(kept)).into_iter().chain(pieces).collect())); + } + } + if changed.is_empty() { + return Err(bad(C, "select paths, or segments, to divide")); + } + let ids = s.edit("Divide into Dashes", |d, sel| { + let mut all = vec![]; + let mut beside = Beside::replacing(d, &changed.iter().map(|(id, _)| *id).collect::>()); + for (id, pieces) in changed { + all.extend(replace_with_pieces(d, &mut beside, id, pieces)?); + } + beside.finish(d)?; + // The pieces join the objects selected (whole, in one go: there may be many). + let before = std::mem::take(&mut sel.objects); + sel.set(before.into_iter().chain(all.iter().copied())); + Ok(all) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "dashes": dashes })) +} + +// ---------- Expand Dashes into Paths ---------- + +/// The paths and compound paths under `roots` whose top stroke is dashed: a compound path's +/// members stand for it, which holds their paint. Clipping paths are left alone. +fn dashed_paths(d: &Document, roots: &[NodeId]) -> Vec { + let editable = d.editable(); + let mut seen = BTreeSet::new(); + let mut out = vec![]; + for id in paths_under(d, roots) { + let compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); + let Some(n) = compound.or_else(|| d.node(id)) else { continue }; + let dashed = n.appearance.stroke().and_then(|st| st.dash.as_ref()).is_some_and(|dash| dash.is_dashed()); + if dashed && !matches!(n.kind, NodeKind::Path { clipping: true, .. }) && editable(n.id) && seen.insert(n.id) { + out.push(n.id); + } + } + out +} + +fn expand_dashes(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.expandDashes"; + let too_many = || bad(C, "that makes too many pieces (at most 100000): make the dashes longer"); + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + // Each dashed path and its dashes, as the canvas draws them. + let mut changed: Vec<(NodeId, Vec)> = vec![]; + let mut count = 0; + for id in dashed_paths(d, &roots) { + let Some(n) = d.node(id) else { continue }; + let (Some(st), Some(bp)) = (n.appearance.stroke(), n.stroke_path()) else { continue }; + let Some(dash) = &st.dash else { continue }; + // The line the stroke draws: the path, its ends trimmed under any arrowheads. + let line = vectorcraft_render::effects::stroke::stroke_pieces(&bp, st).line; + // A pattern too fine to draw is drawn solid: it has too many dashes to expand. + let dashed = vectorcraft_render::effects::stroke::dash(&line, dash).ok_or_else(too_many)?; + let mut pieces = PathData::from_bezpath(&dashed.path).subpaths; + // A dot paints its cap; a path that stays on its point is drawn so too. Under a butt cap it + // paints nothing. + if st.cap != LineCap::Butt { + pieces.extend(dashed.dots.iter().map(|dot| SubPath::polyline(&[dot.at, dot.at], false))); + } + count += pieces.len(); + if count > MAX_PIECES { + return Err(too_many()); + } + if !pieces.is_empty() { + changed.push((id, pieces)); + } + } + if changed.is_empty() { + return Err(bad(C, "select paths with dashed strokes to expand")); + } + let ids = s.edit("Expand Dashes into Paths", |d, sel| { + let mut all = vec![]; + let mut beside = Beside::replacing(d, &changed.iter().map(|(id, _)| *id).collect::>()); + for (id, pieces) in changed { + let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &n.kind else { continue }; + let rule = *rule; + let filled = |i: &AppearanceItem| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none()); + // The dashes: open paths with the strokes (the top one's dashes and arrowheads off). + let mut look = Appearance::clone(&n.appearance); + look.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); + if let Some(st) = look.stroke_mut() { + (st.dash, st.start_arrow, st.end_arrow) = (None, None, None); + } + let mut dash = n.clone(); + dash.kind = NodeKind::Path { path: PathData::default(), rule, live: None, clipping: false, guide: false }; + dash.appearance = look.into(); + // The fills stay on the path, below its dashes; without fills it goes. + let mut parts = vec![]; + if n.appearance.items.iter().any(filled) { + let mut fill = n.clone(); + let mut look = Appearance::clone(&n.appearance); + look.items.retain(filled); + fill.appearance = look.into(); + parts.push(fill); + } + for sp in pieces { + let mut piece = d.reid(&dash); + if let NodeKind::Path { path, .. } = &mut piece.kind { + *path = PathData::single(sp); + } + all.push(piece.id); + parts.push(piece); + } + beside.put(d, id, parts)?; + } + beside.finish(d)?; + // The dashes join the objects selected (whole, in one go: there may be many). + let before = std::mem::take(&mut sel.objects); + sel.set(before.into_iter().filter(|id| d.node(*id).is_some()).chain(all.iter().copied())); + Ok(all) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "dashes": ids.len() })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/corners.rs b/crates/engine/src/cmd/addons/pathtools/corners.rs new file mode 100644 index 0000000000..2f035d8ad4 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/corners.rs @@ -0,0 +1,247 @@ +//! The Corner Tool's commands: the app's Live Corners ([`LiveCorners`]) cut, resized and removed on +//! chosen anchors, each edit one undo step. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveCorners, NodeId, NodeKind}; +use vectorcraft_geom::shapes::CornerKind; +use vectorcraft_tools::addons::corner_tool::MAX_RADIUS; + +use super::super::super::object::recut; +use super::super::super::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, number_or}; +use super::{check_size, paths_under}; +use crate::{Result, Session}; + +pub(super) fn specs() -> Vec { + vec![ + cmd!( + "addon.pathtools.cornerSet", + "Set Corners", + [], + None, + "{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own), every?: \"all\"|\"odd\"|\"even\" (default all: of those anchors, only the odd- or even-numbered ones, counting each path's anchors from 1), minAngle?: degrees 0..180 (default 0), maxAngle?: degrees 0..180 (default 180; of those anchors, only the corners whose sides meet at an angle in this range: small for a sharp spike, near 180 for a shallow bend)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}", + has_doc, + corner_set + ), + cmd!( + "addon.pathtools.cornerRemove", + "Remove Corners", + [], + None, + "{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors)} make those live corners sharp again, as one undo step → {ids, corners (how many)}", + has_doc, + corner_remove + ), + ] +} + +/// The `anchors` of `p`. +fn anchors_param(p: &Value, cmd: &str) -> Result>> { + let Some(v) = p.get("anchors").filter(|v| !v.is_null()) else { return Ok(None) }; + let list = v.as_array().ok_or_else(|| bad(cmd, format!("`anchors` must list anchor indices (0, 1, 2…), not {v}")))?; + list.iter() + .map(|k| { + k.as_u64() + .and_then(|k| usize::try_from(k).ok()) + .ok_or_else(|| bad(cmd, format!("`anchors` must list anchor indices (0, 1, 2…), not {k}"))) + }) + .collect::>() + .map(Some) +} + +/// Which of the chosen anchors `cornerSet` takes, by their number along the path's uncut outline +/// (the first anchor is number 1). +#[derive(Clone, Copy, Debug, PartialEq)] +enum Every { + All, + /// The 1st, 3rd, 5th… anchors: indices 0, 2, 4…. + Odd, + /// The 2nd, 4th, 6th… anchors: indices 1, 3, 5…. + Even, +} + +impl Every { + /// The `every` of `p` (default: all). + fn of(p: &Value, cmd: &str) -> Result { + match p.get("every").filter(|v| !v.is_null()) { + None => Ok(Self::All), + Some(v) => match v.as_str() { + Some("all") => Ok(Self::All), + Some("odd") => Ok(Self::Odd), + Some("even") => Ok(Self::Even), + _ => Err(bad(cmd, format!("`every` must be \"all\", \"odd\" or \"even\", not {v}"))), + }, + } + } + + /// Does it take the anchor at `index`? Anchors that take no corner still count. + fn takes(self, index: usize) -> bool { + match self { + Self::All => true, + Self::Odd => index.is_multiple_of(2), + Self::Even => !index.is_multiple_of(2), + } + } + + /// Where the corners it takes are, for an error: "" for all of them. + fn at(self) -> &'static str { + match self { + Self::All => "", + Self::Odd => " at an odd-numbered anchor (the 1st, 3rd, 5th…)", + Self::Even => " at an even-numbered anchor (the 2nd, 4th, 6th…)", + } + } +} + +/// How far (degrees) past the ends of the angle range a corner's angle may be, so that a typed 90 +/// takes a rectangle's corners whatever the rounding. +const ANGLE_SLACK: f64 = 1e-6; +/// The error when no anchor named is a corner at all. +const NO_CORNER: &str = "choose anchors where two sides meet at an angle: only those take a corner"; + +/// Which of the chosen corners `cornerSet` takes: by their number (`every`) and by the angle their +/// sides meet at (`minAngle`..`maxAngle`, degrees). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Pick { + every: Every, + min_angle: f64, + max_angle: f64, +} + +impl Pick { + /// Every chosen corner. + const ALL: Self = Self { every: Every::All, min_angle: 0.0, max_angle: 180.0 }; + + /// The `every`, `minAngle` and `maxAngle` of `p`. + fn of(p: &Value, cmd: &str) -> Result { + let every = Every::of(p, cmd)?; + let angle = |key: &str, default: f64| -> Result { + let a = number_or(p, key, default, cmd)?; + if !(a.is_finite() && (0.0..=180.0).contains(&a)) { + return Err(bad(cmd, format!("`{key}` must be from 0 to 180 degrees, not {a}"))); + } + Ok(a) + }; + let (min_angle, max_angle) = (angle("minAngle", 0.0)?, angle("maxAngle", 180.0)?); + if min_angle > max_angle { + return Err(bad(cmd, format!("`minAngle` ({min_angle}°) can't be more than `maxAngle` ({max_angle}°)"))); + } + Ok(Self { every, min_angle, max_angle }) + } + + /// Does it take corner `index` of `lc`? + fn takes(&self, lc: &LiveCorners, index: usize) -> bool { + self.every.takes(index) + && lc.corner(index).is_some_and(|c| (self.min_angle - ANGLE_SLACK..=self.max_angle + ANGLE_SLACK).contains(&c.angle_deg())) + } + + /// The error when it takes none of the chosen corners. + fn none(&self) -> String { + let at = self.every.at(); + if self.min_angle > 0.0 || self.max_angle < 180.0 { + format!("none of the chosen corners{at} has an angle from {}° to {}°", self.min_angle, self.max_angle) + } else if at.is_empty() { + NO_CORNER.into() + } else { + format!("none of the chosen corners is{at}") + } + } +} + +/// The corners a request names: each path with the corners (anchor indices of its uncut outline) +/// that `pick` takes. +fn named_corners(s: &Session, p: &Value, cmd: &str, pick: Pick) -> Result)>> { + let shared = anchors_param(p, cmd)?; + // Each path with its own `anchors`, or sharing the request's. + let mut own: Vec>> = vec![]; + let ids: Vec = match p.get("items").filter(|v| !v.is_null()) { + None => paths_under(&s.doc()?.doc, &checked_ids_or_selection(s, p, cmd)?), + Some(Value::Array(items)) => { + let mut ids = vec![]; + for it in items { + ids.push(checked_id(s, it.get("id").unwrap_or(&Value::Null), cmd)?); + own.push(anchors_param(it, cmd)?); + } + ids + } + Some(v) => return Err(bad(cmd, format!("`items` must be a list of {{id, anchors?}}, not {v}"))), + }; + let st = s.doc()?; + let d = &st.doc; + check_size(ids.iter().filter_map(|id| d.node(*id)?.path_data()), cmd)?; + let editable = d.editable(); + let (mut out, mut chosen) = (vec![], false); + for (i, id) in ids.iter().enumerate() { + let Some(lc) = d.node(*id).filter(|_| editable(*id)).and_then(LiveCorners::of) else { continue }; + let corners: BTreeSet = match own.get(i).and_then(Option::as_ref).or(shared.as_ref()) { + Some(given) => { + let n = lc.base.anchor_count(); + if let Some(past) = given.iter().find(|k| **k >= n) { + return Err(bad(cmd, format!("object {id} has {n} anchors, so no anchor {past}"))); + } + given.iter().copied().filter(|k| lc.corner(*k).is_some()).collect() + } + None => st.selection.partial(*id).filter(|a| !a.is_empty()).map_or_else(|| lc.all(), |a| lc.corners_of(a)), + }; + chosen |= !corners.is_empty(); + let corners: BTreeSet = corners.into_iter().filter(|k| pick.takes(&lc, *k)).collect(); + if !corners.is_empty() { + out.push((*id, corners)); + } + } + if out.is_empty() { + return Err(bad(cmd, if chosen { pick.none() } else { NO_CORNER.into() })); + } + Ok(out) +} + +/// Cut `radius` and `kind` on `corners` as one step (none when they have them already). +fn edit_corners(s: &mut Session, label: &str, corners: Vec<(NodeId, BTreeSet)>, radius: f64, kind: Option) -> Result { + let d = &s.doc()?.doc; + let same = corners.iter().all(|(id, picked)| { + d.node(*id) + .and_then(LiveCorners::of) + .is_some_and(|c| picked.iter().all(|k| (c.drawn_radius(*k) - radius).abs() < 1e-9 && kind.is_none_or(|kd| c.kind(*k) == kd))) + }); + let out = json!({ + "ids": corners.iter().map(|(id, _)| id.0).collect::>(), + "corners": corners.iter().map(|(_, c)| c.len()).sum::(), + }); + if !same { + s.edit(label, |d, sel| { + for (id, picked) in corners { + let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) else { continue }; + // A cut changes the anchors, which is all a segment selection goes by. + sel.segments.remove(&id); + recut(path, live, sel.anchors.get_mut(&id), &picked, Some(radius), kind); + } + Ok(()) + })?; + } + Ok(out) +} + +fn corner_set(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.cornerSet"; + let radius = number_or(p, "radius", f64::NAN, C)?; + if !(0.0..=MAX_RADIUS).contains(&radius) { + return Err(bad(C, "`radius` must be from 0 to 1000000 pt")); + } + let kind = p + .get("kind") + .filter(|v| !v.is_null()) + .map(|v| { + serde_json::from_value::(v.clone()) + .map_err(|_| bad(C, format!("`kind` must be \"round\", \"invertedRound\" or \"chamfer\", not {v}"))) + }) + .transpose()?; + let pick = Pick::of(p, C)?; + let corners = named_corners(s, p, C, pick)?; + edit_corners(s, "Set Corners", corners, radius, kind) +} + +fn corner_remove(s: &mut Session, p: &Value) -> Result { + let corners = named_corners(s, p, "addon.pathtools.cornerRemove", Pick::ALL)?; + edit_corners(s, "Remove Corners", corners, 0.0, Some(CornerKind::Round)) +} diff --git a/crates/engine/src/cmd/addons/pathtools/effect_tests.rs b/crates/engine/src/cmd/addons/pathtools/effect_tests.rs new file mode 100644 index 0000000000..3465b72791 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/effect_tests.rs @@ -0,0 +1,186 @@ +//! Path Effects (`addon.path.*`) through the session: live on the canvas, the document's path left +//! alone, and Expand Appearance and a save keeping what they draw. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Effect, Node, NodeId}; +use vectorcraft_geom::{BezPath, Rect}; +use vectorcraft_render::Renderer; +use vectorcraft_render::effects::{GeomContext, apply_geometry_bez, effect_catalog, new_effect, preview, scale_effect}; + +use crate::Session; + +/// A black 4 pt stroke along `anchors`, unfilled. +fn stroked(anchors: Value, closed: bool) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.set([id])).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + (s, id) +} + +fn wave() -> (Session, NodeId) { + let anchors = json!([ + {"x": 20, "y": 100}, + {"x": 60, "y": 60, "in": [40, 60], "out": [80, 60]}, + {"x": 100, "y": 100}, + {"x": 140, "y": 140}, + {"x": 180, "y": 100} + ]); + stroked(anchors, false) +} + +/// Every Path Effect, with parameters that change the wave. +fn effects() -> Vec<(&'static str, Value)> { + vec![ + ("addon.path.dashes", json!({"dash1": 14, "gap1": 6, "dash2": 3, "gap2": 6})), + ("addon.path.dashes", json!({"dash1": 14, "gap1": 6, "alignCorners": true})), + ("addon.path.addAnchors", json!({"count": 3})), + ("addon.path.addAnchors", json!({"spacing": "distance", "distance": 15, "target": "curved"})), + ("addon.path.extend", json!({"startLength": 10, "endPercent": 10, "endShape": "arc"})), + ("addon.path.extend", json!({"startLength": -10, "endLength": -20})), + ("addon.path.close", json!({})), + ("addon.path.close", json!({"mode": "smooth"})), + ("addon.path.smooth", json!({"ratio": 0.3})), + ("addon.path.retract", json!({})), + ("addon.path.reverse", json!({})), + ("addon.path.simplify", json!({"tolerance": 200, "protectCorners": false})), + ("addon.path.split", json!({"anchors": "both"})), + ] +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn picture_of(d: &Document) -> Vec { + let r = Renderer::new().render_region(d, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true); + (0..200).flat_map(|y| (0..200).map(move |x| (x, y))).flat_map(|(x, y)| r.pixel(x, y)).collect() +} + +fn picture(s: &Session) -> Vec { + picture_of(&s.doc().unwrap().doc) +} + +/// The outline of `n`: its path, or those of the compound path it became. +fn outline(n: &Node) -> BezPath { + let mut out = n.path_data().map(|p| p.to_bezpath()).unwrap_or_default(); + n.children().into_iter().flatten().for_each(|c| out.extend(outline(c))); + out +} + +/// How many bytes of two pictures differ by more than antialiasing noise. +fn differing(a: &[u8], b: &[u8]) -> usize { + a.iter().zip(b).filter(|(x, y)| x.abs_diff(**y) > 8).count() +} + +#[test] +fn a_path_effect_draws_live_and_leaves_the_document_path() { + let (mut s, id) = stroked(json!([{"x": 10, "y": 50}, {"x": 190, "y": 50}]), false); + let solid = picture(&s); + let path = node(&s, id).path_data().cloned(); + s.execute("effect.apply", &json!({"effect": "addon.path.dashes", "params": {"dash1": 20, "gap1": 20}})).unwrap(); + assert_eq!(node(&s, id).path_data().cloned(), path, "only the effect holds the geometry"); + let dashed = picture(&s); + let at = |pic: &[u8], x: usize| pic[(50 * 200 + x) * 4]; + assert!(at(&solid, 45) < 40 && at(&dashed, 45) > 200, "a gap: {}", at(&dashed, 45)); + assert!(at(&dashed, 15) < 40, "a dash"); + // Hiding it draws the path again. + s.execute("effect.setParams", &json!({"index": 0, "visible": false})).unwrap(); + assert_eq!(picture(&s), solid); +} + +#[test] +fn a_path_effect_moves_the_bounds_the_object_is_measured_by() { + let (mut s, id) = stroked(json!([{"x": 50, "y": 50}, {"x": 150, "y": 50}]), false); + s.execute("effect.apply", &json!({"effect": "addon.path.extend", "params": {"startLength": 0, "endLength": 30}})).unwrap(); + let drawn = preview::bounds_of(&s.doc().unwrap().doc, &[id], true).unwrap(); + assert!((drawn.x1 - 180.0).abs() < 3.0, "{drawn:?}"); + let pic = picture(&s); + assert!(pic[(50 * 200 + 170) * 4] < 40, "and draws there"); +} + +#[test] +fn expand_appearance_writes_the_outline_the_effect_draws() { + for (effect, params) in effects() { + let (mut s, id) = wave(); + s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap(); + let n = node(&s, id); + let before = n.path_data().cloned().unwrap(); + let live = apply_geometry_bez(&n.appearance.effects, &before.to_bezpath(), before.bounds().unwrap(), &GeomContext::of(&n)); + let pic = picture(&s); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let expanded = node(&s, id); + assert!(expanded.appearance.effects.is_empty(), "{effect} {params}"); + let (out, want) = (outline(&expanded), live); + assert_eq!(out.elements().len(), want.elements().len(), "{effect} {params}"); + for (a, b) in out.elements().iter().zip(want.elements()) { + assert!(a.is_finite() && format!("{a:.4?}") == format!("{b:.4?}"), "{effect} {params}: {a:?} {b:?}"); + } + assert_eq!(differing(&pic, &picture(&s)), 0, "{effect} {params}"); + } +} + +#[test] +fn path_effects_round_trip_through_a_save_and_scale_their_distances() { + for (effect, params) in effects() { + let (mut s, id) = wave(); + s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap(); + let restored = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!(restored.node(id).unwrap().appearance.effects, node(&s, id).appearance.effects, "{effect} {params}"); + assert_eq!(picture_of(&restored), picture(&s), "{effect} {params}"); + } + let mut e = new_effect("addon.path.dashes", &json!({"dash1": 10})).unwrap(); + scale_effect(&mut e, 2.0); + assert_eq!((e.params["dash1"].as_f64(), e.params["gap1"].as_f64()), (Some(20.0), Some(12.0))); +} + +#[test] +fn undo_takes_a_path_effect_off_in_one_step() { + let (mut s, id) = wave(); + s.execute("effect.apply", &json!({"effect": "addon.path.reverse"})).unwrap(); + assert_eq!(node(&s, id).appearance.effects.len(), 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, id).appearance.effects.is_empty()); +} + +/// A file's effects skip the checks `effect.apply` makes: whatever they hold, the object draws and +/// expands. +#[test] +fn path_effects_with_junk_params_from_a_file_draw_and_expand() { + let junk = [ + json!(null), + json!("x"), + json!({"dash1": 1e308, "gap1": -1e308, "offset": "x", "alignCorners": 3}), + json!({"count": 1e308, "maxCount": 1e308, "distance": -1e308, "spacing": "distance", "target": []}), + json!({"startLength": 1e308, "endPercent": -1e308, "endShape": {}, "mode": 1, "ratio": "x", "handles": "shorter", "length": 1e308}), + json!({"tolerance": 1e308, "protectCorners": "no", "anchors": null, "startPercent": 1e308, "startShape": "arc"}), + ]; + let ids = effect_catalog().into_iter().map(|e| e.id).filter(|id| id.starts_with("addon.path.")); + let stack: Vec = + ids.flat_map(|id| junk.iter().map(move |params| Effect { id: id.into(), params: params.clone(), visible: true })).collect(); + let (mut s, id) = wave(); + s.edit("Junk", |d, _| { + if let Some(n) = d.node_mut(id) { + n.appearance.effects = stack; + } + Ok(()) + }) + .unwrap(); + let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false); + picture_of(&vectorcraft_format::load(&saved).unwrap()); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + assert!(node(&s, id).appearance.effects.is_empty()); +} + +#[test] +fn exports_write_the_dashes_as_paths() { + let (mut s, _) = wave(); + s.execute("effect.apply", &json!({"effect": "addon.path.dashes", "params": {"dash1": 10, "gap1": 10}})).unwrap(); + let v = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + let moves = svg.iter().filter(|c| **c == b'M').count(); + assert!(moves > 5, "the exported art holds the dashes: {moves}"); +} diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs new file mode 100644 index 0000000000..4c1ba7e2dd --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/shape.rs @@ -0,0 +1,137 @@ +//! The Parametric Shape Tool's commands (`addon.pathtools.shape.*`): draw a parametric shape, change +//! one's numbers, and turn plain rectangles, ellipses and regular polygons into them. A parametric +//! shape is an ordinary path whose numbers sit in one entry of its object data +//! (`vectorcraft_tools::addons::parametric_shape`), which SVG export leaves out. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_geom::{FillRule, PathData, Point}; +use vectorcraft_pathops::addons::pathtools::shapes::{ParametricShape, ShapeKind, recognise}; +use vectorcraft_tools::addons::parametric_shape::{CREATE, EDIT, KEY, apply, read, stored, to_json}; + +use super::super::super::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection}; +use crate::{EngineError, Result, Session}; + +/// The undo step's name and the command's label. +const CONVERT: &str = "Convert to Parametric Shape"; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.pathtools.shape.create", + "Parametric Shape", + [], + None, + "{center: [x, y], kind?: \"rectangle\"|\"ellipse\"|\"polygon\" (default)|\"star\"|\"ring\"|\"arrow\"|\"cross\"|\"heart\"|\"gear\"|\"bubble\" (a speech bubble), width?, height?: 0.01..16384 pt (100), rotation?: degrees clockwise (0: upright), count?: 3..1000 (a polygon's sides, a star's points, a gear's teeth), a?, b?: the kind's own values (star: inner radius 0.01..1 of the outer, 0.5; ring: hole 0.01..0.99 of the size, 0.5; arrow: head length and shaft width 0.05..0.95, 0.4 and 0.4; cross: bar offset −0.9..0.9 (0, − up) and arm thickness 0.05..0.95 (1/3); heart: notch depth and point roundness 0..1 (0.4 and 0); gear: tooth height 0.01..0.9 (0.2); bubble: tail height 0.05..0.9 (0.25) and tail tip −1..1 across (−0.4)), radius?: corner radius 0..16384 pt (0; no corner rounds past the middle of a side)} draw a parametric shape with the current paint, selected, as one undo step; it stays editable with addon.pathtools.shape.set until its anchors are edited (moving, turning or scaling it keeps it) → {id, shape}", + has_doc, + create + ), + cmd!( + "addon.pathtools.shape.set", + "Edit Parametric Shape", + [], + None, + "{id, kind?, center?, width?, height?, rotation?, count?, a?, b?, radius?} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with none, or the same ones, nothing changes → {id, shape (its numbers now)}", + has_doc, + set + ), + cmd!( + "addon.pathtools.shape.convert", + "Convert to Parametric Shape", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{ids?: [id…] (default: the selection)} make each plain closed path that is a rectangle, an ellipse or a polygon with equal sides and corners (stretched along its own axes at most) a parametric shape of the same outline, as one undo step → {ids (converted)}", + has_selection, + convert + ), + ] +} + +/// Give path node `n` the outline `path` of shape `s` and keep its numbers; a live shape goes. +fn shape_node(n: &mut Node, s: &ParametricShape, path: PathData) { + let entry = stored(s, &path); + if let NodeKind::Path { path: p, live, .. } = &mut n.kind { + *p = path; + *live = None; + } + n.edit_attrs(|a| match a.data.iter_mut().find(|(k, _)| k == KEY) { + Some(e) => e.1 = entry, + None => a.data.push((KEY.into(), entry)), + }); +} + +/// The outline of `s`, checked already. +fn outline(s: &ParametricShape, cmd: &str) -> Result { + s.path().ok_or_else(|| bad(cmd, "the shape's numbers are out of range")) +} + +fn create(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.shape.create"; + if p.get("center").is_none_or(Value::is_null) { + return Err(bad(C, "`center` must be [x, y]")); + } + let shape = apply(ParametricShape::new(ShapeKind::Polygon, Point::ZERO, 100.0, 100.0), p).map_err(|e| bad(C, e))?; + let path = outline(&shape, C)?; + let parent = s.doc()?.target_parent()?; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + // shortcut: always on top of the insertion layer, as Draw Normal; honour Draw Behind/Inside if asked. + let id = s.edit(CREATE, |d, sel| { + let id = d.alloc_id(); + let mut n = Node::new(id, NodeKind::Path { path: PathData::default(), rule: FillRule::NonZero, live: None, clipping: false, guide: false }); + shape_node(&mut n, &shape, path); + look.apply(d, &mut n); + d.insert(parent, usize::MAX, n)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0, "shape": to_json(&shape) })) +} + +fn set(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.shape.set"; + let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?; + let d = &s.doc()?.doc; + if !d.is_editable(id) { + return Err(bad(C, "the path is locked or hidden")); + } + let old = d.node(id).and_then(read).ok_or_else(|| bad(C, "the object is not an editable parametric shape"))?; + let shape = apply(old, p).map_err(|e| bad(C, e))?; + if shape != old { + let path = outline(&shape, C)?; + s.edit(EDIT, |d, sel| { + shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, path); + sel.anchors.remove(&id); + sel.segments.remove(&id); + Ok(()) + })?; + } + Ok(json!({ "id": id.0, "shape": to_json(&shape) })) +} + +fn convert(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.shape.convert"; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let mut found = vec![]; + for id in roots { + let Some(n) = d.node(id).filter(|n| d.is_editable(id) && read(n).is_none()) else { continue }; + if let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind + && let Some(shape) = recognise(path) + { + found.push((id, shape, outline(&shape, C)?)); + } + } + if found.is_empty() { + return Err(bad(C, "select plain rectangles, ellipses or regular polygons to convert")); + } + let ids: Vec = found.iter().map(|(id, ..)| id.0).collect(); + s.edit(CONVERT, |d, sel| { + for (id, shape, path) in found { + shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, path); + sel.anchors.remove(&id); + sel.segments.remove(&id); + } + Ok(()) + })?; + Ok(json!({ "ids": ids })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/shared_edge.rs b/crates/engine/src/cmd/addons/pathtools/shared_edge.rs new file mode 100644 index 0000000000..e5d61c47b0 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/shared_edge.rs @@ -0,0 +1,164 @@ +//! The Shared Edge Merge Tool's command and Keep Shared Points Together: with that option on, the +//! add-on's own commands that move an anchor (Slide Anchor Along Path, Extend Path, Set Anchor) take +//! the anchors coincident with it along. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{AnchorRef, Document, NodeId, NodeKind}; +use vectorcraft_geom::{PathData, Point, Vec2}; +use vectorcraft_pathops::addons::pathtools as pt; +use vectorcraft_tools::addons::shared_edge::{DIAMETER, DIAMETER_RANGE, ID}; + +use super::super::super::{CommandSpec, always, bad, checked_id, cmd, finite_numbers, has_doc, number_or, switch_or, text_param}; +use super::{edit_whole, set_path}; +use crate::{Result, Session}; + +#[cfg(test)] +mod tests; + +pub(super) fn specs() -> Vec { + vec![ + cmd!( + "addon.pathtools.mergeEdge", + "Merge Shared Edge", + [], + None, + "{a, b: two path ids (they needn't be selected), at: [x, y] (where), diameter?: pt 0.25..200 (20; how near `at` the edge is looked for), tolerance?: pt 0..3 (0.002; how near two anchors count as coincident), follow?: \"average\" (half way between the two)|\"a\"|\"b\" (keep that path's outline), ends?: bool (false: true makes an end even where the paths could merge)} where the paths touch at two coincident anchors, one each side of `at`, replace the stretches between them with one shared edge; stretches much longer one than the other (by over 10%) or leaving an end at over 120° aren't merged. Otherwise make an end there: two near anchors meet, and an anchor only one path has there is matched by a new one on the other. Each path stays closed or open; one undo step → {a, b, made: \"edge\"|\"end\"|\"nothing\" (merged already)}", + has_doc, + merge_edge + ), + cmd!( + "addon.pathtools.movePointsTogether", + "Keep Shared Points Together", + [], + None, + "{enabled?: bool (default: the opposite of now)} Keep Shared Points Together: whether anchors coincident (within the Shared Edge Merge Tool's `tolerance`) with one that Slide Anchor Along Path, Extend Path or Set Anchor moves move with it, on any editable path (the `together` option of tool `sharedEdge`, kept with the preferences; off by default) → {enabled}", + always, + move_points_together + ), + ] +} + +/// A path a merge may edit. +fn merge_path<'a>(d: &'a Document, id: NodeId, cmd: &str) -> Result<&'a PathData> { + if !d.is_editable(id) { + return Err(bad(cmd, "the path is locked or hidden")); + } + match d.node(id).map(|n| &n.kind) { + Some(NodeKind::Path { path, guide: false, .. }) => Ok(path), + _ => Err(bad(cmd, "`a` and `b` must be two different paths")), + } +} + +fn merge_edge(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.mergeEdge"; + let a = checked_id(s, p.get("a").unwrap_or(&Value::Null), C)?; + let b = checked_id(s, p.get("b").unwrap_or(&Value::Null), C)?; + if a == b { + return Err(bad(C, "`a` and `b` must be two different paths")); + } + let [x, y] = p.get("at").and_then(finite_numbers::<2>).ok_or_else(|| bad(C, "`at` must be [x, y]"))?; + let at = Point::new(x, y); + let diameter = number_or(p, "diameter", DIAMETER, C)?; + if !(DIAMETER_RANGE.0..=DIAMETER_RANGE.1).contains(&diameter) { + return Err(bad(C, "`diameter` must be from 0.25 to 200 pt")); + } + let tolerance = number_or(p, "tolerance", pt::COINCIDENCE, C)?; + if !(0.0..=pt::MAX_COINCIDENCE).contains(&tolerance) { + return Err(bad(C, "`tolerance` must be from 0 to 3 pt")); + } + let follow = match text_param(p, "follow", C)? { + None => pt::Follow::Average, + Some(f) => pt::Follow::parse(f).ok_or_else(|| bad(C, "`follow` must be \"average\", \"a\" or \"b\""))?, + }; + let ends = switch_or(p, "ends", false, C)?; + let d = &s.doc()?.doc; + let (pa, pb) = (merge_path(d, a, C)?, merge_path(d, b, C)?); + let radius = diameter / 2.0; + let edge = if ends { None } else { pt::stretches_at(pa, pb, at, radius, tolerance) }; + let plan = edge.or_else(|| pt::ends_at(pa, pb, at, radius)).ok_or_else(|| bad(C, "the paths have nothing to merge there"))?; + let (na, nb) = pt::apply_merge(pa, pb, &plan, follow).ok_or_else(|| bad(C, "the paths have nothing to merge there"))?; + let changed: Vec<(NodeId, PathData)> = + [(a, pa, na), (b, pb, nb)].into_iter().filter(|(_, old, new)| *old != new).map(|(id, _, new)| (id, new)).collect(); + let made = match plan { + _ if changed.is_empty() => "nothing", + pt::MergePlan::Edge { .. } => "edge", + pt::MergePlan::Ends { .. } => "end", + }; + edit_whole(s, "Merge Shared Edge", changed)?; + Ok(json!({ "a": a.0, "b": b.0, "made": made })) +} + +fn move_points_together(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pathtools.movePointsTogether"; + let now = s.tool_options_of(ID)["together"].as_bool().unwrap_or(false); + let enabled = switch_or(p, "enabled", !now, C)?; + s.set_tool_options(Some(ID), &Map::from_iter([("together".to_string(), json!(enabled))])); + Ok(json!({ "enabled": enabled })) +} + +/// Anchors to move along with others: each with how far. +pub(super) type SharedPoints = Vec<(NodeId, AnchorRef, Vec2)>; + +/// With Keep Shared Points Together on, the anchors of editable paths coincident with an anchor +/// that `changed` (paths in their new form) moves, and not moving themselves. Subpaths whose +/// anchors `changed` adds or removes move none: their anchors stay put. +pub(super) fn shared_points<'a>(s: &Session, changed: impl IntoIterator) -> Result { + let options = s.tool_options_of(ID); + if options["together"].as_bool() != Some(true) { + return Ok(vec![]); + } + let tol = options["tolerance"].as_f64().unwrap_or(pt::COINCIDENCE); + let d = &s.doc()?.doc; + let mut moved: BTreeSet<(NodeId, AnchorRef)> = BTreeSet::new(); + let mut from: Vec<(Point, Vec2)> = vec![]; + for (id, new) in changed { + let Some(old) = d.node(id).and_then(|n| n.path_data()) else { continue }; + for (si, (o, n)) in old.subpaths.iter().zip(&new.subpaths).enumerate().filter(|(_, (o, n))| o.anchors.len() == n.anchors.len()) { + for (ai, (x, y)) in o.anchors.iter().zip(&n.anchors).enumerate().filter(|(_, (x, y))| x.p != y.p) { + moved.insert((id, (si, ai))); + from.push((x.p, y.p - x.p)); + } + } + } + let mut out = vec![]; + if from.is_empty() { + return Ok(out); + } + from.sort_by(|a, b| a.0.x.total_cmp(&b.0.x)); + let editable = d.editable(); + d.walk(|n| { + let NodeKind::Path { path, guide: false, .. } = &n.kind else { return }; + if !editable(n.id) { + return; + } + for (si, ai, a) in path.anchors() { + let start = from.partition_point(|(p, _)| p.x < a.p.x - tol); + let mut near = from.iter().skip(start).take_while(|(p, _)| p.x <= a.p.x + tol); + if let Some((_, by)) = near.find(|(p, _)| p.distance(a.p) <= tol) + && !moved.contains(&(n.id, (si, ai))) + { + out.push((n.id, (si, ai), *by)); + } + } + }); + Ok(out) +} + +/// Move the anchors [`shared_points`] found; what they are on stops being a live shape. +pub(super) fn move_shared(d: &mut Document, shared: SharedPoints) { + let mut by_path: BTreeMap> = BTreeMap::new(); + for (id, at, by) in shared { + by_path.entry(id).or_default().push((at, by)); + } + for (id, anchors) in by_path { + let Some(mut np) = d.node(id).and_then(|n| n.path_data()).cloned() else { continue }; + for ((si, ai), by) in anchors { + if let Some(a) = np.anchor_mut(si, ai) { + a.translate(by); + } + } + set_path(d, id, np); + } +} diff --git a/crates/engine/src/cmd/addons/pathtools/shared_edge/tests.rs b/crates/engine/src/cmd/addons/pathtools/shared_edge/tests.rs new file mode 100644 index 0000000000..3ffe2fea7c --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/shared_edge/tests.rs @@ -0,0 +1,204 @@ +//! The Shared Edge Merge Tool's command and Keep Shared Points Together: one undo step each, bad +//! params refused, the tool's click through the session, and only the add-on's commands affected. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{PathData, Point}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + +use crate::{Session, ViewInfo}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn line(s: &mut Session, pts: &[(f64, f64)], closed: bool) -> NodeId { + let anchors: Vec = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()["id"].as_u64().unwrap()) +} + +fn path(s: &Session, id: NodeId) -> PathData { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn points(s: &Session, id: NodeId) -> Vec { + path(s, id).anchors().map(|(_, _, a)| a.p).collect() +} + +/// Two closed shapes with a bent edge each between (100, 100) and (200, 100). +fn shapes(s: &mut Session) -> (NodeId, NodeId) { + let a = line(s, &[(100.0, 100.0), (150.0, 104.0), (200.0, 100.0), (200.0, 50.0), (100.0, 50.0)], true); + let b = line(s, &[(200.0, 100.0), (150.0, 96.0), (100.0, 100.0), (100.0, 150.0), (200.0, 150.0)], true); + (a, b) +} + +#[test] +fn merge_edge_replaces_both_stretches_as_one_undo_step() { + let mut s = session(); + let (a, b) = shapes(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let (pa, pb) = (path(&s, a), path(&s, b)); + let n = steps(&s); + let r = s.execute("addon.pathtools.mergeEdge", &json!({"a": a.0, "b": b.0, "at": [125, 100]})).unwrap(); + assert_eq!(r, json!({"a": a.0, "b": b.0, "made": "edge"})); + assert_eq!(steps(&s), n + 1); + assert!(path(&s, a).subpaths[0].closed && path(&s, b).subpaths[0].closed); + assert_eq!(points(&s, a)[..3], [Point::new(100.0, 100.0), Point::new(150.0, 100.0), Point::new(200.0, 100.0)]); + assert_eq!(points(&s, b)[..3], [Point::new(200.0, 100.0), Point::new(150.0, 100.0), Point::new(100.0, 100.0)]); + // Nothing left to do: no step. + let r = s.execute("addon.pathtools.mergeEdge", &json!({"a": a.0, "b": b.0, "at": [125, 100]})).unwrap(); + assert_eq!(r["made"], json!("nothing")); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((path(&s, a), path(&s, b)), (pa, pb)); +} + +#[test] +fn merge_edge_follows_the_path_asked_and_makes_ends() { + let mut s = session(); + let (a, b) = shapes(&mut s); + let pa = path(&s, a); + s.execute("addon.pathtools.mergeEdge", &json!({"a": a.0, "b": b.0, "at": [125, 100], "follow": "a"})).unwrap(); + assert_eq!(path(&s, a), pa); + assert_eq!(points(&s, b)[1], Point::new(150.0, 104.0)); + // Ends asked for: the near anchors of two lines meet, one undo step. + let c = line(&mut s, &[(10.0, 200.0), (50.0, 200.0)], false); + let d = line(&mut s, &[(54.0, 200.0), (90.0, 240.0)], false); + let n = steps(&s); + let r = s.execute("addon.pathtools.mergeEdge", &json!({"a": c.0, "b": d.0, "at": [52, 200], "ends": true})).unwrap(); + assert_eq!((r["made"].clone(), steps(&s)), (json!("end"), n + 1)); + assert_eq!((points(&s, c)[1], points(&s, d)[0]), (Point::new(52.0, 200.0), Point::new(52.0, 200.0))); +} + +#[test] +fn merge_edge_refuses_bad_params_and_locked_paths() { + let mut s = session(); + let (a, b) = shapes(&mut s); + let (i, j) = (a.0, b.0); + let n = steps(&s); + for p in [ + json!({}), + json!({"a": i, "b": i, "at": [125, 100]}), + json!({"a": i, "b": j}), + json!({"a": i, "b": j, "at": [1]}), + json!({"a": i, "b": j, "at": [1, "x"]}), + json!({"a": i, "b": j, "at": [125, 100], "diameter": 0.1}), + json!({"a": i, "b": j, "at": [125, 100], "diameter": 201}), + json!({"a": i, "b": j, "at": [125, 100], "tolerance": 3.5}), + json!({"a": i, "b": j, "at": [125, 100], "tolerance": -1}), + json!({"a": i, "b": j, "at": [125, 100], "follow": "up"}), + json!({"a": i, "b": j, "at": [125, 100], "ends": 1}), + json!({"a": i, "b": u64::MAX, "at": [125, 100]}), + json!({"a": i, "b": j, "at": [390, 290]}), + ] { + assert!(s.execute("addon.pathtools.mergeEdge", &p).is_err(), "{p}"); + } + assert_eq!(steps(&s), n); + s.execute("select.set", &json!({"ids": [i]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + assert!(s.execute("addon.pathtools.mergeEdge", &json!({"a": i, "b": j, "at": [125, 100]})).is_err()); +} + +#[test] +fn the_tool_merges_unselected_paths_on_a_click_with_shift_following_the_upper() { + let mut s = session(); + let (lower, upper) = shapes(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("sharedEdge", view).unwrap(); + let keep = path(&s, upper); + let n = steps(&s); + let shifted = |kind| { + let mut e = PointerEvent::new(kind, 125.0, 100.0); + e.mods = Mods { shift: true, ..Mods::default() }; + e + }; + s.pointer(&shifted(PointerKind::Down), view).unwrap(); + s.pointer(&shifted(PointerKind::Up), view).unwrap(); + assert_eq!(steps(&s), n + 1); + assert_eq!(path(&s, upper), keep); + assert_eq!(points(&s, lower)[1], Point::new(150.0, 96.0)); +} + +#[test] +fn keep_shared_points_together_is_off_by_default_and_a_preference_of_the_tool() { + let mut s = session(); + assert_eq!(s.tool_options_of("sharedEdge")["together"], json!(false)); + assert_eq!(s.execute("addon.pathtools.movePointsTogether", &json!({"enabled": true})).unwrap(), json!({"enabled": true})); + assert_eq!(s.tool_options_of("sharedEdge")["together"], json!(true), "kept with another tool active"); + assert_eq!(s.execute("addon.pathtools.movePointsTogether", &json!({})).unwrap(), json!({"enabled": false})); + assert!(s.execute("addon.pathtools.movePointsTogether", &json!({"enabled": 1})).is_err()); +} + +#[test] +fn a_slide_takes_coincident_anchors_along_in_one_step_when_the_option_is_on() { + let mut s = session(); + let a = line(&mut s, &[(100.0, 100.0), (200.0, 100.0), (300.0, 100.0)], false); + let b = line(&mut s, &[(200.0, 100.0), (200.0, 200.0)], false); + let far = line(&mut s, &[(200.0, 101.0), (250.0, 200.0)], false); + let slide = json!({"id": a.0, "anchor": 1, "t": 0.5}); + let n = steps(&s); + s.execute("addon.pathtools.slideAnchor", &slide).unwrap(); + assert_eq!(points(&s, b)[0], Point::new(200.0, 100.0), "off: it stays"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.pathtools.movePointsTogether", &json!({"enabled": true})).unwrap(); + s.execute("addon.pathtools.slideAnchor", &slide).unwrap(); + assert_eq!(steps(&s), n + 1); + let moved = points(&s, a)[1]; + assert!(moved.distance(Point::new(250.0, 100.0)) < 1e-6, "{moved:?}"); + assert!(points(&s, b)[0].distance(moved) < 1e-9); + assert_eq!(points(&s, b)[1], Point::new(200.0, 200.0)); + assert_eq!(points(&s, far)[0], Point::new(200.0, 101.0), "not coincident"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(points(&s, b)[0], Point::new(200.0, 100.0)); + // A wider coincidence reaches it, and a locked path stays. + s.set_tool_options(Some("sharedEdge"), &serde_json::Map::from_iter([("tolerance".to_string(), json!(2))])); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("addon.pathtools.slideAnchor", &slide).unwrap(); + assert!(points(&s, far)[0].distance(Point::new(250.0, 101.0)) < 1e-6); + assert_eq!(points(&s, b)[0], Point::new(200.0, 100.0)); +} + +#[test] +fn set_anchor_and_extend_take_coincident_anchors_along_but_built_in_moves_do_not() { + let mut s = session(); + let a = line(&mut s, &[(100.0, 100.0), (200.0, 100.0)], false); + let b = line(&mut s, &[(200.0, 100.0), (200.0, 200.0)], false); + s.execute("addon.pathtools.movePointsTogether", &json!({"enabled": true})).unwrap(); + // Set Anchor on one selected anchor. + s.select(|_, sel| { + sel.set([a]); + sel.anchors.insert(a, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + let n = steps(&s); + s.execute("addon.pathtools.setAnchor", &json!({"x": 220, "y": 90})).unwrap(); + assert_eq!(steps(&s), n + 1); + assert_eq!(points(&s, b), [Point::new(220.0, 90.0), Point::new(200.0, 200.0)]); + // An edit that moves no anchor moves none. + s.execute("addon.pathtools.corner", &json!({})).unwrap(); + assert_eq!(points(&s, b)[0], Point::new(220.0, 90.0)); + // Extend Path moves an end only when it adds no anchor. + s.execute("addon.pathtools.extend", &json!({"id": a.0, "end": "end", "length": 10, "mode": "bezier"})).unwrap(); + let end = points(&s, a)[1]; + assert!(points(&s, b)[0].distance(end) < 1e-9); + let end = points(&s, b)[0]; + s.execute("addon.pathtools.extend", &json!({"id": a.0, "end": "end", "length": 10})).unwrap(); + assert_eq!(points(&s, a).len(), 3); + assert_eq!(points(&s, b)[0], end, "the end it left stays with what shares it"); + // The app's own moves are untouched by the option. + s.select(|_, sel| { + sel.set([a]); + sel.anchors.insert(a, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + s.execute("object.move", &json!({"dx": 5, "dy": 5})).unwrap(); + assert_eq!(points(&s, b)[0], end); +} diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs new file mode 100644 index 0000000000..e31aadf56e --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -0,0 +1,1037 @@ +//! Path Precision Tools' commands: each one undo step, bad params refused, and the tools' gestures +//! through the session. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveCorners, LiveShape, NodeId}; +use vectorcraft_geom::shapes::CornerKind; +use vectorcraft_geom::{AnchorKind, PathData, Point}; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use crate::{Session, ViewInfo}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn line(s: &mut Session, pts: &[(f64, f64)], closed: bool) -> NodeId { + let anchors: Vec = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap()) +} + +/// A circle of 16 anchors about (100, 100), radius 50, selected. +fn circle(s: &mut Session) -> NodeId { + let e = id_of(&s.execute("shape.ellipse", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + e +} + +fn path(s: &Session, id: NodeId) -> PathData { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); +} + +/// Direct-select anchors `anchors` (of subpath 0) of `id`. +fn select_anchors(s: &mut Session, id: NodeId, anchors: &[usize]) { + s.select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, anchors.iter().map(|a| (0, *a)).collect::>()); + }) + .unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// Each of `bad` is refused and leaves the document as it was. +fn refuses(s: &mut Session, cmd: &str, bad: &[Value]) { + let (before, n) = (s.doc().unwrap().doc.clone(), steps(s)); + for p in bad { + assert!(s.execute(cmd, p).is_err(), "{cmd} {p}"); + } + assert_eq!(steps(s), n, "{cmd}"); + assert!(*s.doc().unwrap().doc == *before, "{cmd} changed the document"); +} + +#[test] +fn the_brush_removes_anchors_under_it_keeping_the_shape() { + let mut s = session(); + let e = circle(&mut s); + assert_eq!(path(&s, e).anchor_count(), 16); + let bounds = path(&s, e).bounds().unwrap(); + let n = steps(&s); + let r = s.execute("addon.pathtools.erase", &json!({"points": [[150, 40], [150, 160]], "diameter": 60, "tolerance": 100})).unwrap(); + let left = path(&s, e).anchor_count(); + assert!(left < 16 && left > 8, "{left}"); + assert_eq!(r["removed"], json!(16 - left)); + assert_eq!(steps(&s), n + 1, "one undo step"); + let b = path(&s, e).bounds().unwrap(); + assert!((b.x1 - bounds.x1).abs() < 2.5 && (b.y0 - bounds.y0).abs() < 0.01, "{b:?} vs {bounds:?}"); + // The anchors away from the brush stay: those on the left of the circle. + assert!(path(&s, e).anchors().filter(|(_, _, a)| a.p.x < 100.0).count() >= 7); + // A plain delete takes every anchor under it, whatever the shape. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.pathtools.erase", &json!({"points": [[150, 40], [150, 160]], "diameter": 60, "plain": true})).unwrap(); + assert!(path(&s, e).anchors().all(|(_, _, a)| a.p.x < 121.0)); + // Nothing under the brush: no step. + let n = steps(&s); + s.execute("addon.pathtools.erase", &json!({"points": [[390, 290]], "diameter": 5})).unwrap(); + assert_eq!(steps(&s), n); + refuses( + &mut s, + "addon.pathtools.erase", + &[ + json!({}), + json!({"points": "x"}), + json!({"points": [[1, "y"]]}), + json!({"points": [[100, 100]], "diameter": 0}), + json!({"points": [[100, 100]], "diameter": 3000}), + json!({"points": [[100, 100]], "tolerance": 0}), + json!({"points": [[100, 100]], "plain": "yes"}), + ], + ); +} + +#[test] +fn the_brush_tool_is_one_undo_step_per_stroke() { + let mut s = session(); + let e = circle(&mut s); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("anchorEraserBrush", view).unwrap(); + assert_eq!(s.tool_id(), "anchorEraserBrush"); + s.set_tool_option("size", &json!(60)); + s.set_tool_option("tolerance", &json!(100)); + let n = steps(&s); + for (k, y) in + [(PointerKind::Down, 40.0), (PointerKind::Drag, 80.0), (PointerKind::Drag, 120.0), (PointerKind::Drag, 160.0), (PointerKind::Up, 160.0)] + { + s.pointer(&PointerEvent::new(k, 150.0, y), view).unwrap(); + } + assert_eq!(steps(&s), n + 1); + assert!(path(&s, e).anchor_count() < 16); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, e).anchor_count(), 16); +} + +#[test] +fn extend_lengthens_and_shortens_an_end() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 100.0), (100.0, 100.0)], false); + let n = steps(&s); + s.execute("addon.pathtools.extend", &json!({"id": l.0, "end": "end", "length": 50})).unwrap(); + assert_eq!(path(&s, l).subpaths[0].anchors.last().unwrap().p, Point::new(150.0, 100.0)); + assert_eq!(steps(&s), n + 1); + s.execute("addon.pathtools.extend", &json!({"id": l.0, "end": "start", "to": [-30, 120], "mode": "bezier"})).unwrap(); + assert!((path(&s, l).subpaths[0].anchors[0].p.x + 30.0).abs() < 1e-6); + let r = s.execute("addon.pathtools.extend", &json!({"id": l.0, "end": "end", "length": -60})).unwrap(); + assert_eq!(r["length"], json!(-60.0)); + assert!((path(&s, l).length() - 120.0).abs() < 1e-3, "{}", path(&s, l).length()); + assert_eq!(steps(&s), n + 3); + let sq = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + refuses( + &mut s, + "addon.pathtools.extend", + &[ + json!({"id": l.0, "end": "end"}), + json!({"id": l.0, "end": "middle", "length": 5}), + json!({"id": l.0, "end": "end", "length": 5, "to": [1, 1]}), + json!({"id": l.0, "end": "end", "length": 5, "mode": "spiral"}), + json!({"id": l.0, "end": "end", "length": -1000}), + json!({"id": l.0, "end": "end", "length": 1e9}), + json!({"id": l.0, "end": "end", "to": [1]}), + json!({"id": l.0, "subpath": 3, "end": "end", "length": 5}), + json!({"id": sq.0, "end": "end", "length": 5}), + json!({"id": 99999, "end": "end", "length": 5}), + ], + ); +} + +#[test] +fn inspect_reads_the_path_under_a_point() { + let mut s = session(); + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap()); + let v = s.execute("addon.pathtools.inspect", &json!({"id": r.0, "x": 99, "y": 1})).unwrap(); + assert_eq!((v["closed"].clone(), v["anchors"].clone()), (json!(true), json!(4))); + assert!((v["length"].as_f64().unwrap() - 300.0).abs() < 1e-6 && (v["area"].as_f64().unwrap() - 5000.0).abs() < 1e-6); + assert!((v["anchor"]["angle"].as_f64().unwrap() - 90.0).abs() < 1e-9); + assert!(v["radius"].is_null()); + assert!(s.execute("addon.pathtools.inspect", &json!({"id": r.0, "x": 1})).is_err()); + assert!(s.execute("addon.pathtools.inspect", &json!({"id": r.0, "x": 1, "y": 1, "tolerance": -1})).is_err()); +} + +#[test] +fn smooth_corner_and_equalize_edit_the_selected_anchors_in_one_step_each() { + let mut s = session(); + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()); + select(&mut s, &[r]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.smooth", &json!({})).unwrap()["anchors"], json!(4)); + assert!(path(&s, r).anchors().all(|(_, _, a)| a.kind == AnchorKind::Smooth && (a.h_out - a.p).hypot() > 39.0)); + assert_eq!(steps(&s), n + 1); + // Only the direct-selected anchor. + select_anchors(&mut s, r, &[0]); + s.execute("addon.pathtools.corner", &json!({})).unwrap(); + let p = path(&s, r); + assert!(!p.subpaths[0].anchors[0].has_out() && p.subpaths[0].anchors[1].has_out()); + assert_eq!(steps(&s), n + 2); + // Equalise: one handle made to match the other. + select_anchors(&mut s, r, &[1]); + s.execute("addon.pathtools.setAnchor", &json!({"outLength": 10})).unwrap(); + let a = path(&s, r).subpaths[0].anchors[1]; + assert!(((a.h_out - a.p).hypot() - 10.0).abs() < 1e-9 && (a.h_in - a.p).hypot() > 39.0); + s.execute("addon.pathtools.equalize", &json!({})).unwrap(); + let a = path(&s, r).subpaths[0].anchors[1]; + assert!(((a.h_out - a.p).hypot() - (a.h_in - a.p).hypot()).abs() < 1e-9); + // A selection with nothing to change makes no step. + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.equalize", &json!({})).unwrap()["anchors"], json!(0)); + assert_eq!(steps(&s), n); + refuses(&mut s, "addon.pathtools.smooth", &[json!({"ratio": 0.9}), json!({"ratio": "x"})]); + refuses(&mut s, "addon.pathtools.corner", &[json!({"retract": 1})]); +} + +#[test] +fn set_anchor_moves_anchors_and_sets_handles() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (50.0, 0.0), (100.0, 0.0)], false); + select_anchors(&mut s, l, &[1]); + let n = steps(&s); + s.execute("addon.pathtools.setAnchor", &json!({"x": 60, "y": 20, "outLength": 30, "outAngle": 90})).unwrap(); + let a = path(&s, l).subpaths[0].anchors[1]; + assert_eq!(a.p, Point::new(60.0, 20.0)); + assert!(a.h_out.distance(Point::new(60.0, -10.0)) < 1e-9, "{a:?}"); + assert_eq!(steps(&s), n + 1); + refuses(&mut s, "addon.pathtools.setAnchor", &[json!({}), json!({"x": "1"}), json!({"inLength": -2}), json!({"y": f64::MAX})]); +} + +#[test] +fn remove_keep_shape_takes_the_direct_selected_anchors() { + let mut s = session(); + let e = circle(&mut s); + // Selected whole: nothing to say which anchors go. + refuses(&mut s, "addon.pathtools.removeKeepShape", &[json!({})]); + select_anchors(&mut s, e, &[1, 5]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.removeKeepShape", &json!({})).unwrap()["removed"], json!(2)); + assert_eq!(path(&s, e).anchor_count(), 14); + assert_eq!(steps(&s), n + 1); +} + +#[test] +fn add_points_splits_selected_segments_evenly() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false); + select(&mut s, &[l]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.addPoints", &json!({"count": 3})).unwrap()["added"], json!(3)); + let xs: Vec = path(&s, l).anchors().map(|(_, _, a)| a.p.x).collect(); + assert!(xs.iter().zip([0.0, 25.0, 50.0, 75.0, 100.0]).all(|(x, w)| (x - w).abs() < 1e-3), "{xs:?}"); + assert_eq!(steps(&s), n + 1); + refuses(&mut s, "addon.pathtools.addPoints", &[json!({"count": 0}), json!({"count": 101}), json!({"count": 1.5})]); + // An anchor alone selects no segment. + select_anchors(&mut s, l, &[1]); + refuses(&mut s, "addon.pathtools.addPoints", &[json!({})]); +} + +#[test] +fn close_joins_open_ends() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0), (50.0, 80.0)], false); + select(&mut s, &[l]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.close", &json!({"mode": "smooth"})).unwrap()["closed"], json!(1)); + assert!(path(&s, l).subpaths[0].closed); + assert_eq!(steps(&s), n + 1); + refuses(&mut s, "addon.pathtools.close", &[json!({}), json!({"mode": "round"})]); +} + +#[test] +fn crossings_add_anchors_or_cut_in_one_step() { + let mut s = session(); + let a = line(&mut s, &[(0.0, 0.0), (100.0, 100.0)], false); + let b = line(&mut s, &[(0.0, 100.0), (100.0, 0.0)], false); + select(&mut s, &[a, b]); + let n = steps(&s); + assert_eq!(s.execute("addon.pathtools.crossings", &json!({})).unwrap()["crossings"], json!(2)); + assert_eq!((path(&s, a).anchor_count(), path(&s, b).anchor_count()), (3, 3)); + assert!(path(&s, a).subpaths[0].anchors[1].p.distance(Point::new(50.0, 50.0)) < 1e-6); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute("addon.pathtools.crossings", &json!({"cut": true})).unwrap(); + assert_eq!(r["ids"].as_array().unwrap().len(), 4, "{r}"); + assert_eq!(steps(&s), n + 1); + refuses(&mut s, "addon.pathtools.crossings", &[json!({"cut": "yes"}), json!({"ids": [123456]})]); +} + +// ---------- Parametric Shape Tool ---------- + +/// The parametric shape object `id` is now, as the tool reads it. +fn shape_of(s: &Session, id: NodeId) -> Option { + vectorcraft_tools::addons::parametric_shape::read(s.doc().unwrap().doc.node(id).unwrap()) +} + +fn star(s: &mut Session) -> NodeId { + let r = s.execute("addon.pathtools.shape.create", &json!({"kind": "star", "center": [200, 150], "width": 100, "height": 100})).unwrap(); + id_of(&r) +} + +#[test] +fn create_draws_a_selected_parametric_shape_in_one_step() { + let mut s = session(); + let n = steps(&s); + let r = s.execute("addon.pathtools.shape.create", &json!({"kind": "gear", "center": [200, 150], "count": 10, "a": 0.3, "radius": 2})).unwrap(); + let id = id_of(&r); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!((r["shape"]["kind"].clone(), r["shape"]["count"].clone(), r["shape"]["width"].clone()), (json!("gear"), json!(10), json!(100.0))); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + let g = shape_of(&s, id).unwrap(); + assert_eq!((g.count, g.a, g.radius), (10, 0.3, 2.0)); + assert!(path(&s, id).anchor_count() > 40, "40 tooth corners, rounded"); + // Every kind, with its defaults. + for kind in ["rectangle", "ellipse", "polygon", "star", "ring", "arrow", "cross", "heart", "gear", "bubble"] { + let id = id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": kind, "center": [50, 50]})).unwrap()); + assert_eq!(shape_of(&s, id).map(|s| s.kind.id()), Some(kind)); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 10); +} + +#[test] +fn set_changes_the_numbers_in_one_step_and_nothing_without_a_change() { + let mut s = session(); + let id = star(&mut s); + assert_eq!(path(&s, id).anchor_count(), 10); + let n = steps(&s); + let r = s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "count": 8, "a": 0.3, "rotation": 15})).unwrap(); + assert_eq!((r["shape"]["count"].clone(), r["shape"]["rotation"].clone()), (json!(8), json!(15.0))); + assert_eq!(path(&s, id).anchor_count(), 16); + assert_eq!(steps(&s), n + 1); + // The same numbers again, or none: no step. + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "count": 8})).unwrap(); + s.execute("addon.pathtools.shape.set", &json!({"id": id.0})).unwrap(); + assert_eq!(steps(&s), n + 1); + // Another kind takes its own defaults. + let r = s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "kind": "arrow"})).unwrap(); + assert_eq!((r["shape"]["a"].clone(), r["shape"]["rotation"].clone()), (json!(0.4), json!(15.0))); + assert_eq!(path(&s, id).anchor_count(), 7); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id).anchor_count(), 16); +} + +#[test] +fn bad_shape_params_are_refused() { + let mut s = session(); + let id = star(&mut s); + let rect = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()); + let c = json!([10, 10]); + refuses( + &mut s, + "addon.pathtools.shape.create", + &[ + json!({}), + json!({"center": null}), + json!({"center": [1]}), + json!({"center": "here"}), + json!({"center": [1e300, 0]}), + json!({"center": c, "kind": "cloud"}), + json!({"center": c, "kind": 3}), + json!({"center": c, "count": 2}), + json!({"center": c, "count": 1001}), + json!({"center": c, "count": 4.5}), + json!({"center": c, "width": 0}), + json!({"center": c, "height": 16385}), + json!({"center": c, "width": "40"}), + json!({"center": c, "kind": "star", "a": 2}), + json!({"center": c, "kind": "bubble", "b": -1.5}), + json!({"center": c, "radius": -1}), + json!({"center": c, "rotation": "up"}), + ], + ); + refuses( + &mut s, + "addon.pathtools.shape.set", + &[json!({}), json!({"id": rect.0, "count": 6}), json!({"id": 999_999}), json!({"id": id.0, "count": 0}), json!({"id": id.0, "width": -5})], + ); + s.execute("object.setProps", &json!({"ids": [id.0], "locked": true})).unwrap(); + refuses(&mut s, "addon.pathtools.shape.set", &[json!({"id": id.0, "count": 6})]); +} + +#[test] +fn an_anchor_edit_makes_it_a_plain_path_and_transforms_keep_it_editable() { + let mut s = session(); + let id = star(&mut s); + // Moved, turned and scaled with the ordinary commands: still the shape, at its new place. + s.execute("object.move", &json!({"dx": 20, "dy": -10})).unwrap(); + assert!(shape_of(&s, id).is_some_and(|s| s.center.distance(Point::new(220.0, 140.0)) < 1e-6)); + s.execute("object.rotate", &json!({"angle": 30, "origin": [220, 140]})).unwrap(); + let r = shape_of(&s, id).unwrap(); + assert!((r.rotation + 30.0).abs() < 1e-6, "30° counter-clockwise is −30 here: {r:?}"); + s.execute("object.scale", &json!({"sx": 200, "origin": [220, 140]})).unwrap(); + let r = shape_of(&s, id).unwrap(); + assert!((r.width - 200.0).abs() < 1e-6 && r.center.distance(Point::new(220.0, 140.0)) < 1e-6, "{r:?}"); + let n = steps(&s); + s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "count": 6})).unwrap(); + assert_eq!((path(&s, id).anchor_count(), steps(&s)), (12, n + 1)); + assert!((shape_of(&s, id).unwrap().rotation + 30.0).abs() < 1e-6, "the turn stays"); + // Stretched across its own axes (it is turned): skewed, so no longer. + s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140]})).unwrap(); + assert_eq!(shape_of(&s, id), None); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(shape_of(&s, id).is_some(), "undo brings it back"); + // An anchor moved by hand: a plain path, which `set` refuses. + select_anchors(&mut s, id, &[2]); + s.execute("addon.pathtools.setAnchor", &json!({"x": 0})).unwrap(); + assert_eq!(shape_of(&s, id), None); + refuses(&mut s, "addon.pathtools.shape.set", &[json!({"id": id.0, "count": 7})]); +} + +#[test] +fn convert_makes_plain_shapes_parametric_in_one_step() { + let mut s = session(); + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 100, "height": 50})).unwrap()); + let p = id_of(&s.execute("shape.polygon", &json!({"cx": 200, "cy": 150, "radius": 40, "sides": 7})).unwrap()); + let st = id_of(&s.execute("shape.star", &json!({"cx": 300, "cy": 150, "radius1": 40, "radius2": 15})).unwrap()); + select(&mut s, &[r, p, st]); + let n = steps(&s); + let out = s.execute("addon.pathtools.shape.convert", &json!({})).unwrap(); + assert_eq!(out["ids"], json!([r.0, p.0])); + assert_eq!(steps(&s), n + 1); + assert_eq!(shape_of(&s, r).map(|s| s.kind.id()), Some("rectangle")); + assert_eq!(shape_of(&s, p).map(|s| (s.kind.id(), s.count)), Some(("polygon", 7))); + assert_eq!(shape_of(&s, st), None); + assert_eq!(path(&s, r).bounds().map(|b| b.center()), Some(Point::new(60.0, 45.0))); + // Nothing left to convert. + select(&mut s, &[r, st]); + refuses(&mut s, "addon.pathtools.shape.convert", &[json!({}), json!({"ids": [st.0]}), json!({"ids": [123456]})]); +} + +#[test] +fn the_shape_data_stays_out_of_svg_export() { + let mut s = session(); + let id = star(&mut s); + s.execute("object.setProps", &json!({"ids": [id.0], "data": {"pivot": "1,2"}})).unwrap(); + let key = vectorcraft_tools::addons::parametric_shape::KEY; + let node = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(node.extras().attrs.as_deref().is_some_and(|a| a.data.iter().any(|(k, _)| k == key)), "kept with the object"); + assert!(shape_of(&s, id).is_some(), "setting other data keeps it a shape"); + let svg = vectorcraft_svg::export(&s.doc().unwrap().doc, &Default::default()); + assert!(svg.contains("data-pivot=\"1,2\""), "the object's own data still goes out: {svg}"); + assert!(!svg.contains(key) && !svg.contains("fp"") && !svg.contains("\"fp\""), "{svg}"); +} + +#[test] +fn the_tool_draws_one_step_per_drag_and_arrows_change_the_count() { + let mut s = session(); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("parametricShape", view).unwrap(); + s.set_tool_option("kind", &json!("star")); + let n = steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 150.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 100.0), view).unwrap(); + s.tool_key(vectorcraft_tools::ToolKey::Up, vectorcraft_tools::Mods::default(), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 90.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 90.0), view).unwrap(); + assert_eq!(steps(&s), n + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + let shape = shape_of(&s, id).unwrap(); + assert_eq!((shape.kind.id(), shape.count, shape.height, shape.rotation), ("star", 6, 120.0, 0.0)); + // Its size handle (lower right of its box) drags into one more step. + let corner = shape.frame() * Point::new(shape.width / 2.0, shape.height / 2.0); + for (k, x) in [(PointerKind::Down, corner.x), (PointerKind::Drag, corner.x + 30.0), (PointerKind::Up, corner.x + 30.0)] { + s.pointer(&PointerEvent::new(k, x, corner.y), view).unwrap(); + } + assert_eq!(steps(&s), n + 2); + assert!((shape_of(&s, id).unwrap().width - 180.0).abs() < 1e-9); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(shape_of(&s, id).map(|s| s.width), Some(120.0)); +} + +// ---------- Corner Tool ---------- + +/// A square (100, 100)–(300, 300), plain and selected: anchors from the top left, clockwise. +fn square(s: &mut Session) -> NodeId { + let id = line(s, &[(100.0, 100.0), (300.0, 100.0), (300.0, 300.0), (100.0, 300.0)], true); + select(s, &[id]); + id +} + +fn live(s: &Session, id: NodeId) -> Option { + s.doc().unwrap().doc.node(id).unwrap().live_shape().cloned() +} + +fn drawn(s: &Session, id: NodeId, corner: usize) -> f64 { + LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().drawn_radius(corner) +} + +#[test] +fn corner_set_cuts_live_corners_as_one_undo_step() { + let mut s = session(); + let id = square(&mut s); + let plain = path(&s, id); + let n = steps(&s); + // The selected path: all four. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 20, "kind": "chamfer"})).unwrap(); + assert_eq!(r, json!({"ids": [id.0], "corners": 4})); + assert_eq!((steps(&s), path(&s, id).anchor_count()), (n + 1, 8)); + let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).map(|c| (c.drawn_radius(3), c.kind(3))).unwrap(); + assert_eq!(lc, (20.0, CornerKind::Chamfer)); + // The same again changes nothing: no step. + s.execute("addon.pathtools.cornerSet", &json!({"radius": 20, "kind": "chamfer"})).unwrap(); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((path(&s, id), live(&s, id)), (plain, None)); +} + +#[test] +fn corner_set_goes_by_anchors_the_selection_and_items_and_fits() { + let mut s = session(); + let id = square(&mut s); + let other = line(&mut s, &[(350.0, 10.0), (390.0, 10.0), (390.0, 50.0)], false); + // Named anchors, of each path by `items`, at once; an open end takes none. + let items = json!([{"id": id.0, "anchors": [1]}, {"id": other.0, "anchors": [0, 1]}]); + let n = steps(&s); + let r = s.execute("addon.pathtools.cornerSet", &json!({"items": items, "radius": 5})).unwrap(); + assert_eq!((r["corners"].clone(), steps(&s)), (json!(2), n + 1)); + assert_eq!((drawn(&s, id, 1), drawn(&s, id, 0), drawn(&s, other, 1)), (5.0, 0.0, 5.0)); + // `ids` with `anchors`, keeping the kind each has. + s.execute("addon.pathtools.cornerSet", &json!({"ids": [id.0], "anchors": [1], "radius": 9})).unwrap(); + assert_eq!(drawn(&s, id, 1), 9.0); + // Direct-selected anchors: only their corners, which stay selected as they gain anchors. + select_anchors(&mut s, id, &[0]); + s.execute("addon.pathtools.cornerSet", &json!({"radius": 7})).unwrap(); + assert_eq!((drawn(&s, id, 0), drawn(&s, id, 2)), (7.0, 0.0)); + let sel = s.doc().unwrap().selection.anchors[&id].clone(); + let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + assert_eq!(c.corners_of(&sel), BTreeSet::from([0])); + // A radius that doesn't fit is drawn at what does. + s.execute("addon.pathtools.cornerSet", &json!({"ids": [id.0], "anchors": [2], "radius": 5000})).unwrap(); + assert!(drawn(&s, id, 2) <= 200.0 - 7.0 + 1e-9, "{}", drawn(&s, id, 2)); +} + +#[test] +fn corner_remove_makes_corners_sharp_and_a_path_plain_again() { + let mut s = session(); + let id = square(&mut s); + let plain = path(&s, id); + s.execute("addon.pathtools.cornerSet", &json!({"anchors": [0, 1], "radius": 10, "kind": "invertedRound"})).unwrap(); + let n = steps(&s); + let r = s.execute("addon.pathtools.cornerRemove", &json!({"items": [{"id": id.0, "anchors": [0]}]})).unwrap(); + assert_eq!((r["corners"].clone(), steps(&s), drawn(&s, id, 0), drawn(&s, id, 1)), (json!(1), n + 1, 0.0, 10.0)); + s.execute("addon.pathtools.cornerRemove", &json!({})).unwrap(); + assert_eq!((steps(&s), path(&s, id), live(&s, id)), (n + 2, plain, None)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(drawn(&s, id, 1), 10.0); +} + +#[test] +fn corner_commands_refuse_bad_params() { + let mut s = session(); + let id = square(&mut s); + let smooth = circle(&mut s); + let i = id.0; + refuses( + &mut s, + "addon.pathtools.cornerSet", + &[ + json!({"ids": [i]}), + json!({"ids": [i], "radius": -1}), + json!({"ids": [i], "radius": 1e308}), + json!({"ids": [i], "radius": "big"}), + json!({"ids": [i], "radius": 5, "kind": "spiky"}), + json!({"ids": [i], "anchors": "all", "radius": 5}), + json!({"ids": [i], "anchors": [-1], "radius": 5}), + json!({"ids": [i], "anchors": [9], "radius": 5}), + json!({"ids": [u64::MAX], "radius": 5}), + json!({"items": 3, "radius": 5}), + json!({"items": [{"anchors": [0]}], "radius": 5}), + json!({"ids": [smooth.0], "radius": 5}), + ], + ); + refuses(&mut s, "addon.pathtools.cornerRemove", &[json!({"anchors": [9], "ids": [i]}), json!({"ids": [smooth.0]})]); + // Locked: left alone. + s.execute("object.lock", &json!({"ids": [i]})).ok(); + if !s.doc().unwrap().doc.is_editable(id) { + refuses(&mut s, "addon.pathtools.cornerSet", &[json!({"items": [{"id": i}], "radius": 5})]); + } +} + +/// A closed five-pointed star about (200, 150): its points at the even indices 0, 2… (the odd +/// numbers counting from 1), its inner corners at the odd ones. +fn star_path(s: &mut Session) -> NodeId { + let pts: Vec<(f64, f64)> = (0..10) + .map(|i| { + let (r, a) = (if i % 2 == 0 { 100.0 } else { 40.0 }, std::f64::consts::PI * f64::from(i) / 5.0); + (200.0 + r * a.sin(), 150.0 - r * a.cos()) + }) + .collect(); + line(s, &pts, true) +} + +/// The cut corners of `id`: anchor indices of its uncut outline with a radius drawn. +fn cut(s: &Session, id: NodeId) -> Vec { + let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + (0..lc.base.anchor_count()).filter(|k| lc.drawn_radius(*k) > 0.0).collect() +} + +#[test] +fn corner_set_every_takes_the_odd_or_even_numbered_anchors_of_each_path() { + let mut s = session(); + let star = star_path(&mut s); + // An open zig-zag: its ends (1st and 5th) take no corner but still count. + let zig = line(&mut s, &[(10.0, 250.0), (30.0, 210.0), (50.0, 250.0), (70.0, 210.0), (90.0, 250.0)], false); + select(&mut s, &[star, zig]); + let n = steps(&s); + // Odd: the 1st, 3rd, 5th… of each path, as one step. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 4, "every": "odd"})).unwrap(); + assert_eq!((r["corners"].clone(), steps(&s)), (json!(6), n + 1)); + assert_eq!((cut(&s, star), cut(&s, zig)), (vec![0, 2, 4, 6, 8], vec![2])); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((cut(&s, star), cut(&s, zig), steps(&s)), (vec![], vec![], n)); + // Even: the 2nd, 4th, 6th…. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 4, "every": "even"})).unwrap(); + assert_eq!((r["corners"].clone(), steps(&s)), (json!(7), n + 1)); + assert_eq!((cut(&s, star), cut(&s, zig)), (vec![1, 3, 5, 7, 9], vec![1, 3])); + // "all" (and no `every`) is every chosen corner, as before. + s.execute("addon.pathtools.cornerSet", &json!({"ids": [zig.0], "radius": 4, "every": "all"})).unwrap(); + assert_eq!(cut(&s, zig), vec![1, 2, 3]); +} + +#[test] +fn corner_set_every_filters_the_named_and_direct_selected_anchors() { + let mut s = session(); + let star = star_path(&mut s); + // Of the named anchors, only the even-numbered ones (indices 1 and 3); numbers stay the path's. + let r = s.execute("addon.pathtools.cornerSet", &json!({"ids": [star.0], "anchors": [1, 2, 3, 4], "radius": 3, "every": "even"})).unwrap(); + assert_eq!(r["corners"], json!(2)); + assert_eq!(cut(&s, star), vec![1, 3]); + // Per path through `items`. + s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": star.0, "anchors": [5, 6, 7]}], "radius": 3, "every": "odd"})).unwrap(); + assert_eq!(cut(&s, star), vec![1, 3, 6]); + // Of the direct-selected anchors. + s.execute("addon.pathtools.cornerRemove", &json!({"ids": [star.0]})).unwrap(); + select_anchors(&mut s, star, &[7, 8, 9]); + s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "every": "odd"})).unwrap(); + assert_eq!(cut(&s, star), vec![8]); +} + +#[test] +fn corner_set_every_refuses_bad_values_and_says_when_nothing_is_left() { + let mut s = session(); + let zig = line(&mut s, &[(10.0, 250.0), (30.0, 210.0), (50.0, 250.0), (70.0, 210.0)], false); + select(&mut s, &[zig]); + let i = zig.0; + refuses( + &mut s, + "addon.pathtools.cornerSet", + &[ + json!({"ids": [i], "radius": 5, "every": "third"}), + json!({"ids": [i], "radius": 5, "every": "Odd"}), + json!({"ids": [i], "radius": 5, "every": 2}), + json!({"ids": [i], "radius": 5, "every": true}), + json!({"ids": [i], "anchors": [1], "radius": 5, "every": "odd"}), + json!({"ids": [i], "anchors": [0, 1], "radius": 5, "every": "odd"}), + ], + ); + let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "radius": 5, "every": "third"})).unwrap_err().to_string(); + assert!(e.contains("`every` must be \"all\", \"odd\" or \"even\""), "{e}"); + // The 2nd anchor is a corner, but not an odd-numbered one. + let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "anchors": [1], "radius": 5, "every": "odd"})).unwrap_err().to_string(); + assert!(e.contains("odd-numbered"), "{e}"); + // An open end is no corner at all, whatever `every` says. + let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "anchors": [0], "radius": 5, "every": "odd"})).unwrap_err().to_string(); + assert!(e.contains("two sides meet"), "{e}"); +} + +/// A closed house: a 100 × 100 square under a roof, its corners 90°, 90°, 135°, 90° and 135°. +fn house(s: &mut Session) -> NodeId { + line(s, &[(250.0, 100.0), (350.0, 100.0), (350.0, 200.0), (300.0, 250.0), (250.0, 200.0)], true) +} + +#[test] +fn corner_set_angle_range_rounds_only_the_corners_in_it_on_each_path() { + let mut s = session(); + // The star's points meet at about 38°, its inner corners at about 110°. + let (star, home) = (star_path(&mut s), house(&mut s)); + select(&mut s, &[star, home]); + let n = steps(&s); + // The sharp spikes only: the house has none, the star five, as one step. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "maxAngle": 60})).unwrap(); + assert_eq!((r["ids"].clone(), r["corners"].clone(), steps(&s)), (json!([star.0]), json!(5), n + 1)); + assert_eq!((cut(&s, star), cut(&s, home)), (vec![0, 2, 4, 6, 8], vec![])); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((cut(&s, star), steps(&s)), (vec![], n)); + // Exactly 90°: the house's square corners. + s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "minAngle": 90, "maxAngle": 90})).unwrap(); + assert_eq!((cut(&s, star), cut(&s, home)), (vec![], vec![0, 1, 3])); + // 100° to 140°: the star's inner corners and the roof's; the square corners stay as they are. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 2, "minAngle": 100, "maxAngle": 140})).unwrap(); + assert_eq!(r["corners"], json!(7)); + assert_eq!((cut(&s, star), cut(&s, home)), (vec![1, 3, 5, 7, 9], vec![0, 1, 2, 3, 4])); + assert_eq!((drawn(&s, home, 0), drawn(&s, home, 2)), (3.0, 2.0)); + // On top of the named anchors and of `every`. + s.execute("addon.pathtools.cornerRemove", &json!({})).unwrap(); + s.execute("addon.pathtools.cornerSet", &json!({"ids": [home.0], "anchors": [1, 2, 3], "radius": 4, "minAngle": 80, "maxAngle": 100})).unwrap(); + assert_eq!(cut(&s, home), vec![1, 3]); + s.execute("addon.pathtools.cornerSet", &json!({"ids": [star.0], "radius": 4, "every": "even", "minAngle": 100})).unwrap(); + assert_eq!(cut(&s, star), vec![1, 3, 5, 7, 9]); +} + +#[test] +fn corner_set_angle_range_on_a_three_anchor_path() { + let mut s = session(); + // An open pen path of three anchors: one corner, of 90°. + let id = line(&mut s, &[(10.0, 10.0), (60.0, 60.0), (110.0, 10.0)], false); + select(&mut s, &[id]); + let e = s.execute("addon.pathtools.cornerSet", &json!({"radius": 5, "maxAngle": 45})).unwrap_err().to_string(); + assert!(e.contains("none of the chosen corners has an angle from 0° to 45°"), "{e}"); + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 5, "minAngle": 80, "maxAngle": 100})).unwrap(); + assert_eq!(r["corners"], json!(1)); + assert_eq!(cut(&s, id), vec![1]); +} + +#[test] +fn corner_set_angle_range_refuses_bad_values_and_says_when_nothing_matches() { + let mut s = session(); + let star = star_path(&mut s); + select(&mut s, &[star]); + let i = star.0; + refuses( + &mut s, + "addon.pathtools.cornerSet", + &[ + json!({"ids": [i], "radius": 5, "minAngle": -1}), + json!({"ids": [i], "radius": 5, "maxAngle": 181}), + json!({"ids": [i], "radius": 5, "minAngle": 1e308}), + json!({"ids": [i], "radius": 5, "maxAngle": "sharp"}), + json!({"ids": [i], "radius": 5, "minAngle": 120, "maxAngle": 60}), + json!({"ids": [i], "radius": 5, "minAngle": 50, "maxAngle": 100}), + json!({"ids": [i], "radius": 5, "every": "odd", "minAngle": 100}), + ], + ); + let err = |s: &mut Session, p: Value| s.execute("addon.pathtools.cornerSet", &p).unwrap_err().to_string(); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "maxAngle": 200})); + assert!(e.contains("`maxAngle` must be from 0 to 180 degrees"), "{e}"); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "minAngle": 120, "maxAngle": 60})); + assert!(e.contains("`minAngle` (120°) can't be more than `maxAngle` (60°)"), "{e}"); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "minAngle": 50, "maxAngle": 100})); + assert!(e.contains("none of the chosen corners has an angle from 50° to 100°"), "{e}"); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "every": "odd", "minAngle": 100})); + assert!(e.contains("none of the chosen corners at an odd-numbered anchor (the 1st, 3rd, 5th…) has an angle from 100° to 180°"), "{e}"); +} + +#[test] +fn the_corner_tool_clicks_drags_and_removes_in_one_step_each() { + let mut s = session(); + let id = square(&mut s); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("cornerTool", view).unwrap(); + s.set_tool_option("radius", &json!(15)); + let n = steps(&s); + let press = |s: &mut Session, k, x, y| s.pointer(&PointerEvent::new(k, x, y), view).unwrap(); + // A click on the top right anchor. + press(&mut s, PointerKind::Down, 300.0, 100.0); + press(&mut s, PointerKind::Up, 300.0, 100.0); + assert_eq!((steps(&s), drawn(&s, id, 1)), (n + 1, 15.0)); + // A drag from the bottom right anchor, previewed, one step. + press(&mut s, PointerKind::Down, 300.0, 300.0); + press(&mut s, PointerKind::Drag, 280.0, 280.0); + assert_eq!(drawn(&s, id, 2), 20.0, "the preview shows"); + press(&mut s, PointerKind::Drag, 270.0, 270.0); + press(&mut s, PointerKind::Up, 270.0, 270.0); + assert_eq!((steps(&s), drawn(&s, id, 2)), (n + 2, 30.0)); + // A drag on the marker resizes; a double-click on it removes. + press(&mut s, PointerKind::Down, 270.0, 270.0); + press(&mut s, PointerKind::Drag, 260.0, 260.0); + press(&mut s, PointerKind::Up, 260.0, 260.0); + assert_eq!((steps(&s), drawn(&s, id, 2)), (n + 3, 40.0)); + press(&mut s, PointerKind::DoubleClick, 260.0, 260.0); + assert_eq!((steps(&s), drawn(&s, id, 2)), (n + 4, 0.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(drawn(&s, id, 2), 40.0); + // A click on a marker selects the corner and loads its values. + press(&mut s, PointerKind::Down, 285.0, 115.0); + press(&mut s, PointerKind::Up, 285.0, 115.0); + assert_eq!(steps(&s), n + 3, "selecting is no edit"); + assert_eq!(s.doc().unwrap().selection.anchors.get(&id).map(|a| a.len()), Some(2)); + // The bottom right one, resized by its marker, loads its radius. + press(&mut s, PointerKind::Down, 260.0, 260.0); + press(&mut s, PointerKind::Up, 260.0, 260.0); + assert_eq!(s.tool_options_of("cornerTool")["radius"], json!(40.0)); + // An Alt-marquee over the left side: both anchors, in one step. + let alt = vectorcraft_tools::Mods { alt: true, ..Default::default() }; + for (k, x, y) in [(PointerKind::Down, 50.0, 50.0), (PointerKind::Drag, 150.0, 350.0), (PointerKind::Up, 150.0, 350.0)] { + s.pointer(&PointerEvent::new(k, x, y).with_mods(alt), view).unwrap(); + } + assert_eq!((steps(&s), drawn(&s, id, 0), drawn(&s, id, 3)), (n + 4, 40.0, 40.0)); +} + +// ---------- Slide Anchor Along Path ---------- + +#[test] +fn slide_anchor_moves_it_along_the_path_as_one_undo_step() { + let mut s = session(); + let e = circle(&mut s); + let before = path(&s, e); + let area = kurbo::Shape::area(&before.to_bezpath()).abs(); + let want = before.subpaths[0].segment(3); + let n = steps(&s); + let r = s.execute("addon.pathtools.slideAnchor", &json!({"id": e.0, "anchor": 3, "t": 0.5})).unwrap(); + assert!(r["strayed"].as_f64().unwrap() < 0.05, "{r}"); + let after = path(&s, e); + assert_eq!((steps(&s), after.anchor_count()), (n + 1, 16)); + assert!(after.subpaths[0].anchors[3].p.distance(kurbo::ParamCurve::eval(&want, 0.5)) < 1e-9); + assert!((kurbo::Shape::area(&after.to_bezpath()).abs() / area - 1.0).abs() < 1e-3); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, e), before); + // No move, no step. + s.execute("addon.pathtools.slideAnchor", &json!({"id": e.0, "anchor": 3, "t": 0})).unwrap(); + assert_eq!(steps(&s), n); +} + +#[test] +fn slide_anchor_refuses_bad_params() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false); + let i = l.0; + refuses( + &mut s, + "addon.pathtools.slideAnchor", + &[ + json!({"id": i, "anchor": 0, "t": 0.5}), + json!({"id": i, "anchor": 2, "t": -0.5}), + json!({"id": i, "anchor": 9, "t": 0.5}), + json!({"id": i, "anchor": 1, "t": 1.5}), + json!({"id": i, "anchor": 1}), + json!({"id": i, "t": 0.5}), + json!({"id": i, "subpath": 4, "anchor": 1, "t": 0.5}), + json!({"id": u64::MAX, "anchor": 1, "t": 0.5}), + ], + ); +} + +#[test] +fn the_slide_tool_previews_and_commits_one_step() { + let mut s = session(); + let l = line(&mut s, &[(100.0, 100.0), (200.0, 100.0), (300.0, 100.0)], false); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("slideAnchor", view).unwrap(); + let n = steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 120.0), view).unwrap(); + let at = |s: &Session| path(s, l).subpaths[0].anchors[1].p; + assert!(at(&s).distance(Point::new(250.0, 100.0)) < 1e-3, "the preview shows"); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 90.0), view).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 90.0), view).unwrap(); + assert!(steps(&s) == n + 1 && at(&s).distance(Point::new(280.0, 100.0)) < 1e-3); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(at(&s), Point::new(200.0, 100.0)); +} + +fn ids(v: &Value) -> Vec { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +#[test] +fn divide_into_dashes_cuts_a_path_into_open_pieces_keeping_its_look() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false); + select(&mut s, &[l]); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + let n = steps(&s); + let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 30, "gap": 10})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + // 30 + 10 + 30 + 10 + 20: the gaps are left empty. + let pieces = ids(&r); + assert_eq!((pieces.len(), r["dashes"].clone()), (3, json!(3))); + let st = s.doc().unwrap(); + let spans: Vec<(f64, f64)> = pieces.iter().map(|id| path(&s, *id).bounds().map(|b| (b.x0, b.x1)).unwrap()).collect(); + let want = [(0.0, 30.0), (40.0, 70.0), (80.0, 100.0)]; + assert!(spans.iter().zip(want).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6), "{spans:?}"); + assert!(pieces.iter().all(|id| st.doc.node(*id).unwrap().appearance.stroke_width() == 3.0), "the stroke stays"); + assert_eq!(st.selection.objects, pieces); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, l).anchor_count(), 2); + // Kept gaps; fitted 25s with no gap. + let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 30, "gap": 10, "removeGaps": false})).unwrap(); + assert_eq!((ids(&r).len(), r["dashes"].clone()), (5, json!(3))); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 30, "fit": true})).unwrap(); + let spans: Vec = ids(&r).iter().map(|id| path(&s, *id).bounds().unwrap().width()).collect(); + assert_eq!(spans.len(), 3); + assert!(spans.iter().all(|w| (w - 100.0 / 3.0).abs() < 1e-6), "{spans:?}"); +} + +#[test] +fn divide_into_dashes_divides_only_the_selected_segments() { + let mut s = session(); + let u = line(&mut s, &[(0.0, 0.0), (40.0, 0.0), (40.0, 40.0), (0.0, 40.0)], false); + // The middle side, between anchors 1 and 2. + select_anchors(&mut s, u, &[1, 2]); + let r = s.execute("addon.pathtools.divideDashes", &json!({"dash": 10})).unwrap(); + let pieces = ids(&r); + assert_eq!((pieces.len(), r["dashes"].clone()), (6, json!(4)), "the first side, four dashes, the last side"); + assert_eq!(path(&s, pieces[0]).bounds().unwrap().width(), 40.0); + let layer: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(layer, pieces, "in the path's place, in order"); +} + +#[test] +fn divide_into_dashes_refuses_bad_params_and_too_many_pieces() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (1e5, 0.0)], false); + select(&mut s, &[l]); + refuses( + &mut s, + "addon.pathtools.divideDashes", + &[ + json!({"dash": 0}), + json!({"dash": -5}), + json!({"dash": 1e308}), + json!({"dash": "10"}), + json!({"gap": -1}), + json!({"gap": 2e6}), + json!({"fit": "yes"}), + json!({"removeGaps": 1}), + json!({"dash": 0.5}), + ], + ); + // 200000 pieces refused above; 1000 is fine. + assert_eq!(s.execute("addon.pathtools.divideDashes", &json!({"dash": 100})).unwrap()["dashes"], json!(1000)); + s.execute("select.none", &json!({})).unwrap(); + refuses(&mut s, "addon.pathtools.divideDashes", &[json!({})]); +} + +/// The dashes made of `r`'s ids: (first x, last x) of each, by its anchors. +fn dash_spans(s: &Session, r: &Value) -> Vec<(f64, f64)> { + ids(r).iter().map(|id| path(s, *id).bounds().map(|b| (b.x0, b.x1)).unwrap()).collect() +} + +fn near(a: &[(f64, f64)], b: &[(f64, f64)]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6) +} + +#[test] +fn expand_dashes_makes_an_open_path_of_each_dash_keeping_the_stroke() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false); + select(&mut s, &[l]); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("stroke.set", &json!({"weight": 3, "cap": "round", "dash": [30, 10]})).unwrap(); + let n = steps(&s); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert!(near(&dash_spans(&s, &r), &[(0.0, 30.0), (40.0, 70.0), (80.0, 100.0)]), "{:?}", dash_spans(&s, &r)); + assert_eq!(r["dashes"], json!(3)); + let st = s.doc().unwrap(); + for id in ids(&r) { + let node = st.doc.node(id).unwrap(); + let stroke = node.appearance.stroke().unwrap(); + assert_eq!((stroke.width, stroke.cap, stroke.dash.clone()), (3.0, vectorcraft_doc::LineCap::Round, None), "the stroke stays, dashes off"); + assert!(!path(&s, id).subpaths[0].closed); + } + assert_eq!(st.selection.objects, ids(&r)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(l).unwrap().appearance.stroke().unwrap().dash.is_some()); + // The offset shifts the pattern as the stroke draws it: 20 into the first dash. + s.execute("stroke.set", &json!({"dashOffset": 20})).unwrap(); + let r = s.execute("addon.pathtools.expandDashes", &json!({"ids": [l.0]})).unwrap(); + assert!(near(&dash_spans(&s, &r), &[(0.0, 10.0), (20.0, 50.0), (60.0, 90.0)]), "{:?}", dash_spans(&s, &r)); +} + +#[test] +fn expand_dashes_keeps_the_fill_below_and_follows_aligned_corners() { + let mut s = session(); + let rect = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 60})).unwrap()); + select(&mut s, &[rect]); + s.execute("stroke.set", &json!({"dash": [20, 20]})).unwrap(); + let had_fill = !s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint().is_none(); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + // 320 round: eight dashes of 20, a dash bending round each corner it meets. + let pieces = ids(&r); + assert_eq!(pieces.len(), 8); + let st = s.doc().unwrap(); + let layer: Vec = st.doc.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + if had_fill { + let kept = st.doc.node(rect).unwrap(); + assert!(kept.appearance.stroke().is_none() && kept.appearance.fill().is_some(), "the fill stays on the rectangle"); + assert_eq!(layer, [vec![rect], pieces.clone()].concat(), "the fill below its dashes"); + } else { + assert_eq!(layer, pieces); + } + assert!(pieces.iter().all(|id| st.doc.node(*id).unwrap().appearance.fill().is_none()), "an open dash isn't filled"); + s.execute("edit.undo", &json!({})).unwrap(); + // Aligned to corners: a dash centred on each corner, the four sides each starting and ending + // on half a dash; 12 dashes along the sides. + s.execute("stroke.set", &json!({"dash": [10, 10], "alignDashes": true})).unwrap(); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + let corners = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 60.0), Point::new(0.0, 60.0)]; + let mut centred = 0; + for id in ids(&r) { + let sp = path(&s, id).subpaths[0].clone(); + if let [a, b, c] = sp.anchors.as_slice() + && corners.iter().any(|k| b.p.distance(*k) < 1e-6) + { + assert!((a.p.distance(b.p) - 5.0).abs() < 1e-6 && (c.p.distance(b.p) - 5.0).abs() < 1e-6, "{sp:?}"); + centred += 1; + } + } + assert_eq!((ids(&r).len(), centred), (16, 4)); +} + +#[test] +fn expand_dashes_turns_dots_into_paths_on_their_point_and_releases_compound_paths() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)], false); + select(&mut s, &[l]); + s.execute("stroke.set", &json!({"dash": [0, 20], "cap": "round"})).unwrap(); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + assert_eq!(ids(&r).len(), 6, "a dot every 20 from 0 to 100"); + assert!(ids(&r).iter().all(|id| path(&s, *id).bounds().unwrap().width() == 0.0)); + s.execute("edit.undo", &json!({})).unwrap(); + // Under a butt cap a dot paints nothing, so there is nothing to expand. + s.execute("stroke.set", &json!({"cap": "butt"})).unwrap(); + refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]); + // A compound path's dashes are paths of their own with its stroke. + let a = line(&mut s, &[(0.0, 100.0), (50.0, 100.0)], false); + let b = line(&mut s, &[(0.0, 120.0), (50.0, 120.0)], false); + select(&mut s, &[a, b]); + let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + s.execute("stroke.set", &json!({"weight": 2, "dash": [20, 10], "cap": "butt"})).unwrap(); + let r = s.execute("addon.pathtools.expandDashes", &json!({})).unwrap(); + // Each 50 line: 20, gap, 20. + let st = s.doc().unwrap(); + assert_eq!(ids(&r).len(), 4); + for id in ids(&r) { + let n = st.doc.node(id).unwrap(); + assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }), "a plain path"); + assert_eq!(n.appearance.stroke_width(), 2.0); + assert!(n.appearance.stroke().unwrap().dash.is_none()); + } + assert!(st.doc.node(c).is_none_or(|n| n.appearance.stroke().is_none()), "the compound path's dashes are gone from it"); +} + +#[test] +fn expand_dashes_refuses_without_dashes_and_past_the_limit() { + let mut s = session(); + let l = line(&mut s, &[(0.0, 0.0), (1e5, 0.0)], false); + refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]); + select(&mut s, &[l]); + refuses(&mut s, "addon.pathtools.expandDashes", &[json!({}), json!({"ids": "x"}), json!({"zzz": 1})]); + // 125000 dashes refused; 1000 are fine. + s.execute("stroke.set", &json!({"dash": [0.4, 0.4]})).unwrap(); + refuses(&mut s, "addon.pathtools.expandDashes", &[json!({})]); + s.execute("stroke.set", &json!({"dash": [50, 50]})).unwrap(); + assert_eq!(s.execute("addon.pathtools.expandDashes", &json!({})).unwrap()["dashes"], json!(1000)); +} diff --git a/crates/engine/src/cmd/addons/pen.rs b/crates/engine/src/cmd/addons/pen.rs new file mode 100644 index 0000000000..35d0ea5b5d --- /dev/null +++ b/crates/engine/src/cmd/addons/pen.rs @@ -0,0 +1,349 @@ +//! Smart Pen (`addon.pen.*`), a built-in add-on: one tool that draws paths and edits their points, +//! handles and segments without switching tools, and a panel. The commands here are what the tool +//! and the panel do that the standard path commands don't: anchors added with a straight or curved +//! segment into them, segments switched between straight and curved, anchors removed with or +//! without refitting their neighbours, smooth/corner toggles, segments bent by a dragged point, and +//! the panel's next-segment choice and Close or Join. The tool, panel and submenu (Object › +//! Plug-ins › Smart Pen) are the tools crate's and the UI's. + +#[cfg(test)] +mod tests; + +use std::collections::BTreeSet; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{Anchor, AnchorKind, Point, SubPath, Vec2}; +use vectorcraft_pathops::addons::{self as po, pathtools as pt, pen}; +use vectorcraft_tools::addons::smart_pen; + +use super::super::draw2::usize_opt; +use super::super::path::{compound_or_self, join, path_mut}; +use super::super::{CommandSpec, always, bad, checked_id, cmd, finite_numbers, has_doc, has_selection, number_or, switch_or, text_param}; +use crate::{EngineError, Result, Session}; + +/// The largest coordinate or move (pt) the commands take. +const LIMIT: f64 = 1e9; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.pen.append", + "Smart Pen", + [], + None, + "{id, subpath?: index (default: the last open subpath), x, y, in?: [x, y], out?: [x, y], segment?: \"straight\" (the segment into the new anchor is a line: the previous anchor's handle on it goes, and the new anchor's incoming one)|\"curved\" (the previous anchor gets a handle on it if it has none: in line with its other handle, or with a straight segment before it)} add an anchor at the end of an open subpath of path id (default: the handles as given, the previous anchor as it is), as one undo step; the new anchor is selected → {anchor}", + has_doc, + append + ), + cmd!( + "addon.pen.close", + "Close Path", + [], + None, + "{id, subpath?: index (default: the last open subpath), segment?: \"straight\"|\"curved\" (default: the closing segment takes the handles its ends have)} close an open subpath of two anchors or more, as one undo step", + has_doc, + close + ), + cmd!( + "addon.pen.segment", + "Straight or Curved Segment", + [], + None, + "{id, subpath?: index (0), segment: index, curved: bool} make a segment straight (its handles retracted) or curved (each end without a handle on it gets one, in line with its other handle or with a straight segment before it), as one undo step → {changed}", + has_doc, + segment + ), + cmd!( + "addon.pen.removePoint", + "Remove Points, Keep Shape", + [], + None, + "{id, subpath?: index (0), anchor: index, plain?: bool (false: the handles beside it are refitted so the outline keeps its shape, and an open end takes its segment with it; true: it goes and the handles beside it stay as they are)} remove one anchor, as one undo step; a subpath keeps two anchors (three when closed)", + has_doc, + remove_point + ), + cmd!( + "addon.pen.togglePoint", + "Convert Anchor Point", + [], + None, + "{id, subpath?: index (0), anchor: index, ratio?: 0.1..0.5 (0.3905)} a smooth anchor becomes a corner with its handles where they are; any other anchor is made smooth by the auto-smooth rule (a lone handle mirrored; without handles both at right angles to the bisector of the angle at it, ratio × the nearer neighbour's distance long). One undo step → {smooth}", + has_doc, + toggle_point + ), + cmd!( + "addon.pen.reshape", + "Reshape Segment", + [], + None, + "{id, subpath?: index (0), segment: index, t?: 0..1 (where it was grabbed, 0.5; held to 0.05..0.95), dx, dy: pt, mode?: \"free\" (both handles move, the one nearer the grab more)|\"keepAngles\" (each handle keeps its direction)|\"symmetric\" (both handles at right angles to the chord, at one length) (\"free\")} bend a segment so the point grabbed moves by (dx, dy); missing handles grow out of their anchors and a smooth anchor stays smooth. One undo step", + has_doc, + reshape + ), + cmd!( + "addon.pen.nextSegment", + "Next Segment", + ["Object", "Plug-ins", "Smart Pen"], + None, + "{curved: bool} whether a click with the Smart Pen Tool adds a curved segment or a straight one (the tool's `next` option, kept with the preferences) → {next: \"straight\"|\"curved\"}", + always, + next_segment + ), + cmd!( + "addon.pen.closeJoin", + "Close or Join", + ["Object", "Plug-ins", "Smart Pen"], + None, + "{} with exactly two open path ends direct-selected, join them as path.join does; else close the selected open paths keeping their ends' handles, as addon.pathtools.close does. One undo step", + has_selection, + close_join + ), + ] +} + +/// The `segment` param: straight (false) or curved (true), `None` when not given. +fn segment_kind(p: &Value, cmd: &str) -> Result> { + match text_param(p, "segment", cmd)? { + None => Ok(None), + Some("straight") => Ok(Some(false)), + Some("curved") => Ok(Some(true)), + Some(_) => Err(bad(cmd, "`segment` must be \"straight\" or \"curved\"")), + } +} + +/// An index param that must be given. +fn index_req(p: &Value, key: &str, cmd: &str) -> Result { + usize_opt(p, key, cmd)?.ok_or_else(|| bad(cmd, format!("missing integer `{key}`"))) +} + +/// A true or false param that must be given. +fn switch_req(p: &Value, key: &str, cmd: &str) -> Result { + p.get(key).and_then(Value::as_bool).ok_or_else(|| bad(cmd, format!("`{key}` must be true or false"))) +} + +/// Two number params that must be given, finite and within [`LIMIT`]. +fn pair(p: &Value, (a, b): (&str, &str), cmd: &str) -> Result<(f64, f64)> { + let (x, y) = (number_or(p, a, f64::NAN, cmd)?, number_or(p, b, f64::NAN, cmd)?); + if !(x.abs() < LIMIT && y.abs() < LIMIT) { + return Err(bad(cmd, format!("give `{a}` and `{b}`"))); + } + Ok((x, y)) +} + +/// The subpath a request names: its path (`id`, editable), its index (`subpath`; without one the +/// last open subpath with `open`, else the first) and its data. +fn subpath_of(s: &Session, p: &Value, cmd: &str, open: bool) -> Result<(NodeId, usize, SubPath)> { + let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), cmd)?; + let d = &s.doc()?.doc; + if !d.is_editable(id) { + return Err(bad(cmd, "the path is locked or hidden")); + } + let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(cmd, "`id` is not a path"))?; + let si = match usize_opt(p, "subpath", cmd)? { + Some(si) => si, + None if open => path.subpaths.iter().rposition(|sp| !sp.closed).ok_or_else(|| bad(cmd, "the path has no open subpath"))?, + None => 0, + }; + let sp = path.subpaths.get(si).ok_or_else(|| bad(cmd, "no such subpath"))?; + Ok((id, si, sp.clone())) +} + +/// What the selection becomes once a subpath is edited. +enum Pick { + /// As it was (no anchor moved to another index). + Keep, + /// The path (its compound path) selected whole. + Whole, + /// Only this anchor of the subpath, direct-selected. + Anchor(usize), +} + +/// Put `sp` in place of subpath `si` of path `id`, as one undo step labelled `label`. +fn put(s: &mut Session, label: &str, id: NodeId, si: usize, sp: SubPath, pick: Pick) -> Result<()> { + s.edit(label, |d, sel| { + let slot = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + *slot = sp; + let top = compound_or_self(d, id); + match pick { + Pick::Keep => {} + Pick::Whole => sel.set([top]), + Pick::Anchor(ai) => { + sel.set([top]); + sel.anchors.insert(id, BTreeSet::from([(si, ai)])); + } + } + Ok(()) + }) +} + +/// An optional `[x, y]` param, finite and within [`LIMIT`]. +fn point_opt(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key).filter(|v| !v.is_null()) { + None => Ok(None), + Some(v) => finite_numbers::<2>(v) + .filter(|[x, y]| x.abs() < LIMIT && y.abs() < LIMIT) + .map(|[x, y]| Some(Point::new(x, y))) + .ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y]"))), + } +} + +fn append(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.append"; + let (x, y) = pair(p, ("x", "y"), C)?; + let at = Point::new(x, y); + let (h_in, h_out) = (point_opt(p, "in", C)?.unwrap_or(at), point_opt(p, "out", C)?.unwrap_or(at)); + let curved = segment_kind(p, C)?; + let (id, si, mut sp) = subpath_of(s, p, C, true)?; + if sp.closed { + return Err(bad(C, "the subpath is closed")); + } + sp.anchors.push(Anchor::with_handles(at, h_in, h_out)); + let k = sp.anchors.len() - 1; + if let Some(prev) = k.checked_sub(1) { + match curved { + Some(true) => { + pen::leave_handle(&mut sp, prev, true, pt::SMOOTH_RATIO); + } + Some(false) => { + pen::straighten_segment(&mut sp, prev); + } + None => {} + } + } + put(s, "Smart Pen", id, si, sp, Pick::Anchor(k))?; + Ok(json!({ "anchor": k })) +} + +fn close(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.close"; + let curved = segment_kind(p, C)?; + let (id, si, mut sp) = subpath_of(s, p, C, true)?; + if sp.closed || sp.anchors.len() < 2 { + return Err(bad(C, "the subpath is closed or too short to close")); + } + sp.closed = true; + let last = sp.anchors.len() - 1; + match curved { + Some(true) => { + pen::curve_segment(&mut sp, last, pt::SMOOTH_RATIO); + } + Some(false) => { + pen::straighten_segment(&mut sp, last); + } + None => {} + } + put(s, "Close Path", id, si, sp, Pick::Whole)?; + Ok(json!({})) +} + +fn segment(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.segment"; + let seg = index_req(p, "segment", C)?; + let curved = switch_req(p, "curved", C)?; + let (id, si, mut sp) = subpath_of(s, p, C, false)?; + if seg >= sp.segment_count() { + return Err(bad(C, "no such segment")); + } + let changed = if curved { pen::curve_segment(&mut sp, seg, pt::SMOOTH_RATIO) } else { pen::straighten_segment(&mut sp, seg) }; + if changed { + put(s, "Smart Pen", id, si, sp, Pick::Keep)?; + } + Ok(json!({ "changed": changed })) +} + +fn remove_point(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.removePoint"; + let ai = index_req(p, "anchor", C)?; + let plain = switch_or(p, "plain", false, C)?; + let (id, si, mut sp) = subpath_of(s, p, C, false)?; + let n = sp.anchors.len(); + if ai >= n { + return Err(bad(C, "no such anchor")); + } + let end = !sp.closed && (ai == 0 || ai + 1 == n); + let removed = if plain { + pen::delete_anchor(&mut sp, ai) + } else if let Some((out, _)) = po::remove_anchor_keep_shape(&sp, ai) { + sp = out; + true + } else { + // An open end takes its segment with it. + end && n > 2 && vectorcraft_pathops::remove_anchor(&mut sp, ai) + }; + if !removed { + return Err(bad(C, "the path is too short to remove a point from")); + } + let label = if plain { "Delete Anchor Point" } else { "Remove Points, Keep Shape" }; + put(s, label, id, si, sp, Pick::Whole)?; + Ok(json!({})) +} + +fn toggle_point(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.togglePoint"; + let ai = index_req(p, "anchor", C)?; + let r = super::pathtools::ratio(p, C)?; + let (id, si, mut sp) = subpath_of(s, p, C, false)?; + if ai >= sp.anchors.len() { + return Err(bad(C, "no such anchor")); + } + let changed = pen::toggle_smooth(&mut sp, ai, r); + let smooth = sp.anchors.get(ai).is_some_and(|a| a.kind == AnchorKind::Smooth); + if changed { + put(s, "Convert Anchor Point", id, si, sp, Pick::Keep)?; + } + Ok(json!({ "smooth": smooth })) +} + +fn reshape(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.reshape"; + let seg = index_req(p, "segment", C)?; + let t = number_or(p, "t", 0.5, C)?; + if !(0.0..=1.0).contains(&t) { + return Err(bad(C, "`t` must be from 0 to 1")); + } + let (dx, dy) = pair(p, ("dx", "dy"), C)?; + let dv = Vec2::new(dx, dy); + let mode = match text_param(p, "mode", C)? { + None => po::ReshapeMode::Free, + Some(m) => po::ReshapeMode::parse(m).ok_or_else(|| bad(C, "`mode` must be \"free\", \"keepAngles\" or \"symmetric\""))?, + }; + let (id, si, mut sp) = subpath_of(s, p, C, false)?; + if seg >= sp.segment_count() { + return Err(bad(C, "no such segment")); + } + if !po::reshape_segment(&mut sp, seg, t, dv, mode) { + return Err(bad(C, "the segment can't be bent that far")); + } + put(s, "Reshape Segment", id, si, sp, Pick::Keep)?; + Ok(json!({})) +} + +fn next_segment(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.pen.nextSegment"; + let curved = switch_req(p, "curved", C)?; + let next = if curved { "curved" } else { "straight" }; + let values = Map::from_iter([("next".to_string(), json!(next))]); + s.set_tool_options(Some(smart_pen::ID), &values); + Ok(json!({ "next": next })) +} + +fn close_join(s: &mut Session, _: &Value) -> Result { + let st = s.doc()?; + let d = &st.doc; + // The direct-selected anchors that are ends of open subpaths. + let mut picked = 0; + let mut ends = 0; + for (id, set) in &st.selection.anchors { + let path = d.node(*id).and_then(|n| n.path_data()); + for &(si, ai) in set { + picked += 1; + let sp = path.and_then(|pd| pd.subpaths.get(si)); + ends += usize::from(sp.is_some_and(|sp| !sp.closed && (ai == 0 || ai + 1 == sp.anchors.len()))); + } + } + if picked == 2 && ends == 2 { + return join(s, &json!({})); + } + super::pathtools::close(s, &json!({ "mode": "handles" })) +} diff --git a/crates/engine/src/cmd/addons/pen/tests.rs b/crates/engine/src/cmd/addons/pen/tests.rs new file mode 100644 index 0000000000..1bb9f3345e --- /dev/null +++ b/crates/engine/src/cmd/addons/pen/tests.rs @@ -0,0 +1,287 @@ +//! Smart Pen's commands: each one undo step, bad params refused, and the tool's gestures through +//! the session. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{AnchorKind, PathData, Point, Vec2}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::{Session, ViewInfo}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn line(s: &mut Session, pts: &[(f64, f64)]) -> NodeId { + let anchors: Vec = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": false})).unwrap()["id"].as_u64().unwrap()) +} + +fn path(s: &Session, id: NodeId) -> PathData { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// Each of `bad` is refused and leaves the document as it was. +fn refuses(s: &mut Session, cmd: &str, bad: &[Value]) { + let (before, n) = (s.doc().unwrap().doc.clone(), steps(s)); + for p in bad { + assert!(s.execute(cmd, p).is_err(), "{cmd} {p}"); + } + assert_eq!(steps(s), n, "{cmd}"); + assert!(*s.doc().unwrap().doc == *before, "{cmd} changed the document"); +} + +fn parallel(a: Vec2, b: Vec2) -> bool { + a.cross(b).abs() < 1e-9 && a.dot(b) > 0.0 +} + +#[test] +fn append_adds_a_straight_or_curved_segment() { + let mut s = session(); + let id = line(&mut s, &[(0.0, 100.0), (100.0, 100.0)]); + let n = steps(&s); + let r = s.execute("addon.pen.append", &json!({"id": id.0, "x": 150, "y": 150, "segment": "curved"})).unwrap(); + assert_eq!(r["anchor"], json!(2)); + assert_eq!(steps(&s), n + 1, "one undo step"); + let sp = &path(&s, id).subpaths[0]; + // The curve leaves (100, 100) along the straight segment before it. + let a = sp.anchors[1]; + assert!(a.has_out() && !a.has_in() && parallel(a.h_out - a.p, Vec2::new(1.0, 0.0)), "{a:?}"); + assert!(sp.segment_is_line(0) && !sp.segment_is_line(1)); + // The new anchor is the one selected. + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.anchors.get(&id), Some(&BTreeSet::from([(0, 2)]))); + // Straight: the previous anchor's handle on it goes, and the new anchor's incoming one. + s.execute("addon.pen.append", &json!({"id": id.0, "subpath": 0, "x": 250, "y": 150, "in": [200, 100], "out": [300, 200], "segment": "straight"})) + .unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.segment_is_line(2) && sp.anchors[3].has_out() && !sp.anchors[3].has_in()); + assert_eq!(sp.anchors[3].kind, AnchorKind::Corner); + // Without a segment, the handles as given. + s.execute("addon.pen.append", &json!({"id": id.0, "x": 350, "y": 150, "in": [330, 140], "out": [370, 160]})).unwrap(); + assert_eq!(path(&s, id).subpaths[0].anchors[4].kind, AnchorKind::Smooth); + let closed = line(&mut s, &[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)]); + s.execute("path.close", &json!({"id": closed.0})).unwrap(); + refuses( + &mut s, + "addon.pen.append", + &[ + json!({}), + json!({"id": id.0}), + json!({"id": id.0, "x": 1, "y": f64::MAX}), + json!({"id": id.0, "x": 1, "y": 1, "segment": "wavy"}), + json!({"id": id.0, "x": 1, "y": 1, "in": [1]}), + json!({"id": id.0, "x": 1, "y": 1, "subpath": 3}), + json!({"id": closed.0, "x": 1, "y": 1}), + json!({"id": closed.0, "x": 1, "y": 1, "subpath": 0}), + json!({"id": 999_999, "x": 1, "y": 1}), + ], + ); +} + +#[test] +fn close_makes_the_closing_segment_straight_or_curved() { + let mut s = session(); + let id = line(&mut s, &[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)]); + let n = steps(&s); + s.execute("addon.pen.close", &json!({"id": id.0, "segment": "curved"})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert!(sp.closed && !sp.segment_is_line(2)); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.pen.close", &json!({"id": id.0, "segment": "straight"})).unwrap(); + assert!(path(&s, id).subpaths[0].segment_is_line(2)); + let dot = line(&mut s, &[(5.0, 5.0)]); + refuses(&mut s, "addon.pen.close", &[json!({}), json!({"id": id.0}), json!({"id": dot.0}), json!({"id": id.0, "segment": 1})]); +} + +#[test] +fn segment_switches_between_straight_and_curved() { + let mut s = session(); + let id = line(&mut s, &[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)]); + let n = steps(&s); + let r = s.execute("addon.pen.segment", &json!({"id": id.0, "segment": 1, "curved": true})).unwrap(); + assert_eq!(r["changed"], json!(true)); + assert!(!path(&s, id).subpaths[0].segment_is_line(1)); + s.execute("addon.pen.segment", &json!({"id": id.0, "segment": 1, "curved": false})).unwrap(); + assert!(path(&s, id).subpaths[0].segment_is_line(1)); + assert_eq!(steps(&s), n + 2); + // Already straight: no step. + let r = s.execute("addon.pen.segment", &json!({"id": id.0, "segment": 1, "curved": false})).unwrap(); + assert_eq!((r["changed"].clone(), steps(&s)), (json!(false), n + 2)); + refuses( + &mut s, + "addon.pen.segment", + &[ + json!({"id": id.0, "segment": 1}), + json!({"id": id.0, "segment": 2, "curved": true}), + json!({"id": id.0, "curved": true}), + json!({"id": id.0, "segment": -1, "curved": true}), + ], + ); +} + +#[test] +fn remove_point_keeps_the_shape_or_deletes_plainly() { + let mut s = session(); + let e = NodeId(s.execute("shape.ellipse", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + let before = path(&s, e); + let n = steps(&s); + s.execute("addon.pen.removePoint", &json!({"id": e.0, "anchor": 1})).unwrap(); + let after = path(&s, e); + assert_eq!(after.anchor_count(), 7); + assert_eq!(steps(&s), n + 1); + // The outline barely moved: its bounds are the circle's. + let (b0, b1) = (before.bounds().unwrap(), after.bounds().unwrap()); + assert!((b0.width() - b1.width()).abs() < 2.0 && (b0.height() - b1.height()).abs() < 2.0, "{b0:?} {b1:?}"); + // Plain: the handles beside it stay as they were. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.pen.removePoint", &json!({"id": e.0, "anchor": 1, "plain": true})).unwrap(); + let plain = path(&s, e); + assert_eq!( + (plain.subpaths[0].anchors[0].h_out, plain.subpaths[0].anchors[1].h_in), + (before.subpaths[0].anchors[0].h_out, before.subpaths[0].anchors[2].h_in) + ); + // An open end goes with its segment; two anchors stay. + let l = line(&mut s, &[(0.0, 0.0), (50.0, 0.0), (100.0, 0.0)]); + s.execute("addon.pen.removePoint", &json!({"id": l.0, "anchor": 2})).unwrap(); + assert_eq!(path(&s, l).subpaths[0].anchors.len(), 2); + refuses( + &mut s, + "addon.pen.removePoint", + &[ + json!({"id": l.0, "anchor": 0}), + json!({"id": l.0, "anchor": 0, "plain": true}), + json!({"id": l.0, "anchor": 5}), + json!({"id": l.0}), + json!({"id": l.0, "anchor": 1, "plain": 1}), + ], + ); +} + +#[test] +fn toggle_point_and_reshape() { + let mut s = session(); + let id = line(&mut s, &[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)]); + let n = steps(&s); + assert_eq!(s.execute("addon.pen.togglePoint", &json!({"id": id.0, "anchor": 1})).unwrap()["smooth"], json!(true)); + let smooth = path(&s, id).subpaths[0].anchors[1]; + assert_eq!(s.execute("addon.pen.togglePoint", &json!({"id": id.0, "anchor": 1})).unwrap()["smooth"], json!(false)); + let corner = path(&s, id).subpaths[0].anchors[1]; + assert_eq!((corner.h_in, corner.h_out), (smooth.h_in, smooth.h_out), "nothing moved"); + assert_eq!(steps(&s), n + 2); + refuses(&mut s, "addon.pen.togglePoint", &[json!({"id": id.0, "anchor": 9}), json!({"id": id.0, "anchor": 1, "ratio": 2})]); + // The grabbed point follows the drag. + let l = line(&mut s, &[(0.0, 200.0), (100.0, 200.0)]); + for mode in ["free", "keepAngles", "symmetric"] { + s.execute("addon.pen.reshape", &json!({"id": l.0, "segment": 0, "t": 0.5, "dx": 0, "dy": -40, "mode": mode})).unwrap(); + let p = kurbo::ParamCurve::eval(&path(&s, l).subpaths[0].segment(0), 0.5); + assert!(p.distance(Point::new(50.0, 160.0)) < 1e-6, "{mode}: {p:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } + refuses( + &mut s, + "addon.pen.reshape", + &[ + json!({"id": l.0, "segment": 0}), + json!({"id": l.0, "segment": 1, "dx": 1, "dy": 1}), + json!({"id": l.0, "segment": 0, "dx": 1, "dy": 1, "t": 2}), + json!({"id": l.0, "segment": 0, "dx": 1e300, "dy": 1}), + json!({"id": l.0, "segment": 0, "dx": 1, "dy": 1, "mode": "twist"}), + ], + ); +} + +#[test] +fn the_panel_commands_set_the_next_segment_and_close_or_join() { + let mut s = session(); + assert_eq!(s.execute("addon.pen.nextSegment", &json!({"curved": true})).unwrap()["next"], json!("curved")); + assert_eq!(s.tool_options_of("smartPen")["next"], json!("curved")); + assert!(s.execute("addon.pen.nextSegment", &json!({})).is_err()); + // Two open ends direct-selected: joined. + let a = line(&mut s, &[(0.0, 0.0), (100.0, 0.0)]); + let b = line(&mut s, &[(110.0, 0.0), (200.0, 0.0)]); + s.select(|_, sel| { + sel.set([a, b]); + sel.anchors.insert(a, BTreeSet::from([(0, 1)])); + sel.anchors.insert(b, BTreeSet::from([(0, 0)])); + }) + .unwrap(); + let n = steps(&s); + s.execute("addon.pen.closeJoin", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1); + assert!(s.doc().unwrap().doc.node(b).is_none() || s.doc().unwrap().doc.node(a).is_none(), "one path is left"); + // Otherwise the selected open paths close. + let c = line(&mut s, &[(0.0, 100.0), (100.0, 100.0), (100.0, 200.0)]); + s.execute("addon.pen.closeJoin", &json!({})).unwrap(); + assert!(path(&s, c).subpaths[0].closed); +} + +fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..ViewInfo::default() } +} + +/// A gesture of the active tool, `m` held throughout: press at the first point, drag through the +/// others, release at the last. +fn gesture(s: &mut Session, pts: &[(f64, f64)], m: Mods) { + let mut kinds = vec![PointerKind::Down]; + kinds.extend(pts.iter().skip(1).map(|_| PointerKind::Drag)); + for (k, (x, y)) in kinds.into_iter().zip(pts.iter().copied()) { + s.pointer(&PointerEvent::new(k, x, y).with_mods(m), view()).unwrap(); + } + let (x, y) = pts.last().copied().unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, y).with_mods(m), view()).unwrap(); +} + +/// The one path of the session's document. +fn only_path(s: &Session) -> (NodeId, PathData) { + let mut found = vec![]; + s.doc().unwrap().doc.walk(|n| { + if let Some(p) = n.path_data() { + found.push((n.id, p.clone())); + } + }); + assert_eq!(found.len(), 1, "{found:?}"); + found.remove(0) +} + +#[test] +fn the_tool_draws_a_path_one_step_per_anchor_and_closes_it() { + let mut s = session(); + s.select_tool("smartPen", view()).unwrap(); + let n = steps(&s); + gesture(&mut s, &[(50.0, 50.0)], Mods::default()); + gesture(&mut s, &[(150.0, 50.0)], Mods::default()); + s.execute("addon.pen.nextSegment", &json!({"curved": true})).unwrap(); + gesture(&mut s, &[(150.0, 150.0)], Mods::default()); + let (id, p) = only_path(&s); + let sp = &p.subpaths[0]; + assert_eq!(sp.anchors.len(), 3); + assert!(sp.segment_is_line(0) && !sp.segment_is_line(1), "a straight segment, then a curved one leaving it tangent"); + assert!(parallel(sp.anchors[1].h_out - sp.anchors[1].p, Vec2::new(1.0, 0.0))); + // A drag makes a smooth anchor. + gesture(&mut s, &[(50.0, 150.0), (30.0, 170.0)], Mods::default()); + assert_eq!(path(&s, id).subpaths[0].anchors[3].kind, AnchorKind::Smooth); + // Tab between anchors: the last segment straight again. + s.tool_key(ToolKey::Tab, Mods::default(), view()).unwrap(); + assert!(path(&s, id).subpaths[0].segment_is_line(2)); + gesture(&mut s, &[(50.0, 50.0)], Mods::default()); + assert!(path(&s, id).subpaths[0].closed); + assert_eq!(steps(&s), n + 6, "one step per anchor, the Tab and the close"); + // Edits with the same tool: a drag on an anchor moves it, Alt-click removes one keeping the shape. + s.select(|_, sel| sel.set([id])).unwrap(); + gesture(&mut s, &[(150.0, 50.0), (160.0, 40.0)], Mods::default()); + assert_eq!(path(&s, id).subpaths[0].anchors[1].p, Point::new(160.0, 40.0)); + gesture(&mut s, &[(160.0, 40.0)], Mods { alt: true, ..Mods::default() }); + assert_eq!(path(&s, id).subpaths[0].anchors.len(), 3); + assert_eq!(steps(&s), n + 8); +} diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs new file mode 100644 index 0000000000..b2ab59d851 --- /dev/null +++ b/crates/engine/src/cmd/addons/select.rs @@ -0,0 +1,195 @@ +//! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects +//! overlapping, fully inside or fully outside one or more chosen artboards (#5525), and Select by +//! Link Status selects the images and placed documents whose file is linked, embedded, missing or +//! modified (#5526), saying which ones it had to leave out and why. Its submenu (Object › Plug-ins +//! › Selection Tools), the Links panel's menu items and the dialogs are the UI's. + +#[cfg(test)] +mod tests; + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind}; +use vectorcraft_geom::Point; + +use super::super::links::{Status, statuses}; +use super::super::select::{is_selectable, on_artboard, selectable}; +use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param}; +use crate::{DocState, Result, Session}; + +/// How Select by Artboards relates an object to the chosen artboards (`relation`). +pub const RELATIONS: [&str; 3] = ["overlap", "inside", "outside"]; + +/// The link statuses Select by Link Status takes (`status`): a file found unchanged, pixels kept +/// in the document, a file not found, a file changed since it was read. +pub const LINK_STATUSES: [&str; 4] = ["linked", "embedded", "missing", "modified"]; + +/// The add-on's commands: Select by Artboards and Select by Link Status. +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.select.byArtboards", + "Select by Artboards", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", + has_doc, + by_artboards + ), + cmd!( + "addon.select.byLinkStatus", + "Select by Link Status", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{status: \"linked\" (its file found unchanged) | \"embedded\" | \"missing\" | \"modified\" (its file changed since it was read) | [several of them] (at least one), ids?: [object ids] (pick only among these; default: every image and placed document in the layers), add?: false (add to the selection instead of replacing it), zoom?: false (then zoom to the selection: the desktop app runs addon.arrange.zoomSelection when something was selected; elsewhere the result's zoom flag asks the caller to)} select the image objects and placed documents whose link has that status, as links.list reports it. Those that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group or layer are left out and listed with the reason. Only the selection changes, not the document → {count (how many it selected), selected: [ids] (in stacking order, bottom first), skipped: [{id, reason: hidden|locked|template|isolation}], zoom?: true}", + has_doc, + by_link_status + ), + ] +} + +/// `addon.select.byArtboards`: select the objects Select All takes that overlap, lie inside or lie +/// outside the chosen artboards. +fn by_artboards(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.select.byArtboards"; + let relation = text_param(p, "relation", C)?.unwrap_or("overlap"); + if !RELATIONS.contains(&relation) { + return Err(bad(C, "`relation` must be overlap, inside or outside")); + } + let listed = p.get("artboards").ok_or_else(|| bad(C, "missing `artboards`"))?; + let indices = point_indices(listed).ok_or_else(|| bad(C, "`artboards` must be a list of artboard indices"))?; + if indices.is_empty() { + return Err(bad(C, "choose at least one artboard")); + } + let st = s.doc()?; + let rects = + indices.iter().map(|i| st.doc.artboards.get(*i).map(|a| a.rect)).collect::>>().ok_or_else(|| bad(C, "no such artboard"))?; + let symbols = st.doc.symbol_boxes(); + let ids: Vec = selectable(&st.doc, st.isolation) + .into_iter() + .filter(|id| { + let Some(n) = st.doc.node(*id) else { return false }; + match relation { + "inside" => n.geometric_bounds_with(&symbols).is_some_and(|b| { + rects.iter().any(|r| { + vectorcraft_doc::artboard_holds(*r, Point::new(b.x0, b.y0)) && vectorcraft_doc::artboard_holds(*r, Point::new(b.x1, b.y1)) + }) + }), + "outside" => !rects.iter().any(|r| on_artboard(n, &symbols, *r)), + _ => rects.iter().any(|r| on_artboard(n, &symbols, *r)), + } + }) + .collect(); + s.select(|_, sel| sel.set(ids))?; + Ok(json!({ "count": s.doc()?.selection.objects.len() })) +} + +/// The link statuses `p` asks for (`status`: one, or a list of them), each once. +fn link_statuses(p: &Value, cmd: &str) -> Result> { + let given: Vec<&Value> = match p.get("status") { + None | Some(Value::Null) => return Err(bad(cmd, "missing `status`: linked, embedded, missing or modified")), + Some(Value::Array(v)) => v.iter().collect(), + Some(v) => vec![v], + }; + let mut out = vec![]; + for v in given { + let s = v.as_str().ok_or_else(|| bad(cmd, "`status` must be linked, embedded, missing or modified, or a list of them"))?; + let known = + LINK_STATUSES.iter().find(|k| **k == s).ok_or_else(|| bad(cmd, format!("status `{s}`: linked, embedded, missing or modified")))?; + if !out.contains(known) { + out.push(*known); + } + } + if out.is_empty() { + return Err(bad(cmd, "choose at least one status")); + } + Ok(out) +} + +/// The link status of every image object and placed document in the layers of `st`, as +/// `links.list` reports it (`ok` named `linked`), in stacking order (bottom first). Each file is +/// looked at once. +pub(crate) fn link_status_of_objects(st: &DocState) -> Vec<(NodeId, &'static str)> { + let linked = statuses(st); + let mut out = vec![]; + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) { + let status = match linked.get(&n.id).map(|(s, ..)| *s) { + Some(Status::Ok) => "linked", + Some(Status::Modified) => "modified", + Some(Status::Missing) => "missing", + None => "embedded", + }; + out.push((n.id, status)); + } + }); + out +} + +/// Why object `id` of `st` can't be selected now ([`is_selectable`]): it is outside the isolated +/// group or layer, on a template layer, hidden (or inside something hidden), or locked (or inside +/// something locked, or on a locked artboard); `None` when it can be. `locks` is the document's +/// [`vectorcraft_doc::Document::locked_artboards`]. +fn skip_reason(st: &DocState, locks: &LockedArtboards, id: NodeId) -> Option<&'static str> { + let d = &st.doc; + if is_selectable(d, st.isolation, locks, id) { + return None; + } + let ancestry = d.ancestry(id).unwrap_or_default(); + // Outside the isolated container, or the isolated container itself (its art is what's taken). + if let Some(c) = st.isolation.and_then(|i| d.node(i)) + && ancestry.iter().position(|i| *i == c.id).is_none_or(|at| at + 1 == ancestry.len() && c.is_container()) + { + return Some("isolation"); + } + let held: Vec<&Node> = ancestry.iter().filter_map(|i| d.node(*i)).collect(); + Some(if held.iter().any(|n| n.is_template()) { + "template" + } else if held.iter().any(|n| !n.visible) { + "hidden" + } else { + // A locked object, group or layer, or the locked artboard that holds it. + "locked" + }) +} + +/// `addon.select.byLinkStatus`: select the images and placed documents whose link has one of the +/// statuses asked for (among `ids` when given), replacing the selection or adding to it, and list +/// those left out with the reason ([`skip_reason`]). +fn by_link_status(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.select.byLinkStatus"; + let wanted = link_statuses(p, C)?; + let add = switch_or(p, "add", false, C)?; + let zoom = switch_or(p, "zoom", false, C)?; + let only: Option> = match p.get("ids") { + None | Some(Value::Null) => None, + Some(_) => Some(checked_ids_param(s, p, "ids", C)?.into_iter().collect()), + }; + let st = s.doc()?; + let locks = st.doc.locked_artboards(); + let (mut picked, mut skipped) = (vec![], vec![]); + for (id, status) in link_status_of_objects(st) { + if !wanted.contains(&status) || only.as_ref().is_some_and(|o| !o.contains(&id)) { + continue; + } + match skip_reason(st, &locks, id) { + None => picked.push(id), + Some(reason) => skipped.push(json!({ "id": id.0, "reason": reason })), + } + } + s.select(|_, sel| { + if add { + for id in &picked { + sel.add(*id); + } + } else { + sel.set(picked.iter().copied()); + } + })?; + let mut out = json!({ "count": picked.len(), "selected": picked.iter().map(|id| id.0).collect::>(), "skipped": skipped }); + if zoom { + out["zoom"] = json!(true); + } + Ok(out) +} diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs new file mode 100644 index 0000000000..c97b278258 --- /dev/null +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -0,0 +1,310 @@ +//! Select by Artboards. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; + +use crate::Session; + +const C: &str = "addon.select.byArtboards"; + +/// A document with three 100 × 100 artboards in a row, 50 pt apart: 0 at x 0, 1 at x 150, 2 at x 300. +fn three_boards() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for x in [150, 300] { + s.execute("artboard.new", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap(); + } + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +fn pick(s: &mut Session, p: Value) -> Vec { + s.execute("select.none", &json!({})).unwrap(); + let r = s.execute(C, &p).unwrap(); + let mut ids = s.doc().unwrap().selection.objects.clone(); + assert_eq!(r["count"], json!(ids.len())); + ids.sort(); + ids +} + +#[test] +fn selects_by_overlap_inside_and_outside_several_artboards() { + let mut s = three_boards(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); // inside 0 + let ab = rect(&mut s, 90.0, 40.0, 80.0, 20.0); // across 0 and 1 + let b = rect(&mut s, 160.0, 10.0, 20.0, 20.0); // inside 1 + let c = rect(&mut s, 310.0, 10.0, 20.0, 20.0); // inside 2 + let off = rect(&mut s, 0.0, 200.0, 20.0, 20.0); // on no board + let edge = rect(&mut s, 0.0, 0.0, 100.0, 100.0); // flush with board 0 + let want = |mut v: Vec| { + v.sort(); + v + }; + assert_eq!(pick(&mut s, json!({"artboards": [0, 1]})), want(vec![a, ab, b, edge])); + assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "overlap"})), want(vec![a, ab, b, edge])); + // Wholly within one board, edges included; straddling two boards is not inside either. + assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "inside"})), want(vec![a, b, edge])); + assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "outside"})), want(vec![c, off])); + assert_eq!(pick(&mut s, json!({"artboards": [2], "relation": "outside"})), want(vec![a, ab, b, off, edge])); + // One board does what All on Active Artboard does. + for i in 0..3u64 { + s.execute("select.allOnArtboard", &json!({"artboard": i})).unwrap(); + let mut on = s.doc().unwrap().selection.objects.clone(); + on.sort(); + assert_eq!(pick(&mut s, json!({"artboards": [i]})), on, "board {i}"); + } + // A board listed twice counts once. + assert_eq!(pick(&mut s, json!({"artboards": [2, 2]})), vec![c]); +} + +#[test] +fn hidden_locked_and_isolated_art_follow_select_all() { + let mut s = three_boards(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let hidden = rect(&mut s, 40.0, 10.0, 20.0, 20.0); + let locked = rect(&mut s, 70.0, 10.0, 20.0, 20.0); + let far = rect(&mut s, 0.0, 300.0, 20.0, 20.0); + s.execute("object.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap(); + s.execute("object.setProps", &json!({"ids": [locked.0], "locked": true})).unwrap(); + assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![a]); + assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![far]); + // Art held by a locked artboard is left out. + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![]); + s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap(); + // In isolation mode only the isolated group's objects are looked at. + let b = rect(&mut s, 20.0, 50.0, 10.0, 10.0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": g})).unwrap(); + let mut both = vec![a, b]; + both.sort(); + assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), both); + assert_eq!(pick(&mut s, json!({"artboards": [1]})), vec![]); +} + +#[test] +fn bad_params_are_errors_and_leave_the_selection() { + let mut s = three_boards(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + for p in [ + json!({}), + json!({"artboards": []}), + json!({"artboards": [3]}), + json!({"artboards": [-1]}), + json!({"artboards": [0.5]}), + json!({"artboards": "0"}), + json!({"artboards": [0], "relation": "near"}), + json!({"artboards": [0], "relation": 1}), + json!({"artboards": [0], "relatoin": "inside"}), + ] { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{p}"); + } +} + +#[test] +fn a_symbol_instance_is_measured_by_its_art() { + // The symbol's art, (100, 60) to (140, 80), drawn 50 pt up and left: (50, 10) to (90, 30), on + // the 200 × 120 artboard, while the 20 × 20 square around the instance's origin lies off it. + let svg = r##""##; + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "far.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap(); + let mut instance = None; + s.doc().unwrap().doc.walk(|n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. }) { + instance = Some(n.id); + } + }); + let instance = instance.unwrap(); + assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![instance]); + assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), vec![instance]); + assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![]); +} + +/// Select by Link Status. +mod by_link_status { + use serde_json::{Value, json}; + use vectorcraft_doc::{Document, NodeId}; + + use crate::Session; + use crate::tests_links::{BLUE, Folder, RED, place, png, session, write}; + + const C: &str = "addon.select.byLinkStatus"; + + /// One linked image whose file stays as it is (`ok`), one whose file changes (`modified`), + /// one whose file goes (`missing`), an embedded one, and a placed document whose file goes + /// (missing too), bottom to top. + struct Links { + s: Session, + ok: NodeId, + modified: NodeId, + missing: NodeId, + embedded: NodeId, + document: NodeId, + _dir: Folder, + } + + /// [`Links`] in a fresh folder named after `name`: the files placed, then one changed and two + /// removed. + fn links(name: &str) -> Links { + let dir = Folder::new(name); + let (a, b, c, e, d) = (dir.file("ok.png"), dir.file("changes.png"), dir.file("goes.png"), dir.file("kept.png"), dir.file("page.vectorcraft")); + write(&a, &png(10, 10, RED)); + write(&b, &png(12, 10, RED)); + write(&c, &png(14, 10, BLUE)); + write(&e, &png(16, 10, BLUE)); + write(&d, &vectorcraft_format::save_file(&Document::new(80.0, 50.0))); + let mut s = session(); + let (ok, modified, missing) = (place(&mut s, &a), place(&mut s, &b), place(&mut s, &c)); + let embedded = NodeId(s.execute("file.place", &json!({"path": e, "at": [100, 100], "link": false})).unwrap()["ids"][0].as_u64().unwrap()); + let document = place(&mut s, &d); + write(&b, &png(13, 10, BLUE)); + std::fs::remove_file(&c).unwrap(); + std::fs::remove_file(&d).unwrap(); + Links { s, ok, modified, missing, embedded, document, _dir: dir } + } + + /// Run the command with `p`, which must succeed. + fn run(s: &mut Session, p: Value) -> Value { + s.execute(C, &p).unwrap_or_else(|e| panic!("{p}: {e}")) + } + + /// `v` sorted. + fn sorted(mut v: Vec) -> Vec { + v.sort(); + v + } + + /// The selected objects, sorted. + fn selection(s: &Session) -> Vec { + sorted(s.doc().unwrap().selection.objects.clone()) + } + + /// The ids of a JSON list, sorted. + fn ids(v: &Value) -> Vec { + sorted(v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()) + } + + #[test] + fn each_status_selects_its_images_and_placed_documents() { + let Links { mut s, ok, modified, missing, embedded, document, _dir } = links("select-status"); + // As the Links panel lists them. + let listed = s.execute("links.list", &json!({})).unwrap(); + let status = |id: NodeId| listed["links"].as_array().unwrap().iter().find(|r| r["id"] == id.0).unwrap()["status"].clone(); + assert_eq!([ok, modified, missing, embedded, document].map(status), ["ok", "modified", "missing", "embedded", "missing"].map(|s| json!(s))); + let undo = s.doc().unwrap().history.undo.len(); + for (status, want) in [("linked", vec![ok]), ("modified", vec![modified]), ("missing", vec![missing, document]), ("embedded", vec![embedded])] + { + s.execute("select.none", &json!({})).unwrap(); + let r = run(&mut s, json!({"status": status})); + assert_eq!((ids(&r["selected"]), r["count"].as_u64()), (sorted(want.clone()), Some(want.len() as u64)), "{status}: {r}"); + assert_eq!(selection(&s), sorted(want), "{status}"); + assert_eq!(r["skipped"], json!([])); + assert!(r.get("zoom").is_none()); + } + // Several at once, in stacking order (bottom first); a status listed twice counts once. + let r = run(&mut s, json!({"status": ["missing", "linked", "missing"]})); + assert_eq!(r["selected"], json!([ok.0, missing.0, document.0])); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "only the selection changes"); + } + + #[test] + fn ids_add_and_zoom() { + let Links { mut s, ok, modified, embedded, document, _dir, .. } = links("select-options"); + // Only among the ids given; other objects among them (a rectangle) are passed over. + let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap(); + let r = run(&mut s, json!({"status": "missing", "ids": [document.0, ok.0, rect]})); + assert_eq!(r["selected"], json!([document.0])); + assert_eq!(selection(&s), vec![document]); + // Added to the selection. + let r = run(&mut s, json!({"status": "embedded", "add": true})); + assert_eq!((r["count"].as_u64(), r["selected"].clone()), (Some(1), json!([embedded.0]))); + assert_eq!(selection(&s), sorted(vec![document, embedded])); + // Replacing it by default. + run(&mut s, json!({"status": "modified"})); + assert_eq!(selection(&s), vec![modified]); + // Nothing to select: added, the selection stays; replacing, it empties. + let r = run(&mut s, json!({"status": "linked", "ids": [embedded.0], "add": true})); + assert_eq!((r["count"].as_u64(), r["selected"].clone(), r["skipped"].clone()), (Some(0), json!([]), json!([]))); + assert_eq!(selection(&s), vec![modified]); + run(&mut s, json!({"status": "linked", "ids": [embedded.0]})); + assert_eq!(selection(&s), vec![]); + // Zoom is reported for the caller (the desktop app zooms). + assert_eq!(run(&mut s, json!({"status": "linked", "zoom": true}))["zoom"], true); + assert!(run(&mut s, json!({"status": "linked", "zoom": false})).get("zoom").is_none()); + } + + #[test] + fn hidden_locked_template_and_isolated_ones_are_skipped_with_the_reason() { + let dir = Folder::new("select-skipped"); + let files: Vec = (0..6).map(|i| dir.file(&format!("img{i}.png"))).collect(); + for (i, f) in files.iter().enumerate() { + write(f, &png(10 + i as u32, 10, RED)); + } + let mut s = session(); + let [free, hidden, locked, in_group, mate] = [0, 1, 2, 3, 4].map(|i| place(&mut s, &files[i])); + s.execute("object.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap(); + s.execute("object.setProps", &json!({"ids": [locked.0], "locked": true})).unwrap(); + // Inside a locked group. + s.execute("select.set", &json!({"ids": [in_group.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [g], "locked": true})).unwrap(); + // On a template layer. + let layer = s.execute("layer.new", &json!({"name": "Trace"})).unwrap()["id"].as_u64().unwrap(); + let on_template = place(&mut s, &files[5]); + s.execute("layer.setProps", &json!({"id": layer, "template": true})).unwrap(); + let r = run(&mut s, json!({"status": "linked"})); + assert_eq!(ids(&r["selected"]), sorted(vec![free, mate]), "{r}"); + let mut reasons: Vec<(u64, String)> = + r["skipped"].as_array().unwrap().iter().map(|k| (k["id"].as_u64().unwrap(), k["reason"].as_str().unwrap().to_string())).collect(); + reasons.sort(); + let mut want: Vec<(u64, String)> = [(hidden, "hidden"), (locked, "locked"), (in_group, "locked"), (on_template, "template")] + .into_iter() + .map(|(id, why)| (id.0, why.to_string())) + .collect(); + want.sort(); + assert_eq!(reasons, want, "{r}"); + assert!(reasons.iter().all(|(_, why)| ["hidden", "locked", "template", "isolation"].contains(&why.as_str()))); + // In isolation mode, those outside the isolated group are left out. + s.execute("select.set", &json!({"ids": [mate.0]})).unwrap(); + let iso = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": iso})).unwrap(); + let r = run(&mut s, json!({"status": "linked"})); + assert_eq!(r["selected"], json!([mate.0]), "{r}"); + let why = |id: NodeId| r["skipped"].as_array().unwrap().iter().find(|k| k["id"] == id.0).map(|k| k["reason"].clone()); + assert_eq!(why(free), Some(json!("isolation"))); + assert_eq!(why(hidden), Some(json!("isolation"))); + } + + #[test] + fn bad_params_are_errors_and_leave_the_selection() { + let Links { mut s, ok, _dir, .. } = links("select-bad"); + for p in [ + json!({}), + json!({"status": null}), + json!({"status": []}), + json!({"status": "lost"}), + json!({"status": ["linked", "lost"]}), + json!({"status": 3}), + json!({"status": [true]}), + json!({"status": "linked", "add": "yes"}), + json!({"status": "linked", "zoom": 1}), + json!({"status": "linked", "ids": "1"}), + json!({"status": "linked", "ids": [999_999]}), + json!({"status": "linked", "ids": [-1]}), + json!({"status": "linked", "stauts": "missing"}), + ] { + s.execute("select.set", &json!({"ids": [ok.0]})).unwrap(); + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![ok], "{p}"); + } + // Without a document it is off, not a crash. + assert!(Session::new().execute(C, &json!({"status": "linked"})).is_err()); + } +} diff --git a/crates/engine/src/cmd/addons/shapes.rs b/crates/engine/src/cmd/addons/shapes.rs new file mode 100644 index 0000000000..c401733906 --- /dev/null +++ b/crates/engine/src/cmd/addons/shapes.rs @@ -0,0 +1,477 @@ +//! 3D Box and customizable shapes (`addon.shapes.*`), a built-in add-on: creates rotatable 3D boxes +//! (`addon.shapes.box3d`) and customizable rectangles, ellipses, polygons, stars and spirals +//! (`addon.shapes.rectangle`, `addon.shapes.ellipse`, `addon.shapes.polygon`, `addon.shapes.star`, +//! `addon.shapes.spiral`), and configures extended live-shape parameters on selected shapes +//! (`addon.shapes.configure`: symmetric or per-corner radii, pie/chord/arc/whole modes, polygon/star +//! spoke ratio, corner rounding, randomization, spiral turns/divergence/inner radius, and 3D box +//! rotation angles). + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes}; +use vectorcraft_tools::addons::box3d::CustomShape; + +use super::super::create::insert_look; +use super::super::{ + CommandSpec, Result, Session, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_selection, str_param, targets, +}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.shapes.rectangle", + "Rectangle", + [], + None, + "{x, y, width, height, radius?: pt, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + has_doc, + rectangle + ), + cmd!( + "addon.shapes.ellipse", + "Ellipse", + [], + None, + "{x, y, width, height, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + has_doc, + ellipse + ), + cmd!( + "addon.shapes.polygon", + "Polygon", + [], + None, + "{cx, cy, radius, sides=6, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + has_doc, + polygon + ), + cmd!( + "addon.shapes.star", + "Star", + [], + None, + "{cx, cy, radius1, radius2?, points=5, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + has_doc, + star + ), + cmd!( + "addon.shapes.spiral", + "Spiral", + [], + None, + "{cx, cy, radius, turns=3, divergence=1, innerRadius=0, clockwise=true} → {id}", + has_doc, + spiral + ), + cmd!( + "addon.shapes.box3d", + "3D Box", + [], + None, + "{x, y, width, height, angleX=30, angleY=30, angleZ=0, parallelX=false, parallelY=true, parallelZ=false} → {id}", + has_doc, + box3d + ), + cmd!( + "addon.shapes.configure", + "Configure Shape", + [], + None, + "{ids?, radius?, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, sides?, isStar?, spokeRatio?, rounded?, randomized?, turns?, divergence?, innerRadius?, angleX?, angleY?, angleZ?, parallelX?, parallelY?, parallelZ?, reset?: bool} → {updated}", + has_selection, + configure + ), + ] +} + +fn parse_arc_params(p: &Value) -> ((f64, f64), shapes::EllipseMode) { + let start = f64_or(p, "startAngle", 0.0); + let end = f64_or(p, "endAngle", 360.0); + let mode = match str_param(p, "arcMode") { + Some("pie" | "slice") => shapes::EllipseMode::Slice, + Some("chord") => shapes::EllipseMode::Chord, + Some("arc" | "open") => shapes::EllipseMode::Arc, + _ => shapes::EllipseMode::Whole, + }; + let span = (end - start).rem_euclid(360.0); + let pie = if mode == shapes::EllipseMode::Whole && (span < 1e-6 || (span - 360.0).abs() < 1e-6) { (0.0, 360.0) } else { (start, end) }; + (pie, mode) +} + +fn rect_of(p: &Value, c: &str) -> Result { + let x = f64_req(p, "x", c)?; + let y = f64_req(p, "y", c)?; + let w = f64_req(p, "width", c)?; + let h = f64_req(p, "height", c)?; + Ok(Rect::new(x, y, x + w.abs(), y + h.abs()).abs()) +} + +fn rect_xf(r: Rect, rot: f64) -> Affine { + if rot == 0.0 || !rot.is_finite() { + Affine::translate(r.origin().to_vec2()) + } else { + Affine::translate(r.center().to_vec2()) * vectorcraft_geom::rotate_deg(rot) * Affine::translate((-r.width() / 2.0, -r.height() / 2.0)) + } +} + +fn insert_custom(s: &mut Session, label: &str, live: Option, cs: CustomShape) -> Result { + let path = match (&live, cs.needs_extra_storage()) { + (Some(l), false) => l.to_path(), + _ => cs.to_path(), + }; + let kind = NodeKind::Path { path, rule: FillRule::NonZero, live: live.map(Box::new), clipping: false, guide: false }; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let val = insert_look(s, label, kind, look, None, true)?; + if cs.needs_extra_storage() + && let Some(raw_id) = val.get("id").and_then(Value::as_u64) + && let Ok(st) = s.doc_mut() + && let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id)) + { + cs.write_to_node(n); + } + Ok(val) +} + +fn rectangle(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.rectangle"; + check_numbers(p, &["radius", "startAngle", "endAngle", "rotation"], c)?; + let r = rect_of(p, c)?; + let radius = f64_or(p, "radius", 0.0).max(0.0); + let mut radii = [radius; 4]; + if let Some(arr) = p.get("radii").and_then(Value::as_array) + && arr.len() == 4 + { + for (i, item) in arr.iter().enumerate() { + if let Some(val) = item.as_f64().filter(|n| n.is_finite()) { + radii[i] = val.max(0.0); + } + } + } + let (pie, arc_mode) = parse_arc_params(p); + let xf = rect_xf(r, f64_or(p, "rotation", 0.0)); + let live = LiveShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf }; + let cs = CustomShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf, pie, arc_mode }; + let label = if radii.iter().any(|&v| v > 0.0) { "Rounded Rectangle" } else { "Rectangle" }; + insert_custom(s, label, Some(live), cs) +} + +fn ellipse(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.ellipse"; + check_numbers(p, &["startAngle", "endAngle", "rotation"], c)?; + let r = rect_of(p, c)?; + let (pie, arc_mode) = parse_arc_params(p); + let xf = rect_xf(r, f64_or(p, "rotation", 0.0)); + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie, xf }; + let cs = CustomShape::Ellipse { w: r.width(), h: r.height(), pie, arc_mode, xf }; + insert_custom(s, "Ellipse", Some(live), cs) +} + +fn polygon(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.polygon"; + let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?); + let r = f64_req(p, "radius", c)?.abs(); + check_numbers(p, &["sides", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?; + let sides = (f64_or(p, "sides", 6.0).round() as i64).clamp(3, 1000) as u32; + let rot = f64_or(p, "rotation", 0.0); + let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0); + let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0); + let (pie, arc_mode) = parse_arc_params(p); + let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot); + let live = LiveShape::Polygon { radius: r, sides, xf, radii: vec![], kinds: vec![], radii_relative: false }; + let cs = CustomShape::Polygon { + radius: r, + sides, + xf, + radii: vec![], + kinds: vec![], + radii_relative: false, + spoke_ratio: None, + rounded, + randomized, + pie, + arc_mode, + }; + insert_custom(s, "Polygon", Some(live), cs) +} + +fn star(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.star"; + let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?); + let r1 = f64_req(p, "radius1", c)?.abs(); + check_numbers(p, &["radius2", "points", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?; + let r2 = f64_or(p, "radius2", r1 / 2.0).abs(); + let points = (f64_or(p, "points", 5.0).round() as i64).clamp(3, 1000) as u32; + let rot = f64_or(p, "rotation", 0.0); + let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0); + let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0); + let (pie, arc_mode) = parse_arc_params(p); + let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot); + let ratio = if r1 > 1e-9 { (r2 / r1).clamp(0.01, 1.0) } else { 0.5 }; + let cs = CustomShape::Polygon { + radius: r1, + sides: points, + xf, + radii: vec![], + kinds: vec![], + radii_relative: false, + spoke_ratio: Some(ratio), + rounded, + randomized, + pie, + arc_mode, + }; + insert_custom(s, "Star", None, cs) +} + +fn spiral(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.spiral"; + let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?); + let r = f64_req(p, "radius", c)?.abs(); + check_numbers(p, &["turns", "divergence", "innerRadius"], c)?; + check_switches(p, &["clockwise"], c)?; + let turns = f64_or(p, "turns", 3.0).clamp(0.01, 1024.0); + let divergence = f64_or(p, "divergence", 1.0).clamp(0.0, 1000.0); + let inner_radius = f64_or(p, "innerRadius", 0.0).clamp(0.0, 0.999); + let clockwise = bool_or(p, "clockwise", true); + let cs = CustomShape::Spiral { center, radius: r, turns, divergence, inner_radius, clockwise }; + insert_custom(s, "Spiral", None, cs) +} + +fn box3d(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.box3d"; + let r = rect_of(p, c)?; + check_numbers(p, &["angleX", "angleY", "angleZ"], c)?; + check_switches(p, &["parallelX", "parallelY", "parallelZ"], c)?; + let angle_x = f64_or(p, "angleX", 30.0); + let angle_y = f64_or(p, "angleY", 30.0); + let angle_z = f64_or(p, "angleZ", 0.0); + let parallel_x = bool_or(p, "parallelX", false); + let parallel_y = bool_or(p, "parallelY", true); + let parallel_z = bool_or(p, "parallelZ", false); + let cs = CustomShape::Box3d { + w: r.width(), + h: r.height(), + angle_x, + angle_y, + angle_z, + parallel_x, + parallel_y, + parallel_z, + xf: Affine::translate(r.origin().to_vec2()), + }; + let kind = NodeKind::Path { path: cs.to_path(), rule: FillRule::NonZero, live: None, clipping: false, guide: false }; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let val = insert_look(s, "3D Box", kind, look, Some("3D Box".into()), true)?; + if let Some(raw_id) = val.get("id").and_then(Value::as_u64) + && let Ok(st) = s.doc_mut() + && let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id)) + { + cs.write_to_node(n); + } + Ok(val) +} + +fn configure(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.configure"; + check_numbers( + p, + &[ + "radius", + "startAngle", + "endAngle", + "sides", + "spokeRatio", + "rounded", + "randomized", + "turns", + "divergence", + "innerRadius", + "angleX", + "angleY", + "angleZ", + ], + c, + )?; + check_switches(p, &["isStar", "parallelX", "parallelY", "parallelZ", "reset"], c)?; + let ids = targets(s, p)?; + let reset = bool_or(p, "reset", false); + let spiral_hint = p.get("turns").is_some() || p.get("divergence").is_some() || p.get("innerRadius").is_some(); + let updated = s.edit("Live Shape", |d, _| { + let mut count = 0usize; + for id in ids { + let Some(n) = d.node_mut(id) else { continue }; + let Some(mut cs) = CustomShape::read_for_update(n, spiral_hint) else { continue }; + if apply_shape_params(&mut cs, p, reset) { + cs.write_to_node(n); + count += 1; + } + } + Ok(count) + })?; + Ok(json!({ "updated": updated })) +} + +fn num_param(p: &Value, k: &str) -> Option { + p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()) +} + +fn apply_arc_params(p: &Value, pie: &mut (f64, f64), arc_mode: &mut shapes::EllipseMode) -> bool { + let mut changed = false; + if let Some(a0) = num_param(p, "startAngle") { + pie.0 = a0.rem_euclid(360.0); + changed = true; + } + if let Some(a1) = num_param(p, "endAngle") { + pie.1 = a1.rem_euclid(360.0); + changed = true; + } + if let Some(m) = str_param(p, "arcMode") { + *arc_mode = parse_mode(m); + if *arc_mode == shapes::EllipseMode::Whole { + *pie = (0.0, 360.0); + } else if (pie.1 - pie.0).abs() < 1e-6 || ((pie.1 - pie.0).abs() - 360.0).abs() < 1e-6 { + *pie = (0.0, 270.0); + } + changed = true; + } + changed +} + +fn apply_rect_params(p: &Value, reset: bool, max_r: f64, radii: &mut [f64; 4], pie: &mut (f64, f64), arc_mode: &mut shapes::EllipseMode) -> bool { + let mut changed = false; + if reset { + *radii = [0.0; 4]; + *pie = (0.0, 360.0); + *arc_mode = shapes::EllipseMode::Whole; + changed = true; + } + if let Some(r) = num_param(p, "radius") { + *radii = [r.clamp(0.0, max_r); 4]; + changed = true; + } + if let Some(arr) = p.get("radii").and_then(Value::as_array) + && arr.len() == 4 + { + for (i, v) in arr.iter().enumerate() { + if let Some(r) = v.as_f64().filter(|x| x.is_finite()) { + radii[i] = r.clamp(0.0, max_r); + changed = true; + } + } + } + changed | apply_arc_params(p, pie, arc_mode) +} + +fn apply_poly_params(p: &Value, reset: bool, sides: &mut u32, spoke_ratio: &mut Option, rounded: &mut f64, randomized: &mut f64) -> bool { + let mut changed = false; + if reset { + *rounded = 0.0; + *randomized = 0.0; + if spoke_ratio.is_some() { + *spoke_ratio = Some(0.5); + } + changed = true; + } + if let Some(n_sides) = p.get("sides").and_then(Value::as_u64) { + *sides = (n_sides as u32).clamp(3, 1000); + changed = true; + } + if let Some(star) = p.get("isStar").and_then(Value::as_bool) { + *spoke_ratio = if star { Some(spoke_ratio.unwrap_or(0.5)) } else { None }; + changed = true; + } + if let Some(sr) = num_param(p, "spokeRatio") { + *spoke_ratio = Some(sr.clamp(0.01, 1.0)); + changed = true; + } + if let Some(rnd) = num_param(p, "rounded") { + *rounded = rnd.clamp(-10.0, 10.0); + changed = true; + } + if let Some(rand) = num_param(p, "randomized") { + *randomized = rand.clamp(-10.0, 10.0); + changed = true; + } + changed +} + +fn apply_shape_params(cs: &mut CustomShape, p: &Value, reset: bool) -> bool { + match cs { + CustomShape::Rectangle { w, h, radii, pie, arc_mode, .. } => apply_rect_params(p, reset, w.min(*h) / 2.0, radii, pie, arc_mode), + CustomShape::Ellipse { pie, arc_mode, .. } => { + let mut changed = false; + if reset { + *pie = (0.0, 360.0); + *arc_mode = shapes::EllipseMode::Whole; + changed = true; + } + changed | apply_arc_params(p, pie, arc_mode) + } + CustomShape::Polygon { sides, spoke_ratio, rounded, randomized, pie, arc_mode, .. } => { + if reset { + *pie = (0.0, 360.0); + *arc_mode = shapes::EllipseMode::Whole; + } + apply_poly_params(p, reset, sides, spoke_ratio, rounded, randomized) | apply_arc_params(p, pie, arc_mode) + } + CustomShape::Spiral { turns, divergence, inner_radius, .. } => { + let mut changed = false; + if reset { + *turns = 3.0; + *divergence = 1.0; + *inner_radius = 0.0; + changed = true; + } + if let Some(t) = num_param(p, "turns") { + *turns = t.clamp(0.01, 1024.0); + changed = true; + } + if let Some(div) = num_param(p, "divergence") { + *divergence = div.clamp(0.0, 1000.0); + changed = true; + } + if let Some(ir) = num_param(p, "innerRadius") { + *inner_radius = ir.clamp(0.0, 0.999); + changed = true; + } + changed + } + CustomShape::Box3d { angle_x, angle_y, angle_z, parallel_x, parallel_y, parallel_z, .. } => { + let mut changed = false; + if reset { + *angle_x = 30.0; + *angle_y = 30.0; + *angle_z = 0.0; + *parallel_x = false; + *parallel_y = true; + *parallel_z = false; + changed = true; + } + for (k, slot) in [("angleX", angle_x), ("angleY", angle_y), ("angleZ", angle_z)] { + if let Some(v) = num_param(p, k) { + *slot = v; + changed = true; + } + } + for (k, slot) in [("parallelX", parallel_x), ("parallelY", parallel_y), ("parallelZ", parallel_z)] { + if let Some(v) = p.get(k).and_then(Value::as_bool) { + *slot = v; + changed = true; + } + } + changed + } + } +} + +fn parse_mode(m: &str) -> shapes::EllipseMode { + match m { + "pie" | "slice" => shapes::EllipseMode::Slice, + "chord" => shapes::EllipseMode::Chord, + "arc" | "open" => shapes::EllipseMode::Arc, + _ => shapes::EllipseMode::Whole, + } +} diff --git a/crates/engine/src/cmd/addons/shapes/tests.rs b/crates/engine/src/cmd/addons/shapes/tests.rs new file mode 100644 index 0000000000..793ae6074c --- /dev/null +++ b/crates/engine/src/cmd/addons/shapes/tests.rs @@ -0,0 +1,137 @@ +use serde_json::json; +use vectorcraft_doc::{LiveShape, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, Rect, shapes}; +use vectorcraft_tools::addons::box3d::CustomShape; + +use crate::Session; + +fn new_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s +} + +#[test] +fn default_shapes_do_not_alter_standard_documents() { + let mut s = new_session(); + + // Default rectangle: standard LiveShape::Rectangle, no vc-shape-tools attribute. + let rect_id = + NodeId(s.execute("shape.rectangle", &json!({"x": 10.0, "y": 20.0, "width": 100.0, "height": 50.0})).unwrap()["id"].as_u64().unwrap()); + let n = s.doc().unwrap().doc.node(rect_id).unwrap(); + assert!(n.extras().attrs.is_none()); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live path") }; + assert_eq!( + **live, + LiveShape::Rectangle { + w: 100.0, + h: 50.0, + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::translate((10.0, 20.0)) + } + ); + assert_eq!(path, &shapes::rectangle(Rect::new(10.0, 20.0, 110.0, 70.0))); + + // Default ellipse: standard LiveShape::Ellipse, no vc-shape-tools attribute. + let ell_id = NodeId(s.execute("shape.ellipse", &json!({"x": 0.0, "y": 0.0, "width": 80.0, "height": 60.0})).unwrap()["id"].as_u64().unwrap()); + let n = s.doc().unwrap().doc.node(ell_id).unwrap(); + assert!(n.extras().attrs.is_none()); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live path") }; + assert_eq!(**live, LiveShape::Ellipse { w: 80.0, h: 60.0, pie: (0.0, 360.0), xf: Affine::IDENTITY }); + assert_eq!(path, &shapes::ellipse(Rect::new(0.0, 0.0, 80.0, 60.0))); +} + +#[test] +fn addon_shapes_commands_and_format_roundtrip_preserve_paths() { + let mut s = new_session(); + + // Create customizable shapes through addon.shapes.* commands. + let box_id = NodeId( + s.execute( + "addon.shapes.box3d", + &json!({"x": 10.0, "y": 10.0, "width": 100.0, "height": 80.0, "angleX": 30.0, "angleY": 35.0, "angleZ": 0.0}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let n = s.doc().unwrap().doc.node(box_id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") }; + assert_eq!(path.subpaths.len(), 3); + assert!( + matches!(CustomShape::read(n), Some(CustomShape::Box3d { angle_x, angle_y, .. }) if (angle_x - 30.0).abs() < 1e-6 && (angle_y - 35.0).abs() < 1e-6) + ); + + s.execute("addon.shapes.configure", &json!({"angleX": 45.0, "parallelX": true})).unwrap(); + let n = s.doc().unwrap().doc.node(box_id).unwrap(); + assert!(matches!(CustomShape::read(n), Some(CustomShape::Box3d { angle_x, parallel_x: true, .. }) if (angle_x - 45.0).abs() < 1e-6)); + + let ell_id = NodeId( + s.execute( + "addon.shapes.ellipse", + &json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 100.0, "arcMode": "arc", "startAngle": 30.0, "endAngle": 210.0}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let n = s.doc().unwrap().doc.node(ell_id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") }; + assert!(!path.subpaths[0].closed); + + s.execute("addon.shapes.configure", &json!({"arcMode": "chord"})).unwrap(); + let n = s.doc().unwrap().doc.node(ell_id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") }; + assert!(path.subpaths[0].closed); + + let rect_id = NodeId( + s.execute("addon.shapes.rectangle", &json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 80.0, "radii": [10.0, 20.0, 5.0, 0.0], "arcMode": "pie", "startAngle": 0.0, "endAngle": 180.0})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let n = s.doc().unwrap().doc.node(rect_id).unwrap(); + assert!( + matches!(CustomShape::read(n), Some(CustomShape::Rectangle { radii, arc_mode: shapes::EllipseMode::Slice, .. }) if radii == [10.0, 20.0, 5.0, 0.0]) + ); + + let poly_id = NodeId( + s.execute("addon.shapes.polygon", &json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5, "rounded": 0.25, "randomized": 0.1})).unwrap() + ["id"] + .as_u64() + .unwrap(), + ); + s.execute("addon.shapes.configure", &json!({"isStar": true, "spokeRatio": 0.4})).unwrap(); + let n = s.doc().unwrap().doc.node(poly_id).unwrap(); + assert!( + matches!(CustomShape::read(n), Some(CustomShape::Polygon { spoke_ratio: Some(sr), rounded, .. }) if (sr - 0.4).abs() < 1e-6 && (rounded - 0.25).abs() < 1e-6) + ); + + let spiral_id = NodeId( + s.execute("addon.shapes.spiral", &json!({"cx": 60.0, "cy": 60.0, "radius": 45.0, "turns": 4.0, "divergence": 1.4, "innerRadius": 0.2})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let n = s.doc().unwrap().doc.node(spiral_id).unwrap(); + assert!( + matches!(CustomShape::read(n), Some(CustomShape::Spiral { turns, divergence, .. }) if (turns - 4.0).abs() < 1e-6 && (divergence - 1.4).abs() < 1e-6) + ); + + // Verify that saving and reopening a document containing add-on shapes preserves both the + // baked PathData/LiveShape (for a build that ignores the add-on attribute) and the stored + // extras attribute across a save/load roundtrip. + let doc_before = s.doc().unwrap().doc.clone(); + let bytes = vectorcraft_format::save(&doc_before, false); + let doc_after = vectorcraft_format::load(&bytes).unwrap(); + let re_saved = vectorcraft_format::save(&doc_after, false); + assert_eq!(bytes, re_saved); + for id in [box_id, ell_id, rect_id, poly_id, spiral_id] { + let a = doc_before.node(id).unwrap(); + let b = doc_after.node(id).unwrap(); + assert_eq!(a.kind, b.kind); + assert_eq!(CustomShape::read(a), CustomShape::read(b)); + } +} diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs new file mode 100644 index 0000000000..bc1d4e4f25 --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -0,0 +1,350 @@ +//! Type Tools (`addon.type.*`), a built-in add-on: Text Tweaker gives one character attribute to +//! the selected characters letter by letter, from a start value to an end value along a shape +//! (straight, eased, a bow, a spike, or at random), while the text stays live. Values are set as +//! the Character panel sets them (`text.setRangeStyle`), in its units and ranges +//! (). Release Type on a Path +//! splits type on a path into point type holding the same text and the plain path it was set on +//! (#5532). The reference app has no command for it, so it goes beyond parity and changes no +//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_color::recolor::Rng; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, TextKind, TextObject, TextRun}; +use vectorcraft_geom::{Affine, ArcPath, Point}; +use vectorcraft_text::edit; + +use super::super::menucmds::whole_or; +use super::super::object::choice; +use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges}; +use super::super::typecmd::refresh_bounds; +use super::super::typemenu::text_ids; +use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets}; +use crate::{EngineError, Result, Session}; + +/// An attribute Text Tweaker sets: its `text.setRangeStyle` param, the values it takes and its +/// default start and end. +type Attribute = (&'static str, (f64, f64), (f64, f64)); + +/// The attributes Text Tweaker sets. +pub const ATTRIBUTES: [Attribute; 8] = [ + ("size", (0.1, 1296.0), (12.0, 36.0)), + ("baselineShift", (-1296.0, 1296.0), (0.0, 12.0)), + ("rotation", (-360.0, 360.0), (0.0, 30.0)), + ("hScale", (1.0, 10000.0), (100.0, 150.0)), + ("vScale", (1.0, 10000.0), (100.0, 150.0)), + ("tracking", (-1000.0, 10000.0), (0.0, 200.0)), + ("leading", (0.1, 5000.0), (12.0, 36.0)), + ("strokeWidth", (0.0, 1000.0), (0.0, 2.0)), +]; +/// The shapes the values follow from the first character to the last. +pub const SHAPES: [&str; 5] = ["straight", "ease", "bow", "spike", "random"]; +/// The most characters one run changes. +const MAX_CHARS: usize = 100_000; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.type.textTweaker", + "Text Tweaker", + ["Object", "Plug-ins", "Type Tools"], + None, + "{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}", + has_selection, + text_tweaker + ), + cmd!( + "addon.type.releasePath", + "Release Type on a Path…", + ["Object", "Plug-ins", "Type Tools"], + None, + "{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}", + has_selection, + release_path + ), + ] +} + +/// Release Type on a Path's command (the id in [`specs`]). +pub const RELEASE: &str = "addon.type.releasePath"; +/// What Release Type on a Path keeps: both, the path only, or the text only. +pub const RELEASE_MODES: [&str; 3] = ["both", "path", "text"]; + +/// Where along `shape` (0 at `from`, 1 at `to`) character `i` of `n` lands; `random` for the +/// random shape. +fn amount(shape: &str, i: usize, n: usize, random: f64) -> f64 { + let t = if n > 1 { i as f64 / (n - 1) as f64 } else { 0.0 }; + match shape { + "ease" => t * t * (3.0 - 2.0 * t), + "bow" => (std::f64::consts::PI * t).sin(), + "spike" => 1.0 - (2.0 * t - 1.0).abs(), + "random" => random, + _ => t, + } +} + +/// A random number from 0 to 1. +fn unit(rng: &mut Rng) -> f64 { + (rng.next_u64() >> 11) as f64 / (1u64 << 53) as f64 +} + +fn text_tweaker(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.type.textTweaker"; + let attribute = choice(p, C, "attribute", &ATTRIBUTES.map(|a| a.0))?.unwrap_or("size"); + let Some(&(key, (lo, hi), (from0, to0))) = ATTRIBUTES.iter().find(|a| a.0 == attribute) else { + return Err(bad(C, format!("unknown attribute `{attribute}`"))); + }; + let mut ends = [0.0; 2]; + for (end, (k, default)) in ends.iter_mut().zip([("from", from0), ("to", to0)]) { + let v = number_or(p, k, default, C)?; + if !(lo..=hi).contains(&v) { + return Err(bad(C, format!("`{k}` must be from {lo} to {hi} for {key}"))); + } + *end = v; + } + let [from, to] = ends; + let shape = choice(p, C, "shape", &SHAPES)?.unwrap_or("straight"); + let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); + let skip = switch_or(p, "skipSpaces", true, C)?; + let setup = s.doc()?.doc.setup.clone(); + // At a caret, all of the object's text. + let ranges = type_ranges(s, p, C, |text, _| Some((0, text.len())))?; + // Each object's changed characters: (byte, its change), worked out before the edit. + let mut plans: Vec<(NodeId, Vec<(usize, CharChange)>)> = vec![]; + let (mut seen, mut count) = (0, 0); + for (id, a, b, _) in ranges { + let t = text_ref(s, id)?; + let text = t.plain_text(); + let (a, b) = (edit::floor_char(&text, a), edit::floor_char(&text, b)); + let chars: Vec = + text.char_indices().filter(|&(i, c)| (a..b).contains(&i) && !(skip && (c.is_whitespace() || c.is_control()))).map(|(i, _)| i).collect(); + seen += chars.len(); + if seen > MAX_CHARS { + return Err(bad(C, format!("too many characters: at most {MAX_CHARS}"))); + } + // Each run's end byte, to find the style a character has now. + let ends: Vec = t + .runs + .iter() + .scan(0, |off, r| { + *off += r.text.len(); + Some(*off) + }) + .collect(); + let n = chars.len(); + let mut changes = Vec::with_capacity(n); + let mut run = 0; + for (i, at) in chars.into_iter().enumerate() { + let random = if shape == "random" { unit(&mut rng) } else { 0.0 }; + let value = from + (to - from) * amount(shape, i, n, random); + let mut change = CharChange::parse(&json!({ key: value }), C, &setup)?; + change.localize(&t, C)?; + while ends.get(run).is_some_and(|&e| e <= at) { + run += 1; + } + // A character that already has the value is left out, so a run that changes nothing + // makes no step. + if let Some(r) = t.runs.get(run) { + let mut style = r.style.clone(); + change.apply(&mut style); + if style == r.style { + continue; + } + } + changes.push((at, change)); + } + count += changes.len(); + if !changes.is_empty() { + plans.push((id, changes)); + } + } + if plans.is_empty() { + return Ok(json!({ "count": 0, "ids": [] })); + } + let ids: Vec = plans.iter().map(|(id, _)| id.0).collect(); + s.edit("Text Tweaker", |d, _| { + for (id, changes) in &plans { + let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; + t.runs = tweak(std::mem::take(&mut t.runs), changes); + refresh_bounds(t); + } + Ok(()) + })?; + Ok(json!({ "count": count, "ids": ids })) +} + +/// `runs` with each character at a byte of `changes` (in order) changed: its run split into +/// characters, the changes applied, and runs that came out alike merged again. +fn tweak(runs: Vec, changes: &[(usize, CharChange)]) -> Vec { + let mut out = Vec::with_capacity(runs.len() + changes.len() * 2); + let mut next = changes.iter().peekable(); + let mut off = 0; + for r in runs { + let end = off + r.text.len(); + if r.inline.is_some() || next.peek().is_none_or(|(at, _)| *at >= end) { + // An inline graphic is one character: its style changes whole. + if let Some((_, change)) = next.next_if(|(at, _)| (off..end).contains(at)) { + let mut r = r; + change.apply(&mut r.style); + out.push(r); + } else { + out.push(r); + } + off = end; + continue; + } + for (i, c) in r.text.char_indices() { + let mut piece = TextRun::new(c.to_string(), r.style.clone()); + if let Some((_, change)) = next.next_if(|(at, _)| *at == off + i) { + change.apply(&mut piece.style); + } + out.push(piece); + } + off = end; + } + edit::normalize(&mut out); + out +} + +/// Type on a path among the objects `p` names (or the selection), inside groups too, in stacking +/// order. An id that names no object is an error. +fn path_types(s: &Session, p: &Value) -> Result> { + let ids = targets(s, p)?; + let d = &s.doc()?.doc; + if let Some(id) = ids.iter().find(|id| d.node(**id).is_none()) { + return Err(EngineError::NoNode(*id)); + } + let on_path = |id: &NodeId| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, TextKind::OnPath { .. })); + Ok(text_ids(d, &ids).into_iter().filter(on_path).collect()) +} + +/// Where the first character laid out in `lay` starts its baseline: the pen position of the first +/// glyph in text order (a list marker, which has no characters, before the character it leads). +/// None without a glyph. +fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option { + lay.glyphs.iter().filter(|g| g.origin.x.is_finite() && g.origin.y.is_finite()).min_by_key(|g| (g.byte, g.len != 0)).map(|g| g.origin) +} + +/// `t`, type on a path, as point type on one straight line: the same runs and character and +/// paragraph attributes, its baseline starting where its first character sat on the path (in the +/// object's own text space, so its transform stays). Type on a Path Options are dropped. None for +/// other type, or when it can't be placed. +fn released_text(t: &TextObject) -> Option { + let TextKind::OnPath { path, .. } = &t.kind else { return None }; + let db = vectorcraft_text::FontDb::global(); + // Where the first character sat. Text that didn't fit on the path has no glyph there: it + // starts at the start bracket. + let at = first_pen(&vectorcraft_text::layout(db, t)).or_else(|| { + let ap = ArcPath::new(path); + let (from, _) = t.kind.path_span()?; + let (p, _) = ap.at(from * ap.len()); + (p.x.is_finite() && p.y.is_finite()).then_some(p) + })?; + let mut out = t.clone(); + out.kind = TextKind::Point; + out.path_effect = Default::default(); + out.path_align = Default::default(); + out.path_spacing = 0.0; + // Point type is in no thread: its first paragraph starts in it. + out.first_para_continues = false; + // Where the point type puts its own first character; the origin moves so it lands at `at`, + // whatever the paragraph's alignment and direction. + let own = first_pen(&vectorcraft_text::layout(db, &out)).unwrap_or(Point::ZERO); + let shift = at - own; + if !(shift.x.is_finite() && shift.y.is_finite()) { + return None; + } + out.xf *= Affine::translate(shift); + refresh_bounds(&mut out); + Some(out) +} + +/// The path `t` is set on, as a plain path object `id` in document space, with no fill and no +/// stroke: type paths carry no paint of their own. None for other type. +fn released_path(id: NodeId, t: &TextObject) -> Option { + Some(Node::path(id, t.type_path()?, Appearance::basic(Paint::None, Paint::None, 1.0))) +} + +fn release_path(s: &mut Session, p: &Value) -> Result { + const C: &str = RELEASE; + let mode = choice(p, C, "mode", &RELEASE_MODES)?.unwrap_or("both"); + let keep = switch_or(p, "keepOriginal", false, C)?; + let want_path = mode != "text"; + let ids = path_types(s, p)?; + if ids.is_empty() { + return Ok(json!({ "ids": [], "paths": [], "texts": [] })); + } + // The point type, worked out before the edit: one object that can't be placed fails the run. + let mut plans: Vec<(NodeId, Option)> = Vec::with_capacity(ids.len()); + { + let d = &s.doc()?.doc; + for id in ids { + let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { continue }; + let text = match mode { + "path" => None, + _ => Some(released_text(t).ok_or_else(|| bad(C, format!("object {} can't be set as point type", id.0)))?), + }; + plans.push((id, text)); + } + } + let (paths, texts) = s.edit("Release Type on a Path", |d, sel| { + let (mut paths, mut texts) = (vec![], vec![]); + for (id, text) in plans { + let (path, text) = release_one(d, id, text, want_path, keep)?; + paths.extend(path); + texts.extend(text); + } + sel.set(paths.iter().chain(&texts).copied()); + Ok((paths, texts)) + })?; + // Bottom to top. + let d = &s.doc()?.doc; + let mut all: Vec<(Vec, NodeId)> = paths.iter().chain(&texts).map(|id| (d.index_path(*id).unwrap_or_default(), *id)).collect(); + all.sort(); + let nums = |v: &[NodeId]| v.iter().map(|i| i.0).collect::>(); + let all: Vec = all.into_iter().map(|(_, id)| id).collect(); + Ok(json!({ "ids": nums(&all), "paths": nums(&paths), "texts": nums(&texts) })) +} + +/// Release type on a path `id` in `d`: its path (`want_path`) where the type was, or just above it +/// when the original stays (`keep`), then the point type `text` (None: no text) above that. +/// Without `keep` the original goes, and released text takes its place as the same object, so a +/// frame of threaded text leaves its thread with the text it holds, as Convert To Point Type's +/// does. The released (path, text). +fn release_one(d: &mut Document, id: NodeId, text: Option, want_path: bool, keep: bool) -> Result<(Option, Option)> { + let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?; + let original = d.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let NodeKind::Text(t) = &original.kind else { return Ok((None, None)) }; + let path = + if want_path { Some(released_path(d.alloc_id(), t).ok_or_else(|| bad(RELEASE, format!("object {} has no path", id.0)))?) } else { None }; + if !keep && text.is_none() { + d.remove(id)?; + } + // Where the next released object goes: above the original when it stays, else in its place. + let mut at = if keep { idx + 1 } else { idx }; + let path = match path { + Some(n) => { + at += 1; + Some(d.insert(parent, at - 1, n)?) + } + None => None, + }; + let text = match text { + None => None, + Some(text) if keep => { + let mut n = original.clone(); + n.id = d.alloc_id(); + n.kind = NodeKind::Text(Box::new(text)); + Some(d.insert(parent, at, n)?) + } + Some(text) => { + // The original, now just above the path. + d.node_mut(id).ok_or(EngineError::NoNode(id))?.kind = NodeKind::Text(Box::new(text)); + Some(id) + } + }; + Ok((path, text)) +} diff --git a/crates/engine/src/cmd/addons/typetools/tests.rs b/crates/engine/src/cmd/addons/typetools/tests.rs new file mode 100644 index 0000000000..e597525c97 --- /dev/null +++ b/crates/engine/src/cmd/addons/typetools/tests.rs @@ -0,0 +1,606 @@ +//! Text Tweaker: the values each shape gives each character, what it skips and changes, one undo +//! step, and bad params refused without a change. Release Type on a Path ([`release`]). + +use serde_json::json; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject}; + +use super::amount; +use crate::Session; + +const C: &str = "addon.type.textTweaker"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn text(s: &mut Session, words: &str) -> NodeId { + NodeId(s.execute("text.create", &json!({"x": 40, "y": 100, "text": words, "size": 20})).unwrap()["id"].as_u64().unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); +} + +fn obj(s: &Session, id: NodeId) -> TextObject { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +/// Each character of `id` with its style. +fn styles(s: &Session, id: NodeId) -> Vec<(char, CharStyle)> { + obj(s, id).runs.iter().flat_map(|r| r.text.chars().map(|c| (c, r.style.clone())).collect::>()).collect() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn near(a: &[f64], b: &[f64]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) +} + +#[test] +fn the_shapes_run_from_the_start_value_to_the_end_value() { + let at = |shape, n| (0..n).map(|i| amount(shape, i, n, 0.5)).collect::>(); + assert!(near(&at("straight", 5), &[0.0, 0.25, 0.5, 0.75, 1.0])); + assert!(near(&at("ease", 5), &[0.0, 0.15625, 0.5, 0.84375, 1.0]), "slow at both ends"); + let bow = at("bow", 5); + assert!(near(&[bow[0], bow[2], bow[4]], &[0.0, 1.0, 0.0]) && (bow[1] - 0.5f64.sqrt()).abs() < 1e-9, "a smooth arc"); + assert!(near(&at("spike", 5), &[0.0, 0.5, 1.0, 0.5, 0.0]), "straight up and down"); + assert!(near(&at("random", 3), &[0.5; 3])); + assert!(near(&at("straight", 1), &[0.0]), "one character takes the start value"); +} + +#[test] +fn a_straight_ramp_sizes_each_letter_and_skips_spaces() { + let mut s = session(); + let id = text(&mut s, "ab cd"); + select(&mut s, &[id]); + let n = steps(&s); + let out = s.execute(C, &json!({"attribute": "size", "from": 10, "to": 40})).unwrap(); + // `b` is 20 pt already: three characters change. + assert_eq!(out, json!({"count": 3, "ids": [id.0]})); + assert_eq!(steps(&s), n + 1, "one undo step"); + let sizes: Vec<(char, f64)> = styles(&s, id).into_iter().map(|(c, st)| (c, st.size)).collect(); + assert_eq!(sizes, [('a', 10.0), ('b', 20.0), (' ', 20.0), ('c', 30.0), ('d', 40.0)], "the space keeps its size"); + assert_eq!(obj(&s, id).plain_text(), "ab cd", "the text stays live"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(styles(&s, id).iter().all(|(_, st)| st.size == 20.0), "undone"); +} + +#[test] +fn spaces_can_count_too() { + let mut s = session(); + let id = text(&mut s, "a b"); + select(&mut s, &[id]); + s.execute(C, &json!({"attribute": "baselineShift", "from": 0, "to": 10, "skipSpaces": false})).unwrap(); + let shifts: Vec = styles(&s, id).iter().map(|(_, st)| st.baseline_shift).collect(); + assert_eq!(shifts, [0.0, 5.0, 10.0]); +} + +#[test] +fn every_attribute_is_set_as_the_character_panel_sets_it() { + let mut s = session(); + for (attribute, get) in [ + ("size", (|st: &CharStyle| st.size) as fn(&CharStyle) -> f64), + ("baselineShift", |st| st.baseline_shift), + ("rotation", |st| st.rotation), + ("hScale", |st| st.h_scale), + ("vScale", |st| st.v_scale), + ("tracking", |st| st.tracking), + ("leading", |st| st.leading.unwrap_or(-1.0)), + ("strokeWidth", |st| st.stroke_width), + ] { + let id = text(&mut s, "xyz"); + select(&mut s, &[id]); + s.execute(C, &json!({"attribute": attribute, "from": 2, "to": 6})).unwrap(); + let got: Vec = styles(&s, id).iter().map(|(_, st)| get(st)).collect(); + assert!(near(&got, &[2.0, 4.0, 6.0]), "{attribute}: {got:?}"); + } +} + +#[test] +fn each_object_gets_its_own_ramp() { + let mut s = session(); + let (a, b) = (text(&mut s, "abc"), text(&mut s, "de")); + select(&mut s, &[a, b]); + let out = s.execute(C, &json!({"attribute": "rotation", "from": 0, "to": 30})).unwrap(); + // Each first character is upright already. + assert_eq!(out["count"], json!(3)); + let turns = |id| styles(&s, id).iter().map(|(_, st)| st.rotation).collect::>(); + assert_eq!((turns(a), turns(b)), (vec![0.0, 15.0, 30.0], vec![0.0, 30.0])); +} + +#[test] +fn a_range_changes_only_its_characters() { + let mut s = session(); + let id = text(&mut s, "abcde"); + s.execute(C, &json!({"id": id.0, "start": 1, "end": 4, "attribute": "tracking", "from": 100, "to": 300})).unwrap(); + let tracking: Vec = styles(&s, id).iter().map(|(_, st)| st.tracking).collect(); + assert_eq!(tracking, [0.0, 100.0, 200.0, 300.0, 0.0]); +} + +#[test] +fn a_range_inside_a_multibyte_character_uses_character_boundaries() { + let mut s = session(); + let id = text(&mut s, "éx"); + let out = s.execute(C, &json!({"id": id.0, "start": 1, "end": 2, "attribute": "tracking", "from": 100, "to": 300})).unwrap(); + assert_eq!(out["count"], 1); + let tracking: Vec = styles(&s, id).iter().map(|(_, st)| st.tracking).collect(); + assert_eq!(tracking, [100.0, 0.0]); +} + +#[test] +fn random_values_stay_in_range_and_repeat_with_the_seed() { + let mut s = session(); + let id = text(&mut s, "randomness"); + select(&mut s, &[id]); + let run = |s: &mut Session, seed| { + s.execute(C, &json!({"attribute": "vScale", "from": 50, "to": 150, "shape": "random", "seed": seed})).unwrap(); + styles(s, id).iter().map(|(_, st)| st.v_scale).collect::>() + }; + let first = run(&mut s, 7); + assert!(first.iter().all(|v| (50.0..=150.0).contains(v)), "{first:?}"); + assert!(first.windows(2).any(|w| w[0] != w[1]), "values vary"); + assert_eq!(run(&mut s, 7), first, "same seed, same values"); + assert_ne!(run(&mut s, 8), first, "another seed, other values"); +} + +#[test] +fn values_follow_the_text_transform_as_the_character_panel_does() { + let mut s = session(); + let id = text(&mut s, "ab"); + select(&mut s, &[id]); + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + s.execute(C, &json!({"attribute": "size", "from": 20, "to": 40})).unwrap(); + let sizes: Vec = styles(&s, id).iter().map(|(_, st)| st.size).collect(); + // Shown sizes are the asked ones: stored sizes are half, the text being scaled twice. + let scale = obj(&s, id).style_scale().unwrap().points; + assert!(near(&sizes.iter().map(|v| v * scale).collect::>(), &[20.0, 40.0]), "{sizes:?} at {scale}"); +} + +#[test] +fn empty_text_and_only_spaces_change_nothing() { + let mut s = session(); + let id = text(&mut s, " "); + select(&mut s, &[id]); + let n = steps(&s); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"count": 0, "ids": []})); + assert_eq!(steps(&s), n, "no step"); +} + +#[test] +fn characters_that_already_have_the_value_are_left_out() { + let mut s = session(); + let id = text(&mut s, "abc"); + select(&mut s, &[id]); + let p = json!({"attribute": "rotation", "from": 0, "to": 30}); + // The first character already has 0°. + assert_eq!(s.execute(C, &p).unwrap(), json!({"count": 2, "ids": [id.0]})); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + assert_eq!(s.execute(C, &p).unwrap(), json!({"count": 0, "ids": []}), "again: nothing to change"); + assert_eq!((s.doc().unwrap().doc.clone(), steps(&s)), (before, n), "no step"); +} + +#[test] +fn bad_params_are_refused_without_a_change() { + let mut s = session(); + let id = text(&mut s, "abc"); + select(&mut s, &[id]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + for p in [ + json!({"attribute": "colour"}), + json!({"attribute": 3}), + json!({"shape": "zigzag"}), + json!({"attribute": "size", "from": 0}), + json!({"attribute": "size", "to": 5000}), + json!({"attribute": "hScale", "from": -1}), + json!({"from": "big"}), + json!({"to": f64::MAX}), + json!({"seed": -1}), + json!({"skipSpaces": "yes"}), + json!({"ids": [999_999]}), + json!({"id": id.0, "start": -1}), + json!({"id": id.0, "start": 1, "end": 1.5}), + json!({"id": id.0, "end": "2"}), + ] { + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().doc, before, "{p}"); + assert_eq!(steps(&s), n, "{p}"); + } +} + +#[test] +fn it_needs_a_selection() { + let mut s = session(); + text(&mut s, "abc"); + select(&mut s, &[]); + assert!(s.execute(C, &json!({})).is_err()); +} + +/// Release Type on a Path (#5532): each mode, Keep Original, mixed and empty selections, closed, +/// open, curved and flipped paths, transformed and grouped type, multi-style and unicode text, +/// undo and redo, the preview a dialog shows, and bad params. +mod release { + use serde_json::{Value, json}; + use vectorcraft_color::Paint; + use vectorcraft_doc::{Appearance, Document, Justify, NodeId, NodeKind, TextKind, TextObject}; + use vectorcraft_geom::{PathData, Point}; + + use crate::Session; + + const C: &str = "addon.type.releasePath"; + + fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s + } + + fn new_id(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) + } + + /// 12 pt type `words` on a path along `d` (SVG path data), starting where the path is nearest + /// `at`, selected. + fn path_type(s: &mut Session, d: &str, at: [f64; 2], words: &str) -> NodeId { + let pid = s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let id = new_id(&s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": words, "size": 12, "at": at})).unwrap()); + select(s, &[id]); + id + } + + fn rect(s: &mut Session, x: f64) -> NodeId { + new_id(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 20, "height": 20})).unwrap()) + } + + fn point_type(s: &mut Session) -> NodeId { + new_id(&s.execute("text.create", &json!({"x": 40, "y": 500, "text": "point", "size": 12})).unwrap()) + } + + fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); + } + + fn doc(s: &Session) -> Document { + (*s.doc().unwrap().doc).clone() + } + + fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() + } + + fn selected(s: &Session) -> Vec { + s.doc().unwrap().selection.objects.clone() + } + + fn text(s: &Session, id: NodeId) -> TextObject { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + k => panic!("not text: {k:?}"), + } + } + + fn path(s: &Session, id: NodeId) -> PathData { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { path, .. } => path.clone(), + k => panic!("not a path: {k:?}"), + } + } + + /// (parent, index) of `id`. + fn place(s: &Session, id: NodeId) -> (Option, usize) { + let (parent, idx, _) = s.doc().unwrap().doc.position(id).unwrap(); + (parent, idx) + } + + /// Each glyph's pen position in the document and its baseline angle, in text order. + fn pens(t: &TextObject) -> Vec<(Point, f64)> { + let mut g: Vec<_> = + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.into_iter().map(|g| (g.byte, t.xf * g.origin, g.angle)).collect(); + g.sort_by_key(|g| g.0); + g.into_iter().map(|(_, p, a)| (p, a)).collect() + } + + /// How many path objects the document has. + fn paths_in(s: &Session) -> usize { + let mut n = 0; + for l in &s.doc().unwrap().doc.layers { + l.walk(&mut |c| n += usize::from(matches!(c.kind, NodeKind::Path { .. }))); + } + n + } + + fn close(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-4 + } + + fn ids(v: &Value, key: &str) -> Vec { + v[key].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() + } + + /// `after`, released from `before`: point type with the same text and attributes, on one + /// straight line whose first character starts where `before`'s did on its path, with no Type + /// on a Path Options left. + fn assert_released(before: &TextObject, after: &TextObject) { + assert_eq!(after.kind, TextKind::Point); + assert_eq!(after.runs, before.runs, "the same text and character attributes"); + assert_eq!((&after.para, &after.paras), (&before.para, &before.paras), "the same paragraph attributes"); + assert_eq!(after.plain_text(), before.plain_text()); + assert_eq!((after.path_effect, after.path_align, after.path_spacing), Default::default(), "path options dropped"); + let (was, now) = (pens(before), pens(after)); + assert!(!now.is_empty()); + if let Some((first, _)) = was.first() { + assert!(close(now[0].0, *first), "the baseline starts where the first character sat: {:?} vs {first:?}", now[0].0); + } + assert!(now.iter().all(|(_, a)| *a == 0.0), "a straight baseline"); + // On one line through the first pen, along the object's own x axis. + let [a, b, ..] = after.xf.as_coeffs(); + let axis = vectorcraft_geom::Vec2::new(a, b); + for (p, _) in &now { + let off = *p - now[0].0; + assert!(off.cross(axis).abs() < 1e-4 * axis.hypot().max(1.0) * off.hypot().max(1.0), "{p:?} is on the line"); + } + } + + #[test] + fn both_gives_point_type_and_the_path_in_the_types_place() { + let mut s = session(); + let below = rect(&mut s, 10.0); + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], "Curved line"); + let above = rect(&mut s, 50.0); + select(&mut s, &[id]); + let before = text(&s, id); + let (layer, idx) = place(&s, id); + let (start, n) = (doc(&s), steps(&s)); + + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + let (paths, texts) = (ids(&out, "paths"), ids(&out, "texts")); + assert_eq!((paths.len(), texts.len()), (1, 1)); + let (p, t) = (paths[0], texts[0]); + assert_eq!(ids(&out, "ids"), [p, t], "bottom to top"); + assert_eq!(selected(&s), [p, t], "the released objects are selected"); + + // The path: its exact shape, anchors and handles, with no fill and no stroke, where the type was. + assert_eq!(path(&s, p), before.type_path().unwrap()); + assert_eq!(*s.doc().unwrap().doc.node(p).unwrap().appearance, Appearance::basic(Paint::None, Paint::None, 1.0)); + assert_eq!( + (place(&s, below), place(&s, p), place(&s, t), place(&s, above)), + ((layer, idx - 1), (layer, idx), (layer, idx + 1), (layer, idx + 2)) + ); + // The text replaces the type on a path. + assert_released(&before, &text(&s, t)); + assert_eq!(t, id, "the same type object, now point type"); + + let released = doc(&s); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc(&s), start, "undone"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(doc(&s), released, "redone"); + } + + #[test] + fn path_only_and_text_only() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [300.0, 300.0], "Line"); + let before = text(&s, id); + let (layer, idx) = place(&s, id); + let out = s.execute(C, &json!({"mode": "path"})).unwrap(); + let p = ids(&out, "paths")[0]; + assert!(ids(&out, "texts").is_empty()); + assert!(s.doc().unwrap().doc.node(id).is_none(), "the type is gone"); + assert_eq!((path(&s, p), place(&s, p)), (before.type_path().unwrap(), (layer, idx))); + assert_eq!(selected(&s), [p]); + + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[id]); + let out = s.execute(C, &json!({"mode": "text"})).unwrap(); + assert!(ids(&out, "paths").is_empty()); + assert_eq!((ids(&out, "texts"), place(&s, id)), (vec![id], (layer, idx)), "the type stays in its place"); + assert_released(&before, &text(&s, id)); + assert_eq!(paths_in(&s), 0, "no path made"); + } + + #[test] + fn keep_original_adds_the_released_objects_above_it() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Keep"); + let (before, (layer, idx)) = (text(&s, id), place(&s, id)); + let original = s.doc().unwrap().doc.node(id).cloned().unwrap(); + let out = s.execute(C, &json!({"keepOriginal": true})).unwrap(); + let (p, t) = (ids(&out, "paths")[0], ids(&out, "texts")[0]); + assert_eq!(s.doc().unwrap().doc.node(id), Some(&original), "the type on a path stays as it is"); + assert_eq!((place(&s, id), place(&s, p), place(&s, t)), ((layer, idx), (layer, idx + 1), (layer, idx + 2))); + assert_ne!(t, id); + assert_eq!(selected(&s), [p, t], "only the released objects are selected"); + assert_released(&before, &text(&s, t)); + + // Text only, kept: the copy goes just above. + select(&mut s, &[id]); + let out = s.execute(C, &json!({"mode": "text", "keepOriginal": true})).unwrap(); + let t2 = ids(&out, "texts")[0]; + assert_eq!(place(&s, t2), (layer, idx + 1)); + assert_released(&before, &text(&s, t2)); + } + + #[test] + fn other_objects_are_left_alone() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let pt = point_type(&mut s); + let a = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "One"); + let b = path_type(&mut s, "M100 400 L500 400", [100.0, 400.0], "Two"); + let others = [r, pt].map(|id| s.doc().unwrap().doc.node(id).cloned().unwrap()); + select(&mut s, &[r, pt, a, b]); + let n = steps(&s); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step for the whole selection"); + assert_eq!((ids(&out, "paths").len(), ids(&out, "texts")), (2, vec![a, b])); + assert_eq!([r, pt].map(|id| s.doc().unwrap().doc.node(id).cloned().unwrap()), others); + assert_eq!(selected(&s).len(), 4, "the two paths and the two texts"); + assert!(!selected(&s).contains(&r) && !selected(&s).contains(&pt)); + + // `ids` picks the objects instead of the selection. + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[r]); + let out = s.execute(C, &json!({"ids": [r.0, b.0]})).unwrap(); + assert_eq!(ids(&out, "texts"), [b]); + assert!(matches!(text(&s, a).kind, TextKind::OnPath { .. })); + } + + #[test] + fn nothing_to_release_changes_nothing() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let pt = point_type(&mut s); + select(&mut s, &[r, pt]); + let (before, n, sel) = (doc(&s), steps(&s), selected(&s)); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"ids": [], "paths": [], "texts": []})); + assert_eq!((doc(&s), steps(&s), selected(&s)), (before, n, sel), "no change, no step"); + } + + #[test] + fn closed_and_open_paths_keep_their_shape() { + for (d, closed) in [ + ("M200 200 L400 200 L400 400 L200 400 Z", true), + ("M100 300 C150 100 250 500 300 300 S450 100 500 300", false), + ("M300 150 C380 150 450 220 450 300 C450 380 380 450 300 450 C220 450 150 380 150 300 C150 220 220 150 300 150 Z", true), + ] { + let mut s = session(); + let id = path_type(&mut s, d, [200.0, 200.0], "Round and round"); + let before = text(&s, id); + let out = s.execute(C, &json!({})).unwrap(); + let p = path(&s, ids(&out, "paths")[0]); + assert_eq!(p, before.type_path().unwrap(), "{d}"); + assert_eq!(p.is_closed(), closed, "{d}"); + assert_released(&before, &text(&s, ids(&out, "texts")[0])); + } + } + + #[test] + fn flipped_type_releases_its_path_as_it_runs() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [300.0, 200.0], "Flipped"); + s.execute("type.pathOptions", &json!({"flip": true, "effect": "skew", "alignToPath": "center", "spacing": 4})).unwrap(); + let before = text(&s, id); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(path(&s, ids(&out, "paths")[0]), before.type_path().unwrap()); + assert_released(&before, &text(&s, id)); + } + + #[test] + fn transformed_type_keeps_its_transform() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], "Turned"); + s.execute("object.rotate", &json!({"angle": 30, "origin": [300, 300]})).unwrap(); + s.execute("object.scale", &json!({"sx": 150, "sy": 150, "origin": [300, 300]})).unwrap(); + let before = text(&s, id); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(path(&s, ids(&out, "paths")[0]), before.type_path().unwrap(), "the transform is in the path"); + let after = text(&s, id); + assert_eq!(after.xf.as_coeffs()[..4], before.xf.as_coeffs()[..4], "turned and scaled as the type was"); + assert_released(&before, &after); + } + + #[test] + fn grouped_type_releases_inside_its_group() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Grouped"); + select(&mut s, &[r, id]); + s.execute("object.group", &json!({})).unwrap(); + let g = place(&s, id).0.unwrap(); + assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Group { .. })); + select(&mut s, &[g]); + let out = s.execute(C, &json!({})).unwrap(); + let (p, t) = (ids(&out, "paths")[0], ids(&out, "texts")[0]); + assert_eq!((place(&s, p).0, place(&s, t).0), (Some(g), Some(g))); + } + + #[test] + fn styles_and_unicode_text_survive() { + let mut s = session(); + let words = "Größe ✓ 日本語 éa"; + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], words); + // "Gr" (bytes 0..2), and "日本" (bytes 12..18, after "Größe ✓ "). + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 2, "size": 24, "fill": "#ff0000"})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 12, "end": 18, "tracking": 200, "hScale": 150})).unwrap(); + // A centred paragraph: the first character still starts where it sat. + s.edit("centre", |d, _| { + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + t.para.justify = Justify::Center; + } + Ok(()) + }) + .unwrap(); + let before = text(&s, id); + assert!(before.runs.len() >= 3, "several styles: {:?}", before.runs); + let out = s.execute(C, &json!({})).unwrap(); + let after = text(&s, ids(&out, "texts")[0]); + assert_eq!(after.plain_text(), words); + assert_released(&before, &after); + } + + #[test] + fn empty_type_starts_at_its_start_bracket() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [300.0, 300.0], ""); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(ids(&out, "texts"), [id]); + let t = text(&s, id); + assert_eq!(t.kind, TextKind::Point); + assert!(close(t.xf * Point::ZERO, Point::new(300.0, 300.0)), "{:?}", t.xf * Point::ZERO); + } + + /// What a dialog's Preview does: each preview replaces the last, Cancel puts the type back with + /// no step of history, and OK keeps the preview as one step. + #[test] + fn previews_cancel_and_commit() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Preview"); + let (start, n, sel) = (doc(&s), steps(&s), selected(&s)); + let count = paths_in; + s.begin_interaction("Release Type on a Path").unwrap(); + s.preview(C, &json!({"mode": "both"})).unwrap(); + assert_eq!((count(&s), text(&s, id).kind), (1, TextKind::Point)); + s.preview(C, &json!({"mode": "text"})).unwrap(); + assert_eq!(count(&s), 0, "the next preview replaces the last"); + s.preview(C, &json!({"mode": "path", "keepOriginal": true})).unwrap(); + assert_eq!(count(&s), 1); + assert!(matches!(text(&s, id).kind, TextKind::OnPath { .. })); + s.cancel_interaction().unwrap(); + assert_eq!((doc(&s), steps(&s), selected(&s)), (start.clone(), n, sel), "Cancel: as it was, no step"); + + s.begin_interaction("Release Type on a Path").unwrap(); + s.preview(C, &json!({"mode": "both"})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(steps(&s), n + 1, "OK: one step"); + assert_eq!(text(&s, id).kind, TextKind::Point); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc(&s), start); + } + + #[test] + fn bad_params_are_refused_without_a_change() { + let mut s = session(); + path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Bad"); + let (before, n) = (doc(&s), steps(&s)); + for p in [ + json!({"mode": "all"}), + json!({"mode": 1}), + json!({"keepOriginal": "yes"}), + json!({"ids": [999_999]}), + json!({"ids": "1"}), + json!({"id": -1}), + json!({"colour": "red"}), + ] { + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!((doc(&s), steps(&s)), (before.clone(), n), "{p}"); + } + } +} diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 9eee69d27e..be452f6c6d 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -19,13 +19,15 @@ //! shape that a Convert to Shape or Outline Object effect on them gives them, below or above the //! image as its Contents row says; new ones go right below that row. +use std::sync::Arc; + use 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; -use super::edit::{outermost, selected_roots}; +use super::edit::{outermost, roots_of, selected_roots}; use super::opacitymask::percent; use super::paint::paint_from; use super::{AppearanceAttrs, EyedropperAttrs, FillAttrs, StrokeAttrs}; @@ -35,6 +37,7 @@ use super::{ }; use crate::EngineError; +/// The Appearance panel's commands: fills and strokes, their order and copies, and the active item. pub fn specs() -> Vec { vec![ cmd!( @@ -42,7 +45,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row (a copy of its top fill; type without one: its characters' fill; else the default fill)", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, |s, p| add_item(s, p, true) ), @@ -51,7 +54,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], Some("Cmd+Alt+/"), - "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row (a copy of its top stroke, else the default stroke)", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, |s, p| add_item(s, p, false) ), @@ -60,7 +63,7 @@ pub fn specs() -> Vec { "Clear Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode", + "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md)", has_doc, clear_appearance ), @@ -69,7 +72,7 @@ pub fn specs() -> Vec { "Reduce to Basic Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} keep only the topmost visible fill and stroke, without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects", + "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, reduce_basic ), @@ -78,7 +81,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), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack", + "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, set_item ), @@ -87,7 +90,7 @@ pub fn specs() -> Vec { "Remove Item", [], None, - "{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack", + "{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, remove_item ), @@ -105,7 +108,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; 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", + "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)", has_doc, duplicate_item ), @@ -114,7 +117,7 @@ pub fn specs() -> Vec { "Reorder Appearance Item", [], None, - "{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}", + "{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {index: where the item landed | contents: the row's slot}", has_doc, move_item ), @@ -123,7 +126,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead; `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art) → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's solid fill and stroke for this instance only, as the Eyedropper Options allow, and a sampled gradient or pattern, a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}", has_doc, copy_from ), @@ -141,7 +144,7 @@ pub fn specs() -> Vec { "Show All Hidden Attributes", ["Window", "Appearance"], None, - "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden → {ids}", + "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}", has_doc, show_all_hidden ), @@ -159,7 +162,7 @@ pub fn specs() -> Vec { "Move Appearance", [], None, - "{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds → {source, target}", + "{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {source, target}", has_doc, transfer ), @@ -175,6 +178,23 @@ pub(crate) struct ActiveItem { } impl Session { + /// The method returns explicit target parameters and the selected appearance effect list. + pub fn appearance_effect_target(&self, params: &Value) -> Option<(Value, &[vectorcraft_doc::Effect])> { + let mut ids = appearance_targets(self, params).ok()?; + let item = item_target(self, params, "effect.apply").ok()?; + let anchor = item.anchor(self, &ids); + let node = self.active()?.doc.node(*ids.get(anchor)?)?; + let at = item.effects_item(&node.appearance, "effect.apply").ok()?; + let effects = node.appearance.effects_at(at)?; + ids.swap(0, anchor); + let ids: Vec = ids.into_iter().map(|id| id.0).collect(); + let aligned = match item { + ItemTarget::Item { aligned, .. } => aligned, + ItemTarget::Top => aligned(params, "effect.apply").ok()?, + }; + Some((json!({"ids": ids, "item": at, "aligned": aligned}), effects.as_slice())) + } + /// The Appearance panel's active fill/stroke: a paint-order index into the first selected /// object's stack, while the selection it was chosen for is unchanged. pub fn appearance_item(&self) -> Option { @@ -221,11 +241,12 @@ pub(crate) fn item_target(s: &Session, p: &Value, cmd: &str) -> Result Result { + let aligned = aligned(p, cmd)?; match p.get(key) { Some(Value::Null) => Ok(ItemTarget::Top), Some(v) => v .as_u64() - .map(|i| ItemTarget::Item { index: index(i), explicit: true, aligned: aligned(p) }) + .map(|i| ItemTarget::Item { index: index(i), explicit: true, aligned }) .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), @@ -253,17 +274,38 @@ impl ItemTarget { if fits == Some(true) { self } else { ItemTarget::Top } } - /// This target for each of `ids` in `d` (in their order): an aligned item (a row of the first - /// target's stack) is, in each other target, the item equal to it there (see - /// [`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> { + /// This target for each of `ids` (in their order): an aligned item (a row of the first + /// target's stack, or for the active item of the first selected object's, see + /// [`ItemTarget::anchor`]) is, in each other target, the item equal to it there (see + /// [`SharedStack`]), each target matched against that stack on its own, whatever the other + /// targets have. In a target without an equal item, and for any other target, the row stands + /// for itself. Every entry is `Some`. + pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec> { let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] }; - let Some(shared) = shared_stack(d, ids) else { return vec![Some(self); ids.len()] }; - if !shared.has_item(index) { - return vec![Some(self); ids.len()]; - } - (0..ids.len()).map(|k| shared.item_in(index, k).map(|index| ItemTarget::Item { index, explicit, aligned: true })).collect() + let Some(st) = s.active().filter(|_| ids.len() >= 2) else { return vec![Some(self); ids.len()] }; + let k = self.anchor(s, ids); + let Some(first) = ids.get(k).and_then(|id| st.doc.node(*id)) else { return vec![Some(self); ids.len()] }; + ids.iter() + .enumerate() + .map(|(j, id)| match st.doc.node(*id) { + Some(n) if j != k => { + let at = SharedStack::of(&[&*first.appearance, &*n.appearance]).item_in(index, 1); + Some(at.map_or(self, |index| ItemTarget::Item { index, explicit, aligned: true })) + } + _ => Some(self), + }) + .collect() + } + + /// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of + /// is: the first selected object (or the compound path holding it) for the active item, which + /// need not paint first; the first target otherwise, or when that object is not among them. + pub(crate) fn anchor(self, s: &Session, ids: &[NodeId]) -> usize { + let ItemTarget::Item { explicit: false, .. } = self else { return 0 }; + let Some(st) = s.active() else { return 0 }; + let Some(first) = st.selection.subjects().first() else { return 0 }; + let root = roots_of(&st.doc, vec![*first]).first().copied().unwrap_or(*first); + ids.iter().position(|id| *id == root).unwrap_or(0) } /// The item of `ap` a fill (`fill`) or stroke edit changes; `None` = the topmost one. @@ -296,8 +338,8 @@ impl ItemTarget { /// 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) +pub(crate) fn aligned(p: &Value, cmd: &str) -> Result { + switch_or(p, "aligned", false, cmd) } /// What the appearances of `ids` share, when there are several of them and they all exist. @@ -318,11 +360,23 @@ pub(crate) fn appearances_differ(d: &vectorcraft_doc::Document, ids: &[NodeId]) /// 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. +/// index and each target on its own: an index a target doesn't share with the first is left out +/// of that target (never taken as the same index there), whatever the other targets have. 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(), + let aps: Option> = ids.iter().map(|id| d.node(*id).map(|n| &*n.appearance)).collect(); + match aps.filter(|aps| aligned && aps.len() >= 2) { + Some(aps) => aps + .iter() + .enumerate() + .map(|(k, ap)| match aps.first() { + Some(first) if k > 0 => { + let sh = SharedStack::of(&[*first, *ap]); + idx.iter().filter_map(|i| sh.item_in(*i, 1)).collect() + } + _ => idx.to_vec(), + }) + .collect(), None => vec![idx.to_vec(); ids.len()], } } @@ -405,7 +459,7 @@ pub(crate) fn edit_items_then( return Ok(()); } let before = s.doc()?.doc.clone(); - let per = item.per_target(&before, ids); + let per = item.per_target(s, ids); super::overprint::edit_counted(s, label, |d| { let mut edited = Vec::new(); for (id, item) in ids.iter().zip(&per) { @@ -427,7 +481,7 @@ pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_ } /// Whether an edit aimed at `item` changes a stroke: the `stroke` param, else the kind of the -/// targeted item (on the first target object), else `default`. A `stroke` other than true, false or +/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`]), else `default`. A `stroke` other than true, false or /// null is an error of command `cmd`. pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool, cmd: &str) -> Result { check_switches(p, &["stroke"], cmd)?; @@ -437,7 +491,7 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo let ItemTarget::Item { index, .. } = item else { return Ok(default) }; let ids = appearance_targets(s, p)?; let d = &s.doc()?.doc; - Ok(ids.first().and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill())) + Ok(ids.get(item.anchor(s, &ids)).and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill())) } /// The whole number of 0 or more that `key` holds, read with [`index`]. @@ -468,14 +522,54 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result { fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?; let defaults = s.paint.clone(); + // The panel's active Fill row, when the new fill goes on the selection: the new fill takes that + // row's paint, right above it in each target that has it (others take their top fill's paint). // Where the new item went in on the active item's object, when it is an image. let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied()); + // The active row is a row of the active object's stack, which need not come first in `ids` + // (they are in paint order): match the others against it. + let anchor = active.and_then(|a| ids.iter().position(|id| *id == a)); + let selected = match (s.appearance_item(), anchor) { + (Some(index), Some(_)) if fill && p.get("ids").is_none() && p.get("id").is_none() && !targets_contents(p)? => { + ItemTarget::Item { index, explicit: false, aligned: true }.of_kind(s, true) + } + _ => ItemTarget::Top, + }; + let per: Vec> = match (selected, anchor) { + (ItemTarget::Item { index, .. }, Some(k)) => { + let mut order = ids.clone(); + order.swap(0, k); + let mut per: Vec> = + items_per_target(&s.doc()?.doc, &order, &[index], true).into_iter().map(|v| v.first().copied()).collect(); + per.swap(0, k); + per + } + _ => vec![None; ids.len()], + }; + let before = s.doc()?.doc.clone(); let mut inserted = None; + // Where the new fill went in on the active item's object, when it went above the active row. + let mut above = None; s.edit(if fill { "Add New Fill" } else { "Add New Stroke" }, |d, _| { - for id in &ids { + // The objects that got a new topmost row of the kind: the series stores its paint even when the object showed it. + let mut added = Vec::new(); + for (id, row) in ids.iter().zip(&per) { if let Some(n) = d.node_mut(*id) { - // A copy of the top fill (stroke); without one, type's characters' and otherwise the - // default paint, so a new fill on a group or type shows. + if let Some(i) = n.appearance.item_of_kind(*row, true) + && let Some(paint) = n.appearance.paint_at(Some(i), true).cloned() + { + n.appearance.insert_item(i + 1, AppearanceItem::Fill(FillLayer::new(paint))); + if let Some(kind) = top_row_kind(&n.appearance, i + 1) { + added.push((*id, kind)); + } + if active == Some(*id) { + above = Some(i + 1); + } + continue; + } + // The top fill's (stroke's) paint; without one, type's characters' and otherwise the + // default paint, so a new fill on a group or type shows. A new stroke takes the top + // stroke's weight when that stroke has paint, at least 1 pt. let paint = match (n.appearance.paint_at(None, fill), &n.kind) { (Some(p), _) => p.clone(), (None, NodeKind::Text(_)) => super::paint::proxy_paint(n, !fill, None), @@ -502,13 +596,22 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { } } else { n.appearance.items.push(item); + added.push((*id, fill)); + } + if !fill { + super::object::snap_if_aligned(n); } } } + super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); + let mut rows = top_paint_changed(&before, d, &ids); + rows.extend(painted_rows(d, added)); + super::graph::capture_series_top_paints(d, &rows); Ok(()) })?; - // The rows above the new item move up by one. - s.remap_appearance_item(&ids, |a| Some(a + usize::from(inserted.is_some_and(|k| k <= a)))); + // A fill added above the active row becomes the active row; otherwise the rows above the new + // item move up by one. + s.remap_appearance_item(&ids, |a| above.or(Some(a + usize::from(inserted.is_some_and(|k| k <= a))))); ok() } @@ -520,14 +623,99 @@ fn clear_appearance(s: &mut Session, p: &Value) -> Result { for id in &ids { if let Some(n) = d.node_mut(*id) { clear(n); + super::object::snap_if_aligned(n); } } - Ok(count_changed(d, &before, &ids)) + let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids)); + let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); + let object = super::graph::capture_series_object_opacity(d, &ids); + Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || object)) })?; s.active_appearance_item = None; ok() } +/// Each of `ids` whose object opacity or blend mode is another in `d` than in `before`, for +/// [`super::graph::capture_series_object_opacity`]. +fn object_opacity_changed(before: &vectorcraft_doc::Document, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec { + let of = |d: &vectorcraft_doc::Document, id: NodeId| d.node(id).map(|n| (n.opacity, n.blend)); + ids.iter().copied().filter(|id| of(before, *id) != of(d, *id)).collect() +} + +/// Each of `ids` with both kinds of row (fill, then stroke), for [`super::graph::capture_series_opacity`] after an +/// edit that replaces whole stacks. +fn both_kinds(ids: &[NodeId]) -> Vec<(NodeId, bool)> { + ids.iter().flat_map(|id| [(*id, true), (*id, false)]).collect() +} + +/// Each of `ids` with each kind of row (fill `true`, stroke `false`) whose topmost visible row has another opacity or blend +/// mode in `d` than in `before` (no row counts as opaque and Normal), for [`super::graph::capture_series_opacity`]. +fn top_opacity_changed(before: &vectorcraft_doc::Document, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<(NodeId, bool)> { + let top = |d: &vectorcraft_doc::Document, id: NodeId, fill: bool| { + d.node(id) + .and_then(|n| n.appearance.items.iter().rev().find(|it| it.is_fill() == fill && it.visible()).map(|it| (it.opacity(), it.blend()))) + .unwrap_or((1.0, BlendMode::Normal)) + }; + ids.iter().flat_map(|id| [(*id, true), (*id, false)]).filter(|(id, fill)| top(before, *id, *fill) != top(d, *id, *fill)).collect() +} + +/// Each of `ids` with each kind of row (fill `true`, stroke `false`) whose topmost visible row has another paint, or a +/// stroke another weight, in `d` than in `before` (no row counts as no paint), for +/// [`super::graph::capture_series_top_paints`]. +fn top_paint_changed(before: &vectorcraft_doc::Document, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<(NodeId, bool)> { + let top = |d: &vectorcraft_doc::Document, id: NodeId, fill: bool| d.node(id).map(|n| super::graph::shown_paint(n, fill)); + ids.iter().flat_map(|id| [(*id, true), (*id, false)]).filter(|(id, fill)| top(before, *id, *fill) != top(d, *id, *fill)).collect() +} + +/// `rows` (each object with the kind of row) whose topmost visible row of that kind has paint: a command that wrote them +/// replaces the paint another mark of the series left on the graph, even when the mark's own row comes out as it was. +fn painted_rows(d: &vectorcraft_doc::Document, rows: impl IntoIterator) -> Vec<(NodeId, bool)> { + rows.into_iter().filter(|(id, fill)| d.node(*id).is_some_and(|n| !super::graph::shown_paint(n, *fill).0.is_none())).collect() +} + +/// Store on the graph what an edit of `ids` (from `before` to `d`) leaves on the topmost visible fill and stroke of the +/// series marks among them: a paint, weight, opacity or blend mode that changed, and the paint (`paints`) and opacity and +/// blend mode (`opacities`) of the kinds of row the edit wrote, as (fill, stroke). With `top_only` the edit wrote the +/// topmost row of each kind, which counts only when it is visible. It also stores the marks' object opacity and blend mode +/// when they changed, or on every mark when the edit wrote them (`object`). Returns whether the stored paint changed. +pub(super) fn capture_series_writes( + before: &vectorcraft_doc::Document, + d: &mut vectorcraft_doc::Document, + ids: &[NodeId], + paints: (bool, bool), + opacities: (bool, bool), + top_only: bool, + object: bool, +) -> bool { + let top_shows = |d: &vectorcraft_doc::Document, id: NodeId, kind: bool| { + let items = d.node(id).map_or(&[][..], |n| &n.appearance.items[..]); + items.iter().rev().find(|it| it.is_fill() == kind).is_some_and(AppearanceItem::visible) + }; + let kinds = |(fill, stroke): (bool, bool)| -> Vec<(NodeId, bool)> { + let rows = ids.iter().flat_map(|id| [fill.then_some((*id, true)), stroke.then_some((*id, false))]).flatten(); + rows.filter(|(id, kind)| !top_only || top_shows(d, *id, *kind)).collect() + }; + let written = |d: &vectorcraft_doc::Document, rows: (bool, bool)| painted_rows(d, kinds(rows)); + let mut opacity_rows = top_opacity_changed(before, d, ids); + // A written row that had paint before the edit counts too when the edit left it without paint: only a row without + // paint both before and after keeps what the graph stores. + opacity_rows.extend(painted_rows(before, kinds(opacities))); + opacity_rows.extend(written(d, opacities)); + let mut rows = top_paint_changed(before, d, ids); + rows.extend(written(d, paints)); + let kept = super::graph::capture_series_opacity(d, &opacity_rows); + let painted = super::graph::capture_series_top_paints(d, &rows); + let objects = if object { ids.to_vec() } else { object_opacity_changed(before, d, ids) }; + let stored = super::graph::capture_series_object_opacity(d, &objects); + kept || painted || stored +} + +/// The kind of the row at `at` (fill `true`, stroke `false`) when it is the topmost visible row of that kind in `ap`. +fn top_row_kind(ap: &Appearance, at: usize) -> Option { + let fill = ap.items.get(at)?.is_fill(); + (ap.items.iter().rposition(|it| it.is_fill() == fill && it.visible()) == Some(at)).then_some(fill) +} + /// Clear Appearance on `n`: no fill, no stroke, and the object's Opacity row back to Default. A /// group keeps no fill or stroke rows of its own. fn clear(n: &mut Node) { @@ -559,11 +747,20 @@ fn transfer(s: &mut Session, p: &Value) -> Result { } to.appearance = ap; (to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) = (src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape); + super::object::snap_if_aligned(to); if !copy && let Some(n) = d.node_mut(source) { clear(n); (n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false); + super::object::snap_if_aligned(n); } - Ok(count_changed(d, &before, &[source, target])) + let changed = if copy { vec![target] } else { vec![source, target] }; + let kept = super::graph::capture_series_opacity(d, &both_kinds(&changed)); + // The target last: on marks of one series, its paint is the one the series keeps. + let mut rows = top_paint_changed(&before, d, &changed); + rows.extend(painted_rows(d, both_kinds(&[target]))); + let painted = super::graph::capture_series_top_paints(d, &rows); + let object = super::graph::capture_series_object_opacity(d, &changed); + Ok(count_changed(d, &before, &[source, target]) + usize::from(kept || painted || object)) })?; s.active_appearance_item = None; Ok(json!({ "source": source.0, "target": target.0 })) @@ -578,11 +775,30 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result { let ids = require_targets(s, p, "appearance.reduceToBasic")?; // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); + // The Appearance panel's active row (a row of the first selected object's stack, and in each + // other target the row equal to it there), when the command acts on that selection. The targets + // are in paint order, so the first selected object can be any of them. + let first = s.doc()?.selection.subjects().first().and_then(|f| ids.iter().position(|id| id == f)); + let active = match (s.appearance_item(), first) { + (Some(index), Some(k)) if p.get("ids").is_none() && p.get("id").is_none() && !targets_contents(p)? => { + let mut from = ids.clone(); + from.swap(0, k); + let mut rows = items_per_target(&before, &from, &[index], true); + rows.swap(0, k); + rows + } + _ => vec![Vec::new(); ids.len()], + }; super::overprint::edit_counted(s, "Reduce to Basic Appearance", |d| { - for id in &ids { + for (id, at) in ids.iter().zip(&active) { if let Some(n) = d.node_mut(*id) { - // The topmost visible fill and stroke stay, without their own transparency or effects. - let top = |fill: bool| n.appearance.items.iter().rev().find(|i| i.visible() && i.is_fill() == fill).cloned(); + // The active row stays when it is a visible fill or stroke; otherwise the topmost + // visible one of each kind does. Both lose their own transparency and effects. + let picked = at.first().and_then(|i| n.appearance.items.get(*i)).filter(|i| i.visible()).cloned(); + let top = |fill: bool| match &picked { + Some(i) if i.is_fill() == fill => Some(i.clone()), + _ => n.appearance.items.iter().rev().find(|i| i.visible() && i.is_fill() == fill).cloned(), + }; let (fill, stroke) = (top(true), top(false)); // Other objects always keep a fill row (None when there was none); a group only // keeps the rows it had. @@ -595,9 +811,12 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result { st.blend = BlendMode::Normal; n.appearance.items.push(AppearanceItem::Stroke(st)); } + super::object::snap_if_aligned(n); } } - Ok(count_changed(d, &before, &ids)) + let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids)); + let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); + Ok(count_changed(d, &before, &ids) + usize::from(kept || painted)) })?; s.active_appearance_item = None; ok() @@ -617,8 +836,9 @@ 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)); + let per = items_per_target(&before, &ids, &[idx], aligned(p, "appearance.setItem")?); super::overprint::edit_counted(s, "Appearance", |d| { + let mut edited = Vec::new(); for (id, at) in ids.iter().zip(&per) { let Some(&idx) = at.first() else { continue }; let Some(n) = d.node_mut(*id) else { continue }; @@ -651,8 +871,27 @@ fn set_item(s: &mut Session, p: &Value) -> Result { if let Some(v) = p.get("visible").and_then(Value::as_bool) { *vis = v; } + super::object::snap_if_aligned(n); + let items = &n.appearance.items; + if let Some(fill) = + items.get(idx).map(AppearanceItem::is_fill).filter(|f| items.iter().rposition(|it| it.is_fill() == *f && it.visible()) == Some(idx)) + { + edited.push((*id, fill)); + } } - Ok(count_changed(d, &before, &ids)) + // The graph keeps an opacity, blend mode, paint or weight set on the topmost visible fill or stroke of its series art + // for when it is drawn again, and hiding or showing a row changes which row that is. + let mut opacities = top_opacity_changed(&before, d, &ids); + if p.get("opacity").and_then(Value::as_f64).is_some() || blend.is_some() { + opacities.extend(edited.iter().copied()); + } + let kept = super::graph::capture_series_opacity(d, &opacities); + // A weight goes with the paint of its stroke; a stroke without paint leaves the series' paint alone. + let written = edited.iter().copied().filter(|(_, fill)| paint.is_some() || (!*fill && p.get("weight").is_some())); + let mut rows = top_paint_changed(&before, d, &ids); + rows.extend(painted_rows(d, written)); + let painted = super::graph::capture_series_top_paints(d, &rows); + Ok(count_changed(d, &before, &ids) + usize::from(kept || painted)) })?; if let Some(pa) = &paint { s.remember_paint(pa); @@ -662,7 +901,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result { /// The paint-order item indices a command acts on (`indices`, else `index`), ascending and /// without repeats. -fn item_indices(p: &Value, cmd: &str) -> Result> { +pub(super) fn item_indices(p: &Value, cmd: &str) -> Result> { let mut v = match p.get("indices") { Some(a) => a .as_array() @@ -676,13 +915,14 @@ fn item_indices(p: &Value, cmd: &str) -> Result> { Ok(v) } +/// `appearance.removeItem`: removes fill/stroke `index`, or every one of `indices`, from the selected objects in one undo step. fn remove_item(s: &mut Session, p: &Value) -> Result { let idx = item_indices(p, "appearance.removeItem")?; let ids = require_targets(s, p, "appearance.removeItem")?; // 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)); + let per = items_per_target(&before, &ids, &idx, aligned(p, "appearance.removeItem")?); super::overprint::edit_counted(s, "Remove Item", |d| { for (id, idx) in ids.iter().zip(&per) { if let Some(n) = d.node_mut(*id) { @@ -692,82 +932,154 @@ fn remove_item(s: &mut Session, p: &Value) -> Result { for &i in idx.iter().rev() { n.appearance.remove_item(i); } + super::object::snap_if_aligned(n); } } - Ok(count_changed(d, &before, &ids)) + let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); + let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); + Ok(count_changed(d, &before, &ids) + usize::from(kept || painted)) })?; s.remap_appearance_item(&ids, |a| (!idx.contains(&a)).then(|| a - idx.iter().filter(|i| **i < a).count())); ok() } +/// `appearance.duplicateItem`: copies fill/stroke `index`, or the rows `indices` as one block at `to` (with the Contents row when `contents` says so), in one undo step. fn duplicate_item(s: &mut Session, p: &Value) -> Result { const C: &str = "appearance.duplicateItem"; let idx = item_indices(p, C)?; let to = p.get("to").map(|_| index_param(p, "to", C)).transpose()?; - if to.is_some() && idx.len() > 1 { - return Err(bad(C, "`to` takes a single `index`")); + let contents = p.get("contents").map(|_| index_param(p, "contents", C)).transpose()?; + if contents.is_some() && to.is_none() { + return Err(bad(C, "`contents` goes with `to`")); } let ids = require_targets(s, p, C)?; - // Where the first object's copy landed (the active item lives in the first object's stack). + // Where the first target's copy landed, and where it landed on the active row's object (the + // first selected one, not always the first target): copies placed at `to` land at a different + // index on stacks of other lengths. let mut first_at = None; + let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied()); + let mut active_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() { + if aligned(p, C)? && 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)); + let before = s.doc()?.doc.clone(); + let per = items_per_target(&before, &ids, &idx, aligned(p, C)?); s.edit("Duplicate Item", |d, _| { let mut any = false; + // Copies that became the topmost visible row of their kind: the series stores their paint even when the object + // showed it. + let mut added = Vec::new(); for (id, idx) in ids.iter().zip(&per) { let Some(n) = d.node_mut(*id) else { continue }; + let has_contents = n.contents_label().is_some(); let ap = &mut n.appearance; + if let Some(t) = to { + // The copies land together at `to`, in their order; every item must exist. + if idx.iter().any(|i| *i >= ap.items.len()) { + return Err(bad(C, format!("no item at one of the indices {idx:?}"))); + } + let copies: Vec<_> = idx.iter().filter_map(|&i| ap.items.get(i).cloned()).collect(); + let at = t.min(ap.items.len()); + first_at.get_or_insert(at); + if active == Some(*id) { + active_at = Some(at); + } + let count = copies.len(); + for (k, item) in copies.into_iter().enumerate() { + ap.insert_item(at + k, item); + } + added.extend((at..at + count).filter_map(|k| top_row_kind(ap, k)).map(|kind| (*id, kind))); + if let Some(c) = contents.filter(|_| has_contents) { + ap.set_contents_at(c); + } + any = true; + continue; + } 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() { - let at = to.map_or(i + 1, |t| t.min(ap.items.len())); - first_at.get_or_insert(at); - ap.insert_item(at, item); + first_at.get_or_insert(i + 1); + ap.insert_item(i + 1, item); + // Copies below this one go in lower down, so a copy that is the topmost row of its kind stays it. + if let Some(kind) = top_row_kind(ap, i + 1) { + added.push((*id, kind)); + } any = true; } } } - if any { Ok(()) } else { Err(bad(C, format!("no item at index {}", idx[0]))) } + if !any { + return Err(bad(C, format!("no item at index {}", idx[0]))); + } + super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); + let mut rows = top_paint_changed(&before, d, &ids); + rows.extend(painted_rows(d, added)); + super::graph::capture_series_top_paints(d, &rows); + Ok(()) })?; - // Rows at or above each copy move up by one. + // Rows at or above each copy move up by one (by the block, for copies placed at `to`). + let m = idx.len(); + let landed = active_at.or(first_at); s.remap_appearance_item(&ids, |a| { Some(match to { - Some(_) => a + usize::from(first_at.is_some_and(|at| at <= a)), + Some(_) => a + if landed.is_some_and(|at| at <= a) { m } else { 0 }, None => a + idx.iter().filter(|i| **i < a).count(), }) }); ok() } +/// `appearance.showAllHidden`: shows every hidden fill, stroke and effect of the selected objects. fn show_all_hidden(s: &mut Session, p: &Value) -> Result { let roots = require_targets(s, p, "appearance.showAllHidden")?; + let before = s.doc()?.doc.clone(); let ids = s.edit("Show All Hidden Attributes", |d, _| { - let shown: Vec = roots.iter().copied().filter(|id| d.node_mut(*id).is_some_and(|n| n.appearance.show_all())).collect(); + let shown: Vec = roots + .iter() + .copied() + .filter(|id| { + d.node_mut(*id).is_some_and(|n| { + let shown = n.appearance.show_all(); + if shown { + super::object::snap_if_aligned(n); + } + shown + }) + }) + .collect(); if shown.is_empty() { return Err(EngineError::Other("Show All Hidden Attributes: nothing is hidden".into())); } + super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &shown)); + super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &shown)); Ok(shown) })?; Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) } +/// `appearance.moveItem`: moves fill/stroke `from` (or the Contents row) to `to`, or the rows `indices` as one block; the active item stays on its row. fn move_item(s: &mut Session, p: &Value) -> Result { const C: &str = "appearance.moveItem"; let to = index_param(p, "to", C)?; let ids = require_targets(s, p, C)?; + let aligned = aligned(p, C)?; if p.get("from").and_then(Value::as_str) == Some("contents") { 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) { + if aligned && appearances_differ(&s.doc()?.doc, &ids) { return Err(bad(C, "rows of objects whose appearances differ can't be reordered together")); } + if p.get("indices").is_some() { + if p.get("from").is_some() { + return Err(bad(C, "give `from` or `indices`, not both")); + } + return move_items(s, p, &ids, to); + } + let from = index_param(p, "from", C)?; 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 @@ -781,7 +1093,9 @@ fn move_item(s: &mut Session, p: &Value) -> Result { n.appearance.set_contents_at(k); } } - Ok(count_changed(d, &before, &ids)) + let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); + let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); + Ok(count_changed(d, &before, &ids) + usize::from(kept || painted)) })?; // The moved row stays the active one; the rows it passed shift by one. s.remap_appearance_item(&ids, |a| { @@ -798,6 +1112,52 @@ fn move_item(s: &mut Session, p: &Value) -> Result { Ok(json!({ "index": landed })) } +/// `appearance.moveItem {indices}`: move several items as one block (the lowest landing at `to`), +/// placing the Contents row with `contents` when given, as one undo step. The active row moves with +/// its row; the rows the block passes are renumbered. +fn move_items(s: &mut Session, p: &Value, ids: &[NodeId], to: usize) -> Result { + const C: &str = "appearance.moveItem"; + let idx = item_indices(p, C)?; + let contents = p.get("contents").map(|_| index_param(p, "contents", C)).transpose()?; + // Where the block landed on the first target (stacks of other lengths clamp `to` differently): + // the result, as the panel lists the first object's stack. + let mut first_landed = None; + // Where it landed on the active row's object: the active row is in its stack. + let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied()); + let mut active_landed = None; + let before = s.doc()?.doc.clone(); + super::overprint::edit_counted(s, "Reorder Appearance", |d| { + for id in ids { + let Some(n) = d.node_mut(*id) else { continue }; + let landed = n.appearance.move_items(&idx, to).ok_or_else(|| bad(C, format!("no item at one of the indices {idx:?}")))?; + first_landed.get_or_insert(landed); + if active == Some(*id) { + active_landed = Some(landed); + } + if let Some(k) = contents.filter(|_| n.contents_label().is_some()) { + n.appearance.set_contents_at(k); + } + } + let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, ids)); + let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, ids)); + Ok(count_changed(d, &before, ids) + usize::from(kept || painted)) + })?; + let m = idx.len(); + let landed = first_landed.unwrap_or(to); + let at = active_landed.unwrap_or(landed); + s.remap_appearance_item(ids, |a| { + Some(match idx.iter().position(|i| *i == a) { + Some(k) => at + k, + None => { + // Its place among the unmoved rows, then above the block if it is at or above it. + let r = a - idx.iter().filter(|i| **i < a).count(); + if r < at { r } else { r + m } + } + }) + }); + Ok(json!({ "index": landed })) +} + /// `appearance.moveItem {from: "contents"}`: put the Contents (Characters) row of each target that /// has one above its bottom `to` items. fn move_contents(s: &mut Session, ids: &[NodeId], to: usize) -> Result { @@ -838,52 +1198,129 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { const C: &str = "appearance.copyFrom"; let clicked = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?; let (reverse, append) = (switch_or(p, "reverse", false, C)?, switch_or(p, "append", false, C)?); + let defaults_only = switch_or(p, "defaultsOnly", false, C)?; + if defaults_only && (reverse || append || p.get("ids").is_some()) { + return Err(bad(C, "`defaultsOnly` cannot be combined with `ids`, `reverse` or `append`")); + } let attrs = s.prefs.eyedropper.attrs(p).map_err(|e| bad(C, e))?; - let range = if !reverse && !append && p.get("ids").is_none() { super::textedit::editing_range(s)?.filter(|(_, a, b)| a != b) } else { None }; - let selected = match ids_param(p, "ids") { - Some(v) => outermost(&s.doc()?.doc, v), - None => selected_roots(s)?, - }; - // Reversed, the first selected object's attributes go onto the clicked object. - let (src_id, mut targets) = if reverse { - let first = leaf_targets(s, &selected)?.into_iter().next().ok_or_else(|| bad(C, "select the object to copy from"))?; - (first, leaf_targets(s, &[clicked])?) + // An object of a dynamic symbol instance's art selected with Direct Selection takes the clicked + // object's solid fill and stroke, as the Eyedropper Options allow, for this instance only. A + // gradient or pattern sampled for it, a source that is not a path, compound path or type (a + // symbol instance's own appearance is empty), and options that pick up neither color are + // refused, and the paint defaults stay as they are. A path of a compound path stands for the + // compound path, which holds the paint. + if !reverse + && !append + && !defaults_only + && p.get("ids").is_none() + && let Some((id, path)) = super::brushsym::selected_part(s)? + { + let d = &s.doc()?.doc; + let src = Arc::new(d.node(super::path::compound_or_self(d, clicked)).ok_or(EngineError::NoNode(clicked))?.clone()); + let (fill, stroke) = (super::paint::proxy_paint(&src, false, None), super::paint::proxy_paint(&src, true, None)); + let a = attrs.appearance; + if !vectorcraft_doc::symbol_overrides::takes_part_paint(&src) + || !(a.fill.color || a.stroke.color) + || (a.fill.color && !super::paint::part_takes(&fill)) + || (a.stroke.color && !super::paint::part_takes(&stroke)) + { + return Err(super::brushsym::part_only()); + } + super::brushsym::edit_part(s, id, &path, "Eyedropper", |o| { + if a.fill.color { + o.fill = Some(fill); + } + if a.stroke.color { + o.stroke = Some(stroke); + } + })?; + // The clicked object becomes the Eyedropper's sample, and new art takes its paint. + Picked::of(&src).to_defaults(s, &attrs.appearance); + s.eyedropper_sample = Some(src); + return Ok(json!({ "ids": [id.0] })); + } + let range = if !defaults_only && !reverse && !append && p.get("ids").is_none() { + super::textedit::editing_range(s)?.filter(|(_, a, b)| a != b) } else { - (clicked, leaf_targets(s, &selected)?) + None + }; + let selected = if defaults_only { + vec![] + } else { + match ids_param(p, "ids", C)? { + Some(v) => outermost(&s.doc()?.doc, v), + None => selected_roots(s)?, + } + }; + // Reversed, the first selected object's attributes go onto the clicked object; with nothing + // selected, what the Eyedropper picked up last does (#4382). + let (source, mut targets) = if reverse { + let source = match leaf_targets(s, &selected)?.into_iter().next() { + Some(first) => Some(first), + None if s.eyedropper_sample.is_some() => None, + None => return Err(bad(C, "select the object to copy from")), + }; + (source, leaf_targets(s, &[clicked])?) + } else { + (Some(clicked), leaf_targets(s, &selected)?) + }; + targets.retain(|id| Some(*id) != source); + let node = match source { + Some(id) => Arc::new(s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone()), + None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?, + }; + let picked = Picked::of(&node); + if !reverse && !defaults_only { + s.eyedropper_sample = Some(node); + } + // The highlighted characters' type objects and ranges: after Select All in threaded text, all + // the text of every frame of the story, except a frame the attributes come from, in place of + // the object selection. + let story = super::textedit::editing_story(s); + let ranges: Vec<(NodeId, Option<(usize, usize)>)> = match range { + Some((id, _, _)) if story.contains(&id) => { + targets.clear(); + story.iter().copied().filter(|f| Some(*f) != source).map(|f| (f, None)).collect() + } + Some((id, start, end)) if targets.contains(&id) => vec![(id, Some((start, end)))], + _ => vec![], }; - 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 attrs.appearance.transparency { + for (id, _) in &ranges { + 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() { + if (targets.is_empty() && ranges.is_empty()) || attrs.is_empty() { return Ok(json!({ "ids": [] })); } - if let Some((id, start, end)) = range { + if !ranges.is_empty() { + let ids: Vec = ranges.iter().map(|(f, _)| *f).collect(); 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()); + for &(id, range) in &ranges { + let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; + let (start, end) = range.unwrap_or((0, vectorcraft_text::edit::runs_len(&t.runs))); + let placed = picked.placed(Some(t.local_bounds())); + vectorcraft_text::edit::style_range(&mut t.runs, start, end, |st| picked.run(st, &placed, &attrs)); + 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); } - super::typecmd::refresh_bounds(t); - Ok(count_changed(d, &before, &[id])) + Ok(count_changed(d, &before, &ids)) })?; - return Ok(json!({ "ids": [id.0] })); + return Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })); } // When every target comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); @@ -893,7 +1330,44 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { picked.apply(n, &attrs, append); } } - Ok(count_changed(d, &before, &targets)) + // The paints the pick wrote, with a weight going with the paint of its stroke, as in `set_item`. `append` adds + // only the colors of the visible rows the source has. + let (fill, stroke) = (attrs.appearance.fill, attrs.appearance.stroke); + let source_has = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind); + let source_shows = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible()); + let (paints, opacities) = if append { + let rows = (fill.color && source_shows(true), stroke.color && source_shows(false)); + (rows, rows) + } else { + ( + (fill.color, stroke.color || (stroke.weight && source_has(false))), + (fill.transparency && source_has(true), stroke.transparency && source_has(false)), + ) + }; + // A pick of some attributes edits the topmost row of its kind, which may be hidden; `append` and a whole pick write rows. + let rows_written = append || (fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL); + let top_shows = |id: NodeId, kind: bool| { + let items = d.node(id).map_or(&[][..], |n| &n.appearance.items[..]); + items.iter().rev().find(|it| it.is_fill() == kind).is_some_and(|it| it.visible()) + }; + let written = |(fill, stroke): (bool, bool)| -> Vec<(NodeId, bool)> { + targets + .iter() + .flat_map(|id| [fill.then_some((*id, true)), stroke.then_some((*id, false))]) + .flatten() + .filter(|(id, kind)| rows_written || top_shows(*id, *kind)) + .collect() + }; + let mut opacity_rows = top_opacity_changed(&before, d, &targets); + opacity_rows.extend(painted_rows(d, written(opacities))); + let mut rows = top_paint_changed(&before, d, &targets); + rows.extend(painted_rows(d, written(paints))); + let kept = super::graph::capture_series_opacity(d, &opacity_rows); + let painted = super::graph::capture_series_top_paints(d, &rows); + // A pick of the object's transparency writes it on every target. + let objects = if attrs.appearance.transparency { targets.clone() } else { object_opacity_changed(&before, d, &targets) }; + let object = super::graph::capture_series_object_opacity(d, &objects); + Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object)) })?; Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::>() })) } @@ -975,6 +1449,7 @@ impl Picked { let placed = self.placed(n.geometric_bounds()); n.appearance.items.extend(placed.items.into_iter().filter(|it| if it.is_fill() { ap.fill.color } else { ap.stroke.color })); n.appearance.effects.extend(placed.effects); + super::object::snap_if_aligned(n); return; } if let NodeKind::Text(t) = &mut n.kind { @@ -998,6 +1473,7 @@ impl Picked { } else { focal_attrs(&mut n.appearance, &placed, ap); } + super::object::snap_if_aligned(n); } } diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index 975b8e93fd..8c225b877b 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -3,12 +3,17 @@ //! settings Export for Screens shares (`document.exportSettings`). File → Export Selection collects //! the selection this way and opens Export for Screens on its Assets tab (a UI command). +use std::collections::HashSet; + use serde_json::{Map, Value, json}; use vectorcraft_doc::{ExportAsset, NodeId}; use super::edit::{roots_of, selected_roots}; -use super::fileio::{SCREEN_SETTINGS_KEYS, check_screen_settings, export_crop, export_screens, store_screen_settings}; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param}; +use super::fileio::{ + DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files, + safe_file_name, store_screen_settings, with_screen_export_preset, write_file, +}; +use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param, switch_or, text_param}; /// The longest asset name kept (characters). const MAX_NAME: usize = 255; @@ -39,7 +44,7 @@ pub fn specs() -> Vec { "Assets", [], None, - "{} → {assets: [{id, name, nodes: [id…], bounds: [x, y, width, height] | null (the crop: the bounds the renderer measures for what its art draws, effects included)}]} the Asset Export panel's assets, in order", + "{} → {assets: [{id, name, nodes: [id…], bounds: [x, y, width, height] | null (the crop: the bounds the renderer measures for what its art draws, effects included), format3D: usda|usdz|gltf|obj | null (a 3D asset's mesh format; null for art exported as pictures)}]} the Asset Export panel's assets, in order", has_doc, list ), @@ -48,16 +53,43 @@ pub fn specs() -> Vec { "Export Assets", [], None, - "{assets?: [asset id…] (default all), folder?, zip?, openLocation?, formats?, preset?, settings?, prefix?, subfolders?, antiAlias?} each asset's art alone, cropped to it, in every format row: document.exportForScreens {assets} at the document's export settings (document.exportSettings) under the ones given → what document.exportForScreens returns (no folder: the files, or one zip, as dataBase64). Leaves the remembered settings as they are (assets.settings.set changes them)", + "{assets?: [asset id…] (default all but the 3D assets, which assets.export3D writes), folder?, zip?, openLocation?, formats?, preset?, settings?, prefix?, subfolders?, antiAlias?} each asset's art alone, cropped to it, in every format row: document.exportForScreens {assets} at the document's export settings (document.exportSettings) under the ones given; with subfolders false every file goes into the folder itself, mobile and density rows too → what document.exportForScreens returns (no folder: the files, or one zip, as dataBase64). Leaves the remembered settings as they are (assets.settings.set changes them)", has_doc, export ), + cmd!( + "assets.add3D", + "Export 3D Object", + [], + None, + "{ids?: [id…] (default: the selected objects), format?: usda|usdz|gltf|obj (default usda)} collect each object with an Extrude & Bevel, Revolve, Inflate or Rotate effect as a 3D asset of Window › Asset Export, named after the object (else Asset 1, Asset 2…): assets.export3D writes it as a mesh file. An object already collected as a 3D asset keeps it; an object without such an effect is refused → {assets: [asset id…] (in order), added: n}", + has_doc, + add_3d + ), + cmd!( + "assets.set3DFormat", + "3D Export Format", + [], + None, + "{assets: [asset id…], format: usda|usdz|gltf|obj} the mesh format 3D assets export to (Asset Export's Format for a 3D asset) → {changed: n}", + has_doc, + set_3d_format + ), + cmd!( + "assets.export3D", + "Export 3D Assets", + [], + None, + "{assets?: [asset id…] (default every 3D asset), folder?, zip?} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})", + has_doc, + export_3d + ), cmd!( "assets.settings.set", "Asset Export Settings", [], None, - "{formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?, antiAlias?} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step", + "{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?, antiAlias?} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step", has_doc, settings_set ), @@ -115,7 +147,9 @@ fn add(s: &mut Session, p: &Value) -> Result { if name.is_some() && sets.len() > 1 { return Err(bad(C, "a name names one asset: give multiple: false, or one object")); } - let existing = |d: &vectorcraft_doc::Document, nodes: &[NodeId]| d.assets.iter().find(|a| a.nodes == nodes).map(|a| a.id); + // A 3D asset of the same art is another asset. + let existing = + |d: &vectorcraft_doc::Document, nodes: &[NodeId]| d.assets.iter().find(|a| a.nodes == nodes && a.format_3d.is_none()).map(|a| a.id); let d = &s.doc()?.doc; // Nothing new: no undo step. if sets.iter().all(|set| existing(d, set).is_some()) { @@ -134,7 +168,7 @@ fn add(s: &mut Session, p: &Value) -> Result { }; let name = name.clone().or(own).unwrap_or_else(|| d.next_asset_name()); let id = d.alloc_id().0; - d.assets.push(ExportAsset { id, name, nodes }); + d.assets.push(ExportAsset { id, name, nodes, format_3d: None }); out.push(id); added += 1; } @@ -142,6 +176,161 @@ fn add(s: &mut Session, p: &Value) -> Result { }) } +/// The format of param `format` of command `cmd` ([`FORMATS_3D`]), `default` when it is not given. +fn format_3d_param(p: &Value, cmd: &str, default: Option<&str>) -> Result { + match (p.get("format"), default) { + (None, Some(d)) => Ok(d.to_string()), + (Some(Value::String(f)), _) if FORMATS_3D.contains(&f.as_str()) => Ok(f.clone()), + _ => { + let key = "format"; + Err(bad(cmd, format!("`{key}` must be one of {}", FORMATS_3D.join(", ")))) + } + } +} + +/// The asset ids of param `key` of command `cmd`, each a 3D asset of `d`. +fn three_d_asset_ids(d: &vectorcraft_doc::Document, p: &Value, key: &str, cmd: &str) -> Result> { + let ids = asset_ids(p, key, cmd)?; + for id in &ids { + match d.asset(*id) { + None => return Err(bad(cmd, "no such assets (see assets.list)")), + Some(a) if a.format_3d.is_none() => return Err(bad(cmd, format!("asset {id} isn't a 3D asset"))), + _ => {} + } + } + Ok(ids) +} + +fn add_3d(s: &mut Session, p: &Value) -> Result { + const C: &str = "assets.add3D"; + let format = format_3d_param(p, C, Some(DEFAULT_FORMAT_3D))?; + let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { selected_roots(s)? }; + if ids.is_empty() { + return Err(bad(C, "select an object with a 3D effect (or give its ids)")); + } + let d = &s.doc()?.doc; + let mut ids = d.paint_order(ids); + ids.dedup(); + for id in &ids { + let n = d.node(*id).ok_or_else(|| bad(C, format!("no such object {0}", id.0)))?; + if let Err(e) = vectorcraft_render::effects::three_d_meshes(n) { + let what = n.name.clone().unwrap_or_else(|| format!("#{}", id.0)); + return Err(bad(C, format!("{what} can't be exported in 3D: {e}"))); + } + } + let existing = |d: &vectorcraft_doc::Document, id: NodeId| d.assets.iter().find(|a| a.nodes == [id] && a.format_3d.is_some()).map(|a| a.id); + // Nothing new: no undo step. + if ids.iter().all(|id| existing(d, *id).is_some()) { + return Ok(json!({ "assets": ids.iter().filter_map(|id| existing(d, *id)).collect::>(), "added": 0 })); + } + s.edit("Export 3D Object", |d, _| { + let (mut out, mut added) = (vec![], 0); + for node in ids { + if let Some(id) = existing(d, node) { + out.push(id); + continue; + } + let name = d.node(node).and_then(|n| n.name.as_deref()).and_then(clean_name).unwrap_or_else(|| d.next_asset_name()); + let id = d.alloc_id().0; + d.assets.push(ExportAsset { id, name, nodes: vec![node], format_3d: Some(format.clone()) }); + out.push(id); + added += 1; + } + Ok(json!({ "assets": out, "added": added })) + }) +} + +fn set_3d_format(s: &mut Session, p: &Value) -> Result { + const C: &str = "assets.set3DFormat"; + let d = &s.doc()?.doc; + let ids = three_d_asset_ids(d, p, "assets", C)?; + let format = format_3d_param(p, C, None)?; + let changed = d.assets.iter().filter(|a| ids.contains(&a.id) && a.format_3d.as_deref() != Some(format.as_str())).count(); + // Nothing changes: no undo step. + if changed == 0 { + return Ok(json!({ "changed": 0 })); + } + s.edit("3D Export Format", |d, _| { + for a in d.assets.iter_mut().filter(|a| ids.contains(&a.id)) { + a.format_3d = Some(format.clone()); + } + Ok(json!({ "changed": changed })) + }) +} + +fn export_3d(s: &mut Session, p: &Value) -> Result { + const C: &str = "assets.export3D"; + let d = &s.doc()?.doc; + let ids = if p.get("assets").is_some_and(|v| !v.is_null()) { + three_d_asset_ids(d, p, "assets", C)? + } else { + d.assets.iter().filter(|a| a.format_3d.is_some()).map(|a| a.id).collect() + }; + if ids.is_empty() { + return Err(bad(C, "no 3D assets yet: collect an object with a 3D effect first (assets.add3D)")); + } + let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()); + let zip = switch_or(p, "zip", false, C)?; + // Every file's name, compared without case: a later file that would take one gets -2, -3… + let mut taken: HashSet = HashSet::new(); + let mut files: Vec<(String, Vec)> = vec![]; + for id in ids { + let Some(a) = d.asset(id) else { continue }; + let format = a.format_3d.as_deref().unwrap_or(DEFAULT_FORMAT_3D); + let nodes = + a.nodes.iter().map(|node| d.node(*node).ok_or_else(|| bad(C, format!("no such object {0}", node.0)))).collect::>>()?; + // The asset's objects share one budget of triangles. + let what = &a.name; + let parts = vectorcraft_render::effects::three_d_meshes_of(nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?; + let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into()); + let mut stem = base.clone(); + let mut k = 1; + loop { + let names = mesh_file_names(&stem, format).map_err(|e| bad(C, e))?; + if names.iter().all(|n| !taken.contains(&n.to_lowercase())) { + break; + } + k += 1; + stem = format!("{base}-{k}"); + } + let made = mesh_files(&stem, format, &parts).map_err(|e| bad(C, e))?; + taken.extend(made.iter().map(|(n, _)| n.to_lowercase())); + files.extend(made); + } + let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect(); + if zip { + let archive = super::fileio::zip::store(&files).map_err(|e| bad(C, e))?; + // "-3D" keeps it apart from the picture assets' ZIP, which is named after the document. + let name = Some(safe_file_name(&d.title)).filter(|t| !t.is_empty()).map_or_else(|| "3D Assets.zip".into(), |t| format!("{t}-3D.zip")); + return match folder { + Some(dir) => { + create_dir(dir)?; + let path = format!("{dir}/{name}"); + write_file(&path, &archive)?; + Ok(json!({ "path": path, "bytes": archive.len(), "files": names })) + } + None => Ok(json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(&archive), "bytes": archive.len(), "files": names })), + }; + } + match folder { + Some(dir) => { + create_dir(dir)?; + let mut written = vec![]; + for (name, bytes) in &files { + let path = format!("{dir}/{name}"); + write_file(&path, bytes)?; + written.push(path); + } + Ok(json!({ "files": written })) + } + None => { + let files: Vec = + files.iter().map(|(name, bytes)| json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) })).collect(); + Ok(json!({ "files": files })) + } + } +} + /// The asset ids of param `key`. fn asset_ids(p: &Value, key: &str, cmd: &str) -> Result> { let ids = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be an array of asset ids (see assets.list)")))?; @@ -186,6 +375,7 @@ fn list(s: &mut Session, _: &Value) -> Result { "name": a.name, "nodes": a.nodes.iter().map(|n| n.0).collect::>(), "bounds": bounds.map(|b| [b.x0, b.y0, b.width(), b.height()]), + "format3D": a.format_3d, }) }) .collect(); @@ -223,8 +413,14 @@ fn export(s: &mut Session, p: &Value) -> Result { if let Some(o) = p.as_object() { overlay(&mut q, o); } + // Create Sub-folders off puts every file in the folder itself, mobile and density rows too. + if q.get("subfolders").and_then(Value::as_bool) == Some(false) && p.get("folders").is_none() { + q.insert("folders".into(), json!("none")); + } + let d = &s.doc()?.doc; + // 3D assets are written as mesh files, by assets.export3D: the export refuses one it is given. if !q.contains_key("assets") { - let all: Vec = s.doc()?.doc.assets.iter().map(|a| a.id).collect(); + let all: Vec = d.assets.iter().filter(|a| a.format_3d.is_none()).map(|a| a.id).collect(); if all.is_empty() { return Err(bad(C, "no assets yet: collect art for export first (assets.add)")); } @@ -236,11 +432,22 @@ fn export(s: &mut Session, p: &Value) -> Result { fn settings_set(s: &mut Session, p: &Value) -> Result { const C: &str = "assets.settings.set"; let o = p.as_object().ok_or_else(|| bad(C, "give the settings to change, e.g. {\"formats\": [{\"format\": \"png\", \"scale\": \"2x\"}]}"))?; - if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str())) { + if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && k.as_str() != "exportPreset") { return Err(bad(C, format!("`{k}` isn't an export setting: {}", SCREEN_SETTINGS_KEYS.join(", ")))); } let mut settings = s.doc()?.doc.export_settings.clone(); - overlay(&mut settings, o); + let mut given = o.clone(); + if let Some(name) = given.remove("exportPreset") { + let name = name.as_str().ok_or_else(|| bad(C, "`exportPreset` is the name of a preset of document.exportPresets.list"))?; + with_screen_export_preset(s, C, &mut settings, name)?; + } + // Create Sub-folders is Export for Screens' folder per row: the dialog opens on the choice. + match given.get("subfolders").and_then(Value::as_bool) { + Some(true) => _ = settings.insert("folders".into(), json!("rows")), + Some(false) if settings.get("folders").and_then(Value::as_str) == Some("rows") => _ = settings.insert("folders".into(), json!("none")), + _ => {} + } + overlay(&mut settings, &given); check_screen_settings(s, &Value::Object(settings.clone())).map_err(|e| of_cmd(C, e))?; store_screen_settings(s, settings)?; Ok(json!({ "settings": shared_settings(s)? })) diff --git a/crates/engine/src/cmd/attributes.rs b/crates/engine/src/cmd/attributes.rs index 0265b4ccd4..684d33a53d 100644 --- a/crates/engine/src/cmd/attributes.rs +++ b/crates/engine/src/cmd/attributes.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { "Attributes", [], None, - "{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG export links the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}", + "{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}", has_doc, set ), diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 9bb04dac92..8f36e16f61 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -107,10 +107,14 @@ impl BrushLibrary { /// `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)) { + // Names looked up in sets: scanning the lists for each brush made a library of N brushes + // cost N² comparisons. + let have: HashSet<&str> = all.iter().map(|b| b.name.as_str()).collect(); + if let Some(n) = names.iter().find(|n| !have.contains(n.as_str())) { return Err(format!("no brush `{n}`")); } - let picked = all.iter().filter(|b| names.is_empty() || names.contains(&b.name)); + let wanted: HashSet<&str> = names.iter().map(String::as_str).collect(); + let picked = all.iter().filter(|b| names.is_empty() || wanted.contains(b.name.as_str())); let clip = Clipboard::gather(src, picked.map(|b| stroke(&b.name)).collect()); let mut doc = clip.to_document(); for l in &mut doc.layers { @@ -120,7 +124,8 @@ impl BrushLibrary { } // 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(); + let kept: HashSet<&str> = clip.brushes.iter().map(|c| c.name.as_str()).collect(); + let brushes: Vec = all.iter().filter(|b| kept.contains(b.name.as_str())).cloned().collect(); brush::store(&mut doc, &brushes); doc.title = name.clone(); Ok(Self { name, brushes, doc }) @@ -335,7 +340,7 @@ fn scatter_shapes() -> BrushLibrary { a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(gold)))); a }); - doc.symbols.push(Symbol { name: "Sparkle".into(), art: Arc::new(sparkle) }); + doc.symbols.push(Symbol { dynamic: false, name: "Sparkle".into(), art: Arc::new(sparkle) }); let instance = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Sparkle".into(), xf: Affine::scale(0.3) }); let random = |a: f64, b: f64| (a, b); let base = Scatter { colorization: Colorization::Tints, ..Default::default() }; diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 8ef171d326..53f373a3bd 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -19,12 +19,16 @@ use super::edit::{outermost, selected_roots}; use super::pathops::{remove_each, separate}; use super::swatch::{anchor, names_param}; use super::{ - CommandSpec, Result, Session, bad, check_numbers, cmd, color_value, find_command, has_doc, has_selection, id_param, ids_param, number_or, ok, + CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok, str_param, switch_or, }; use crate::EngineError; +/// Whether Reset Transformation changes a symbol instance. +pub use symbols::reset_transformation_changes; + mod brushes; +mod dynamic; mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; @@ -32,10 +36,16 @@ use brushes::{ brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_remove, brush_selection_art, brush_set_current, brush_unused, expand_brush, }; -pub(crate) use symbols::{natural_size, normalize, place_xf, set_natural_size}; +pub(crate) use dynamic::{edit_part, part_only, selected_part}; +use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance}; +use symbols::selected_instances; +pub(crate) use symbols::{ + expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol, + stored_natural_size, +}; use symbols::{ - symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_edit, symbol_list, symbol_new, symbol_options, symbol_place, - symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_update, + symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_instance_reset_transform, symbol_list, symbol_new, symbol_options, + symbol_place, symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update, }; const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES; @@ -125,7 +135,7 @@ pub fn specs() -> Vec { "Select All Unused", [], None, - "{} → {names: [the brushes no stroke paints with, in library order]} (the Brushes panel selects them): strokes in the art (opacity masks included), symbols, graph designs, pattern tiles and graphic styles count, and so do strokes in the art of a brush that is used", + "{} → {names: [the brushes no stroke paints with, in library order]} (the Brushes panel selects them): strokes in the art (opacity masks included), symbols, graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do strokes in the art of a brush that is used", has_doc, brush_unused ), @@ -134,7 +144,7 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art). scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), @@ -157,13 +167,21 @@ pub fn specs() -> Vec { brush_freehand ), // ----- symbols ----- - cmd!(query "symbol.list", "Symbols", [], None, "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic}], current}", has_doc, symbol_list), + cmd!( + query "symbol.list", + "Symbols", + [], + None, + "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic}], current}", + has_doc, + symbol_list + ), cmd!( "symbol.new", "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a third each) → {name, id, registration, exportType, nineSlice}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions 0..1 of the natural size (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}", has_selection, symbol_new ), @@ -172,7 +190,7 @@ pub fn specs() -> Vec { "Symbol Options…", [], None, - "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array} rename a symbol and/or set Symbol Options › Registration and Export Type and 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1; default name: current) → {name, registration, exportType, nineSlice}", + "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}", has_doc, symbol_options ), @@ -190,7 +208,7 @@ pub fn specs() -> Vec { "Break Link to Symbol", [], None, - "{ids?|id?} expand selected instances into plain art → {ids}", + "{ids?|id?} expand selected instances into plain art (with their appearance changes to a dynamic symbol), placed through the symbol's 9-slice guides when it has them, with the instance's opacity mask → {ids}", has_selection, symbol_break_link ), @@ -199,16 +217,25 @@ pub fn specs() -> Vec { "Edit Symbol", [], None, - "{id?, ids?: [id…] (instead of id)} break the link of the selected instance so its art can be edited; finish with symbol.update → {name, ids}", - has_selection, - symbol_edit + "{id?, ids?: [id…] (instead of id), name?, x?, y?, artboard?: index=0 (the active artboard; the app passes it), viewCenter?: [x, y] (the app passes the view's center)} edit a symbol's art in symbol editing mode: the instance `id` (default: the selected instances, which must share one symbol) where it shows the art, else the symbol `name` (default: the current symbol) centered on (x, y) (default: the center of artboard `artboard`, or of the first artboard when there is no such artboard; in a document without artboards, viewCenter, else (0, 0)); every instance follows each edit and the instance stays linked (symbol.breakLink expands one); refused while a pattern or an opacity mask is edited → {name, layer, id?}", + has_doc, + super::symboledit::enter + ), + cmd!( + "symbol.exitEditing", + "Exit Symbol Editing Mode", + [], + None, + "{} leave symbol editing mode; after an edit, select the instance it was entered from; leaving without having changed the art adds no undo step and restores the selection from before entry (object.exitIsolation also leaves it) → {name?}", + has_doc, + super::symboledit::leave ), cmd!( "symbol.update", "Redefine Symbol", [], None, - "{name, ids?|id?} replace the symbol's art with the selection (instances update; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}", + "{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}", has_selection, symbol_update ), @@ -217,7 +244,7 @@ pub fn specs() -> Vec { "Delete Symbol", [], None, - "{name, expandInstances?: true} delete a symbol; its instances are expanded (or deleted with false)", + "{name | names: [name…], expandInstances?: true} delete a symbol (or several, in one undo step); its instances are expanded (or deleted with false)", has_doc, symbol_delete ), @@ -227,10 +254,46 @@ pub fn specs() -> Vec { "Replace Symbol", [], None, - "{name, ids?|id?} swap the symbol of the selected instances → {ids}", + "{name, ids?|id?} swap the symbol of the selected instances (an instance given a different symbol drops its appearance changes; one given its own symbol keeps them) → {ids}", has_selection, symbol_replace ), + cmd!( + "symbol.instance.setAppearance", + "Symbol Instance Appearance", + [], + None, + "{id?|ids?: [one id] (default: the one selected object), path: [i…] (the object in the symbol's art: child indices in paint order from the art's root down through its groups; [] the root), fill?: \"#rrggbb\"|{…paint params of paint.setFill: color, none, swatch, tint, gradient, keepModel}|null (null: the symbol's own again), stroke?: as fill, opacity?: 0..100|null, blend?: name|null} change the appearance of one object of a dynamic symbol instance's art, for that instance only: it stays linked, so editing the symbol reshapes it and keeps the change; refused for a static symbol, a path naming no object, or a fill or stroke other than null for an object that does not draw it (a guide, blend, envelope, Repeat, Intertwine group, gradient mesh or placed document; a symbol instance's stroke, and its fill unless a solid color or none, which stains its art; an image's fill or stroke without a Convert to Shape or Outline Object effect), with nothing of the call applied; opacity, blend and null are taken for every object → {id, overrides: how many objects the instance changes}", + has_selection, + symbol_instance_set_appearance + ), + cmd!( + "symbol.instance.selectPart", + "Select Symbol Instance Part", + [], + None, + "{id, path: [i…] (as symbol.instance.setAppearance)} select one path, compound path or type object of a dynamic symbol instance's art, as a Direct Selection click on it does: the instance is selected alone, and until the selection changes paint.setFill and paint.setStroke with a solid color or none, paint.invert and paint.complement on a solid color (without ids, id or item; type whose characters differ in color is refused) and appearance.copyFrom with a solid fill and stroke (the Eyedropper, without ids, reverse or append; options that pick up neither color are refused) change that object's fill or stroke for this instance only; gradients and patterns are refused, and so are the commands that change the selected objects without ids (transparency.set, the gradient commands, object.group, edit.cut and edit.clear among them); edit.copy copies the instance whole, and selection exports, artboard.fitToSelection, object.liquify, object.isolate, library.add and select.save use the instance (docs/mcp.md); selectPart itself is refused for a static symbol, a path naming no object, a group, image or other kind of object, a hidden, locked or template object or one inside such a group, and a hidden or locked instance → {id, path}", + has_doc, + symbol_instance_select_part + ), + cmd!( + "symbol.instance.reset", + "Reset Symbol Instance", + [], + None, + "{ids?|id?} drop the selected dynamic symbol instances' own appearance changes, so they show the symbol's appearance again → {ids: the instances that had changes}", + has_selection, + symbol_instance_reset + ), + cmd!( + "symbol.instance.resetTransform", + "Reset Transformation", + [], + None, + "{ids?|id?} give the selected symbol instances (in groups too) their symbol's own scale, without rotation, shear or reflection, keeping the center of each one's bounding box in place, as one undo step; other objects, instances in perspective and instances already at their symbol's scale are left as they are, and no undo step is added when nothing changes; an id naming no object, or no symbol instance among the objects, is an error → {ids: the instances changed}", + has_selection, + symbol_instance_reset_transform + ), cmd!( "symbol.setCurrent", "Current Symbol", @@ -240,6 +303,15 @@ pub fn specs() -> Vec { has_doc, symbol_set_current ), + cmd!( + query "symbol.unused", + "Select All Unused", + [], + None, + "{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used", + has_doc, + symbol_unused + ), cmd!(query "symbol.selectInstances", "Select All Instances", [], None, "{name} select every instance of a symbol → {count}", has_doc, symbol_select_instances), cmd!( "symbol.spray", @@ -255,7 +327,7 @@ pub fn specs() -> Vec { "Symbolism Tool", [], None, - "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color?, keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}", + "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}", has_doc, symbol_adjust ), @@ -267,7 +339,7 @@ fn ids_json(ids: &[NodeId]) -> Value { } pub(crate) fn roots(s: &Session, p: &Value) -> Result> { - match ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])) { + match named_ids(p)? { Some(mut v) => { // Explicit ids: only existing, non-layer objects, none inside another of them. let d = &s.doc()?.doc; diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 66dd546e90..9cc52c82c8 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -362,14 +362,15 @@ fn art_brushes(n: &Node, out: &mut Vec) { } /// The brushes no stroke paints with. Strokes in the art (opacity masks included), symbols, graph -/// designs, pattern tiles and graphic styles count, and so do the strokes in the art of every brush -/// that a counted stroke paints with. +/// designs, pattern tiles and the tiles that pattern editing's Cancel puts back, and graphic styles +/// count, and so do the strokes in the art of every brush that a counted stroke paints with. pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result { let d = &s.doc()?.doc; let lib = brush::library(d); let mut todo = vec![]; let trees = d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)).chain(d.graph_designs.iter().map(|g| &g.art)); - trees.chain(d.patterns.iter().flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo)); + let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); + trees.chain(patterns.flat_map(|p| &p.art)).for_each(|n| art_brushes(n, &mut todo)); d.graphic_styles.iter().for_each(|g| stroke_brushes(&g.appearance.items, &mut todo)); let mut used = BTreeSet::new(); while let Some(name) = todo.pop() { @@ -389,7 +390,77 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result { let i = lib.iter().position(|b| b.name == name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?; let mut v = serde_json::to_value(&lib[i]).unwrap_or_default(); if let Some(params) = p.get("params") { + let original = v.clone(); merge(&mut v, params); + if lib[i].kind.type_id() == "pattern" { + let tiles = [ + ("side_tile", "side"), + ("outer_corner_tile", "outer_corner"), + ("inner_corner_tile", "inner_corner"), + ("start_tile", "start"), + ("end_tile", "end"), + ]; + // Resolve all Original choices against the brush before any tile can clear the art + // another corner borrows. Keep the matching frame with each copied tile. + let originals: Vec<_> = tiles + .iter() + .map(|(_, art)| { + let from = if art.ends_with("corner") + && original.get(art).is_none_or(Value::is_null) + && original.get(if *art == "outer_corner" { "outer_source" } else { "inner_source" }).is_none_or(Value::is_null) + { + if *art == "outer_corner" { "inner_corner" } else { "outer_corner" } + } else { + *art + }; + (original.get(from).cloned().unwrap_or(Value::Null), original.get(format!("{from}_frame")).cloned().unwrap_or(Value::Null)) + }) + .collect(); + for ((tile, art), (original_art, original_frame)) in tiles.into_iter().zip(originals) { + let frame = format!("{art}_frame"); + let swatch = format!("{art}_swatch"); + let Some(choice) = params.get(tile) else { + if params.get(art).is_some() { + if params.get(frame.as_str()).is_none() { + v[frame.as_str()] = Value::Null; + } + if params.get(swatch.as_str()).is_none() { + v[swatch.as_str()] = Value::Null; + } + } + continue; + }; + let (choice, swatch_only) = if let Some(name) = choice.as_object() { + (name.get("pattern").and_then(Value::as_str).ok_or_else(|| bad(C, "invalid pattern tile choice"))?, true) + } else { + (choice.as_str().ok_or_else(|| bad(C, "invalid pattern tile choice"))?, false) + }; + if art == "side" && choice == "none" && !swatch_only { + return Err(bad(C, "You must choose a side pattern.")); + } + if choice == "original" && !swatch_only { + v[art] = original_art; + v[frame.as_str()] = original_frame; + v[swatch.as_str()] = Value::Null; + } else if !swatch_only && (choice == "none" || (art.ends_with("corner") && brush::CornerSource::parse(choice).is_some())) { + v[art] = Value::Null; + v[frame.as_str()] = Value::Null; + v[swatch.as_str()] = Value::Null; + if art.ends_with("corner") { + v[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = json!(choice); + } + } else { + let pattern = s.doc()?.doc.pattern(choice).ok_or_else(|| bad(C, format!("no pattern named `{choice}`")))?; + let copy = Node::new(NodeId(0), NodeKind::Group { children: pattern.art.clone(), clip: false }); + v[art] = serde_json::to_value(copy).unwrap_or_default(); + v[frame.as_str()] = serde_json::to_value(pattern.tile).unwrap_or_default(); + v[swatch.as_str()] = json!(choice); + if art.ends_with("corner") { + v[if art == "outer_corner" { "outer_source" } else { "inner_source" }] = Value::Null; + } + } + } + } } let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty() && *n != name).map(str::to_string); if let Some(nn) = &new_name { diff --git a/crates/engine/src/cmd/brushsym/dynamic.rs b/crates/engine/src/cmd/brushsym/dynamic.rs new file mode 100644 index 0000000000..89c7c3c522 --- /dev/null +++ b/crates/engine/src/cmd/brushsym/dynamic.rs @@ -0,0 +1,258 @@ +//! Dynamic symbols (Symbol Options › Symbol Type): an instance of a dynamic symbol changes the +//! appearance of objects in the symbol's art and stays linked to the symbol +//! (`symbol.instance.setAppearance`, `symbol.instance.reset`). The changes live on the instance +//! ([`vectorcraft_doc::symbol_overrides`]); editing the symbol keeps those whose object is still +//! there ([`fit_overrides`]). + +use std::sync::Arc; + +use vectorcraft_color::BlendMode; +use vectorcraft_doc::symbol_overrides::{self, SymbolOverride}; + +use super::{Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, ids_json, json, roots, selected_instances}; + +/// The `type` param, Symbol Options › Symbol Type: `Some(true)` for dynamic. +pub(super) fn type_param(p: &Value, cmd: &str) -> Result> { + let Some(v) = p.get("type").filter(|v| !v.is_null()) else { return Ok(None) }; + match v.as_str() { + Some("static") => Ok(Some(false)), + Some("dynamic") => Ok(Some(true)), + _ => Err(bad(cmd, format!("type must be static or dynamic, not {v}"))), + } +} + +/// The `type` a symbol reports. +pub(super) fn type_id(dynamic: bool) -> &'static str { + if dynamic { "dynamic" } else { "static" } +} + +/// Fit the appearance changes of instances `ids` to their symbols: an instance of a static (or +/// missing) symbol keeps none, an instance of a dynamic one those naming an object of its art. +pub(super) fn fit_overrides(d: &mut Document, ids: &[NodeId]) { + for id in ids { + let art = match d.node(*id) { + Some(n) if !n.extras().symbol_overrides.is_empty() => match &n.kind { + NodeKind::SymbolInstance { symbol, .. } => d.symbols.iter().find(|s| s.name == *symbol).filter(|s| s.dynamic).map(|s| s.art.clone()), + _ => continue, + }, + _ => continue, + }; + let Some(n) = d.node_mut(*id) else { continue }; + let mut e = n.extras_mut(); + match art { + Some(art) => symbol_overrides::retain_parts(&mut e.symbol_overrides, &art), + None => e.symbol_overrides.clear(), + } + } +} + +/// The instance `id` names (else the one selected object) and its symbol's art; the symbol must +/// be dynamic. +fn dynamic_instance(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, Arc)> { + let d = &s.doc()?.doc; + let not_one = || EngineError::Other("select a symbol instance".into()); + let [id] = roots(s, p)?[..] else { return Err(not_one()) }; + let Some(NodeKind::SymbolInstance { symbol, .. }) = d.node(id).map(|n| &n.kind) else { return Err(not_one()) }; + let sym = d.symbols.iter().find(|x| x.name == *symbol).ok_or_else(|| bad(cmd, format!("no symbol named `{n}`", n = symbol)))?; + if !sym.dynamic { + let name = &sym.name; + return Err(bad(cmd, format!("`{name}` is a static symbol: set its Symbol Type to Dynamic first"))); + } + Ok((id, sym.art.clone())) +} + +/// The selected object of a dynamic symbol instance's art (Direct Selection): the instance and the +/// object's path in the symbol's art. +pub(crate) fn selected_part(s: &Session) -> Result)>> { + Ok(s.doc()?.selection.symbol_part.as_ref().map(|sp| (sp.instance, sp.path.clone()))) +} + +/// Change instance `id`'s own appearance for the object at `path` of its art by `f`, as one undo +/// step named `label`; nothing is recorded when the change leaves it as it was. Replies how many +/// objects the instance changes. +pub(crate) fn edit_part(s: &mut Session, id: NodeId, path: &[u32], label: &str, f: impl FnOnce(&mut SymbolOverride)) -> Result { + let list = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.extras().symbol_overrides.clone(); + let old = list.iter().find(|o| o.path == path).cloned().unwrap_or_else(|| SymbolOverride { path: path.to_vec(), ..Default::default() }); + let mut new = old.clone(); + f(&mut new); + if new == old { + return Ok(list.len()); + } + s.edit(label, |d, _| { + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + let mut e = n.extras_mut(); + let list = &mut e.symbol_overrides; + list.retain(|o| o.path != path); + if !new.is_empty() { + list.push(new); + } + Ok(list.len()) + }) +} + +/// The refusal of anything but a solid color fill or stroke change while an object of a symbol +/// instance's art is selected ([`selected_part`]), and of selecting any other object of the art. +pub(crate) fn part_only() -> EngineError { + EngineError::Other("Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change".into()) +} + +pub(super) fn symbol_instance_select_part(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.instance.selectPart"; + if p.get("id").is_none() { + return Err(bad(C, "missing id")); + } + let (id, art) = dynamic_instance(s, p, C)?; + let path = path_param(p, &art, C)?; + // Direct Selection passes over hidden, locked and template objects, and over everything in a + // group or layer that is: the instance in the document, and the object in the symbol's art. + let editable = |n: &Node| n.visible && !n.locked && !n.is_template(); + if !s.doc()?.doc.is_editable(id) || !(0..=path.len()).all(|k| symbol_overrides::part(&art, &path[..k]).is_some_and(editable)) { + return Err(bad(C, "the object is hidden or locked")); + } + if !symbol_overrides::part(&art, &path).is_some_and(symbol_overrides::takes_part_paint) { + return Err(part_only()); + } + let shown = json!(path); + s.select(|_, sel| sel.set_symbol_part(id, path))?; + Ok(json!({ "id": id.0, "path": shown })) +} + +/// The `path` param: child indices from the art's root, naming an object of `art`. +fn path_param(p: &Value, art: &Node, cmd: &str) -> Result> { + let path: Option> = + p.get("path").and_then(Value::as_array).and_then(|a| a.iter().map(|i| i.as_u64().and_then(|i| u32::try_from(i).ok())).collect()); + let path = path.ok_or_else(|| bad(cmd, "path must be a list of child indices"))?; + if symbol_overrides::part(art, &path).is_none() { + let shown = json!(path); + return Err(bad(cmd, format!("no object at path {shown} in the symbol's art"))); + } + Ok(path) +} + +/// The refusal of `key` (`fill` or `stroke`) for `n`, an object of a dynamic symbol's art, when `n` +/// does not draw that paint of its own; `None` when it does. Paths (not guides), +/// compound paths, type, groups and layers draw them; a symbol instance draws its fill as a stain +/// on its art ([`solid_fill_check`]) and no stroke; an image draws one only when that fill or +/// stroke has a Convert to Shape or Outline Object effect. +fn paint_refusal(n: &Node, key: &str, cmd: &str) -> Option { + Some(match &n.kind { + NodeKind::Path { guide: true, .. } => bad(cmd, format!("{key} cannot be set on a guide")), + NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_) | NodeKind::Group { .. } | NodeKind::Layer { .. } => return None, + NodeKind::Image(_) => { + let effects = if key == "fill" { n.appearance.fill().map(|f| &f.effects) } else { n.appearance.stroke().map(|s| &s.effects) }; + if effects.is_some_and(|e| vectorcraft_render::effects::gives_image_shape(e)) { + return None; + } + bad(cmd, format!("{key} cannot be set on an image without a Convert to Shape or Outline Object effect on it")) + } + NodeKind::SymbolInstance { .. } if key == "fill" => return None, + NodeKind::SymbolInstance { .. } => bad(cmd, "stroke cannot be set on a symbol instance"), + NodeKind::Blend { .. } => bad(cmd, format!("{key} cannot be set on a blend")), + NodeKind::Envelope { .. } => bad(cmd, format!("{key} cannot be set on an envelope")), + NodeKind::Mesh(_) => bad(cmd, format!("{key} cannot be set on a gradient mesh")), + NodeKind::Repeat(_) => bad(cmd, format!("{key} cannot be set on a Repeat")), + NodeKind::PlacedDocument(_) => bad(cmd, format!("{key} cannot be set on a placed document")), + NodeKind::Intertwine { .. } => bad(cmd, format!("{key} cannot be set on an Intertwine group")), + }) +} + +/// Refuse a `fill` or `stroke` other than null that the object at `path` of `art` does not draw +/// ([`paint_refusal`]); null, which takes a change back, is taken for every object. +fn check_paint_kinds(p: &Value, art: &Node, path: &[u32], cmd: &str) -> Result<()> { + let Some(n) = symbol_overrides::part(art, path) else { return Ok(()) }; + for key in ["fill", "stroke"] { + if p.get(key).is_some_and(|v| !v.is_null()) + && let Some(e) = paint_refusal(n, key, cmd) + { + return Err(e); + } + } + Ok(()) +} + +/// Refuse `fill`, the paint `p` asks for the object at `path` of `art`, when that object is a +/// symbol instance and `fill` is a gradient or a pattern: an instance stains its art with a solid +/// fill only, so such a fill draws nothing. +fn solid_fill_check(p: &Value, art: &Node, path: &[u32], fill: Option<&vectorcraft_color::Paint>, cmd: &str) -> Result<()> { + let asked = p.get("fill").is_some_and(|v| !v.is_null()); + let is_instance = symbol_overrides::part(art, path).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })); + let draws_nothing = |f: &vectorcraft_color::Paint| match f { + vectorcraft_color::Paint::Gradient(_) => true, + vectorcraft_color::Paint::Pattern { .. } => true, + vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. } => false, + }; + if asked && is_instance && fill.is_some_and(draws_nothing) { + return Err(bad(cmd, "fill on a symbol instance must be a solid color or none")); + } + Ok(()) +} + +/// `fill` or `stroke` of `p` for override `o`: absent leaves it, null clears it, a colour string or +/// an object of `paint.setFill`'s paint params sets it. +fn paint_change(s: &Session, p: &Value, key: &str, cmd: &str) -> Result>> { + let Some(v) = p.get(key) else { return Ok(None) }; + if v.is_null() { + return Ok(Some(None)); + } + let v = if v.is_string() { json!({ "color": v }) } else { v.clone() }; + let paint = crate::cmd::paint::paint_from(s, &v)?.ok_or_else(|| bad(cmd, "give color, none, swatch or gradient"))?; + Ok(Some(Some(paint))) +} + +/// The change `p` asks of the override `old` (for the object at `path`). +fn changed(s: &Session, p: &Value, old: SymbolOverride, cmd: &str) -> Result { + let mut o = old; + if let Some(fill) = paint_change(s, p, "fill", cmd)? { + o.fill = fill; + } + if let Some(stroke) = paint_change(s, p, "stroke", cmd)? { + o.stroke = stroke; + } + check_numbers(p, &["opacity"], cmd)?; + if let Some(v) = p.get("opacity") { + o.opacity = v.as_f64().map(crate::cmd::opacitymask::percent); + } + if let Some(v) = p.get("blend") { + o.blend = match v { + Value::Null => None, + b => Some(b.as_str().and_then(BlendMode::parse).ok_or_else(|| bad(cmd, format!("unknown blend mode {b}")))?), + }; + } + Ok(o) +} + +pub(super) fn symbol_instance_set_appearance(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.instance.setAppearance"; + if !["fill", "stroke", "opacity", "blend"].iter().any(|k| p.get(k).is_some()) { + return Err(bad(C, "give fill, stroke, opacity and/or blend")); + } + let (id, art) = dynamic_instance(s, p, C)?; + let path = path_param(p, &art, C)?; + check_paint_kinds(p, &art, &path, C)?; + let d = &s.doc()?.doc; + let old = d.node(id).and_then(|n| n.extras().symbol_overrides.iter().find(|o| o.path == path).cloned()); + let new = changed(s, p, old.unwrap_or_else(|| SymbolOverride { path: path.clone(), ..Default::default() }), C)?; + solid_fill_check(p, &art, &path, new.fill.as_ref(), C)?; + let count = edit_part(s, id, &path, "Symbol Instance Appearance", |o| *o = new)?; + Ok(json!({ "id": id.0, "overrides": count })) +} + +pub(super) fn symbol_instance_reset(s: &mut Session, p: &Value) -> Result { + let ids = selected_instances(s, p)?; + if ids.is_empty() { + return Err(EngineError::Other("no symbol instances selected".into())); + } + let d = &s.doc()?.doc; + let changed: Vec = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| !n.extras().symbol_overrides.is_empty())).collect(); + if !changed.is_empty() { + s.edit("Reset Symbol Instance", |d, _| { + for id in &changed { + if let Some(n) = d.node_mut(*id) { + n.extras_mut().symbol_overrides.clear(); + } + } + Ok(()) + })?; + } + Ok(json!({ "ids": ids_json(&changed) })) +} diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 8e8ba163ee..60353921e4 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1,17 +1,19 @@ +use super::dynamic::{fit_overrides, type_id, type_param}; use super::{ Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result, - SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_value, ids_json, json, + SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_param, ids_json, json, name_param, number_or, ok, remove_each, roots, selection_art, separate, set_unknown, str_param, switch_or, }; // ---------- 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)) + stored_natural_size(d, name).unwrap_or((2.0 * HALF, 2.0 * HALF)) +} + +/// The natural size `d` records for symbol `name` (`None` when it records none). +pub(crate) fn stored_natural_size(d: &Document, name: &str) -> Option<(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()?))) } pub(crate) fn set_natural_size(d: &mut Document, name: &str, size: Option<(f64, f64)>) { @@ -46,7 +48,8 @@ fn export_type_param(p: &Value, cmd: &str) -> Result> { /// `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). +/// on with guides `g` (the symbol's current ones, else a quarter in from each edge, when none are +/// given). fn nine_slice_param(p: &Value, cmd: &str, current: Option) -> Result>> { let on = match p.get("nineSlice") { None | Some(Value::Null) => None, @@ -106,6 +109,37 @@ fn instances_of(d: &Document, name: Option<&str>) -> Vec { v } +/// The symbols an instance in `n` (its opacity masks included) places, pushed onto `out`. +fn art_symbols(n: &Node, out: &mut Vec) { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + if let NodeKind::SymbolInstance { symbol, .. } = &m.kind { + out.push(symbol.clone()); + } + }); +} + +/// Select All Unused (#4918): the symbols nothing places. Instances in the art (opacity masks +/// included), graph designs, pattern tiles and the tiles that pattern editing's Cancel puts back, +/// and the art of the document's brushes count, and so do the instances in the art of every symbol +/// a counted instance places. A symbol placed only inside an unused symbol is unused too. +pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result { + let d = &s.doc()?.doc; + let mut todo = vec![]; + let lib = brush::library(d); + let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); + let trees = d.layers.iter().map(|l| &**l).chain(d.graph_designs.iter().map(|g| &*g.art)); + trees.chain(patterns.flat_map(|p| p.art.iter().map(|n| &**n))).chain(lib.iter().flat_map(|b| b.art())).for_each(|n| art_symbols(n, &mut todo)); + let mut used = std::collections::BTreeSet::new(); + while let Some(name) = todo.pop() { + if !used.contains(&name) { + d.symbols.iter().filter(|sym| sym.name == name).for_each(|sym| art_symbols(&sym.art, &mut todo)); + used.insert(name); + } + } + let names: Vec<&str> = d.symbols.iter().map(|sym| sym.name.as_str()).filter(|n| !used.contains(*n)).collect(); + Ok(json!({ "names": names })) +} + fn symbol_names(d: &Document) -> Vec { d.symbols.iter().map(|s| s.name.clone()).collect() } @@ -128,12 +162,32 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result { "registration": d.symbol_registration(&sym.name).0, "exportType": d.symbol_export_type(&sym.name).id(), "nineSlice": nine_slice_json(d, &sym.name), + "type": type_id(sym.dynamic), }) }) .collect(); Ok(json!({ "symbols": list, "current": current_symbol(d).or_else(|| symbol_names(d).into_iter().next()) })) } +/// Store `art` ([`normalize`]d, of natural size `size`) as symbol `name`, which becomes the +/// current symbol. +pub(crate) fn store_symbol(d: &mut Document, art: &Node, name: &str, size: (f64, f64)) { + let art = d.reid(art); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + set_natural_size(d, name, Some(size)); + d.unknown.insert(CURRENT_SYMBOL.into(), json!(name)); +} + +/// Replace the root nodes `ids` with one instance of symbol `name` (already stored) placed by +/// `xf`. Frames of threaded text among them leave their threads with the text they show. Returns +/// the instance's id. +pub(crate) fn instance_in_place(d: &mut Document, ids: &[NodeId], name: &str, xf: Affine) -> Result { + let threaded = crate::cmd::threads::frames(d); + let id = replace_with_instance(d, ids, name, xf)?; + crate::cmd::threads::leave_threads(d, &threaded); + Ok(id) +} + /// Replace the root nodes `ids` with one instance of `name` (art already stored). Returns the id. fn replace_with_instance(d: &mut Document, ids: &[NodeId], name: &str, xf: Affine) -> Result { let top = *ids.last().ok_or_else(|| EngineError::Other("nothing selected".into()))?; @@ -160,26 +214,29 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { let reg = registration_param(p, C)?.unwrap_or(SymbolRegistration::CENTER); let export = export_type_param(p, C)?.unwrap_or_default(); let nine = nine_slice_param(p, C, None)?.flatten(); + let dynamic = type_param(p, C)?.unwrap_or(false); // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); let id = s.edit("New Symbol", |d, sel| { - let art = d.reid(&art); - d.symbols.push(Symbol { name: name.clone(), art: Arc::new(art) }); - set_natural_size(d, &name, Some(size)); + store_symbol(d, &art, &name, size); + if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) { + sym.dynamic = dynamic; + } d.set_symbol_registration(&name, reg); d.set_symbol_export_type(&name, export); d.set_symbol_nine_slice(&name, nine); - d.unknown.insert(CURRENT_SYMBOL.into(), json!(name)); - let threaded = crate::cmd::threads::frames(d); - let id = replace_with_instance(d, &ids, &name, place)?; - // Frames of threaded text in the symbol leave their threads with the text they show. - crate::cmd::threads::leave_threads(d, &threaded); + let id = instance_in_place(d, &ids, &name, place)?; sel.set([id]); Ok(id) })?; - Ok( - json!({ "name": name, "id": id.0, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }), - ) + Ok(json!({ + "name": name, + "id": id.0, + "registration": reg.0, + "exportType": export.id(), + "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value), + "type": type_id(dynamic), + })) } pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { @@ -188,9 +245,10 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { let export = export_type_param(p, C)?; let reg = registration_param(p, C)?; let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?; + let dynamic = type_param(p, C)?; let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); - if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() { - return Err(bad(C, "pass newName, registration, exportType and/or nineSlice")); + if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() { + return Err(bad(C, "pass newName, registration, exportType, nineSlice and/or type")); } if let Some(ref n) = new_name && n != &name @@ -218,6 +276,14 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { d.unknown.insert(CURRENT_SYMBOL.into(), json!(n)); } + // Symbol editing mode follows the new name, and so does its layer. + if let Some(e) = d.symbol_edit.as_mut().filter(|e| e.symbol == name) { + e.symbol = n.clone(); + let layer = e.layer; + if let Some(l) = d.node_mut(layer) { + l.name = Some(n.clone()); + } + } } if let Some(r) = reg { d.set_symbol_registration(&final_name, r); @@ -228,6 +294,13 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { if let Some(g) = nine { d.set_symbol_nine_slice(&final_name, g); } + if let Some(dynamic) = dynamic + && let Some(sym) = d.symbols.iter_mut().find(|x| x.name == final_name) + { + // A static symbol's instances drop their own appearance changes. + sym.dynamic = dynamic; + fit_overrides(d, &instances_of(d, Some(&final_name))); + } Ok(()) })?; let d = &s.doc()?.doc; @@ -236,6 +309,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { "registration": d.symbol_registration(&final_name).0, "exportType": d.symbol_export_type(&final_name).id(), "nineSlice": nine_slice_json(d, &final_name), + "type": type_id(d.symbols.iter().any(|x| x.name == final_name && x.dynamic)), })) } @@ -266,17 +340,18 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0 })) } -/// The plain art of instance `inst` in document space (fresh ids). -fn expanded_instance(d: &mut Document, inst: &Node) -> Option { +/// The plain art of instance `inst` in document space (fresh ids), with the instance's own +/// appearance changes to a dynamic symbol's art when `own`, placed through its symbol's 9-slice +/// guides when it has them. The instance's opacity mask goes on the art, or on a group around it +/// when the art has a mask of its own. +fn expanded_instance(d: &mut Document, inst: &Node, own: bool) -> Option { let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None }; let sym = d.symbols.iter().find(|s| &s.name == symbol)?; - let mut art = (*sym.art).clone(); - if let Some(f) = inst.appearance.fill() - && let Some(c) = f.paint.color() - { - brush::tint_node(&mut art, &c, f.opacity); + let mut art = if own { vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst) } else { (*sym.art).clone() }; + if let Some((color, amount)) = brush::stain(inst) { + brush::tint_node(&mut art, &color, amount); } - art.transform(*xf, false); + let art = d.place_symbol_art(symbol, &art, *xf)?; let mut art = d.reid(&art); if inst.opacity < 1.0 || inst.blend != vectorcraft_color::BlendMode::Normal { if !matches!(art.kind, NodeKind::Group { .. }) { @@ -286,14 +361,47 @@ fn expanded_instance(d: &mut Document, inst: &Node) -> Option { art.opacity *= inst.opacity; art.blend = inst.blend; } + if let Some(mask) = &inst.extras().mask { + if art.extras().mask.is_some() { + let id = d.alloc_id(); + art = Node::group(id, vec![Arc::new(art)]); + } + art.extras_mut().mask = Some(mask.clone()); + } Some(art) } -fn break_links(d: &mut Document, ids: &[NodeId]) -> Result> { +/// The most objects [`expanded_instance`] makes of instance `inst` in `d` (`own` as there): its +/// symbol's object count with the art of its opacity masks, or +/// [`vectorcraft_doc::NineSliceMap::most_placed`] when it is placed through 9-slice guides, plus +/// the group that opacity, a blending mode or the instance's opacity mask adds, plus the art of +/// the instance's opacity mask. 0 for any other object. +fn expanded_bound(d: &Document, inst: &Node, own: bool) -> u64 { + let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return 0 }; + let Some(sym) = d.symbols.iter().find(|s| &s.name == symbol) else { return 0 }; + let dynamic = own && !inst.extras().symbol_overrides.is_empty(); + let most = match d.symbol_slice_map(symbol, *xf) { + Some(m) if dynamic => m.most_placed(&vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst), d), + Some(m) => m.most_placed(&sym.art, d), + None if dynamic => vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst).count_with_masks() as u64, + None => sym.art.count_with_masks() as u64, + }; + let mask = inst.extras().mask.as_ref().map_or(0, |m| m.art.count_with_masks() as u64); + most.saturating_add(1).saturating_add(mask) +} + +/// Replace instances `ids` with their art ([`expanded_instance`], `own` as there). Returns the +/// art's ids. Fails before any edit when the instances together would make more than +/// [`MAX_EXPAND_NODES`] objects. +fn break_links(d: &mut Document, ids: &[NodeId], own: bool) -> Result> { + let total = ids.iter().filter_map(|id| d.node(*id)).fold(0u64, |sum, n| sum.saturating_add(expanded_bound(d, n, own))); + if total > MAX_EXPAND_NODES as u64 { + return Err(EngineError::Other("Too many pieces to make at once".into())); + } let mut out = vec![]; for id in ids { let Some(inst) = d.node(*id).cloned() else { continue }; - let Some(art) = expanded_instance(d, &inst) else { continue }; + let Some(art) = expanded_instance(d, &inst, own) else { continue }; let (par, idx, _) = d.position(*id).ok_or(EngineError::NoNode(*id))?; let aid = art.id; d.remove(*id)?; @@ -303,7 +411,67 @@ fn break_links(d: &mut Document, ids: &[NodeId]) -> Result> { Ok(out) } -fn selected_instances(s: &Session, p: &Value) -> Result> { +/// Object › Expand: the symbol instances under `roots` of `d` ([`expandable_instances`]) replaced +/// by their art, as Break Link places it, each keeping the instance's id and place. The instances +/// that art holds stay instances. A hidden or locked instance's art stays hidden or locked. When +/// the instances together would make more than [`MAX_EXPAND_NODES`] objects, all of them stay +/// instances. Returns whether any instance was expanded. +pub(crate) fn expand_instances_under(d: &mut Document, roots: &[NodeId]) -> Result { + let ids = expandable_instances(d, roots); + let total = ids.iter().filter_map(|id| d.node(*id)).fold(0u64, |sum, n| sum.saturating_add(expanded_bound(d, n, true))); + if total > MAX_EXPAND_NODES as u64 { + return Ok(false); + } + let mut any = false; + for id in ids { + let Some(inst) = d.node(id).cloned() else { continue }; + let Some(mut art) = expanded_instance(d, &inst, true) else { continue }; + let (par, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?; + art.id = id; + art.visible &= inst.visible; + art.locked |= inst.locked; + d.remove(id)?; + d.insert(par, idx, art)?; + any = true; + } + Ok(any) +} + +/// The symbol instances under `roots` of `d` that Object › Expand turns into their art: those +/// without effects (Expand Appearance bakes the others), with no effects on their fills and +/// strokes, not in perspective, and whose symbol `d` holds. The instances in blends, repeats and +/// Intertwine groups are left to Expand, which turns those into plain groups. +pub(crate) fn expandable_instances(d: &Document, roots: &[NodeId]) -> Vec { + fn collect(d: &Document, n: &Node, out: &mut Vec) { + match &n.kind { + NodeKind::SymbolInstance { symbol, .. } => { + if n.appearance.effects.is_empty() + && n.appearance.items.iter().all(|i| i.effects().is_empty()) + && n.projection().is_none() + && d.symbols.iter().any(|s| &s.name == symbol) + { + out.push(n.id); + } + } + NodeKind::Blend { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => {} + _ => { + for c in n.children().into_iter().flatten() { + collect(d, c, out); + } + } + } + } + let mut out = vec![]; + for n in roots.iter().filter_map(|r| d.node(*r)) { + collect(d, n, &mut out); + } + out +} + +/// How many objects [`break_links`] and [`expand_instances_under`] may make at once. +const MAX_EXPAND_NODES: usize = 1_000_000; + +pub(super) fn selected_instances(s: &Session, p: &Value) -> Result> { let d = &s.doc()?.doc; let mut out = vec![]; for id in roots(s, p)? { @@ -324,86 +492,151 @@ pub(super) fn symbol_break_link(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other("no symbol instances selected".into())); } let out = s.edit("Break Link to Symbol", |d, sel| { - let out = break_links(d, &ids)?; + let out = break_links(d, &ids, true)?; sel.set(out.iter().copied()); Ok(out) })?; Ok(json!({ "ids": ids_json(&out) })) } -pub(super) fn symbol_edit(s: &mut Session, p: &Value) -> Result { - let ids = selected_instances(s, p)?; - let first = *ids.first().ok_or_else(|| EngineError::Other("select a symbol instance".into()))?; - let name = match &s.doc()?.doc.node(first).map(|n| n.kind.clone()) { - Some(NodeKind::SymbolInstance { symbol, .. }) => symbol.clone(), - _ => return Err(EngineError::Other("select a symbol instance".into())), - }; - let out = s.edit("Edit Symbol", |d, sel| { - let out = break_links(d, &[first])?; - sel.set(out.iter().copied()); - Ok(out) - })?; - Ok(json!({ "name": name, "ids": ids_json(&out) })) -} - pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { const C: &str = "symbol.update"; let name = name_param(p, C)?.to_string(); if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) { return Err(bad(C, format!("no symbol named `{name}`"))); } + // Redefining the symbol being edited leaves symbol editing mode in the same step. + let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name); + if session.is_some() { + crate::cmd::settle_interaction(s)?; + s.end_text_edit(); + } let ids = roots(s, p)?; + // The art on the editing layer can't redefine it: the symbol would hold an instance of itself. + if let Some(se) = &session { + let d = &s.doc()?.doc; + if ids.iter().any(|i| d.ancestry(*i).is_some_and(|a| a.contains(&se.layer))) { + return Err(EngineError::Other("a symbol can't hold an instance of itself".into())); + } + } let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?; crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art); let (art, size, c) = normalize(art)?; let old = natural_size(&s.doc()?.doc, &name); + let editing = session.is_some(); let id = s.edit("Redefine Symbol", |d, sel| { + if editing { + crate::cmd::symboledit::finish(d, sel); + } let art = d.reid(&art); if let Some(sym) = d.symbols.iter_mut().find(|x| x.name == name) { sym.art = Arc::new(art); } set_natural_size(d, &name, Some(size)); let fix = Affine::scale_non_uniform(size.0 / old.0, size.1 / old.1); - for i in instances_of(d, Some(&name)) { - if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(i).map(|n| &mut n.kind) { + let instances = instances_of(d, Some(&name)); + for i in &instances { + if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(*i).map(|n| &mut n.kind) { *xf *= fix; } } + // Each instance keeps its appearance changes to the objects the new art still has. + fit_overrides(d, &instances); let reg = d.symbol_registration(&name); - let threaded = crate::cmd::threads::frames(d); - let id = replace_with_instance(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?; - // Frames of threaded text in the symbol leave their threads with the text they show. - crate::cmd::threads::leave_threads(d, &threaded); + let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?; sel.set([id]); Ok(id) })?; + if let Some(se) = &session { + crate::cmd::symboledit::leave_editing(s, se)?; + } Ok(json!({ "name": name, "id": id.0 })) } +/// How many levels of nested instances Delete Symbol expands before it gives up. +const MAX_DELETE_ROUNDS: usize = 256; + pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result { const C: &str = "symbol.delete"; - let name = name_param(p, C)?.to_string(); - if !s.doc()?.doc.symbols.iter().any(|x| x.name == name) { + // `names` deletes several symbols in one undo step (the Symbols panel's Select All Unused, #4918). + let names: Vec = match p.get("names") { + Some(v) => { + let a = v.as_array().ok_or_else(|| bad(C, "names must be an array of symbol names"))?; + let mut names = Vec::with_capacity(a.len()); + for n in a { + let n = n.as_str().ok_or_else(|| bad(C, "names must be an array of symbol names"))?; + if !names.iter().any(|x: &String| x == n) { + names.push(n.to_string()); + } + } + if names.is_empty() { + return Err(bad(C, "names is empty")); + } + names + } + None => vec![name_param(p, C)?.to_string()], + }; + let d = &s.doc()?.doc; + if let Some(name) = names.iter().find(|n| !d.symbols.iter().any(|x| &x.name == *n)) { return Err(bad(C, format!("no symbol named `{name}`"))); } let expand = switch_or(p, "expandInstances", true, C)?; - s.edit("Delete Symbol", |d, _| { - let inst = instances_of(d, Some(&name)); - if expand { - break_links(d, &inst)?; - } else { - remove_each(d, &inst)?; + // Deleting the symbol being edited leaves symbol editing mode in the same step. + let session = s.doc()?.doc.symbol_edit.clone().filter(|e| names.contains(&e.symbol)); + let editing = session.is_some(); + if editing { + crate::cmd::settle_interaction(s)?; + s.end_text_edit(); + } + let label = if names.len() == 1 { "Delete Symbol" } else { "Delete Symbols" }; + s.edit(label, |d, sel| { + if editing { + crate::cmd::symboledit::finish(d, sel); } - d.symbols.retain(|x| x.name != name); - set_natural_size(d, &name, None); - d.set_symbol_registration(&name, SymbolRegistration::CENTER); - d.clear_symbol_export_type(&name); - d.set_symbol_nine_slice(&name, None); - if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { - d.unknown.remove(CURRENT_SYMBOL); + // Every instance goes before any definition, whatever the order of `names`: expanding an + // instance of one symbol can bring out instances of another being deleted (nested in its + // art), which expand in turn while their definitions are still there. Each round expands + // one level of nesting, so the rounds are capped. + let of_names = |d: &Document| { + let mut v = vec![]; + d.walk(|n| { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && names.contains(symbol) + { + v.push(n.id); + } + }); + v + }; + for _ in 0..=MAX_DELETE_ROUNDS { + let inst = of_names(d); + if inst.is_empty() { + break; + } + if expand { + break_links(d, &inst, true)?; + } else { + remove_each(d, &inst)?; + } + } + if !of_names(d).is_empty() { + return Err(EngineError::Other("the symbols are nested too deeply to expand their instances".into())); + } + for name in &names { + d.symbols.retain(|x| &x.name != name); + set_natural_size(d, name, None); + d.set_symbol_registration(name, SymbolRegistration::CENTER); + d.clear_symbol_export_type(name); + d.set_symbol_nine_slice(name, None); + if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { + d.unknown.remove(CURRENT_SYMBOL); + } } Ok(()) })?; + if let Some(se) = &session { + crate::cmd::symboledit::leave_editing(s, se)?; + } ok() } @@ -420,7 +653,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result { let nine = d.symbol_nine_slice(&name); s.edit("Duplicate Symbol", |d, _| { let art = d.reid(&sym.art); - d.symbols.push(Symbol { name: new.clone(), art: Arc::new(art) }); + d.symbols.push(Symbol { dynamic: sym.dynamic, name: new.clone(), art: Arc::new(art) }); set_natural_size(d, &new, Some(size)); d.set_symbol_registration(&new, reg); d.set_symbol_export_type(&new, export); @@ -443,20 +676,82 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result { s.edit("Replace Symbol", |d, _| { let new = natural_size(d, &name); for id in &ids { - let old = match d.node(*id).map(|n| &n.kind) { - Some(NodeKind::SymbolInstance { symbol, .. }) => natural_size(d, symbol), + let (old, other) = match d.node(*id).map(|n| &n.kind) { + Some(NodeKind::SymbolInstance { symbol, .. }) => (natural_size(d, symbol), *symbol != name), _ => continue, }; - if let Some(NodeKind::SymbolInstance { symbol, xf }) = d.node_mut(*id).map(|n| &mut n.kind) { + let Some(n) = d.node_mut(*id) else { continue }; + if let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind { *symbol = name.clone(); *xf *= Affine::scale_non_uniform(new.0 / old.0, new.1 / old.1); } + // An override's path names an object of the old symbol's art. + if other && !n.extras().symbol_overrides.is_empty() { + n.extras_mut().symbol_overrides.clear(); + } } + fit_overrides(d, &ids); Ok(()) })?; Ok(json!({ "ids": ids_json(&ids) })) } +/// How far a transform coefficient may be from Reset Transformation's for the instance to count as +/// already reset. +const RESET_TOLERANCE: f64 = 1e-9; + +/// The transform Reset Transformation gives instance `n` of the document of `boxes`: its symbol's +/// own scale, without rotation, shear or reflection, with the center of its art's bounding box +/// where it is. `None` when [`reset_transformation_changes`] is false for `n`. +fn reset_transformation(boxes: &vectorcraft_doc::SymbolBoxes, n: &Node) -> Option { + let d = boxes.document(); + if !reset_transformation_changes(d, n) { + return None; + } + let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None }; + let scale = d.symbol_natural_xf(symbol); + // The art's box in symbol space (the ±HALF square when the art cannot be measured): its + // center keeps its place on the page. + let art = boxes.art_bounds(symbol).unwrap_or_else(|| vectorcraft_geom::Rect::new(-HALF, -HALF, HALF, HALF)); + let center = xf.transform_rect_bbox(art).center(); + Some(Affine::translate(center - scale * art.center()) * scale) +} + +/// Does Reset Transformation change `n`? True for an instance of a symbol `d` holds, not in +/// perspective, whose scale, rotation, shear or reflection differs from the symbol's own scale +/// (its stored natural size, or the art unscaled when that size is not positive and finite). +/// It does not measure the art. +pub fn reset_transformation_changes(d: &Document, n: &Node) -> bool { + let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return false }; + if n.extras().perspective.is_some() || !d.symbols.iter().any(|s| s.name == *symbol) { + return false; + } + let natural = d.symbol_natural_xf(symbol).as_coeffs(); + xf.as_coeffs()[..4].iter().zip(&natural[..4]).any(|(a, b)| (a - b).abs() > RESET_TOLERANCE) +} + +pub(super) fn symbol_instance_reset_transform(s: &mut Session, p: &Value) -> Result { + let ids = selected_instances(s, p)?; + if ids.is_empty() { + return Err(EngineError::Other("no symbol instances selected".into())); + } + let d = &s.doc()?.doc; + let boxes = d.symbol_boxes(); + let changes: Vec<(NodeId, Affine)> = ids.iter().filter_map(|id| Some((*id, reset_transformation(&boxes, d.node(*id)?)?))).collect(); + if !changes.is_empty() { + s.edit("Reset Transformation", |d, _| { + for (id, new) in &changes { + if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(*id).map(|n| &mut n.kind) { + *xf = *new; + } + } + Ok(()) + })?; + } + let changed: Vec = changes.iter().map(|(id, _)| *id).collect(); + Ok(json!({ "ids": ids_json(&changed) })) +} + 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)))?; @@ -593,8 +888,10 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { let radius = number_or(p, "radius", 40.0, C)?.clamp(1.0, 2000.0); let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0; let alt = switch_or(p, "alt", false, C)?; + // Refused while an object of a dynamic instance's art is selected: the instance stays as it is. + crate::cmd::edit::refuse_symbol_part(s)?; let st = s.doc()?; - let color = match p.get("color").and_then(color_value) { + let color = match color_param(p, "color", C)? { Some(c) => crate::cmd::paint::new_color(s, p, c), None => s.paint.fill.color().unwrap_or(Color::BLACK), }; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 155e7d1647..d392449247 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -29,7 +29,7 @@ use super::edit::{outermost, selected_roots}; use super::paint::paint_from; use super::pathops::{Beside, shape_node}; use super::{ - CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, finite_numbers, has_doc, id_param, ids_param, + CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, finite_numbers, has_doc, id_param, named_ids, number_or, point_param, str_param, switch_or, }; @@ -40,7 +40,9 @@ 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}; +pub(crate) use trace::TracePresetChanges; +pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced}; +use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view}; /// Name of an Image Trace group. pub const TRACE_NAME: &str = "Image Trace"; @@ -70,7 +72,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Live Paint"], Some("Cmd+Alt+X"), - "{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}", + "{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); each covered face starts with its front-most covering source's fill; 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 ), @@ -106,7 +108,7 @@ pub fn specs() -> Vec { "Gap Options", [], None, - "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", + "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", has_selection_or_ids, lp_gap_options ), @@ -115,7 +117,7 @@ pub fn specs() -> Vec { "Live Paint Bucket", [], None, - "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}", + "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}", has_doc, lp_fill ), @@ -142,7 +144,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), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, white is always its own colour, at most ten; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white unless ignoreWhite makes them holes; fills/strokes are ignored; gradients and photos are refused)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), @@ -151,7 +153,7 @@ pub fn specs() -> Vec { "Make and Expand", ["Object", "Image Trace"], None, - "{…as imageTrace.make} same as imageTrace.make, then expand → {id, paths, anchors, colors}", + "{…as imageTrace.make, byColor?: false (each color's paths in a group of their own, as imageTrace.expand)} same as imageTrace.make, then expand → {id, paths, anchors, colors, warnings: [text…] (as imageTrace.make)}", has_selection_or_ids, |s, p| trace_make(s, p, true) ), @@ -169,7 +171,7 @@ pub fn specs() -> Vec { "Expand", ["Object", "Image Trace"], None, - "{id?, ids?: [id…] (instead of id)} keep only the traced paths (drop the source image) → {ids}", + "{id?, ids?: [id…] (instead of id), byColor?: false (each color's paths in a group of their own, named by the swatch the color links to or as #rrggbb, gradient fills in one group named Gradients; the groups stack by their lowest path and keep their paths' order; a color whose paths overlap another color's from above and below gets a group for each part, so the art draws the same; refused for a trace made with autoGrouping and for a trace with a live Pathfinder effect)} keep only the traced paths (drop the source image) → {ids}", has_selection_or_ids, trace_expand ), @@ -182,9 +184,29 @@ pub fn specs() -> Vec { has_selection_or_ids, trace_set_view ), - cmd!(query "imageTrace.presets", "Image Trace Presets", [], None, "{} → {presets: [{name, params, enhanced: the params of the preset's enhanced version, null if it has none}]}", always, |_, _| { - Ok(json!({ "presets": tr::presets().into_iter().map(|(n, p)| json!({ "name": n, "params": p, "enhanced": tr::enhanced_preset(n) })).collect::>() })) + cmd!(query "imageTrace.presets", "Image Trace Presets", [], None, "{} → {presets: [{name, builtIn, params, enhanced: the params of the preset's enhanced version, null if it has none}], revision: grows each time the saved presets change} the built-in presets, then the saved ones (builtIn false, enhanced null); any of these names works as imageTrace.make's `preset`", always, |s, _| { + let builtin = tr::presets().into_iter().map(|(n, p)| json!({ "name": n, "builtIn": true, "params": p, "enhanced": tr::enhanced_preset(n) })); + let saved = s.prefs.trace_presets.iter().map(|p| json!({ "name": p.name, "builtIn": false, "params": p.params, "enhanced": null })); + Ok(json!({ "presets": builtin.chain(saved).collect::>(), "revision": s.trace_presets_revision() })) }), + cmd!( + query "imageTrace.presets.save", + "Save Image Trace Preset", + [], + None, + "{name?: (default: a new \"Tracing Preset N\"), newName?: rename the saved preset `name`, preset?: the preset to start from (default: the saved preset `name`, else Default), enhanced?, params?: {settings, as imageTrace.make takes them, over the preset's}} create or change a saved tracing preset, kept with the preferences (built-in ones can't change) → {name, params, created, renamedFrom: the name before `newName` changed it, else null}", + always, + trace_presets_save + ), + cmd!( + query "imageTrace.presets.delete", + "Delete Image Trace Preset", + [], + None, + "{name} delete a saved tracing preset (built-in ones stay) → {deleted: name}", + always, + trace_presets_delete + ), ] } @@ -198,7 +220,7 @@ fn has_multi_or_ids(s: &Session) -> std::result::Result<(), String> { } fn root_ids(s: &Session, p: &Value) -> Result> { - let ids = match ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])) { + let ids = match named_ids(p)? { Some(v) => v, None => selected_roots(s)?, }; diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index c1e66d27cd..9c6c28b900 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -1,8 +1,19 @@ +use std::collections::HashMap; + +use vectorcraft_color::Swatch; +use vectorcraft_doc::ImageObject; + use super::{ - Appearance, AppearanceItem, Arc, Beside, Color, Document, EngineError, LineCap, LineJoin, LiveShape, Node, NodeId, NodeKind, Paint, Point, + Appearance, AppearanceItem, Arc, Beside, Color, Document, EngineError, LineCap, LineJoin, LiveShape, Node, NodeId, NodeKind, Paint, Point, Rect, Result, Session, StrokeLayer, TRACE_NAME, TraceView, Value, bad, fill_only, ids_json, json, root_ids, shape_node, str_param, switch_or, tr, }; +#[cfg(test)] +thread_local! { + static BOX_TESTS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static CANDIDATE_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + // ---------- Image Trace ---------- fn is_trace_group(n: &Node) -> bool { @@ -11,6 +22,8 @@ fn is_trace_group(n: &Node) -> bool { && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) } +const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor"; + /// The `view` param ([`TraceView`] id), if given. fn view_param(cmd: &str, p: &Value) -> Result> { let Some(v) = p.get("view").filter(|v| !v.is_null()) else { return Ok(None) }; @@ -18,24 +31,183 @@ fn view_param(cmd: &str, p: &Value) -> Result> { 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"); +/// A saved Image Trace preset ([`crate::Prefs::trace_presets`]): a name and its settings. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TracePreset { + pub name: String, + #[serde(default)] + pub params: tr::TraceParams, +} + +/// A change to the saved tracing presets: `imageTrace.presets.save` saved `name` (made it, +/// changed its settings, or renamed it from `renamed_from`), or `imageTrace.presets.delete` +/// deleted it. `revision` is [`Session::trace_presets_revision`] after the change. +#[derive(Clone, Debug, PartialEq)] +pub struct TracePresetChange { + pub revision: u64, + pub name: String, + pub renamed_from: Option, + pub deleted: bool, +} + +/// The revision of the saved tracing presets and their latest changes ([`TracePresetChange`]). +#[derive(Default)] +pub(crate) struct TracePresetChanges { + revision: u64, + /// Every change the commands made in this session, oldest first, so a panel that was closed + /// meanwhile still follows a rename (one record for each save or delete). + changes: Vec, +} + +impl TracePresetChanges { + /// A change the commands made: a new revision that records it. + fn note(&mut self, mut change: TracePresetChange) { + self.revision += 1; + change.revision = self.revision; + self.changes.push(change); + } + + /// A change made by replacing the preferences: a new revision with no record. + pub(crate) fn replaced(&mut self) { + self.revision += 1; + } +} + +impl Session { + /// A number that grows each time the saved tracing presets change: saved, renamed or deleted + /// by `imageTrace.presets.save` and `.delete`, or replaced with the preferences + /// ([`Session::apply_prefs`]). A list read at one revision holds until the number changes. + pub fn trace_presets_revision(&self) -> u64 { + self.trace_preset_changes.revision + } + + /// The changes `imageTrace.presets.save` and `.delete` made after `revision`, oldest first. + pub fn trace_preset_changes_since(&self, revision: u64) -> impl Iterator { + let changes = &self.trace_preset_changes.changes; + let from = changes.partition_point(|c| c.revision <= revision); + changes.get(from..).unwrap_or_default().iter() + } + + /// The saved tracing preset `name`, any case. + pub fn trace_preset(&self, name: &str) -> Option<&TracePreset> { + self.prefs.trace_presets.iter().find(|q| q.name.eq_ignore_ascii_case(name.trim())) + } + + /// The index of the saved tracing preset `name`. + fn trace_preset_index(&self, name: &str) -> Option { + self.prefs.trace_presets.iter().position(|q| q.name.eq_ignore_ascii_case(name.trim())) + } + + /// Whether `name` is a built-in preset's, "Custom" (changed settings, as the panel and a traced + /// object show them), or a saved preset's other than the one at `except`. + fn trace_preset_taken(&self, name: &str, except: Option) -> bool { + tr::preset(name).is_some() || name.trim().eq_ignore_ascii_case("Custom") || self.trace_preset_index(name).is_some_and(|i| Some(i) != except) + } + + /// The first free "Tracing Preset N": the name a new tracing preset gets. + pub fn new_trace_preset_name(&self) -> String { + (1..).map(|i| format!("Tracing Preset {i}")).find(|n| !self.trace_preset_taken(n, None)).unwrap_or_default() + } +} + +pub(super) fn trace_presets_save(s: &mut Session, p: &Value) -> Result { + const C: &str = "imageTrace.presets.save"; + // A name or preset of the wrong type is an error, not dropped: dropping it would save other + // settings, or under another name. + let new_name = opt_str(C, p, "newName")?; + let preset = opt_str(C, p, "preset")?; + let name = match opt_str(C, p, "name")?.map(str::trim) { + Some("") => return Err(bad(C, "`name` is empty")), + Some(n) => n.to_string(), + None => s.new_trace_preset_name(), + }; + if tr::preset(&name).is_some() { + return Err(bad(C, format!("`{name}` is a built-in preset and can't change: save it under another name"))); + } + if name.eq_ignore_ascii_case("Custom") { + return Err(bad(C, "`Custom` stands for changed settings: save the preset under another name")); + } + let at = s.trace_preset_index(&name); + // The saved preset's name as it was saved. + let old = at.and_then(|i| s.prefs.trace_presets.get(i)).map(|q| q.name.clone()); + if old.is_none() && new_name.is_some() { + return Err(bad(C, format!("no saved preset named `{name}` to rename"))); + } + // A saved preset changes from its own settings unless `preset` says where to start. + let mut q = p.clone(); + if let (Some(old), Some(o), None) = (&old, q.as_object_mut(), preset) { + o.insert("preset".into(), json!(old)); + } + let params = trace_params(s, C, &q)?; + let name = match new_name.map(str::trim) { + Some("") => return Err(bad(C, "`newName` is empty")), + Some(n) if s.trace_preset_taken(n, at) => return Err(bad(C, format!("a preset named `{n}` exists"))), + Some(n) => n.to_string(), + None => old.clone().unwrap_or(name), + }; + let json_params = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?; + let preset = TracePreset { name: name.clone(), params }; + match at.and_then(|i| s.prefs.trace_presets.get_mut(i)) { + Some(slot) => *slot = preset, + None => s.prefs.trace_presets.push(preset), + } + let renamed_from = old.as_ref().filter(|o| **o != name).cloned(); + s.trace_preset_changes.note(TracePresetChange { revision: 0, name: name.clone(), renamed_from: renamed_from.clone(), deleted: false }); + Ok(json!({"name": name, "params": json_params, "created": old.is_none(), "renamedFrom": renamed_from})) +} + +pub(super) fn trace_presets_delete(s: &mut Session, p: &Value) -> Result { + const C: &str = "imageTrace.presets.delete"; + let name = opt_str(C, p, "name")?.ok_or_else(|| bad(C, "missing `name`"))?; + if tr::preset(name).is_some() { + return Err(bad(C, format!("`{name}` is a built-in preset and stays"))); + } + let i = s.trace_preset_index(name).ok_or_else(|| bad(C, format!("no saved preset named `{name}`")))?; + let deleted = s.prefs.trace_presets.remove(i).name; + s.trace_preset_changes.note(TracePresetChange { revision: 0, name: deleted.clone(), renamed_from: None, deleted: true }); + Ok(json!({ "deleted": deleted })) +} + +/// The string `key` of `p` (`None` when it is missing or null); any other type is an error of +/// command `c`. +fn opt_str<'a>(c: &str, p: &'a Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(v)) => Ok(Some(v)), + Some(_) => Err(bad(c, format!("`{key}` must be a string"))), + } +} + +/// The parameters command `c` traces with: the preset's (built-in, else the `savedPreset` +/// settings a journal entry records, else saved), with `params` over them. +fn trace_params(s: &Session, c: &str, p: &Value) -> Result { + let name = opt_str(c, 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 recorded = match p.get("savedPreset").filter(|v| !v.is_null()) { + Some(v) => Some(serde_json::from_value::(v.clone()).map_err(|e| bad(c, format!("savedPreset: {e}")))?), + None => None, + }; + // (A preset without an enhanced version, a saved one too, 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()))?; + let base = base.or(recorded).or_else(|| s.trace_preset(name).map(|q| q.params.clone())); + let base = base.ok_or_else(|| bad(c, format!("unknown preset `{name}`: not a built-in or saved preset (see imageTrace.presets)")))?; + let params: tr::TraceParams = match p.get("params").filter(|v| !v.is_null()) { + None => base, + Some(over) => { + 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()); + } + serde_json::from_value(v).map_err(|e| bad(c, e.to_string()))? + } + }; + // (Recorded and saved settings are checked too.) if !params.fills && !params.strokes { return Err(bad(c, "Create needs fills, strokes or both")); } @@ -58,41 +230,55 @@ fn trace_params(c: &str, p: &Value) -> Result { Ok(params) } +/// Document swatch `w`'s displayed solid color and unlinked trace paint. A tint uses its tinted +/// color; a Lab spot color uses its CMYK equivalent when the Spot Colors options use CMYK values. +fn trace_swatch_paint(d: &Document, w: &Swatch) -> Option<(Color, Paint)> { + let linked = d.swatch_link(&w.name).and_then(|(base, tint)| d.tint_paint(&base, tint)); + let color = linked.as_ref().and_then(Paint::color).or_else(|| w.paint.color())?; + Some((color, Paint::solid(color))) +} + /// 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; +/// `name` (so named exactly, else ignoring case), each with its unlinked paint ([`trace_swatch_paint`]). +/// Errors name command `c`. ([`trace_params`] has checked that the library is the document's +/// swatches.) +fn trace_group_colors(c: &str, s: &Session, name: &str) -> Result> { + let d = &s.doc()?.doc; + let groups = &d.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()) + Ok(group.swatches.iter().filter_map(|w| trace_swatch_paint(d, w)).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> { +/// `params.swatches` → each one as traced (sRGB) with its unlinked paint. Errors name command `c`. +fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result> { 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 { + let missing = || bad(c, format!("no swatch library `{key}` (see swatch.library.list; \"document\": the document's swatches)")); + let colors: Vec<(Color, Paint)> = 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)")))?, + None if key == crate::cmd::swatchlib::DOCUMENT_SWATCHES => { + let d = &s.active().ok_or_else(missing)?.doc; + d.swatches_iter().filter_map(|w| trace_swatch_paint(d, w)).collect() + } + None => crate::cmd::swatchlib::library_colors(s, key).ok_or_else(missing)?.into_iter().map(|c| (c, Paint::solid(c))).collect(), }; if colors.is_empty() { return Err(bad(c, format!("`{key}` has no colours"))); } - let library: Vec<([u8; 3], Color)> = colors + let library: Vec<([u8; 3], Paint)> = colors .into_iter() - .map(|c| { + .map(|(c, paint)| { let [r, g, b, _] = c.to_rgba8(1.0); - ([r, g, b], c) + ([r, g, b], paint) }) .collect(); params.swatches = library.iter().map(|l| l.0).collect(); @@ -190,19 +376,204 @@ fn grouped(d: &mut Document, nodes: Vec, parents: &[Option]) -> Vec roots.iter().filter_map(|&r| built.get_mut(r)?.take()).chain(ring).collect() } -pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result { - let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; - let mut params = trace_params(c, p)?; +/// The `byColor` param of an Expand (false when not given). +fn by_color_param(cmd: &str, p: &Value) -> Result { + match p.get("byColor").filter(|v| !v.is_null()) { + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "byColor must be true or false")), + None => Ok(false), + } +} + +/// Expand by color: an expanded trace's `items` (bottom-most first) in a group for each paint, a +/// stroked line counted by its stroke. A solid color's group is named by the swatch it links to (a +/// tint with its percentage) or as `#rrggbb`, and gradient fills share one group, "Gradients". The +/// groups stack in the order of the lowest item in each, and each keeps its items' order. When the +/// paths meet, an item joins its paint's last group only if no item of a later group meets it +/// (by the boxes of everything they paint, effects included, within one point); otherwise it +/// starts another group of that paint, which keeps the stacking order of those items. Items +/// farther apart can still share antialiased pixels at small view or raster-export scales, so +/// their edge pixels may change. A group among `items` (Auto Grouping) is refused. +fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result>> { + use std::collections::{BTreeMap, HashMap}; + use std::ops::Bound::{Excluded, Unbounded}; + use vectorcraft_color::tint_percent; + // Grouped by the paint: unlinked (its #rrggbb), linked (the swatch and its exact tint), a + // gradient, or another paint (its label). The name is apart from it: a swatch may be named as + // a color's `#rrggbb` or as "Gradients". + type PaintKey = (u8, String, u32); + struct Run { + name: String, + members: Vec>, + } + // Boxes closer than a point count as overlapping: their antialiased edges can share pixels. + let meet = |a: &Rect, b: &Rect| { + #[cfg(test)] + BOX_TESTS.with(|n| n.set(n.get() + 1)); + let b = b.inflate(1.0, 1.0); + a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1 + }; + // Choose a cell size from the painted extent and path count. A box over more than eight cells + // across but at most eight down (a stripe) is indexed by its rows, one the other way round by + // its columns, and one over more than eight both ways stays in a separate list, keeping the + // index bounded even when a path covers most of the document. + let items: Vec<_> = items + .into_iter() + .map(|item| { + let bounds = vectorcraft_render::painted_bounds(d, &item); + (item, bounds) + }) + .collect(); + let extent = items.iter().filter_map(|(_, b)| *b).reduce(|a, b| a.union(b)); + let cell_size = extent.map_or(1.0, |r| ((r.x1 - r.x0).abs() * (r.y1 - r.y0).abs() / items.len().max(1) as f64).sqrt().max(1.0)); + // The first and last column and row of the cells `r` covers; `None` when it isn't finite. + let span = |r: Rect| -> Option<(i64, i64, i64, i64)> { + let coord = |v: f64| (v / cell_size).floor() as i64; + [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()).then(|| (coord(r.x0), coord(r.y0), coord(r.x1), coord(r.y1))) + }; + let count = |first: i64, last: i64| i128::from(last) - i128::from(first) + 1; + // A box over more cells than this is checked against every box. + const MAX_CELLS: i128 = 1024; + let mut groups: Vec = vec![]; + let mut latest: HashMap = HashMap::new(); + // An item can join an earlier group, so insertion order is not group-index order. Index + // boxes by group to skip older groups without scanning their entries. + let mut spatial: HashMap<(i64, i64), BTreeMap>> = HashMap::new(); + let mut rows: HashMap>> = HashMap::new(); + let mut columns: HashMap>> = HashMap::new(); + let mut large: BTreeMap> = BTreeMap::new(); + let mut all_boxes: BTreeMap> = BTreeMap::new(); + for (item, bounds) in items { + if matches!(item.kind, NodeKind::Group { .. }) { + return Err(bad(cmd, "byColor can't split Auto Grouping groups: trace without Auto Grouping")); + } + let paint = match item.appearance.fill_paint() { + Paint::None => item.appearance.stroke_paint(), + fill => fill, + }; + let (key, name) = match &paint { + Paint::Solid { swatch: Some(n), tint, .. } => { + let percent = tint_percent(*tint); + let name = if *tint < 1.0 { format!("{n} {percent}%") } else { n.clone() }; + ((1, n.clone(), tint.to_bits()), name) + } + Paint::Solid { color, .. } => ((0, color.to_hex(), 0), color.to_hex()), + Paint::Gradient(_) => ((2, String::new(), 0), "Gradients".to_string()), + other => ((3, other.label(), 0), other.label()), + }; + // Joining an earlier group moves the item under every later group's items. + let hidden_by_later = |at: usize| { + bounds.is_some_and(|b| { + let overlaps_later = |boxes: &BTreeMap>| { + boxes.range((Excluded(at), Unbounded)).rev().any(|(_, group_boxes)| { + group_boxes.iter().rev().any(|box_bounds| { + #[cfg(test)] + CANDIDATE_VISITS.with(|n| n.set(n.get() + 1)); + meet(box_bounds, &b) + }) + }) + }; + match span(b) { + Some((x0, y0, x1, y1)) if count(x0, x1) * count(y0, y1) <= MAX_CELLS => { + (y0..=y1).flat_map(|y| (x0..=x1).map(move |x| (x, y))).filter_map(|c| spatial.get(&c)).any(overlaps_later) + || (y0..=y1).filter_map(|y| rows.get(&y)).any(overlaps_later) + || (x0..=x1).filter_map(|x| columns.get(&x)).any(overlaps_later) + || overlaps_later(&large) + } + _ => overlaps_later(&all_boxes), + } + }) + }; + let at = latest.get(&key).copied().filter(|&at| !hidden_by_later(at)); + let mut started = Run { name, members: vec![] }; + let joins = at.and_then(|at| groups.get_mut(at)); + let new = joins.is_none(); + let g = joins.unwrap_or(&mut started); + g.members.push(item); + if new { + groups.push(started); + latest.insert(key, groups.len() - 1); + } + if let Some(b) = bounds { + let index = if new { groups.len() - 1 } else { at.unwrap_or_default() }; + all_boxes.entry(index).or_default().push(b); + match span(b.inflate(1.0, 1.0)) { + Some((x0, y0, x1, y1)) if count(x0, x1) <= 8 && count(y0, y1) <= 8 => { + for place in (y0..=y1).flat_map(|y| (x0..=x1).map(move |x| (x, y))) { + spatial.entry(place).or_default().entry(index).or_default().push(b); + } + } + Some((_, y0, _, y1)) if count(y0, y1) <= 8 => { + for y in y0..=y1 { + rows.entry(y).or_default().entry(index).or_default().push(b); + } + } + Some((x0, _, x1, _)) if count(x0, x1) <= 8 => { + for x in x0..=x1 { + columns.entry(x).or_default().entry(index).or_default().push(b); + } + } + _ => large.entry(index).or_default().push(b), + } + } + } + Ok(groups + .into_iter() + .map(|run| { + let mut g = Node::group(d.alloc_id(), run.members); + g.name = Some(run.name); + Arc::new(g) + }) + .collect()) +} + +/// What a trace depends on: the object traced (an image, or an Image Trace object traced again), +/// its image, and the settings it is traced with. The tracer makes the same paths of the same +/// inputs, so a trace made away from the command ([`TraceRun`]) stands in for the command's own. +#[derive(Clone, Debug, PartialEq)] +struct TraceInputs { + target: NodeId, + image: Box, + /// The settings traced with, as JSON. + params: Value, + /// Document Library: the library's colours, which the JSON leaves out + /// ([`tr::TraceParams::swatches`]). + swatches: Vec<[u8; 3]>, +} + +/// What `imageTrace.make` and `imageTrace.makeAndExpand` take from the session before they trace. +struct Prepared { + inputs: TraceInputs, + trace: tr::TraceParams, + view: Option, + /// The settings asked for, which the Image Trace object keeps. + params_json: Value, + preset_label: String, + library: Vec<([u8; 3], Paint)>, + bytes: Arc>, +} + +/// What command `c` with params `p` traces, and how, from the session: everything but the trace. +fn prepare(s: &Session, c: &str, p: &Value) -> Result { + let mut params = trace_params(s, c, p)?; let view = view_param(c, p)?; + let by_color = c == "imageTrace.makeAndExpand" && by_color_param(c, p)?; + if by_color && params.auto_grouping { + return Err(bad(c, "byColor can't split Auto Grouping groups: trace without Auto Grouping")); + } let params_json = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?; - // The preset's name if the parameters are exactly that preset's or its enhanced version's, - // else "Custom". + // The preset's name if the parameters are exactly that preset's or its enhanced version's (a + // saved preset's under its saved name), else "Custom". 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 saved = s.trace_preset(named).filter(|q| tr::preset(named).is_none() && is(Some(q.params.clone()))).map(|q| q.name.clone()); + let preset_label = match saved { + Some(name) => name, + None if is(tr::preset(named)) || is(tr::enhanced_preset(named)) => named.to_string(), + None => "Custom".to_string(), + }; let roots = root_ids(s, p)?; // The image (inside a trace group, or selected directly). - let (target, img) = { + let (target, image) = { let d = &s.doc()?.doc; roots .iter() @@ -219,20 +590,144 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result bool + Sync)) -> Result { + // An image over the tracer's size is traced scaled down (the paths are scaled back). + let raster = tr::Raster::decode_to_fit(bytes).map_err(|e| EngineError::Other(e.to_string()))?; + if !steps(0, 0) { + return Err(EngineError::Cancelled); + } + let res = tr::trace_watched(&raster, params, MAX_TRACE_ANCHORS, steps).map_err(|e| match e { + tr::TraceError::Cancelled => EngineError::Cancelled, + e => EngineError::Other(e.to_string()), + })?; + Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res }) +} + +/// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`] +/// takes what `imageTrace.make` or `imageTrace.makeAndExpand` traces from the session, checked as +/// the command checks it; [`TraceRun::run`] decodes and traces the image without the session, on +/// any thread; [`Traced::hand_in`] gives the result to the command. +pub struct TraceRun { + command: &'static str, + params: Value, + prepared: Prepared, +} + +impl TraceRun { + /// The trace `command` (`imageTrace.make` or `imageTrace.makeAndExpand`) with params `p` makes + /// in the active document. + pub fn prepare(s: &Session, command: &str, p: &Value) -> Result { + let command = match command { + "imageTrace.make" => "imageTrace.make", + "imageTrace.makeAndExpand" => "imageTrace.makeAndExpand", + other => return Err(EngineError::Other(format!("`{other}` doesn't trace an image"))), + }; + let prepared = prepare(s, command, p)?; + // The object traced is named, so the command applies the trace to it whatever is + // selected by then. + let mut params = if p.is_object() { p.clone() } else { json!({}) }; + if let Some(o) = params.as_object_mut() { + o.remove("ids"); + o.insert("id".into(), json!(prepared.inputs.target.0)); + } + Ok(TraceRun { command, params, prepared }) + } + + /// `imageTrace.make` or `imageTrace.makeAndExpand`. + pub fn command(&self) -> &'static str { + self.command + } + + /// The command's params that apply this trace: those it was prepared with, the object traced + /// in `id`. + pub fn params(&self) -> &Value { + &self.params + } + + /// The object it traces: an image, or an Image Trace object traced again. + pub fn target(&self) -> NodeId { + self.prepared.inputs.target + } + + /// The size in pixels of the image it traces. + pub fn image_size(&self) -> (u32, u32) { + (self.prepared.inputs.image.width, self.prepared.inputs.image.height) + } + + /// Does it still apply: would the command trace the same object, image and settings now? + pub fn current(&self, s: &Session) -> bool { + prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs) + } + + /// Decode and trace the image, telling `steps` how far it has got → what it traced, or why it + /// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no + /// document, so it can run on any thread. + pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { + trace_now(&self.prepared.inputs, &self.prepared.trace, &self.prepared.bytes, steps) + } +} + +pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result { + let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; + let Prepared { inputs, trace, view, params_json, preset_label, library, bytes } = prepare(s, c, p)?; + let group_by_color = expand && by_color_param(c, p)?; + // A saved preset's settings join the journal entry, so a replay traces as this run did after + // the preset is changed, renamed or deleted. + let named = str_param(p, "preset").unwrap_or("Default"); + if let Some(q) = s.trace_preset(named).filter(|_| tr::preset(named).is_none()) { + let recorded = serde_json::to_value(&q.params).map_err(|e| EngineError::Other(e.to_string()))?; + s.note_journal("savedPreset", recorded); + } + // A trace handed in for these very inputs ([`TraceRun`]), else one made now. + let Traced { raster, res, .. } = match s.trace_hand_off.take() { + Some(traced) if traced.inputs == inputs => traced, + _ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?, + }; + let TraceInputs { target, image: img, .. } = inputs; + let mut warnings = keep_warnings(&trace, &res); + warnings.extend(trace_warnings((img.width, img.height), raster, res.worked_at)); // Pixel space of the decoded raster → the image object's pixel space → document. - let sx = img.width.max(1) as f64 / raster.width.max(1) as f64; - let sy = img.height.max(1) as f64 / raster.height.max(1) as f64; + let sx = img.width.max(1) as f64 / raster.0.max(1) as f64; + let sy = img.height.max(1) as f64 / raster.1.max(1) as f64; let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy); // Document units per raster pixel (stroke widths). let unit = xf.determinant().abs().sqrt(); let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len()); let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" }; + // A library color fills with the swatch's displayed color (its model kept), unlinked. + // Keep the first swatch that traces as a given color. Build the lookup once per trace. + let mut by_color: HashMap<[u8; 3], &Paint> = HashMap::new(); + for (rgb, paint) in &library { + by_color.entry(*rgb).or_insert(paint); + } let id = s.edit(label, |d, sel| { let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?; let mut image = if is_trace_group(&src) { @@ -260,10 +755,10 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Appearance { @@ -280,6 +775,9 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Vec { + if params.keep_colors.is_empty() { + return vec![]; + } + if params.mode == tr::Mode::Logo { + return vec!["Flat Logo mode does not use keepColors: it traces the colors named in logoColors, or the colors it finds.".to_string()]; + } + if res.paths.is_empty() && res.keep_unmatched.len() == params.keep_colors.len() { + return vec![format!("Nothing was traced: none of the colors the trace found matches keepColors ({}).", params.keep_colors.join(", "))]; + } + let mut out = vec![]; + if res.paths.is_empty() && res.keep_ignored { + out.push("Nothing was traced: Ignore Color leaves out every area of the colors keepColors lists.".to_string()); + } else if res.paths.is_empty() { + out.push("Nothing was traced: the colors that match keepColors produce no paths.".to_string()); + } + out.extend(res.keep_unmatched.iter().map(|c| format!("keepColors: none of the colors the trace found matches {c}, so nothing of it is traced."))); + 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(); @@ -378,7 +900,20 @@ pub(super) fn trace_release(s: &mut Session, p: &Value) -> Result { } pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result { + const C: &str = "imageTrace.expand"; + let by_color = by_color_param(C, p)?; let targets = trace_targets(s, p)?; + if by_color { + // A trace made with Auto Grouping is refused even when none of its paths were grouped. + let d = &s.doc()?.doc; + let grouped = |n: &Node| n.extras().trace.as_deref().and_then(|t| t.pointer("/params/autoGrouping")).and_then(Value::as_bool) == Some(true); + if targets.iter().any(|g| d.node(*g).is_some_and(grouped)) { + return Err(bad(C, "byColor can't split Auto Grouping groups: trace without Auto Grouping")); + } + if targets.iter().any(|g| d.node(*g).is_some_and(vectorcraft_render::effects::has_pathfinder)) { + return Err(bad(C, LIVE_PATHFINDER_BY_COLOR)); + } + } s.edit("Expand Image Trace", |d, sel| { for g in &targets { let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?; @@ -387,6 +922,15 @@ pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result { if let Some(ch) = n.children_mut() { ch.retain(|c| !matches!(c.kind, NodeKind::Image(_))); } + if by_color { + let items = d.node(*g).and_then(Node::children).cloned().unwrap_or_default(); + // The paths may have been moved or reshaped since the trace was made, so any trace's + // paths are taken to overlap. + let groups = color_groups(C, d, items)?; + if let Some(ch) = d.node_mut(*g).and_then(Node::children_mut) { + *ch = groups; + } + } } sel.set(targets.iter().copied()); Ok(()) @@ -394,9 +938,181 @@ pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&targets) })) } +#[cfg(test)] +mod color_group_tests { + use super::*; + use vectorcraft_geom::{PathData, SubPath}; + + fn area(d: &mut Document, x0: f64, y0: f64, x1: f64, y1: f64, color: Color) -> Arc { + let path = PathData::single(SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true)); + Arc::new(Node::path(d.alloc_id(), path, fill_only(Paint::solid(color)))) + } + + #[test] + fn abutting_color_groups_preserve_order_at_shared_edges() { + let mut d = Document::new(100.0, 100.0); + let a = Color::rgb(1.0, 0.0, 0.0); + let b = Color::rgb(0.0, 0.0, 1.0); + let items = vec![area(&mut d, 0.0, 0.0, 20.0, 20.0, a), area(&mut d, 20.0, 0.0, 40.0, 20.0, b), area(&mut d, 40.0, 0.0, 60.0, 20.0, a)]; + let original: Vec<_> = items.iter().map(|n| n.id).collect(); + let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap(); + let actual: Vec<_> = groups.iter().flat_map(|g| g.children().unwrap().iter().map(|n| n.id)).collect(); + assert_eq!(actual, original, "shared-edge paths changed stacking order"); + } + + #[test] + fn dense_color_groups_use_bounded_box_tests() { + let mut d = Document::new(200.0, 200.0); + let a = Color::rgb(1.0, 0.0, 0.0); + let b = Color::rgb(0.0, 0.0, 1.0); + let items = (0..4000) + .map(|i| { + if i % 2 == 0 { + let x = 100.0 + (i % 40) as f64 * 0.01; + area(&mut d, x, 100.0, x + 0.1, 100.1, a) + } else { + let x = if i % 4 == 1 { 0.0 } else { 198.0 }; + area(&mut d, x, x, x + 2.0, x + 2.0, b) + } + }) + .collect(); + BOX_TESTS.with(|n| n.set(0)); + let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap(); + let tests = BOX_TESTS.with(std::cell::Cell::get); + assert_eq!(groups.iter().map(|g| g.children().map_or(0, Vec::len)).sum::(), 4000); + assert!(tests < 4000 * 32, "{tests} box tests for 4000 paths"); + } + + #[test] + fn overlapping_alternating_colors_visit_bounded_candidates() { + const COUNT: usize = 3000; + let mut d = Document::new(100.0, 100.0); + let colors = [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)]; + let items = (0..COUNT).map(|i| area(&mut d, 10.0, 10.0, 20.0, 20.0, colors[i % 2])).collect(); + CANDIDATE_VISITS.with(|n| n.set(0)); + let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap(); + let visits = CANDIDATE_VISITS.with(std::cell::Cell::get); + assert_eq!(groups.len(), COUNT); + assert!(visits < COUNT * 16, "{visits} candidate visits for {COUNT} paths"); + } + + #[test] + fn separate_stripes_of_alternating_colors_visit_bounded_candidates() { + const COUNT: usize = 2000; + let mut d = Document::new(1000.0, 4000.0); + let colors = [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)]; + for tall in [false, true] { + let items = (0..COUNT) + .map(|i| { + let at = i as f64 * 2.0; + if tall { area(&mut d, at, 0.0, at + 0.5, 1000.0, colors[i % 2]) } else { area(&mut d, 0.0, at, 1000.0, at + 0.5, colors[i % 2]) } + }) + .collect(); + CANDIDATE_VISITS.with(|n| n.set(0)); + let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap(); + let visits = CANDIDATE_VISITS.with(std::cell::Cell::get); + assert_eq!(groups.len(), 2, "tall {tall}"); + assert!(visits < COUNT * 32, "tall {tall}: {visits} candidate visits for {COUNT} stripes"); + } + } + + #[test] + fn spatial_color_groups_match_simple_scan() { + let colors = [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::rgb(0.0, 1.0, 0.0)]; + for layout in 0..6 { + let mut d = Document::new(200.0, 200.0); + let items: Vec<_> = (0..90) + .map(|i| { + let x = match layout { + 0 => i as f64 * 2.0, + 1 => (i % 10) as f64 * 5.0, + 2 => (i % 7) as f64 * 3.0, + 3 => (i % 13) as f64 * 9.0, + 4 => (i % 4) as f64 * 10.0, + _ => i as f64 * 1.5, + }; + let y = match layout { + 0 => 0.0, + 1 => (i / 10) as f64 * 5.0, + 2 => (i / 7) as f64 * 3.0, + 3 => (i / 13) as f64 * 9.0, + 4 => i as f64 * 1.5, + _ => (i % 4) as f64 * 10.0, + }; + // Layouts 4 and 5: wide and tall stripes, some meeting their neighbors. + let (w, h) = match layout { + 4 => (150.0, 1.0), + 5 => (1.0, 150.0), + _ => (3.0, 3.0), + }; + area(&mut d, x, y, x + w, y + h, colors[i % 3]) + }) + .collect(); + let mut expected: Vec<(String, Vec<(NodeId, Rect)>)> = vec![]; + for item in &items { + let key = item.appearance.fill_paint().color().unwrap().to_hex(); + let bounds = vectorcraft_render::painted_bounds(&d, item).unwrap(); + let previous = expected.iter().rposition(|(k, _)| *k == key); + let can_join = previous.filter(|&at| { + !expected.iter().skip(at + 1).any(|(_, boxes)| { + boxes.iter().any(|(_, m)| { + let b = bounds.inflate(1.0, 1.0); + m.x0 < b.x1 && b.x0 < m.x1 && m.y0 < b.y1 && b.y0 < m.y1 + }) + }) + }); + match can_join.and_then(|at| expected.get_mut(at)) { + Some((_, members)) => members.push((item.id, bounds)), + None => expected.push((key, vec![(item.id, bounds)])), + } + } + let actual = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap(); + let actual: Vec> = actual.iter().map(|g| g.children().unwrap().iter().map(|n| n.id).collect()).collect(); + let expected: Vec> = expected.into_iter().map(|(_, members)| members.into_iter().map(|(id, _)| id).collect()).collect(); + assert_eq!(actual, expected, "layout {layout}"); + } + } + + #[test] + fn an_abutting_gradient_stays_above_the_solid_area_it_borders() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let ramp = || Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops.clone())))); + let mut d = Document::new(100.0, 100.0); + let mut area = |x0: f64, x1: f64, paint: Paint| { + let path = + PathData::single(SubPath::polyline(&[Point::new(x0, 0.0), Point::new(x1, 0.0), Point::new(x1, 60.0), Point::new(x0, 60.0)], true)); + Arc::new(Node::path(d.alloc_id(), path, fill_only(paint))) + }; + // A gradient, a solid area beside it and a second gradient beside that, bottom to top. + let items = vec![area(0.0, 50.0, ramp()), area(50.0, 80.0, Paint::solid(Color::rgb(0.2, 0.6, 0.2))), area(80.0, 100.0, ramp())]; + let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap(); + let names: Vec<_> = groups.iter().map(|g| g.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["Gradients", "#339933", "Gradients"]); + } +} + #[cfg(test)] mod trace_limit_tests { - use super::{MAX_TRACE_ANCHORS, trace_warnings}; + use super::{MAX_TRACE_ANCHORS, keep_warnings, trace_warnings}; + use vectorcraft_trace as tr; + + #[test] + fn keep_warnings_name_matched_colors_that_produce_no_paths() { + let params = tr::TraceParams { keep_colors: vec!["#ff0000".into()], ..tr::TraceParams::default() }; + // A listed color was traced, and produced no paths: the palette lists no color without paths. + let traced = tr::TraceResult::default(); + let none = vec!["Nothing was traced: the colors that match keepColors produce no paths.".to_string()]; + assert_eq!(keep_warnings(¶ms, &traced), none); + // With Ignore Color, too: Ignore Color did not leave that color out. + let ignoring = tr::TraceParams { ignore_white: true, ..params.clone() }; + assert_eq!(keep_warnings(&ignoring, &traced), none); + // Ignore Color left out every color that matches: none was traced. + assert_eq!( + keep_warnings(&ignoring, &tr::TraceResult { keep_ignored: true, ..tr::TraceResult::default() }), + vec!["Nothing was traced: Ignore Color leaves out every area of the colors keepColors lists.".to_string()] + ); + } #[test] fn trace_warnings_name_a_large_or_scaled_down_image() { diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 887c5b47a5..6d1e7284c9 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -11,19 +11,21 @@ mod flavours; pub(crate) mod resources; +mod table; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::Swatch; -use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, PatternDef, Symbol, TextStyleDef}; -use vectorcraft_geom::Rect; +use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef}; +use vectorcraft_geom::{PathData, 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 use flavours::{ImageRead, read_image}; pub(crate) use resources::SwatchChoices; -pub use resources::{ArtResources, art_resources}; +pub use resources::{ArtResources, SymbolOptions, art_resources}; use super::{CommandSpec, Result, Session, always, bad, cmd, f64_or, has_doc, point_param, str_param}; use crate::DocState; @@ -69,6 +71,8 @@ pub struct Clipboard { pub images: BTreeMap, /// Symbols the objects place (also inside other symbols and patterns). pub symbols: Vec, + /// The Symbol Options of [`Self::symbols`] (which the document keeps by name), by symbol name. + pub symbol_options: BTreeMap, /// Patterns the objects paint with (pasting makes their swatches again). pub patterns: Vec, /// Global and spot swatches the objects' colours link to, the tint swatches of the tints they @@ -92,23 +96,164 @@ pub struct Clipboard { /// The artboards copied with the Artboard tool (`artboard.copy`); `nodes` are then their art. /// Pasting adds a copy of each with the art. pub artboards: Vec, + /// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on + /// no layer: pasting puts them on the layer new art goes to, moved as the objects are. + pub guides: Vec, +} + +/// Indices of segments selected on `sp` (either explicitly or via incident anchors). +pub(crate) fn subpath_selected_segments( + sp: &vectorcraft_geom::SubPath, + si: usize, + seg_refs: Option<&BTreeSet<(usize, usize)>>, + anchor_refs: Option<&BTreeSet<(usize, usize)>>, +) -> BTreeSet { + let seg_count = sp.segment_count(); + if seg_count == 0 { + return BTreeSet::new(); + } + let n = sp.anchors.len(); + let mut selected_segs = BTreeSet::new(); + + let has_explicit_segs = seg_refs.is_some_and(|segments| segments.iter().any(|&(s, _)| s == si)); + if has_explicit_segs { + if let Some(segments) = seg_refs { + for &(s, seg) in segments { + if s == si && seg < seg_count { + selected_segs.insert(seg); + } + } + } + return selected_segs; + } + + if let Some(anchors) = anchor_refs { + let sub_anchors: BTreeSet = anchors.iter().filter_map(|&(s, a)| (s == si && a < n).then_some(a)).collect(); + if !sub_anchors.is_empty() { + for i in 0..seg_count { + let next = (i + 1) % n; + if sub_anchors.contains(&i) && sub_anchors.contains(&next) { + selected_segs.insert(i); + } + } + + for &i in &sub_anchors { + let prev_selected = if sp.closed { sub_anchors.contains(&((i + n - 1) % n)) } else { i > 0 && sub_anchors.contains(&(i - 1)) }; + let next_selected = if sp.closed { sub_anchors.contains(&((i + 1) % n)) } else { i + 1 < n && sub_anchors.contains(&(i + 1)) }; + if !prev_selected && !next_selected { + if sp.closed { + selected_segs.insert((i + n - 1) % n); + selected_segs.insert(i); + } else { + if i > 0 { + selected_segs.insert(i - 1); + } + if i < seg_count { + selected_segs.insert(i); + } + } + } + } + } + } + + selected_segs +} + +/// When direct selection is active on a path (some anchors or segments selected), extract only +/// the selected runs as new open path nodes (with retracted endpoint handles). Returns `None` +/// when the node is selected whole or is not a path. +pub(crate) fn extract_direct_selection(node: &Node, selection: &Selection) -> Option> { + let seg_refs = selection.segments.get(&node.id); + let anchor_refs = selection.anchors.get(&node.id); + if seg_refs.is_none() && anchor_refs.is_none() { + return None; + } + let path = node.path_data()?; + let mut subpath_segs = Vec::new(); + let mut total_segs = 0; + let mut total_selected = 0; + + for (si, sp) in path.subpaths.iter().enumerate() { + let segs = subpath_selected_segments(sp, si, seg_refs, anchor_refs); + total_segs += sp.segment_count(); + total_selected += segs.len(); + subpath_segs.push(segs); + } + + if total_selected == 0 { + return None; + } + + // When every segment of the path is selected, copy the object unchanged. + if total_segs > 0 && total_selected == total_segs { + return None; + } + + let mut pieces = vec![]; + for (sp, selected_segs) in path.subpaths.iter().zip(subpath_segs) { + let seg_count = sp.segment_count(); + if selected_segs.is_empty() || seg_count == 0 { + continue; + } + let unselected: BTreeSet = (0..seg_count).filter(|i| !selected_segs.contains(i)).collect(); + let surviving = if unselected.is_empty() { vec![sp.clone()] } else { super::path::without_segments(sp.clone(), &unselected) }; + for surviving_sp in surviving { + let mut piece = node.clone(); + if let NodeKind::Path { rule, clipping, guide, .. } = &node.kind { + piece.kind = NodeKind::Path { path: PathData::single(surviving_sp), rule: *rule, live: None, clipping: *clipping, guide: *guide }; + } + pieces.push(piece); + } + } + if pieces.is_empty() { None } else { Some(pieces) } } impl Clipboard { pub fn is_empty(&self) -> bool { - self.nodes.is_empty() && self.artboards.is_empty() + self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty() + } + + /// Does it hold art (objects or artboards) for other apps? Ruler guides stay in VectorCraft: + /// a Copy of guides alone empties the system clipboard (#3226). + pub fn has_art(&self) -> bool { + !self.nodes.is_empty() || !self.artboards.is_empty() + } + + /// One newly made clipboard object and the source document resources it uses. Type-range + /// Copy builds an object from selected runs rather than copying a whole document node. + pub fn from_node(st: &DocState, node: Node) -> Self { + let mut clip = Self::gather(&st.doc, vec![node]); + clip.source_doc = Some(st.uid); + clip } /// Objects `roots` of `st`'s document with their resources, source artboard and layers. - pub(crate) fn copy(st: &DocState, roots: &[NodeId]) -> Self { + pub(crate) fn copy(st: &DocState, roots: &[NodeId], direct: bool) -> Self { let d = &*st.doc; let mut nodes = vec![]; let mut source_layers = vec![]; for id in roots { let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue }; - nodes.push(n.clone()); - // The nearest enclosing layer (or sublayer). - source_layers.push(anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone())); + let layer_name = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone()); + let compound_parent = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|p| matches!(p.kind, NodeKind::Compound { .. }))); + let inherit_appearance = |mut piece: Node| { + if let Some(parent) = compound_parent + && piece.appearance.items.is_empty() + { + piece.appearance = parent.appearance.clone(); + } + piece + }; + if direct && let Some(pieces) = extract_direct_selection(n, &st.selection) { + for piece in pieces { + nodes.push(inherit_appearance(piece)); + source_layers.push(layer_name.clone()); + } + } else { + nodes.push(inherit_appearance(n.clone())); + source_layers.push(layer_name); + } } // Symbol instances are measured by their art. let symbols = d.symbol_boxes(); @@ -160,10 +305,19 @@ impl Clipboard { d.para_styles = self.para_styles.clone().into(); if !self.brushes.is_empty() { let mut lib = vectorcraft_brush::library(&d); + // Each brush's place in the library by name: finding it by scanning the growing list + // made a library of N brushes cost N² comparisons. + let mut at: std::collections::HashMap = std::collections::HashMap::new(); + for (i, b) in lib.iter().enumerate() { + at.entry(b.name.clone()).or_insert(i); + } for b in &self.brushes { - match lib.iter_mut().find(|x| x.name == b.name) { + match at.get(&b.name).and_then(|&i| lib.get_mut(i)) { Some(x) => *x = b.clone(), - None => lib.push(b.clone()), + None => { + at.insert(b.name.clone(), lib.len()); + lib.push(b.clone()); + } } } vectorcraft_brush::store(&mut d, &lib); @@ -185,7 +339,7 @@ impl Clipboard { /// The objects as standalone SVG (`None` when there are none). pub fn svg(&self) -> Option { - if self.is_empty() { + if !self.has_art() { return None; } let d = self.to_document(); diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index b7b046824c..1d6f2af3e1 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -10,8 +10,8 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Document, ImageObject, Node, NodeId, NodeKind, TextObject}; use vectorcraft_geom::{Affine, Point}; -use super::super::fileio; use super::super::place::pt_per_px; +use super::super::{fileio, links}; use super::{Clipboard, CommandSpec, Result, Session, always, bad, cmd, f64_or, has_doc, looks_like_svg, point_param, str_param}; /// Plain text: a type-only copy's text, else the SVG markup (Include SVG Code). @@ -125,6 +125,10 @@ pub struct Flavour { /// Longest side (px) of the PNG Copy offers: larger art is scaled down to fit. const COPY_PNG_SIDE: f64 = 4096.0; +/// The smallest scale (pixels a point) the PNG encoder renders at. +const MIN_COPY_PNG_SCALE: f64 = 0.01; +/// What Copy says when the art is too large for its PNG. +const TOO_LARGE_FOR_PNG: &str = "The art is too large to copy as a picture: other apps get no PNG of it"; /// Most bytes of text `clipboard.importText` takes. const MAX_TEXT: usize = 1 << 20; /// Most bytes of images the SVG markup may embed and still go out as plain text. A paste reads the @@ -178,7 +182,7 @@ pub fn specs() -> Vec { "Load Image into Clipboard", [], None, - "{dataBase64 (PNG, JPEG, GIF, WebP, TIFF or BMP bytes), mime?: the type the system clipboard gave (an image/… type; the format is read from the bytes), center?: [x, y]} replace the clipboard with the image, embedded at 100% of its physical size (its resolution, else 72 ppi), centred on `center` (default: the first artboard) → {count, width, height (pt), pixelWidth, pixelHeight}; then run edit.paste", + "{dataBase64 (PNG, JPEG, GIF, WebP, TIFF or BMP bytes), mime?: the type the system clipboard gave (an image/… type; the format is read from the bytes), center?: [x, y]} replace the clipboard with the image, embedded at 100% of its physical size (its resolution, else 72 ppi), centred on `center` (default: the first artboard) → {count, width, height (pt), pixelWidth, pixelHeight}; then run edit.paste. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error", has_doc, import_image ), @@ -187,7 +191,7 @@ pub fn specs() -> Vec { "Load Text into Clipboard", [], None, - "{text, center?: [x, y]} replace the clipboard with point text of `text` (one paragraph per line; trailing line breaks dropped) in the default type style, centred on `center` (default: the first artboard) → {count}; then run edit.paste", + "{text, center?: [x, y], table?: true} replace the clipboard with point text of `text` (one paragraph per line; trailing line breaks dropped) in the default type style, centred on `center` (default: the first artboard) → {count}; then run edit.paste. Cells copied from a spreadsheet (tab-separated, at least two columns, every row with the same number of cells, cells in double quotes may hold tabs and line breaks; at most 1000 rows, 256 columns and 20,000 cells) become a group \"Table\": point type for each cell that holds text, in columns as wide as their widest cell and rows as tall as their tallest, over a group \"Gridlines\" of 0.5 pt black lines around every cell → {count, rows, columns}; table: false pastes them as plain text", has_doc, import_text ), @@ -282,18 +286,30 @@ impl Clipboard { /// The MIME types of [`Self::flavours`], without making them. pub fn flavour_types(&self, svg: bool, pdf: bool) -> Vec<&'static str> { - if self.is_empty() { + if !self.has_art() { return vec![]; } let text = (svg && self.image_bytes() <= COPY_TEXT_IMAGE_BYTES) || self.nodes.iter().all(type_only); // Art without an area (a lone guide-like line) has no page or picture. let area = self.bounds().is_some_and(|b| b.width() > 0.0 && b.height() > 0.0); - [(TEXT, text), (SVG, svg), (PDF, pdf && area), (PNG, area)].into_iter().filter_map(|(m, on)| on.then_some(m)).collect() + [(TEXT, text), (SVG, svg), (PDF, pdf && area), (PNG, area && self.png_scale().is_some())] + .into_iter() + .filter_map(|(m, on)| on.then_some(m)) + .collect() + } + + /// The scale (pixels a point) of the PNG Copy offers: at most [`COPY_PNG_SIDE`] pixels a side, + /// and `None` when even [`MIN_COPY_PNG_SCALE`], the encoder's smallest, can't bring it that small + /// (rather than a PNG of up to a gigabyte of pixels). + fn png_scale(&self) -> Option { + let side = self.bounds().map_or(1.0, |b| b.width().max(b.height())); + Some((COPY_PNG_SIDE / side).min(1.0)).filter(|s| *s >= MIN_COPY_PNG_SCALE) } /// What Copy offers other apps, best first, with Include SVG Code (`svg`) and On Copy: PDF /// (`pdf`) as given (see `clipboard.flavours`). A [`Flavour`] that can't be made (art too large - /// to render) is left out; the PNG is scaled down to at most [`COPY_PNG_SIDE`] pixels a side. + /// to render) is left out; the PNG is scaled down to at most [`COPY_PNG_SIDE`] pixels a side, and + /// left out when even [`MIN_COPY_PNG_SCALE`] can't bring it that small. pub fn flavours(&self, svg: bool, pdf: bool) -> Vec { self.flavours_with_warnings(svg, pdf).0 } @@ -305,6 +321,9 @@ impl Clipboard { let svg = types.contains(&SVG).then(|| self.svg()).flatten(); let mut out = vec![]; let mut warnings: Vec = vec![]; + if !self.is_empty() && self.png_scale().is_none() { + warnings.push(TOO_LARGE_FOR_PNG.to_string()); + } let mut keep = |(bytes, notes): (Vec, Vec)| { for w in notes { if !warnings.contains(&w) { @@ -318,11 +337,10 @@ impl Clipboard { TEXT => self.text().or_else(|| svg.clone()).map(String::into_bytes), SVG => svg.clone().map(String::into_bytes), PDF => self.pdf().inspect_err(|e| log::warn!("clipboard PDF: {e}")).ok().flatten().map(&mut keep), - _ => { - let side = self.bounds().map_or(1.0, |b| b.width().max(b.height())); - let scale = (COPY_PNG_SIDE / side).clamp(0.01, 1.0); - self.png(scale).inspect_err(|e| log::warn!("clipboard PNG: {e}")).ok().flatten().map(|(png, _, _, notes)| keep((png, notes))) - } + _ => self + .png_scale() + .and_then(|scale| self.png(scale).inspect_err(|e| log::warn!("clipboard PNG: {e}")).ok().flatten()) + .map(|(png, _, _, notes)| keep((png, notes))), }; out.extend(data.map(|data| Flavour { mime, data })); } @@ -413,12 +431,38 @@ fn flavours(s: &mut Session, _: &Value) -> Result { Ok(json!({ "flavours": s.clipboard_flavour_types() })) } +/// A bitmap read as `clipboard.importImage` reads its `dataBase64` ([`read_image`]), for +/// [`Session::import_image_read`]. +pub struct ImageRead(fileio::RasterImage); + +/// Read `bytes` as `clipboard.importImage` reads its `dataBase64`, on any thread: the formats it +/// stores as PNG are decoded and encoded here. +pub fn read_image(bytes: &[u8]) -> Result { + let mut img = fileio::raster_image(bytes).map_err(|e| bad("clipboard.importImage", e.to_string()))?; + img.blob = links::readable_and_kept(img.blob, links::kept_unread(bytes), false).map_err(|e| bad("clipboard.importImage", e.to_string()))?; + Ok(ImageRead(img)) +} + +impl Session { + /// `clipboard.importImage` with `p` (its `mime` and `center`) for an image [`read_image`] read + /// (off the UI thread in the desktop app), which it loads instead of reading `dataBase64`. + pub fn import_image_read(&mut self, read: ImageRead, p: &Value) -> Result { + self.image_hand_off = Some(read); + let r = self.execute("clipboard.importImage", p); + self.image_hand_off = None; + r + } +} + fn import_image(s: &mut Session, p: &Value) -> Result { const C: &str = "clipboard.importImage"; if let Some(m) = str_param(p, "mime").filter(|m| !m.starts_with("image/") || *m == SVG) { return Err(bad(C, format!("`{m}` isn't a bitmap: use clipboard.importSvg, importPdf or importText"))); } - let img = fileio::raster_image(&data_param(p, C)?).map_err(|e| bad(C, e.to_string()))?; + let ImageRead(img) = match s.image_hand_off.take() { + Some(read) => read, + None => read_image(&data_param(p, C)?)?, + }; let (sx, sy) = pt_per_px(img.ppi); let (w, h) = (img.width, img.height); let image = ImageObject { @@ -447,9 +491,24 @@ fn import_text(s: &mut Session, p: &Value) -> Result { if text.trim().is_empty() { 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 style = super::super::create::new_type_style(s, &Value::Null); + let system_layout = s.doc()?.doc.setup.system_layout; + let layout = |t: &mut TextObject| { + t.system_layout = system_layout; + crate::cmd::typecmd::refresh_bounds(t); + }; + let table = match p.get("table").filter(|v| !v.is_null()) { + None => true, + Some(v) => v.as_bool().ok_or_else(|| bad(C, "table must be true or false"))?, + }; + // Cells copied from a spreadsheet paste as a table of type over gridlines. + if let Some(rows) = table.then(|| super::table::parse(text)).flatten() { + let n = super::table::table(&rows, &style, layout); + let count = s.load_clipboard(Clipboard { nodes: vec![n], ..Default::default() }, p)?; + return Ok(json!({ "count": count, "rows": rows.len(), "columns": rows.first().map_or(0, Vec::len) })); + } + let mut t = TextObject::point(Point::ZERO, text, style); + layout(&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)?; Ok(json!({ "count": count })) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index e6bd96371b..4488b4746f 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -14,13 +14,18 @@ //! uses its resources as they are now. use std::cell::OnceCell; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::Arc; use serde_json::{Map, Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::{Color, Paint, Swatch}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeKind, PatternDef, Symbol, TextStyleDef}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, + TextStyleDef, +}; + +use super::super::brushsym::{set_natural_size, stored_natural_size}; use super::super::patterncmds::add_pattern; use super::super::{Result, bad, unique_name}; @@ -149,6 +154,39 @@ struct Defs<'a> { char_styles: &'a [TextStyleDef], para_styles: &'a [TextStyleDef], brushes: Brushes<'a>, + /// Where each name is defined, built the first time a kind is followed. + index: DefIndex, +} + +/// The positions of a kind's definitions by name. +type NameIndex = HashMap>; + +/// [`Defs`]' definitions by name (graphic styles by id), each kind indexed the first time a +/// reference to it is followed: finding a name's definitions by scanning them all made a +/// document or library of N definitions that use each other cost N² comparisons. +#[derive(Default)] +struct DefIndex { + swatches: OnceCell, + symbols: OnceCell, + patterns: OnceCell, + styles: OnceCell>>, + char_styles: OnceCell, + para_styles: OnceCell, + brushes: OnceCell, +} + +/// The items of `list` named `name`, in order, `index` holding their positions (built from +/// `list` the first time). +fn named<'l, T>(index: &OnceCell, list: &'l [T], name_of: impl Fn(&T) -> &str, name: &str) -> impl Iterator { + let index = index.get_or_init(|| { + let mut by: NameIndex = HashMap::new(); + for (i, item) in list.iter().enumerate() { + by.entry(name_of(item).to_string()).or_default().push(i); + } + by + }); + let at: &[usize] = index.get(name).map_or(&[], Vec::as_slice); + at.iter().filter_map(move |&i| list.get(i)) } /// The brushes references lead to: a document's library, read the first time a brush is used @@ -178,6 +216,7 @@ impl<'a> Defs<'a> { char_styles: &d.char_styles, para_styles: &d.para_styles, brushes: Brushes::Lazy(d, brushes), + index: DefIndex::default(), } } } @@ -202,9 +241,29 @@ pub(super) struct Used { impl Used { fn of<'a>(defs: &Defs<'a>, nodes: impl IntoIterator) -> Self { let mut used = Used::default(); - let mut todo: Vec> = nodes.into_iter().map(Source::Node).collect(); + used.follow(defs, nodes.into_iter().map(Source::Node).collect()); + used + } + + /// Every character style of `defs` (with `chars`) and every paragraph style (with `paras`), and + /// the resources they use, styles of the other kind included. + fn of_text_styles(defs: &Defs<'_>, chars: bool, paras: bool) -> Self { + let mut used = Used::default(); + let mut todo = vec![]; + for s in defs.char_styles.iter().filter(|_| chars) { + used.note(defs, Ref::Name(Res::CharStyle, &s.name), &mut todo); + } + for s in defs.para_styles.iter().filter(|_| paras) { + used.note(defs, Ref::Name(Res::ParaStyle, &s.name), &mut todo); + } + used.follow(defs, todo); + used + } + + /// Note the references of `todo`'s sources and of the definitions they lead to. + fn follow<'a>(&mut self, defs: &Defs<'a>, mut todo: Vec>) { while let Some(src) = todo.pop() { - let mut found = |r: Ref<'_>| used.note(defs, r, &mut todo); + let mut found = |r: Ref<'_>| self.note(defs, r, &mut todo); match src { Source::Node(n) => node_refs(n, &mut found), Source::Appearance(a) => appearance_refs(a, &mut found), @@ -212,15 +271,22 @@ impl Used { Source::Paint(p) => paint_refs(p, &mut found), } } - used } /// Note `r`; a definition seen for the first time joins `todo`. fn note<'a>(&mut self, defs: &Defs<'a>, r: Ref<'_>, todo: &mut Vec>) { let (res, name) = match r { Ref::Style(id) => { - if self.styles.insert(id) { - todo.extend(defs.styles.iter().filter(|g| g.id != 0 && g.id == id).map(|g| Source::Appearance(&g.appearance))); + if self.styles.insert(id) && id != 0 { + let index = defs.index.styles.get_or_init(|| { + let mut by: HashMap> = HashMap::new(); + for (i, g) in defs.styles.iter().enumerate() { + by.entry(g.id).or_default().push(i); + } + by + }); + let at = index.get(&id).map_or(&[][..], Vec::as_slice); + todo.extend(at.iter().filter_map(|&i| defs.styles.get(i)).map(|g| Source::Appearance(&g.appearance))); } return; } @@ -237,15 +303,16 @@ impl Used { return; } set.insert(name.to_string()); + let ix = &defs.index; match res { // A tint swatch's base, a gradient swatch's linked stops. - Res::Swatch => todo.extend(defs.swatches.iter().filter(|w| w.name == name).map(|w| Source::Paint(&w.paint))), - Res::Symbol => todo.extend(defs.symbols.iter().filter(|s| s.name == name).map(|s| Source::Node(&s.art))), - 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))), + Res::Swatch => todo.extend(named(&ix.swatches, &defs.swatches, |w| &w.name, name).map(|w| Source::Paint(&w.paint))), + Res::Symbol => todo.extend(named(&ix.symbols, defs.symbols, |s| &s.name, name).map(|s| Source::Node(&s.art))), + Res::Pattern => todo.extend(named(&ix.patterns, defs.patterns, |p| &p.name, name).flat_map(|p| p.art.iter().map(|a| Source::Node(a)))), + Res::CharStyle => todo.extend(named(&ix.char_styles, defs.char_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))), + Res::ParaStyle => todo.extend(named(&ix.para_styles, defs.para_styles, |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))), + Res::Brush => todo.extend(named(&ix.brushes, defs.brushes.get(), |b| &b.name, name).flat_map(|b| b.art().into_iter().map(Source::Node))), _ => {} } } @@ -457,7 +524,7 @@ impl SwatchChoices { } /// How pasted art is relinked to the document's resources. -#[derive(Debug, Default)] +#[derive(Clone, Debug, Default)] struct Relink { renames: BTreeMap>, /// Graphic style id on the clipboard → its id in the document. Links to other ids are dropped. @@ -585,10 +652,266 @@ fn shows_definitions(b: &Brush) -> bool { found } +/// A symbol's Symbol Options, which its document keeps by symbol name: copied with the symbol and +/// given to it under the name pasting adds it as. +#[derive(Clone, Debug, PartialEq)] +pub struct SymbolOptions { + /// Natural size `(w, h)` (`None`: the document records none). + pub size: Option<(f64, f64)>, + pub registration: SymbolRegistration, + pub export_type: SymbolExportType, + /// 9-slice guides (`None`: 9-slice scaling off). + pub nine_slice: Option, +} + +impl SymbolOptions { + /// The options `d` keeps for symbol `name`. + fn of(d: &Document, name: &str) -> Self { + Self { + size: stored_natural_size(d, name), + registration: d.symbol_registration(name), + export_type: d.symbol_export_type(name), + nine_slice: d.symbol_nine_slice(name), + } + } + + /// Make them the options of `d`'s symbol `name`. + fn give(&self, d: &mut Document, name: &str) { + set_natural_size(d, name, self.size); + d.set_symbol_registration(name, self.registration); + d.set_symbol_export_type(name, self.export_type); + d.set_symbol_nine_slice(name, self.nine_slice); + } +} + +/// A character or paragraph style, symbol (with the Symbol Options copied with it), pattern or +/// brush (placed with the others only when they are placed in use order) to place +/// ([`Clipboard::import_used`]). +#[derive(Clone, Copy)] +enum Def<'c> { + Style(Res, &'c TextStyleDef), + Symbol(&'c Symbol, Option<&'c SymbolOptions>), + Pattern(&'c PatternDef), + Brush(&'c Brush), +} + +impl<'c> Def<'c> { + fn key(&self) -> (Res, &'c str) { + match self { + Def::Style(r, s) => (*r, &s.name), + Def::Symbol(s, _) => (Res::Symbol, &s.name), + Def::Pattern(p) => (Res::Pattern, &p.name), + Def::Brush(b) => (Res::Brush, &b.name), + } + } + + /// Call `f` with each resource it refers to by name. + fn each_use(&self, f: &mut dyn FnMut(Res, &str)) { + let mut g = |r: Ref<'_>| { + if let Ref::Name(res, n) = r { + f(res, n); + } + }; + match self { + Def::Style(_, s) => attrs_refs(&s.attrs, &mut g), + Def::Symbol(s, _) => node_refs(&s.art, &mut g), + Def::Pattern(p) => p.art.iter().for_each(|a| node_refs(a, &mut g)), + Def::Brush(b) => b.art().into_iter().for_each(|a| node_refs(a, &mut g)), + } + } + + /// Is it the definition `d` has under `name`, once relinked by `r`? (`brushes`: the brush + /// library of `d`.) + fn same_in(&self, d: &Document, brushes: &Brushes<'_>, name: &str, r: &Relink) -> bool { + match self { + Def::Style(res, s) => { + let theirs = if *res == Res::CharStyle { &d.char_styles } else { &d.para_styles }; + let mut attrs = s.attrs.clone(); + r.attrs(&mut attrs); + theirs.iter().any(|x| x.name == name && x.attrs == attrs) + } + Def::Symbol(s, options) => d.symbols.iter().any(|x| { + x.name == name + && options.is_none_or(|o| SymbolOptions::of(d, name) == *o) + && same_art(r, std::slice::from_ref(&x.art), std::slice::from_ref(&s.art)) + }), + Def::Pattern(p) => { + let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() }; + d.pattern(name).is_some_and(|x| bare(x) == bare(p) && same_art(r, &x.art, &p.art)) + } + Def::Brush(b) => brushes.get().iter().any(|x| x.name == name && same_brush(r, x, b)), + } + } + + /// The names of its kind in `d` (`brushes`: its brush library) that are its name or a numbered + /// copy of it. + fn names_in(&self, d: &Document, brushes: &Brushes<'_>) -> Vec { + let (res, name) = self.key(); + let names: Vec = match res { + Res::CharStyle => d.char_styles.iter().map(|s| s.name.clone()).collect(), + Res::ParaStyle => d.para_styles.iter().map(|s| s.name.clone()).collect(), + Res::Symbol => d.symbols.iter().map(|s| s.name.clone()).collect(), + Res::Brush => brushes.get().iter().map(|b| b.name.clone()).collect(), + _ => d.patterns.iter().map(|p| p.name.clone()).collect(), + }; + names.into_iter().filter(|n| copy_of(name, n)).collect() + } +} + +/// `defs` in rounds: each round takes those that use none of the others left, in their order. +/// → (those, the rest, which use each other in a loop or use one that does, in their order) +fn use_order(defs: Vec>) -> (Vec>, Vec>) { + let uses = uses_of(&defs); + // The round of each definition; `None` for one in a loop or one that uses such a definition. + let mut round: Vec> = vec![None; defs.len()]; + // A group outside a loop holds one definition, and comes after the groups it uses. + for (group, looped) in components(&uses) { + for v in group.into_iter().filter(|_| !looped) { + let r = uses[v].iter().try_fold(0, |r, &w| round.get(w).copied().flatten().map(|k| r.max(k + 1))); + round[v] = r; + } + } + let mut ready: Vec<(usize, usize)> = round.iter().enumerate().filter_map(|(i, r)| r.map(|r| (r, i))).collect(); + ready.sort_unstable(); + let order = ready.into_iter().filter_map(|(_, i)| defs.get(i).copied()).collect(); + let rest = defs.iter().zip(&round).filter(|(_, r)| r.is_none()).map(|(def, _)| *def).collect(); + (order, rest) +} + +/// The positions in `defs` of the definitions each one uses, itself included. +fn uses_of(defs: &[Def<'_>]) -> Vec> { + let mut at: BTreeMap<(Res, &str), Vec> = BTreeMap::new(); + for (i, def) in defs.iter().enumerate() { + at.entry(def.key()).or_default().push(i); + } + defs.iter() + .map(|def| { + let mut to = vec![]; + def.each_use(&mut |res, n| to.extend(at.get(&(res, n)).into_iter().flatten())); + to.sort_unstable(); + to.dedup(); + to + }) + .collect() +} + +/// `rest` ([`use_order`]'s definitions that use each other in a loop or use one that does) split +/// into its loops and the definitions outside a loop, each group after the groups it uses: +/// (positions in `rest`, in their order; true for a loop, definitions that use each other or one +/// that uses itself). +fn loop_groups(rest: &[Def<'_>]) -> Vec<(Vec, bool)> { + components(&uses_of(rest)) +} + +/// The strongly connected components of the graph `uses` (each node's successors), each after +/// those it reaches: (nodes, in their order; true for a loop, two or more nodes or one that uses +/// itself). +fn components(uses: &[Vec]) -> Vec<(Vec, bool)> { + // Tarjan's algorithm, with an explicit stack of calls. + const NONE: usize = usize::MAX; + let (mut index, mut low, mut on) = (vec![NONE; uses.len()], vec![0; uses.len()], vec![false; uses.len()]); + let (mut stack, mut next, mut groups) = (vec![], 0, vec![]); + for root in 0..uses.len() { + if index[root] != NONE { + continue; + } + let mut calls: Vec<(usize, usize)> = vec![(root, 0)]; + (index[root], low[root], on[root]) = (next, next, true); + next += 1; + stack.push(root); + while let Some(&(v, k)) = calls.last() { + if let Some(&w) = uses[v].get(k) { + if let Some(top) = calls.last_mut() { + top.1 += 1; + } + if index[w] == NONE { + (index[w], low[w], on[w]) = (next, next, true); + next += 1; + stack.push(w); + calls.push((w, 0)); + } else if on[w] { + low[v] = low[v].min(index[w]); + } + continue; + } + calls.pop(); + if let Some(&(u, _)) = calls.last() { + low[u] = low[u].min(low[v]); + } + if low[v] == index[v] { + let mut group = vec![]; + while let Some(w) = stack.pop() { + on[w] = false; + group.push(w); + if w == v { + break; + } + } + group.sort_unstable(); + let looped = group.len() > 1 || uses[v].contains(&v); + groups.push((group, looped)); + } + } + } + groups +} + +/// The names in `d` that `looped` (a loop of definitions that use each other, [`loop_groups`]) +/// all have at once, each the same once relinked by `r` with those names: each one's name or a +/// numbered copy of it. The names are picked one definition at a time, in order, and each +/// definition is compared as soon as the names of those it uses are picked, so a pick that does +/// not fit is dropped with every combination that follows from it; at most 65,536 comparisons are +/// made. `None` when no combination fits, or none was found within that many comparisons. The brush +/// library of `d` is read once, the first time a brush is compared. +fn names_of_loop(d: &Document, looped: &[Def<'_>], r: &Relink) -> Option> { + let library = OnceCell::new(); + let brushes = Brushes::Lazy(d, &library); + let names: Vec> = looped.iter().map(|def| def.names_in(d, &brushes)).collect(); + if names.is_empty() || names.iter().any(Vec::is_empty) { + return None; + } + // The definitions compared once the name at each position is picked. + let mut compare_at: Vec> = vec![vec![]; looped.len()]; + for (i, uses) in uses_of(looped).iter().enumerate() { + compare_at[uses.iter().copied().fold(i, usize::max)].push(i); + } + let (mut pick, mut guess, mut budget, mut k) = (vec![0usize; looped.len()], r.clone(), 1usize << 16, 0); + loop { + let (res, own) = looped[k].key(); + guess.renames.entry(res).or_default().insert(own.to_string(), names[k][pick[k]].clone()); + let fits = compare_at[k].iter().all(|&i| { + budget = budget.saturating_sub(1); + looped[i].same_in(d, &brushes, &names[i][pick[i]], &guess) + }); + if fits && k + 1 == looped.len() { + return Some(names.iter().zip(&pick).map(|(l, &p)| l[p].clone()).collect()); + } + if budget == 0 { + return None; + } + if fits { + k += 1; + pick[k] = 0; + continue; + } + // The next name at this position, or back to the position before. + loop { + pick[k] += 1; + if pick[k] < names[k].len() { + break; + } + k = k.checked_sub(1)?; + } + } +} + /// What pasting did to the document's resources (part of the paste result). #[derive(Debug, Default)] pub(crate) struct Imported { relink: Relink, + /// Whether relinking can change a pasted copy: a resource has another name or color in the + /// document, or the objects link a graphic style. + relinks: bool, /// Resources added to the document (renamed ones included). pub added: usize, /// Swatch conflicts resolved by merging. @@ -610,7 +933,9 @@ impl Imported { } /// Point a pasted copy at the document's resources. pub(crate) fn apply(&self, n: &mut Node) { - self.relink.node(n); + if self.relinks { + self.relink.node(n); + } } } @@ -619,6 +944,12 @@ impl Clipboard { pub(crate) fn gather(src: &Document, nodes: Vec) -> Self { let library = OnceCell::new(); let used = Used::of(&Defs::of(src, &library), &nodes); + Self::with_used(src, &used, &library, nodes) + } + + /// `nodes` and the resources of `src` that `used` names (`library`: the brush library of `src`, + /// read when a brush was used). + fn with_used(src: &Document, used: &Used, library: &OnceCell>, nodes: Vec) -> Self { let pick = |r: Res, list: &[TextStyleDef]| list.iter().filter(|s| used.has(r, &s.name)).cloned().collect::>(); // Read when a brush was used. let brushes = match (used.names.get(&Res::Brush), library.get()) { @@ -628,6 +959,12 @@ impl Clipboard { Self { images: src.images.iter().filter(|(k, _)| used.has(Res::Image, k)).map(|(k, b)| (k.clone(), b.clone())).collect(), symbols: src.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).cloned().collect(), + symbol_options: src + .symbols + .iter() + .filter(|s| used.has(Res::Symbol, &s.name)) + .map(|s| (s.name.clone(), SymbolOptions::of(src, &s.name))) + .collect(), patterns: src.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).cloned().collect(), swatches: src.swatches_iter().filter(|w| used.carries(w)).cloned().collect(), graphic_styles: src.graphic_styles.iter().filter(|g| g.id != 0 && used.styles.contains(&g.id)).cloned().collect(), @@ -649,6 +986,7 @@ impl Clipboard { char_styles: &self.char_styles, para_styles: &self.para_styles, brushes: Brushes::Ready(&self.brushes), + index: DefIndex::default(), }; Used::of(&defs, &self.nodes) } @@ -665,47 +1003,158 @@ impl Clipboard { /// Add the resources the objects use to `d` (inside the paste's undo step) and work out how /// pasted copies relink to them. pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Imported { - let used = self.used(); + self.import_used(d, &self.used(), choices, same_doc, false) + } + + /// [`Self::import_into`] for the resources `used` names. The character and paragraph styles + /// come before the symbols and patterns, whose art may set type in them; with `in_use_order`, + /// each style, symbol, pattern and brush comes after the styles, symbols, patterns and brushes it uses + /// ([`use_order`]), so that it is compared and relinked with their names here, and each loop + /// of definitions that use each other is matched on its own ([`loop_groups`]). + fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Imported { let mut out = Imported::default(); - self.import_images(d, &used, same_doc, &mut out); - self.import_swatches(d, &used, choices, same_doc, &mut out); + self.import_images(d, used, same_doc, &mut out); + self.import_swatches(d, used, choices, same_doc, &mut out); // Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art - // they may brush; the others once those are in. - let mut added_brushes = 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)) { - let mut s = def.clone(); - out.relink.attrs(&mut s.attrs); - let p = place(theirs, &s, same_doc, PartialEq::eq); - out.placed(r, &def.name, &p); + // they may brush; the others once those are in. With `in_use_order`, the brushes are + // placed in use order with the others. + let mut added_brushes: HashSet = + if in_use_order { HashSet::new() } else { self.import_brushes(d, used, same_doc, false, &mut out).into_iter().collect() }; + let mut defs: Vec> = vec![]; + for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] { + defs.extend(list.iter().filter(|s| used.has(r, &s.name)).map(|s| Def::Style(r, s))); + } + defs.extend(self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).map(|s| Def::Symbol(s, self.symbol_options.get(&s.name)))); + defs.extend(self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).map(Def::Pattern)); + if in_use_order { + defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush)); + } + // Groups to place in order; true for a loop of definitions that use each other. + let groups: Vec<(Vec>, bool)> = if in_use_order { + let (order, rest) = use_order(defs); + let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped)); + std::iter::once((order, false)).chain(loops).collect() + } else { + vec![(defs, false)] + }; + // Styles (their colors relinked first), symbols and patterns (compared once relinked, + // symbols with their options too). The symbols and patterns added are relinked at the end, + // when every new name and graphic style id is known; with `in_use_order`, so are the + // styles added, which a loop of uses may place before a pattern they paint with. + let (mut added_symbols, mut added_patterns, mut added_styles) = (HashSet::new(), HashSet::new(), vec![]); + // Each definition, whether it is in a loop, and the loop it starts. + let steps = groups + .iter() + .flat_map(|(group, looped)| group.iter().enumerate().map(move |(i, def)| (*def, *looped, (*looped && i == 0).then_some(group)))); + // In a loop the document does not have all at once, every definition uses one that is + // added under a free name, so each one is added too. + let mut fresh = false; + // The names in the document of the loop being placed, when it has them all at once. + let mut matched: BTreeMap<(Res, String), String> = BTreeMap::new(); + // The document's brush library, read the first time a brush is placed in use order and + // stored again after each brush added; nothing else in the loop changes it. + let mut library: Option> = None; + for (def, looped, starts) in steps { + fresh &= looped; + if !looped { + matched.clear(); + } + // A loop of uses that the document has all at once is known under those names before + // its definitions are compared. + if let Some(group) = starts { + matched.clear(); + match names_of_loop(d, group, &out.relink) { + Some(names) => { + for (def, name) in group.iter().zip(names) { + let (res, own) = def.key(); + if own != name { + out.relink.renames.entry(res).or_default().insert(own.to_string(), name.clone()); + } + matched.insert((res, own.to_string()), name); + } + fresh = false; + } + None => fresh = true, + } + } + // A definition of such a loop is the document's under the name found for it. + let (res, own) = def.key(); + if let Some(name) = matched.get(&(res, own.to_string())) { + let p = if name == own { Placed::Existing } else { Placed::Reused(name.clone()) }; + out.placed(res, own, &p); + continue; + } + match def { + Def::Style(r, def) => { + let mut s = def.clone(); + out.relink.attrs(&mut s.attrs); + let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles }; + let p = place(theirs, &s, same_doc, |a, b| !fresh && a == b); + if in_use_order && let Some(name) = p.new_name(&def.name) { + added_styles.push((r, name, def)); + } + out.placed(r, &def.name, &p); + } + Def::Symbol(def, options) => { + let theirs: HashMap = match options { + Some(_) => d + .symbols + .iter() + .filter(|s| copy_of(&def.name, &s.name)) + .map(|s| (s.name.clone(), SymbolOptions::of(d, &s.name))) + .collect(), + None => HashMap::new(), + }; + let r = &out.relink; + let p = place(&mut d.symbols, def, same_doc, |a, b| { + !fresh + && options.is_none_or(|o| theirs.get(&a.name) == Some(o)) + && same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art)) + }); + if let Some(name) = p.new_name(&def.name) { + if let Some(o) = options { + o.give(d, &name); + } + added_symbols.insert(name); + } + out.placed(Res::Symbol, &def.name, &p); + } + Def::Pattern(def) => { + // Tile options alike, and the art once relinked. + let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() }; + let same = |n: &str| !fresh && d.pattern(n).is_some_and(|x| bare(x) == bare(def) && same_art(&out.relink, &x.art, &def.art)); + let p = existing(&def.name, d.patterns.iter().map(|p| p.name.as_str()), same_doc, same).unwrap_or_else(|| { + // Its swatch comes along under the same name. + let name = unique_name(&def.name, |n| d.pattern(n).is_some() || d.swatch_name_taken(n)); + add_pattern(d, PatternDef { name: name.clone(), ..def.clone() }); + Placed::added(&def.name, name) + }); + added_patterns.extend(p.new_name(&def.name)); + out.placed(Res::Pattern, &def.name, &p); + } + Def::Brush(b) => { + let lib = library.get_or_insert_with(|| vectorcraft_brush::library(d)); + let r = &out.relink; + let p = place(lib, b, same_doc, |ours, theirs| !fresh && same_brush(r, ours, theirs)); + if let Some(name) = p.new_name(&b.name) { + vectorcraft_brush::store(d, lib); + added_brushes.insert(name); + } + out.placed(Res::Brush, &b.name, &p); + } } } - // Symbols and patterns, compared once relinked. Those added are relinked at the end, when - // every new name and graphic style id is known. - let mut added_symbols = vec![]; - for def in self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)) { - let r = &out.relink; - let p = place(&mut d.symbols, def, same_doc, |a, b| same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))); - added_symbols.extend(p.new_name(&def.name)); - out.placed(Res::Symbol, &def.name, &p); + if !in_use_order { + added_brushes.extend(self.import_brushes(d, used, same_doc, true, &mut out)); } - let mut added_patterns = vec![]; - for def in self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)) { - // Tile options alike, and the art once relinked. - let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() }; - let same = |n: &str| d.pattern(n).is_some_and(|x| bare(x) == bare(def) && same_art(&out.relink, &x.art, &def.art)); - let p = existing(&def.name, d.patterns.iter().map(|p| p.name.as_str()), same_doc, same).unwrap_or_else(|| { - // Its swatch comes along under the same name. - let name = unique_name(&def.name, |n| d.pattern(n).is_some() || d.swatch_name_taken(n)); - add_pattern(d, PatternDef { name: name.clone(), ..def.clone() }); - Placed::added(&def.name, name) - }); - added_patterns.extend(p.new_name(&def.name)); - out.placed(Res::Pattern, &def.name, &p); + self.import_graphic_styles(d, used, same_doc, &mut out); + for (r, name, def) in added_styles { + let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles }; + if let Some(s) = theirs.iter_mut().find(|s| s.name == name) { + s.attrs = def.attrs.clone(); + out.relink.attrs(&mut s.attrs); + } } - 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)); } @@ -721,6 +1170,7 @@ impl Clipboard { } vectorcraft_brush::store(d, &lib); } + out.relinks = !(out.relink.renames.is_empty() && out.relink.styles.is_empty() && out.relink.colors.is_empty() && used.styles.is_empty()); out } @@ -818,6 +1268,43 @@ impl Clipboard { } } +/// Where a loaded text style is in the document ([`import_text_styles`]). +pub(crate) struct LoadedStyle { + /// A paragraph style (else a character style). + pub para: bool, + /// Its name in the document. + pub name: String, + /// It was added (else the document's own was the same). + pub added: bool, +} + +/// Add every character style of `src` (with `chars`) and every paragraph style (with `paras`) to +/// `d`, with the swatches, patterns and what their art uses (styles of the other kind included) +/// that the styles' fill and stroke lead to, as Paste adds those of pasted type +/// ([`Clipboard::import_into`]; a global or spot color whose name `d` gives another color is +/// `d`'s). Each style, symbol and pattern is placed after those it uses, so that a style follows +/// a pattern added under a free name and a pattern follows a style renamed on the way in. A style +/// `d` has under its name, or a numbered copy of it ("Body 2"), that is the same once relinked is +/// used; any other is added under a free name. → each style of `src` placed, in order, character +/// styles first. +pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, paras: bool) -> Vec { + let library = OnceCell::new(); + let used = Used::of_text_styles(&Defs::of(src, &library), chars, paras); + let clip = Clipboard::with_used(src, &used, &library, vec![]); + let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::>()); + let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true); + let mut placed: Vec = vec![]; + for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] { + for s in list { + let name = out.relink.renamed(r, &s.name); + let again = placed.iter().any(|p| p.para == para && p.name == name); + let added = !again && !before[usize::from(para)].contains(&name); + placed.push(LoadedStyle { para, name, added }); + } + } + placed +} + /// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups /// share one namespace). fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed { diff --git a/crates/engine/src/cmd/clipboard/table.rs b/crates/engine/src/cmd/clipboard/table.rs new file mode 100644 index 0000000000..392be98951 --- /dev/null +++ b/crates/engine/src/cmd/clipboard/table.rs @@ -0,0 +1,203 @@ +//! Cells copied from a spreadsheet (Excel, Google Sheets, LibreOffice Calc, Numbers): the plain +//! text they put on the clipboard is tab-separated values, one row a line, every row with the +//! same number of cells. `clipboard.importText` pastes such text as a table: a group of point +//! type, one object for each cell that holds text, laid out in columns as wide as their widest +//! cell and rows as tall as their tallest, over gridlines around every cell. + +use std::sync::Arc; + +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, CharStyle, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect}; + +/// Most rows a pasted table takes; more pastes as plain text. +pub(crate) const MAX_ROWS: usize = 1000; +/// Most columns a pasted table takes; more pastes as plain text. +pub(crate) const MAX_COLUMNS: usize = 256; +/// Most cells (rows × columns) a pasted table takes; more pastes as plain text. +pub(crate) const MAX_CELLS: usize = 20_000; +/// Space between a cell's text and its gridlines, in points. +const PAD: f64 = 4.0; +/// The gridlines' stroke weight, in points. +const GRIDLINE: f64 = 0.5; + +/// The rows of `text` (line breaks already `\n`, trailing ones dropped) when it is a table copied +/// from a spreadsheet: tab-separated cells, at least two columns, every row with the same number +/// of cells, within the caps above. A cell in double quotes may hold tabs, line breaks and +/// doubled quotes (`""`), as the spreadsheets write them. `None` for any other text, which pastes +/// as it always has. +pub(crate) fn parse(text: &str) -> Option>> { + if !text.contains('\t') { + return None; + } + let mut rows: Vec> = vec![]; + let mut row: Vec = vec![]; + let mut cell = String::new(); + let mut chars = text.chars().peekable(); + // At the start of a cell, a quote opens a quoted cell. + let mut start = true; + let mut quoted = false; + let mut cells = 0usize; + while let Some(c) = chars.next() { + if quoted { + if c == '"' { + if chars.peek() == Some(&'"') { + chars.next(); + cell.push('"'); + } else { + quoted = false; + } + } else { + cell.push(c); + } + continue; + } + match c { + '"' if start => { + quoted = true; + start = false; + } + '\t' | '\n' => { + row.push(std::mem::take(&mut cell)); + cells += 1; + if row.len() > MAX_COLUMNS || cells > MAX_CELLS { + return None; + } + if c == '\n' { + rows.push(std::mem::take(&mut row)); + if rows.len() > MAX_ROWS { + return None; + } + } + start = true; + } + c => { + cell.push(c); + start = false; + } + } + } + // A quote left open is not a spreadsheet's. + if quoted { + return None; + } + row.push(cell); + rows.push(row); + if rows.iter().any(|r| r.len() > MAX_COLUMNS) || cells + 1 > MAX_CELLS { + return None; + } + let columns = rows.first()?.len(); + let fits = columns >= 2 && rows.len() <= MAX_ROWS && rows.iter().all(|r| r.len() == columns); + // The first and last columns hold something: text indented with tabs is not a table. + let used = |k: usize| rows.iter().any(|r| r.get(k).is_some_and(|c| !c.trim().is_empty())); + (fits && used(0) && used(columns - 1)).then_some(rows) +} + +/// `rows` laid out as a table (see the module docs) with its top left at the origin: one group +/// holding a group of gridlines and the cells' type. `style` is the type's style; `layout` +/// refreshes a type object's bounds. +pub(crate) fn table(rows: &[Vec], style: &CharStyle, layout: impl Fn(&mut TextObject)) -> Node { + let columns = rows.iter().map(Vec::len).max().unwrap_or(0); + let mut next = 0u64; + let mut id = || { + next += 1; + NodeId(next) + }; + // Each cell's type, at the origin, with its bounds. + let mut cells: Vec>> = vec![]; + for row in rows { + let mut out = vec![]; + for text in row { + if text.trim().is_empty() { + out.push(None); + continue; + } + let text = text.replace("\r\n", "\n").replace('\r', "\n"); + let mut t = TextObject::point(Point::ZERO, &text, style.clone()); + layout(&mut t); + let n = Node::new(id(), NodeKind::Text(Box::new(t))); + out.push(n.geometric_bounds().filter(|b| b.is_finite()).map(|b| (n, b))); + } + cells.push(out); + } + // A row with nothing in it is as tall as one line of the type. + let line = style.size.max(1.0) * 1.2; + let widths: Vec = + (0..columns).map(|k| cells.iter().filter_map(|r| r.get(k)?.as_ref()).map(|(_, b)| b.width()).fold(line, f64::max) + 2.0 * PAD).collect(); + let heights: Vec = cells.iter().map(|r| r.iter().flatten().map(|(_, b)| b.height()).fold(line, f64::max) + 2.0 * PAD).collect(); + let xs: Vec = std::iter::once(0.0) + .chain(widths.iter().scan(0.0, |x, w| { + *x += w; + Some(*x) + })) + .collect(); + let ys: Vec = std::iter::once(0.0) + .chain(heights.iter().scan(0.0, |y, h| { + *y += h; + Some(*y) + })) + .collect(); + let (right, bottom) = (xs.last().copied().unwrap_or(0.0), ys.last().copied().unwrap_or(0.0)); + let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), GRIDLINE); + let mut lines = vec![]; + for y in &ys { + lines.push(segment(id(), (0.0, *y), (right, *y), &stroke)); + } + for x in &xs { + lines.push(segment(id(), (*x, 0.0), (*x, bottom), &stroke)); + } + let mut grid = Node::group(id(), lines); + grid.name = Some("Gridlines".into()); + let mut children = vec![Arc::new(grid)]; + for (r, row) in cells.into_iter().enumerate() { + for (k, cell) in row.into_iter().enumerate() { + let (Some((mut n, b)), Some(x), Some(y)) = (cell, xs.get(k), ys.get(r)) else { continue }; + // The text's top left a pad inside the cell's. + n.transform(Affine::translate((x + PAD - b.x0, y + PAD - b.y0)), false); + children.push(Arc::new(n)); + } + } + let mut group = Node::group(id(), children); + group.name = Some("Table".into()); + group +} + +/// A straight stroked line from `a` to `b`. +fn segment(id: NodeId, a: (f64, f64), b: (f64, f64), stroke: &Appearance) -> Arc { + let mut p = BezPath::new(); + p.move_to(a); + p.line_to(b); + Arc::new(Node::path(id, PathData::from_bezpath(&p), stroke.clone())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn spreadsheet_cells_are_told_from_other_text() { + let rows = parse("Name\tQty\nApples\t3\nPears\t").unwrap(); + assert_eq!(rows, vec![vec!["Name", "Qty"], vec!["Apples", "3"], vec!["Pears", ""]]); + // Quoted cells hold line breaks, tabs and quotes. + let rows = parse("\"Two\nlines\"\t\"a\tb\"\n\"say \"\"hi\"\"\"\tx").unwrap(); + assert_eq!(rows, vec![vec!["Two\nlines", "a\tb"], vec!["say \"hi\"", "x"]]); + // Not tables: no tabs, ragged rows, indented text, an unclosed quote. + for t in ["plain words", "one\ntwo", "a\tb\nc", "\tindented\n\tcode", "a\t\"open", "x\t"] { + assert_eq!(parse(t), None, "{t:?}"); + } + // A quote inside a cell is just a character. + assert_eq!(parse("5\" pipe\t2").unwrap(), vec![vec!["5\" pipe", "2"]]); + } + + #[test] + fn tables_past_the_caps_paste_as_text() { + let wide = vec!["x"; MAX_COLUMNS + 1].join("\t"); + assert_eq!(parse(&wide), None); + let tall = vec!["a\tb"; MAX_ROWS + 1].join("\n"); + assert_eq!(parse(&tall), None); + let many = vec![vec!["c"; 100].join("\t"); MAX_CELLS / 100 + 1].join("\n"); + assert_eq!(parse(&many), None); + let fits = vec!["a\tb"; MAX_ROWS].join("\n"); + assert_eq!(parse(&fits).map(|r| r.len()), Some(MAX_ROWS)); + } +} diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 49b729c8ad..221521efbb 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -30,9 +30,9 @@ pub fn specs() -> Vec { "Invert Colors", ["Edit", "Edit Colors"], None, - "{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step → {changed}", + "{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step → {changed}", has_selection, - |s, p| recolor(s, p, "Invert Colors", &invert) + |s, p| recolor(s, p, "edit.colors.invert", "Invert Colors", &invert) ), cmd!( "edit.colors.toCMYK", @@ -41,7 +41,7 @@ pub fn specs() -> Vec { None, "{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert) → {changed}", has_selection, - |s, p| recolor(s, p, "Convert to CMYK", &to_cmyk) + |s, p| recolor(s, p, "edit.colors.toCMYK", "Convert to CMYK", &to_cmyk) ), cmd!( "edit.colors.toGrayscale", @@ -50,7 +50,7 @@ pub fn specs() -> Vec { None, "{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert) → {changed}", has_selection, - |s, p| recolor(s, p, "Convert to Grayscale", &to_gray) + |s, p| recolor(s, p, "edit.colors.toGrayscale", "Convert to Grayscale", &to_gray) ), cmd!( "edit.colors.toRGB", @@ -60,7 +60,7 @@ pub fn specs() -> Vec { "{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert) → {changed}", has_selection, |s, p| { - recolor(s, p, "Convert to RGB", &|c| { + recolor(s, p, "edit.colors.toRGB", "Convert to RGB", &|c| { let [r, g, b] = c.to_rgb(); Color::rgb(r, g, b) }) @@ -116,7 +116,7 @@ pub fn specs() -> Vec { "Color Guide", [], None, - "{color, rule: complementary|complementary2|splitComplementary|leftComplement|rightComplement|analogous|analogous2|monochromatic|shades|triad|triad2|triad3|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast2|highContrast3|pentagram (or its label), steps?: 1..20 (4), variation?: \"tintsShades\"|\"warmCool\"|\"vividMuted\", amount?: 0..100 (50; how far the outermost steps go), limitTo?: swatch library id or name; or \"document\" (the document's swatches): every colour snaps to its nearest colour there (ΔE 2000)} the Color Guide for a base colour → {rule, colors: [\"#rrggbb\", the base first], grid: [per colour, 2·steps+1 variations from shades/cool/muted to tints/warm/vivid with the colour itself in the centre]}", + "{color (#rrggbbaa and #rgba are refused), rule: complementary|complementary2|splitComplementary|leftComplement|rightComplement|analogous|analogous2|monochromatic|shades|triad|triad2|triad3|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast2|highContrast3|pentagram (or its label), steps?: 1..20 (4), variation?: \"tintsShades\"|\"warmCool\"|\"vividMuted\", amount?: 0..100 (50; how far the outermost steps go), limitTo?: swatch library id or name; or \"document\" (the document's swatches): every colour snaps to its nearest colour there (ΔE 2000)} the Color Guide for a base colour → {rule, colors: [\"#rrggbb\", the base first], grid: [per colour, 2·steps+1 variations from shades/cool/muted to tints/warm/vivid with the colour itself in the centre]}", always, harmony ), @@ -178,10 +178,10 @@ impl Scope { /// One recolouring pass, the colour visitor Edit Colors and Recolor Artwork share: `f` maps the /// solid colours and gradient stops of fills, strokes and text runs, gradient-mesh points, the -/// pixels of embedded images and the art of patterns used as fills or strokes. A recoloured image -/// becomes a new image and a recoloured pattern a new pattern swatch ("Dots 2"); the originals stay -/// as they are for other objects. Colours that change lose their swatch link. Only nodes that -/// change are kept as copies. +/// pixels of embedded images without a colorize paint and the art of patterns used as fills or +/// strokes. A recoloured image becomes a new image and a recoloured pattern a new pattern swatch +/// ("Dots 2"); the originals stay as they are for other objects. Colours that change lose their +/// swatch link. Only nodes that change are kept as copies. pub(crate) struct Recolor<'a> { f: &'a dyn Fn(Color) -> Color, /// Maps solid colours and gradient stops with their link and tint in place of `f`. @@ -331,23 +331,35 @@ impl ColorVisitor for Visit<'_, '_> { } } -pub(crate) fn recolor(s: &mut Session, p: &Value, label: &str, f: &dyn Fn(Color) -> Color) -> Result { - run_pass(s, p, label, Recolor::new(Scope::of(p), f)) +pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result { + run_pass(s, p, cmd, label, Recolor::new(Scope::of(p), f)) } -/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step. -fn run_pass(s: &mut Session, p: &Value, label: &str, pass: Recolor) -> Result { - let ids = match ids_param(p, "ids") { +/// [`recolor`] with solid colours and gradient stops mapped through `links`, with their swatch +/// link and tint. +pub(crate) fn recolor_links(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, links: &LinkMap) -> Result { + run_pass(s, p, cmd, label, Recolor::with_links(Scope::of(p), f, links)) +} + +/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step named `label`; +/// errors name the command `cmd`. +fn run_pass(s: &mut Session, p: &Value, cmd: &str, label: &str, pass: Recolor) -> Result { + let ids = match ids_param(p, "ids", cmd)? { Some(v) => v, None => selected_roots(s)?, }; - let n = s.edit(label, |d, _| Ok(pass.run(d, &ids)))?; + let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); + let n = s.edit(label, |d, _| { + let n = pass.run(d, &ids); + super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(cmd, e))?; + Ok(n) + })?; Ok(json!({ "changed": n })) } fn saturate(s: &mut Session, p: &Value) -> Result { let i = (f64_req(p, "intensity", "edit.colors.saturate")?.clamp(-100.0, 100.0) / 100.0) as f32; - recolor(s, p, "Saturate", &move |c| { + recolor(s, p, "edit.colors.saturate", "Saturate", &move |c| { let [h, sat, v] = c.to_hsb(); let to = (sat * (1.0 + i)).clamp(0.0, 1.0); // A color whose saturation stays the same is returned as it is, so it keeps its swatch link. @@ -405,12 +417,12 @@ fn adjust_balance(s: &mut Session, p: &Value) -> Result { (*tint, *c) = (t, base.tinted(t)); true }; - return run_pass(s, p, "Adjust Colors", Recolor::links(Scope::of(p), &shift)); + return run_pass(s, p, C, "Adjust Colors", Recolor::links(Scope::of(p), &shift)); } other => return Err(bad(C, format!("unknown mode `{other}` (rgb|cmyk|gray|global)"))), }; let convert = bool_or(p, "convert", false); - recolor(s, p, "Adjust Colors", &move |c| { + recolor(s, p, C, "Adjust Colors", &move |c| { let out = adjust(c); if convert { out } else { keep_model(c, out) } }) @@ -451,6 +463,7 @@ fn filled_leaves(d: &Document, roots: &[NodeId]) -> Vec { fn fill_color(n: &Node) -> Option { match &n.kind { NodeKind::Text(t) => t.first_style().fill.color(), + NodeKind::Image(_) => n.extras().colorize.as_deref().and_then(Paint::color).or_else(|| n.appearance.fill_paint().color()), NodeKind::Mesh(m) => { let k = m.points.len() as f32; let sum = m.points.iter().map(|p| p.color.to_rgb()).reduce(|a, c| [a[0] + c[0], a[1] + c[1], a[2] + c[2]])?; @@ -487,6 +500,7 @@ fn blend(s: &mut Session, order: BlendOrder) -> Result { BlendOrder::Vertical => "Blend Vertically", }; let fills = Scope { fill: true, stroke: false, images: false, patterns: false }; + let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); let changed = s.edit(label, |d, _| { let mut changed = 0; for (i, id) in ids.iter().enumerate().take(n - 1).skip(1) { @@ -504,6 +518,7 @@ fn blend(s: &mut Session, order: BlendOrder) -> Result { }; changed += Recolor::new(fills, &*f).run(d, &[*id]); } + super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(label, e))?; Ok(changed) })?; Ok(json!({ "changed": changed })) diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index b1ad12800e..d9b5784b68 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -19,7 +19,7 @@ use vectorcraft_render::proof; #[cfg(not(target_arch = "wasm32"))] use super::EngineError; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, color_value, has_doc, str_param, targets}; +use super::{CommandSpec, Result, Session, always, bad, cmd, color_value, has_doc, switch_or, targets, text_param}; /// `Document.unknown` key under which files before format v3 kept the assigned profiles (migrated /// to `Document::color_profiles` on load). @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Convert Color", [], None, - "{color, to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}", + "{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}", always, convert_color ), @@ -86,7 +86,7 @@ pub fn specs() -> Vec { "Gamut Warning", [], None, - "{ids?|id?, colors?: [color]} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}", + "{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}", has_doc, gamut_check ), @@ -100,7 +100,7 @@ pub fn specs() -> Vec { proof_setup ), cmd!(query "view.proofColors", "Proof Colors", ["View"], None, "{on?: bool (default: toggle)} → proof state", always, |s, p| { - toggle_view(s, p, |v, on| v.proof_colors = on.unwrap_or(!v.proof_colors)) + toggle_view(s, p, "view.proofColors", |v, on| v.proof_colors = on.unwrap_or(!v.proof_colors)) }), cmd!( query "view.overprintPreview", @@ -109,7 +109,7 @@ pub fn specs() -> Vec { Some("Cmd+Alt+Shift+Y"), "{on?: bool (default: toggle)} → proof state", always, - |s, p| toggle_view(s, p, |v, on| v.overprint = on.unwrap_or(!v.overprint)) + |s, p| toggle_view(s, p, "view.overprintPreview", |v, on| v.overprint = on.unwrap_or(!v.overprint)) ), cmd!( query "view.separationsPreview", @@ -143,12 +143,21 @@ pub fn specs() -> Vec { } fn intent_param(p: &Value, cmd: &str) -> Result> { - match str_param(p, "intent") { + match text_param(p, "intent", cmd)? { None => Ok(None), Some(i) => Intent::parse(i).map(Some).ok_or_else(|| bad(cmd, format!("unknown intent `{i}`"))), } } +/// The true or false `p` gives for `key`, or `None` when `p` leaves it out or gives null. Any other +/// value is an error, as [`switch_or`] reads it. +fn on_param(p: &Value, key: &str, cmd: &str) -> Result> { + if p.get(key).is_none_or(Value::is_null) { + return Ok(None); + } + switch_or(p, key, false, cmd).map(Some) +} + fn settings_json(st: &ColorSettings) -> Value { json!({ "rgb": st.rgb, @@ -171,16 +180,16 @@ fn color_settings(s: &mut Session, p: &Value) -> Result { const C: &str = "edit.colorSettings"; let mut st = cms::active_settings(); let before = st.clone(); - if let Some(v) = str_param(p, "rgb") { + if let Some(v) = text_param(p, "rgb", C)? { st.rgb = cms::canonical_name(v).to_string(); } - if let Some(v) = str_param(p, "cmyk") { + if let Some(v) = text_param(p, "cmyk", C)? { st.cmyk = cms::canonical_name(v).to_string(); } if let Some(i) = intent_param(p, C)? { st.intent = i; } - st.bpc = bool_or(p, "bpc", st.bpc); + st.bpc = switch_or(p, "bpc", st.bpc, C)?; if st != before { cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?; touch_all(s); @@ -191,7 +200,7 @@ fn color_settings(s: &mut Session, p: &Value) -> Result { #[cfg(not(target_arch = "wasm32"))] fn load_profile(s: &mut Session, p: &Value) -> Result { const C: &str = "color.loadProfile"; - let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?; + let path = text_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path`"))?; crate::file_access::check_read(path).map_err(EngineError::Other)?; let bytes = crate::store::read_capped(std::path::Path::new(path), crate::store::MAX_PROFILE_FILE).map_err(|e| bad(C, format!("{path}: {e}")))?; let info = cms::register_icc(&bytes, None).map_err(|e| bad(C, e.to_string()))?; @@ -209,7 +218,7 @@ fn load_profile(s: &mut Session, p: &Value) -> Result { /// Forget a profile `color.loadProfile` loaded, and the copy that is kept of it. fn remove_profile(s: &mut Session, p: &Value) -> Result { const C: &str = "color.removeProfile"; - let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?; + let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing `name`"))?; let info = cms::profiles().into_iter().find(|i| i.name == name).ok_or_else(|| bad(C, format!("no profile named `{name}`")))?; if info.builtin { return Err(bad(C, format!("`{name}` is a built-in profile and stays"))); @@ -278,7 +287,8 @@ fn assign_profile(s: &mut Session, p: &Value) -> Result { /// How Document Color Mode converts neutral RGB greys (R = G = B) to CMYK (the `grays` param). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Grays { - /// Through the CMYK profile like any colour: four-colour greys and a rich black. + /// Through the CMYK profile like any colour: light grays in cyan, magenta and yellow only, darker + /// grays in four inks, and a rich black. #[default] Profile, /// On the black plate only: K is the grey's ink percentage (as Convert to Grayscale and then @@ -289,7 +299,7 @@ pub enum Grays { impl Grays { /// The `grays` param of `cmd`: `"profile"` (default) or `"black"`. pub(crate) fn param(cmd: &str, p: &Value) -> Result { - match str_param(p, "grays").map(str::to_ascii_lowercase).as_deref() { + match text_param(p, "grays", cmd)?.map(str::to_ascii_lowercase).as_deref() { None | Some("profile") => Ok(Grays::Profile), Some("black") => Ok(Grays::Black), Some(g) => Err(bad(cmd, format!("grays must be \"profile\" or \"black\", not `{g}`"))), @@ -302,34 +312,155 @@ impl Grays { /// colour through the colour settings. pub(crate) fn convert_mode(s: &mut Session, p: &Value) -> Result { const C: &str = "file.documentColorMode"; - let mode = match str_param(p, "mode").map(str::to_ascii_lowercase).as_deref() { + let mode = match p.get("mode").and_then(Value::as_str).map(str::to_ascii_lowercase).as_deref() { Some("cmyk") => ColorMode::Cmyk, Some("rgb") => ColorMode::Rgb, _ => return Err(bad(C, "mode must be \"cmyk\" or \"rgb\"")), }; let intent = intent_param(p, C)?; let grays = Grays::param(C, p)?; + let convert = switch_or(p, "convert", true, C)?; // Choosing the mode the document already has (the checked menu item) is not an edit. if s.doc()?.doc.color_mode == mode { return Ok(json!({ "changed": 0 })); } - let convert = bool_or(p, "convert", true); let mut changed = 0usize; s.edit("Document Color Mode", |d, _| { changed = set_color_mode(d, mode, convert, intent, grays); Ok(()) })?; + if convert { + if s.in_interaction() && s.batch_stash.is_none() { + if let Some(it) = &mut s.doc_mut()?.interaction { + it.deferred_color_mode = Some(DeferredColorMode { mode, intent, grays }); + } + } else { + let before = new_art_colors_before(s)?; + convert_new_art_colors(s, mode, intent, grays)?; + record_new_art_colors(s, before)?; + } + } else if s.batch_stash.is_some() || s.doc()?.undo_group.is_some() { + let before = new_art_colors_before(s)?; + record_new_art_colors(s, before)?; + } Ok(json!({ "changed": changed })) } -/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks -/// included), symbols, graph designs, pattern tiles (the tile that pattern editing's Cancel puts -/// back included), graphic styles, brushes (their art and a Hue Shift key color) and swatches -/// through the color settings (`intent`, default: theirs) → how many colors of the art (opacity -/// masks included), symbols, graph designs and pattern tiles changed; the colors of graphic -/// styles and brushes convert without being counted. Gray colors stay -/// Gray (they print on the black plate in either mode); RGB grays are colors like any other and -/// separate through the CMYK profile, unless `grays` puts them on the black plate. Lab colors +/// The validated conversion choices of the current tentative color-mode preview. +#[derive(Clone, Copy, Debug)] +pub(crate) struct DeferredColorMode { + mode: ColorMode, + intent: Option, + grays: Grays, +} + +/// Complete the deferred new-art conversion before the interaction becomes an Undo step. +pub(crate) fn commit_new_art_colors(s: &mut Session) -> Result<()> { + let pending = + s.doc()?.interaction.as_ref().filter(|it| it.preview.is_some() && it.color_mode_paints.is_none()).and_then(|it| it.deferred_color_mode); + if let Some(DeferredColorMode { mode, intent, grays }) = pending { + let before = new_art_colors_before(s)?; + convert_new_art_colors(s, mode, intent, grays)?; + record_new_art_colors(s, before)?; + } + Ok(()) +} + +fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> { + let after = s.paint.clone(); + if before != after || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() { + let st = s.doc_mut()?; + let slot = if let Some(it) = &mut st.interaction { + Some(&mut it.color_mode_paints) + } else { + st.history.undo.last_mut().map(|e| &mut e.color_mode_paints) + }; + if let Some(slot) = slot { + match slot { + Some((_, end)) => *end = after, + slot => *slot = Some((before, after)), + } + } + if st.interaction.is_none() { + if let Some(e) = st.history.undo.last_mut() { + e.recost_paints(); + } + st.history.trim(); + } + } + Ok(()) +} + +fn new_art_colors_before(s: &Session) -> Result { + let st = s.doc()?; + Ok(st.undo_group.as_ref().map(|g| &g.paint).or_else(|| st.interaction.as_ref().map(|it| &it.paint)).cloned().unwrap_or_else(|| s.paint.clone())) +} + +/// Convert the fill and stroke that new art takes, and the colors of its template appearance +/// (paints and effect colors), as [`set_color_mode`] converted the active document's art. The +/// command records their original values for Undo. Previews defer this until acceptance; +/// a batch converts immediately and restores the values itself when it fails. +fn convert_new_art_colors(s: &mut Session, mode: ColorMode, intent: Option, grays: Grays) -> Result<()> { + let d = &s.doc()?.doc; + let bases = global_bases(d); + let conv = mode_converter(mode, intent, grays); + let mut f = |col: &Color, link: proof::Link| mode_color(col, link, &bases, &conv); + map_paint_colors(&mut s.paint.fill, &mut f); + map_paint_colors(&mut s.paint.stroke, &mut f); + if let Some(a) = s.paint.appearance.as_mut() { + for it in &mut a.items { + let paint = match it { + vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint, + vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint, + }; + map_paint_colors(paint, &mut f); + } + map_effect_colors(a, &mut f); + } + Ok(()) +} + +/// How Document Color Mode converts a color to `mode` through the color settings (`intent`, +/// default: theirs): Gray and Lab colors stay as they are; with `grays` on the black plate, an RGB +/// gray becomes K only in CMYK. +fn mode_converter(mode: ColorMode, intent: Option, grays: Grays) -> impl Fn(&Color) -> Color { + let c = cms::active(); + let intent = intent.unwrap_or(c.settings().intent); + let model = if mode == ColorMode::Cmyk { Model::Cmyk } else { Model::Rgb }; + let k_only = model == Model::Cmyk && grays == Grays::Black; + move |col: &Color| match col { + Color::Gray { .. } | Color::Lab { .. } => *col, + // Grey ink percentage, then K only (a Gray colour's CMYK). + Color::Rgb { .. } if k_only && Neutral::of(col).is_some() => c.convert(&c.convert(col, Model::Gray, intent), Model::Cmyk, intent), + _ => c.convert(col, model, intent), + } +} + +/// The name and color of each global swatch of `d`, for [`mode_color`]. +fn global_bases(d: &vectorcraft_doc::Document) -> Vec<(String, Color)> { + d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect() +} + +/// The color Document Color Mode gives `col` (swatch link `link`): a tint of a global swatch in +/// `bases` (already converted) is that swatch's color at its tint; any other color goes through +/// `conv` ([`mode_converter`]). +fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &dyn Fn(&Color) -> Color) -> Color { + match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) { + Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint), + _ => conv(col), + } +} + +/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks, +/// effect colors and the series paints and label styles that graphs keep included), symbols, +/// graph designs, pattern tiles (the tile that pattern editing's Cancel puts back included), +/// graphic styles (their effects included), brushes (their art and a Hue Shift key color) and +/// swatches through the color settings (`intent`, default: theirs) → how many colors of the art +/// (opacity masks, effect colors and graphs' paints included), symbols, graph designs and pattern +/// tiles changed; the colors of graphic styles and brushes convert without being counted. Gray +/// colors stay Gray (they print on the black plate in either mode); RGB grays are colors like any +/// other and separate through the CMYK profile, unless `grays` puts them on the black plate +/// ([`mode_converter`]). Lab colors /// (spot color definitions) are device independent and fit either mode. A tint of a global /// swatch becomes the converted swatch's color at its tint. Document Color Mode and /// `document.open {colorMode}` both convert this way. @@ -338,16 +469,7 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, if !convert { return 0; } - let c = cms::active(); - let intent = intent.unwrap_or(c.settings().intent); - let model = if mode == ColorMode::Cmyk { Model::Cmyk } else { Model::Rgb }; - let k_only = model == Model::Cmyk && grays == Grays::Black; - let conv = |col: &Color| match col { - Color::Gray { .. } | Color::Lab { .. } => *col, - // Grey ink percentage, then K only (a Gray colour's CMYK). - Color::Rgb { .. } if k_only && Neutral::of(col).is_some() => c.convert(&c.convert(col, Model::Gray, intent), Model::Cmyk, intent), - _ => c.convert(col, model, intent), - }; + let conv = mode_converter(mode, intent, grays); for sw in d.swatches_iter_mut() { match &mut sw.paint { Paint::Solid { color, .. } => *color = conv(color), @@ -360,13 +482,10 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, } } // Tints are their converted swatch's colour at their tint (exact ink percentages). - let bases: Vec<(String, Color)> = d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect(); + let bases = global_bases(d); let changed = std::cell::Cell::new(0usize); let mut count = |col: &Color, link: proof::Link| { - let n = match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) { - Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint), - _ => conv(col), - }; + let n = mode_color(col, link, &bases, &conv); if n != *col { changed.set(changed.get() + 1); } @@ -384,12 +503,15 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, } // The reply counts the colors of the document's art only, not those of the graphic styles and brushes. let in_art = changed.get(); - for it in d.graphic_styles.iter_mut().flat_map(|g| &mut g.appearance.items) { - let paint = match it { - vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint, - vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint, - }; - map_paint_colors(paint, &mut count); + for g in &mut d.graphic_styles { + for it in &mut g.appearance.items { + let paint = match it { + vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint, + vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint, + }; + map_paint_colors(paint, &mut count); + } + map_effect_colors(&mut g.appearance, &mut count); } // Convert each brush's art. A Hue Shift key color takes the converted color of the art color // it matches (a tint of a global swatch included), so the key still matches the converted art; @@ -438,19 +560,28 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, in_art } -/// [`proof::map_node_colors`] over `n`'s subtree and the art of every opacity mask in it. +/// [`proof::map_node_colors`] over `n`'s subtree, then [`map_more_colors`]. fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { proof::map_node_colors(n, f); - map_mask_colors(n, f); + map_more_colors(n, f); } -fn map_mask_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { - if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) { - map_art_colors(Arc::make_mut(&mut mask.art), f); +/// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the +/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps +/// ([`map_graph_colors`]) and the art of every opacity mask. +fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + map_effect_colors(&mut n.appearance, f); + if let Some(e) = n.extras_if_any() { + if let Some(g) = e.graph.as_deref_mut() { + map_graph_colors(g, f); + } + if let Some(mask) = e.mask.as_deref_mut() { + map_art_colors(Arc::make_mut(&mut mask.art), f); + } } if let Some(ch) = n.children_mut() { for c in ch.iter_mut() { - map_mask_colors(Arc::make_mut(c), f); + map_more_colors(Arc::make_mut(c), f); } } } @@ -461,7 +592,46 @@ fn matches_key(c: &Color, key: &Color) -> bool { c.to_rgb().iter().zip(key.to_rgb()).map(|(a, b)| (a - b).abs()).sum::() < 0.02 } -/// `f` applied to a solid paint's color or a gradient's stop colors, given their swatch link. +/// `f` applied to the `color` of each effect in appearance `a` (the object's effects and those of +/// each fill and stroke) that has one ([`super::params::effect_color`]). An effect that draws its +/// default color stores the new color as its own. The light colors of the 3D effects stay as they +/// are. +fn map_effect_colors(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut()); + for e in a.effects.iter_mut().chain(items) { + if !(e.params.is_object() || e.params.is_null()) { + continue; + } + let Some(color) = super::params::effect_color(&e.id, &e.params) else { continue }; + let n = f(&color, None); + if n == color { + continue; + } + match &mut e.params { + Value::Object(m) => { + m.insert("color".into(), json!(n)); + } + p => *p = json!({ "color": n }), + } + } +} + +/// `f` applied to the series paints and the label styles that graph `g` keeps, which its marks and +/// labels take each time it is drawn again. +fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + for p in g.series_paints.iter_mut() { + for paint in [&mut p.fill, &mut p.stroke].into_iter().flatten() { + map_paint_colors(paint, f); + } + } + let styles = &mut g.label_styles; + for st in [&mut styles.values, &mut styles.categories, &mut styles.legend].into_iter().flatten() { + map_paint_colors(&mut st.fill, f); + map_paint_colors(&mut st.stroke, f); + } +} + +/// `f` applied to solid, gradient-stop and freeform-control colors, with any swatch link. fn map_paint_colors(p: &mut Paint, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { match p { Paint::Solid { color, swatch, tint } => *color = f(color, swatch.as_deref().map(|s| (s, *tint))), @@ -469,6 +639,11 @@ fn map_paint_colors(p: &mut Paint, f: &mut dyn FnMut(&Color, proof::Link) -> Col for st in &mut g.gradient.stops { st.color = f(&st.color, st.swatch.as_deref().map(|s| (s, st.tint))); } + if let Some(freeform) = &mut g.freeform { + for point in &mut freeform.points { + point.color = f(&point.color, None); + } + } } _ => {} } @@ -489,7 +664,7 @@ fn convert_color(_: &mut Session, p: &Value) -> Result { let c = cms::active(); let intent = intent_param(p, C)?.unwrap_or(c.settings().intent); let lab = c.lab(&col); - let (model, vals) = match str_param(p, "to").unwrap_or("rgb") { + let (model, vals) = match text_param(p, "to", C)?.unwrap_or("rgb") { "rgb" => ("rgb", values(&c.convert(&col, Model::Rgb, intent))), "cmyk" => ("cmyk", values(&c.convert(&col, Model::Cmyk, intent))), "gray" | "grayscale" => ("gray", values(&c.convert(&col, Model::Gray, intent))), @@ -509,8 +684,14 @@ fn convert_color(_: &mut Session, p: &Value) -> Result { fn gamut_check(s: &mut Session, p: &Value) -> Result { let mut cols: Vec = vec![]; - if let Some(a) = p.get("colors").and_then(Value::as_array) { - cols.extend(a.iter().filter_map(color_value)); + let colors = p.get("colors").filter(|v| !v.is_null()); + if let Some(v) = colors.filter(|v| !v.is_array()) { + return Err(bad("color.gamutCheck", format!("`colors` must be an array of colors, not {v}"))); + } + if let Some(a) = colors.and_then(Value::as_array) { + for v in a { + cols.push(color_value(v).ok_or_else(|| bad("color.gamutCheck", format!("bad color {v}")))?); + } } else { let st = s.doc()?; let ids = targets(s, p)?; @@ -561,7 +742,7 @@ fn view_json(v: &proof::ProofView) -> Value { fn proof_setup(s: &mut Session, p: &Value) -> Result { const C: &str = "view.proofSetup"; let mut v = proof::view(); - if let Some(t) = str_param(p, "target") { + if let Some(t) = text_param(p, "target", C)? { let t = ProofTarget::parse(t).ok_or_else(|| bad(C, format!("unknown proof target `{t}`")))?; if let ProofTarget::Cmyk(name) = &t && !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Cmyk) @@ -573,8 +754,8 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result { if let Some(i) = intent_param(p, C)? { v.setup.intent = i; } - v.setup.simulate_paper = bool_or(p, "simulatePaper", v.setup.simulate_paper); - if let Some(on) = p.get("proof").and_then(Value::as_bool) { + v.setup.simulate_paper = switch_or(p, "simulatePaper", v.setup.simulate_paper, C)?; + if let Some(on) = on_param(p, "proof", C)? { v.proof_colors = on; } proof::set_view(v.clone()); @@ -582,9 +763,10 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result { Ok(view_json(&v)) } -fn toggle_view(s: &mut Session, p: &Value, f: impl FnOnce(&mut proof::ProofView, Option)) -> Result { +fn toggle_view(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut proof::ProofView, Option)) -> Result { + let on = on_param(p, "on", cmd)?; let mut v = proof::view(); - f(&mut v, p.get("on").and_then(Value::as_bool)); + f(&mut v, on); proof::set_view(v.clone()); touch_all(s); Ok(view_json(&v)) @@ -612,16 +794,23 @@ fn separations(s: &mut Session, p: &Value) -> Result { .map(|d| proof::plates(&d.doc).into_iter().map(|p| p.name).collect()) .unwrap_or_else(|| cms::PROCESS_PLATES.iter().map(|s| s.to_string()).collect()); let check = |n: &str| if all.iter().any(|a| a == n) { Ok(n.to_string()) } else { Err(bad(C, format!("unknown plate `{n}`"))) }; - if let Some(on) = p.get("on").and_then(Value::as_bool) { + if let Some(on) = on_param(p, "on", C)? { v.separations = if on { Some(v.separations.take().unwrap_or_else(|| all.clone())) } else { None }; } - if let Some(a) = p.get("plates").and_then(Value::as_array) { - v.separations = Some(a.iter().filter_map(Value::as_str).map(check).collect::>>()?); + match p.get("plates") { + None | Some(Value::Null) => {} + Some(Value::Array(a)) if a.iter().all(Value::is_string) => { + v.separations = Some(a.iter().filter_map(Value::as_str).map(check).collect::>>()?); + } + Some(_) => { + let key = "plates"; + return Err(bad(C, format!("`{key}` must be an array of these names: {}", all.join(", ")))); + } } - if let Some(n) = str_param(p, "only") { + if let Some(n) = text_param(p, "only", C)? { v.separations = Some(vec![check(n)?]); } - if let Some(n) = str_param(p, "toggle") { + if let Some(n) = text_param(p, "toggle", C)? { let n = check(n)?; let vis = v.separations.get_or_insert_with(|| all.clone()); if let Some(i) = vis.iter().position(|x| *x == n) { @@ -637,14 +826,15 @@ fn separations(s: &mut Session, p: &Value) -> Result { fn set_spot(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.setSpot"; - let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?.to_string(); - let spot = bool_or(p, "spot", true); + let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing `name`"))?.to_string(); + let spot = switch_or(p, "spot", true, C)?; let sw = s.doc()?.doc.swatch(&name).ok_or_else(|| bad(C, format!("no swatch `{name}`")))?; if !matches!(sw.paint, Paint::Solid { .. }) { return Err(bad(C, "only solid-colour swatches can be spot colours")); } if sw.spot != spot { let n = name.clone(); + let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); s.edit("Swatch Options", |d, _| { if let Some(w) = d.swatch_mut(&n) { w.spot = spot; @@ -652,7 +842,7 @@ fn set_spot(s: &mut Session, p: &Value) -> Result { w.global = true; } } - Ok(()) + super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e)) })?; } Ok(json!({"name": name, "spot": spot})) diff --git a/crates/engine/src/cmd/colortheme.rs b/crates/engine/src/cmd/colortheme.rs index 9321fc12bc..b61432aea1 100644 --- a/crates/engine/src/cmd/colortheme.rs +++ b/crates/engine/src/cmd/colortheme.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Save Theme", ["Window", "Color Themes"], None, - "{colors: [1–5 colours] | color + rule (a harmony rule id or label, see color.harmony: its 5-colour theme from that base colour, base first), rule?: the rule it was made with, name?: (default \"Theme N\"), replace?: a saved theme's name (overwrite that theme in place, e.g. after editing it; it may be renamed), color?: one colour (as colors: [colour])} save a colour theme to the local theme library (the preferences) → {name, count: themes saved}", + "{colors: [1–5 colours] (#rrggbbaa and #rgba are refused) | color + rule (a harmony rule id or label, see color.harmony: its 5-colour theme from that base colour, base first), rule?: the rule it was made with, name?: (default \"Theme N\"), replace?: a saved theme's name (overwrite that theme in place, e.g. after editing it; it may be renamed), color?: one colour (as colors: [colour])} save a colour theme to the local theme library (the preferences) → {name, count: themes saved}", always, save ), diff --git a/crates/engine/src/cmd/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs new file mode 100644 index 0000000000..3925612a14 --- /dev/null +++ b/crates/engine/src/cmd/compositefonts.rs @@ -0,0 +1,327 @@ +//! Type › Composite Fonts…: the document's composite fonts ([`vectorcraft_doc::CompositeFont`]), +//! which set each class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals) in a +//! font of its own. Type names a composite font as its family, and the font menus list them first. +//! The font database holds the active document's composite fonts ([`sync`]); a file exported here +//! carries them to another document. +//! +//! Behavior reference (public documentation): +//! . + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX}; +use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts}; +use vectorcraft_text::FontDb; + +use super::fileio::{read_file_head, write_file}; +use super::textstyles::each_text_mut; +use super::typecmd::refresh_bounds; +use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_param}; + +/// The extension of the files Export writes and Import reads. +pub const EXTS: &[&str] = &["vccomposite"]; + +/// The largest file Import reads, in bytes. +const MAX_FILE_BYTES: usize = 4 << 20; + +/// The keys a part may give. +const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"]; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "type.compositeFonts.list", + "Composite Fonts", + [], + None, + "{} the active document's composite fonts → {fonts: [{name, parts: {kanji, kana, punctuation, symbols, roman, numerals: {font, style, size: % of the type size, baseline: % of the type size (positive raises), hScale: %, vScale: %, scaleAtCenter?: bool}}}]}", + has_doc, + list + ), + cmd!( + "type.compositeFonts.set", + "Composite Fonts…", + ["Type"], + None, + "{fonts: [{name, parts: {kanji: {font, style?: \"Regular\", size?: % 10..400 = 100, baseline?: % -100..100 = 0}, kana?, punctuation?, symbols?, roman?, numerals?: {font, style?, size?, baseline?, hScale?, vScale?: % 10..400 = 100, scaleAtCenter?: bool = false}}}]} replace the active document's composite fonts (Type › Composite Fonts…'s OK), as one undo step, none when nothing changes. A composite font sets each class of character in its part's font: kanji (the base: ideographs, full-width letters and digits and anything no other class takes), kana (hiragana and katakana, both widths), punctuation (East Asian and full-width punctuation, quotes and dashes), symbols (arrows, math, shapes and other symbols), roman (half-width letters, their punctuation and spaces) and numerals (the digits 0 to 9); a part left out is the kanji part. size and baseline are percent of the type's size, hScale and vScale scale kana, roman and numerals only, and scaleAtCenter (kana only) scales them from the em box's center instead of the baseline. Names are trimmed, unique in any case, at most 255 characters, and may not name an installed font; a part's font may not be a composite font; at most 256. Type set in a composite font names it as its family (text.setStyle {font: name}), and the font menus list composite fonts first. A font taken out stays named by its type, which then shows as missing → {fonts}", + has_doc, + set + ), + cmd!( + query "type.compositeFonts.export", + "Export Composite Fonts", + [], + None, + "{path?: .vccomposite file, names?: [name] (default: all), fonts?: [{name, parts}] (as type.compositeFonts.set takes them)} write the active document's composite fonts (all, or those named, any case), or the fonts given, to a file type.compositeFonts.import reads; without path the file's text comes back as data → {path, count} | {data, count}", + has_doc, + export + ), + cmd!( + "type.compositeFonts.import", + "Import Composite Fonts", + [], + None, + "{path: .vccomposite file | data: its text | dataBase64: its bytes (at most 4 MB), apply?: bool = true} read the composite fonts a file holds (type.compositeFonts.export writes them); with apply they join the active document's, a font of the same name (any case) replaced, as one undo step, none when nothing changes; apply false only reads them → {fonts, imported: [name]}", + has_doc, + import + ), + ] +} + +/// Register the active document's composite fonts in the font database, and remove the ones the +/// other open documents (or an earlier active document) defined. Run after each command and when +/// another document takes the front, so an undo, a revert, an opened or closed file or a document +/// switch draws type in the active document's own composite fonts, and type naming one it does +/// not define shows as missing. The lowercased names of the composite fonts added, changed or +/// removed. +pub(crate) fn sync(s: &mut Session) -> Vec { + let db = FontDb::global(); + let mut names = Vec::new(); + let mut changed = Vec::new(); + for f in s.active().map(|d| d.doc.composite_fonts.to_vec()).unwrap_or_default() { + let name = f.name.to_lowercase(); + if db.set_composite_font(&f) { + changed.push(name.clone()); + } + names.push(name); + } + let others = s.docs.iter().flat_map(|d| d.doc.composite_fonts.iter().map(|f| f.name.to_lowercase())); + let stale: Vec = s.composite_names.iter().cloned().chain(others).filter(|n| !names.contains(n)).collect(); + for gone in stale { + if db.remove_composite_font(&gone) { + changed.push(gone); + } + } + s.composite_names_registered.extend(names.iter().chain(&changed).cloned()); + s.composite_names = names; + changed +} + +/// The lowercased names of the composite fonts the open documents define, the font database holds +/// and the session has registered before: the names type may have been laid out in. +pub(crate) fn names_in_use(s: &Session) -> std::collections::HashSet { + let defined = s.docs.iter().flat_map(|d| d.doc.composite_fonts.iter().map(|f| f.name.to_lowercase())); + let held = FontDb::global().composite_font_names().into_iter().map(|n| n.to_lowercase()); + defined.chain(held).chain(s.composite_names_registered.iter().cloned()).collect() +} + +/// Leave out a file's unusable composite fonts before registering and measuring its type. +pub(crate) fn filter_loaded(doc: &mut vectorcraft_doc::Document) { + let db = FontDb::global(); + if let Some(kept) = CompositeFont::usable(&doc.composite_fonts) { + *doc.composite_fonts = kept; + } + doc.composite_fonts.retain(|f| !db.has_installed_family(&f.name)); +} + +fn list(s: &mut Session, _: &Value) -> Result { + Ok(json!({ "fonts": *s.doc()?.doc.composite_fonts })) +} + +/// Composite font `v` from command parameters or a file: its name trimmed, each part left out a +/// copy of the Kanji part, and keys or values a part can't take refused. +fn parse_font(v: &Value, c: &str) -> Result { + let o = v.as_object().ok_or_else(|| bad(c, "each font must be {name, parts}"))?; + if let Some(k) = o.keys().find(|k| !["name", "parts"].contains(&k.as_str())) { + return Err(bad(c, format!("unknown key `{k}`; a font takes name and parts"))); + } + let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, "each font needs a name"))?; + let name = CompositeFont::clean_name(raw) + .ok_or_else(|| bad(c, format!("`{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters)")))?; + let parts = o.get("parts").and_then(Value::as_object).ok_or_else(|| bad(c, format!("`{name}`: parts must be an object")))?; + if let Some(k) = parts.keys().find(|k| !CharClass::ALL.iter().any(|c| c.key() == k.as_str())) { + return Err(bad(c, format!("`{name}`: unknown class `{k}`; the classes are kanji, kana, punctuation, symbols, roman and numerals"))); + } + let part = |class: CharClass| -> Result> { + let Some(p) = parts.get(class.key()) else { return Ok(None) }; + let po = p.as_object().ok_or_else(|| bad(c, format!("`{name}`: {} must be an object", class.key())))?; + if let Some(k) = po.keys().find(|k| !PART_KEYS.contains(&k.as_str())) { + return Err(bad(c, format!("`{name}`: unknown key `{k}` in {}", class.key()))); + } + serde_json::from_value(p.clone()).map(Some).map_err(|e| bad(c, format!("`{name}`: {}: {e}", class.key()))) + }; + let kanji = part(CharClass::Kanji)?.ok_or_else(|| bad(c, format!("`{name}`: give the kanji part")))?; + let mut f = CompositeFont { name: name.clone(), parts: CompositeParts::all(kanji) }; + for class in CharClass::ALL.into_iter().skip(1) { + if let Some(p) = part(class)? { + *f.parts.get_mut(class) = p; + } + } + f.check().map_err(|e| bad(c, format!("`{}`: {e}", f.name)))?; + Ok(f) +} + +/// Error unless `fonts` can stand together in a document: names unique in any case, none naming +/// an installed font, no part set in a composite font, and at most [`COMPOSITE_FONTS_MAX`]. +fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> { + if fonts.len() > COMPOSITE_FONTS_MAX { + return Err(bad(c, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts"))); + } + let db = FontDb::global(); + let mut names = std::collections::HashSet::new(); + for f in fonts { + if !names.insert(f.name.to_lowercase()) { + return Err(bad(c, format!("two composite fonts are named `{}`", f.name))); + } + if db.has_installed_family(&f.name) { + return Err(bad(c, format!("`{}` is the name of an installed font", f.name))); + } + } + for f in fonts { + for class in CharClass::ALL { + let font = &f.parts.get(class).font; + if names.contains(&font.to_lowercase()) || db.composite_font(font).is_some() { + return Err(bad(c, format!("`{}`: {} is set in `{font}`, a composite font", f.name, class.key()))); + } + } + } + Ok(()) +} + +/// Make `after` the active document's composite fonts, as one undo step named `label` (none when +/// they are what it has). The font database forgets the ones taken out, and type set in a font +/// that changed is measured again. +fn replace(s: &mut Session, label: &str, after: Vec) -> Result<()> { + let before = s.doc()?.doc.composite_fonts.to_vec(); + if before == after { + return Ok(()); + } + let changed: Vec = + before.iter().filter(|b| !after.contains(b)).chain(after.iter().filter(|a| !before.contains(a))).map(|f| f.name.to_lowercase()).collect(); + // A refused or panicked edit leaves the document without the new fonts: `sync` forgets a name + // listed here that the document doesn't define. + s.composite_names.extend(after.iter().map(|f| f.name.to_lowercase())); + let db = FontDb::global(); + for f in &before { + if !after.iter().any(|a| CompositeFont::same_name(&a.name, &f.name)) { + db.remove_composite_font(&f.name); + } + } + for f in &after { + db.set_composite_font(f); + } + let r = s.edit(label, |d, _| { + *d.composite_fonts = after.clone(); + each_text_mut(d, &mut |t| { + if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) { + refresh_bounds(t); + } + Ok(()) + }) + }); + sync(s); + r +} + +fn set(s: &mut Session, p: &Value) -> Result { + const C: &str = "type.compositeFonts.set"; + let list = p.get("fonts").and_then(Value::as_array).ok_or_else(|| bad(C, "give fonts: [{name, parts}…]"))?; + let fonts = list.iter().map(|v| parse_font(v, C)).collect::>>()?; + check_set(&fonts, C)?; + replace(s, "Composite Fonts", fonts.clone())?; + Ok(json!({ "fonts": fonts })) +} + +fn export(s: &mut Session, p: &Value) -> Result { + const C: &str = "type.compositeFonts.export"; + let path = text_param(p, "path", C)?; + if path.is_some_and(|p| p.trim().is_empty()) { + return Err(bad(C, "path is empty")); + } + let all = match p.get("fonts") { + None | Some(Value::Null) => s.doc()?.doc.composite_fonts.to_vec(), + Some(Value::Array(list)) => { + let fonts = list.iter().map(|v| parse_font(v, C)).collect::>>()?; + check_set(&fonts, C)?; + fonts + } + Some(_) => return Err(bad(C, "fonts must be a list of composite fonts")), + }; + let fonts = match p.get("names") { + None | Some(Value::Null) => all, + Some(Value::Array(names)) => { + let mut out = Vec::with_capacity(names.len()); + for n in names { + let n = n.as_str().ok_or_else(|| bad(C, "names must be strings"))?; + let f = all + .iter() + .find(|f| CompositeFont::same_name(&f.name, n.trim())) + .ok_or_else(|| bad(C, format!("no composite font named `{n}`")))?; + if !out.contains(f) { + out.push(f.clone()); + } + } + out + } + Some(_) => return Err(bad(C, "names must be a list of names")), + }; + if fonts.is_empty() { + return Err(bad(C, "no composite fonts to export")); + } + let mut file = Map::new(); + file.insert("compositeFonts".into(), json!(fonts)); + let text = serde_json::to_string_pretty(&file).map_err(|e| bad(C, e.to_string()))?; + match path { + Some(path) => { + write_file(path, text.as_bytes())?; + Ok(json!({ "path": path, "count": fonts.len() })) + } + None => Ok(json!({ "data": text, "count": fonts.len() })), + } +} + +/// The composite fonts in the bytes of an exported file. +fn read_fonts(bytes: &[u8], c: &str) -> Result> { + let v: Value = serde_json::from_slice(bytes).map_err(|e| bad(c, format!("not a composite fonts file: {e}")))?; + let list = v.get("compositeFonts").and_then(Value::as_array).ok_or_else(|| bad(c, "not a composite fonts file: no compositeFonts list"))?; + if list.len() > COMPOSITE_FONTS_MAX { + return Err(bad(c, format!("the file holds more than {COMPOSITE_FONTS_MAX} composite fonts"))); + } + list.iter().map(|f| parse_font(f, c)).collect() +} + +fn import(s: &mut Session, p: &Value) -> Result { + const C: &str = "type.compositeFonts.import"; + let apply = switch_or(p, "apply", true, C)?; + let given = (text_param(p, "path", C)?, text_param(p, "data", C)?, text_param(p, "dataBase64", C)?); + let too_large = || bad(C, "the file is larger than 4 MB"); + let bytes = match given { + (Some(path), None, None) if !path.trim().is_empty() => read_file_head(path, MAX_FILE_BYTES + 1)?, + (None, Some(text), None) => text.as_bytes().to_vec(), + (None, None, Some(b64)) => { + if b64.len() > MAX_FILE_BYTES / 3 * 4 + 4 { + return Err(too_large()); + } + vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(C, "dataBase64 is not base64"))? + } + _ => return Err(bad(C, "give one of path, data or dataBase64")), + }; + if bytes.len() > MAX_FILE_BYTES { + return Err(too_large()); + } + let fonts = read_fonts(&bytes, C)?; + if fonts.is_empty() { + return Err(bad(C, "the file holds no composite fonts")); + } + let mut names = std::collections::HashSet::new(); + if let Some(f) = fonts.iter().find(|f| !names.insert(f.name.to_lowercase())) { + return Err(bad(C, format!("the file holds two composite fonts named `{}`", f.name))); + } + if apply { + let mut after = s.doc()?.doc.composite_fonts.to_vec(); + for f in &fonts { + match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) { + Some(a) => *a = f.clone(), + None => after.push(f.clone()), + } + } + check_set(&after, C)?; + replace(s, "Import Composite Fonts", after)?; + } else { + check_set(&fonts, C)?; + } + let imported: Vec<&str> = fonts.iter().map(|f| f.name.as_str()).collect(); + Ok(json!({ "fonts": fonts, "imported": imported })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/compositefonts/tests.rs b/crates/engine/src/cmd/compositefonts/tests.rs new file mode 100644 index 0000000000..f51f066dfe --- /dev/null +++ b/crates/engine/src/cmd/compositefonts/tests.rs @@ -0,0 +1,646 @@ +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use crate::Session; + +/// A composite font named `name`: Source Sans 3 for the base, JetBrains Mono at half size for +/// Roman, Inter for numerals. +fn font(name: &str) -> Value { + json!({"name": name, "parts": { + "kanji": {"font": "Source Sans 3"}, + "roman": {"font": "JetBrains Mono", "size": 50, "baseline": 10}, + "numerals": {"font": "Inter", "hScale": 80}, + }}) +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn names(s: &Session) -> Vec { + s.doc().unwrap().doc.composite_fonts.iter().map(|f| f.name.clone()).collect() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn text(s: &Session, id: u64) -> vectorcraft_doc::TextObject { + match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +/// A scratch folder of the test's own. +fn folder(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("vectorcraft-composite-fonts-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Composite Fonts' OK replaces the document's composite fonts as one undo step (none when nothing +/// changes); parts left out copy the Kanji part; they are saved with the document and undone with +/// it. +#[test] +fn composite_fonts_are_set_as_one_undo_step_and_saved() { + let mut s = session(); + let before = steps(&s); + let r = s.execute("type.compositeFonts.set", &json!({"fonts": [font(" CF Saved A "), font("CF Saved B")]})).unwrap(); + assert_eq!(r["fonts"][0]["name"], "CF Saved A"); + assert_eq!(names(&s), ["CF Saved A", "CF Saved B"]); + assert_eq!(steps(&s), before + 1); + let f = &s.doc().unwrap().doc.composite_fonts[0]; + assert_eq!((f.parts.kana.font.as_str(), f.parts.roman.size, f.parts.numerals.h_scale), ("Source Sans 3", 50.0, 80.0)); + // The same fonts again change nothing. + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Saved A"), font("CF Saved B")]})).unwrap(); + assert_eq!(steps(&s), before + 1); + let listed = s.execute("type.compositeFonts.list", &json!({})).unwrap(); + assert_eq!(listed["fonts"].as_array().map(Vec::len), Some(2)); + // They travel with the file. + let back = vectorcraft_format::load(&vectorcraft_format::save_file(&s.doc().unwrap().doc)).unwrap(); + assert_eq!(*back.composite_fonts, *s.doc().unwrap().doc.composite_fonts); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(names(&s).is_empty()); +} + +/// Bad fonts are refused with an error and no undo step: a name that is empty, shared (in any +/// case) or an installed font's; a part set in a composite font; an unknown class or key; a value +/// out of range, of the wrong type, or on a class that can't take it; no Kanji part. +#[test] +fn bad_composite_fonts_are_refused() { + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Refused Base")]})).unwrap(); + let before = steps(&s); + let with = |f: &dyn Fn(&mut Value)| { + let mut v = font("CF Refused"); + f(&mut v); + json!({"fonts": [v]}) + }; + for bad in [ + json!({}), + json!({"fonts": "CF"}), + json!({"fonts": [font(" ")]}), + json!({"fonts": [font("CF Twice"), font("cf twice")]}), + json!({"fonts": [font("Source Sans 3")]}), + json!({"fonts": [font("Tab\tName")]}), + with(&|v| v["parts"]["roman"]["font"] = json!("CF Refused Base")), + with(&|v| v["parts"]["roman"]["font"] = json!("CF Refused")), + with(&|v| v["parts"]["hangul"] = json!({"font": "Inter"})), + with(&|v| v["parts"]["Roman"] = json!({"font": "Inter"})), + with(&|v| v["parts"]["roman"]["width"] = json!(3)), + with(&|v| v["parts"]["roman"]["size"] = json!(5)), + with(&|v| v["parts"]["roman"]["size"] = json!("50")), + with(&|v| v["parts"]["roman"]["baseline"] = json!(-120)), + with(&|v| v["parts"]["kanji"]["hScale"] = json!(90)), + with(&|v| v["parts"]["punctuation"] = json!({"font": "Inter", "vScale": 90})), + with(&|v| v["parts"]["roman"]["scaleAtCenter"] = json!(true)), + with(&|v| v["parts"]["kana"] = json!({"font": "Inter", "scaleAtCenter": "yes"})), + with(&|v| v["parts"]["roman"]["font"] = json!("")), + with(&|v| v["extra"] = json!(1)), + with(&|v| { + v["parts"].as_object_mut().unwrap().remove("kanji"); + }), + ] { + assert!(s.execute("type.compositeFonts.set", &bad).is_err(), "accepted {bad}"); + assert_eq!(names(&s), ["CF Refused Base"]); + assert_eq!(steps(&s), before); + } + // Kana scaled at the center is allowed. + let ok = with(&|v| v["parts"]["kana"] = json!({"font": "Inter", "vScale": 80, "scaleAtCenter": true})); + s.execute("type.compositeFonts.set", &ok).unwrap(); + assert_eq!(names(&s), ["CF Refused"]); +} + +/// Type set in a composite font names it and is not missing; each class is drawn in its part's +/// font; changing the font measures the type again, and taking it out leaves the type naming it, +/// shown as missing. +#[test] +fn type_set_in_a_composite_font_follows_it() { + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Type")]})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20})).unwrap()["id"].as_u64().unwrap(); + let r = s.execute("text.setStyle", &json!({"ids": [id], "font": "CF Type"})).unwrap(); + assert!(r.get("warning").is_none(), "{r}"); + let t = text(&s, id); + assert_eq!(t.runs[0].style.font_family, "CF Type"); + let db = vectorcraft_text::FontDb::global(); + let face = |family: &str| db.face(family, "Regular").unwrap().id(); + let lay = vectorcraft_text::layout(db, &t); + let fonts: Vec = lay.glyphs.iter().map(|g| g.font_id).collect(); + assert_eq!(fonts, [face("JetBrains Mono"), face("JetBrains Mono"), face("Inter"), face("Inter")]); + let missing = |s: &mut Session| s.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().filter(|f| f["missing"] == true).count(); + assert_eq!(missing(&mut s), 0); + // Roman at full size makes the type wider, measured again in the same step. + let wide = t.cached_bounds.unwrap().width(); + let mut full = font("CF Type"); + full["parts"]["roman"]["size"] = json!(100); + let before = steps(&s); + s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap(); + assert_eq!(steps(&s), before + 1); + assert!(text(&s, id).cached_bounds.unwrap().width() > wide + 1.0); + s.execute("edit.undo", &json!({})).unwrap(); + assert!((text(&s, id).cached_bounds.unwrap().width() - wide).abs() < 1e-6); + assert_eq!(db.composite_font("CF Type").unwrap().parts.roman.size, 50.0); + // Taken out, the type keeps the name, now missing; undone, the font is back. + s.execute("type.compositeFonts.set", &json!({"fonts": []})).unwrap(); + assert!(db.composite_font("CF Type").is_none()); + assert_eq!(text(&s, id).runs[0].style.font_family, "CF Type"); + assert_eq!(missing(&mut s), 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(db.composite_font("CF Type").is_some()); + assert_eq!(missing(&mut s), 0); +} + +/// Type in a symbol's art is measured again too when the composite font it names changes. +#[test] +fn type_in_symbol_art_follows_its_composite_font() { + fn width(s: &Session) -> f64 { + fn find(n: &vectorcraft_doc::Node) -> Option { + if let NodeKind::Text(t) = &n.kind { + return t.cached_bounds.map(|b| b.width()); + } + n.children().into_iter().flatten().find_map(|c| find(c)) + } + s.doc().unwrap().doc.symbols.iter().find_map(|sym| find(&sym.art)).unwrap() + } + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Symbol")]})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Symbol"})).unwrap()["id"].as_u64().unwrap(); + s.execute("symbol.new", &json!({"name": "CF Mark", "ids": [id]})).unwrap(); + let narrow = width(&s); + let mut full = font("CF Symbol"); + full["parts"]["roman"]["size"] = json!(100); + s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap(); + assert!(width(&s) > narrow + 1.0); +} + +/// The font database forgets a composite font once no open document defines it: after the step +/// that added it is undone, and after its document closes. +#[test] +fn composite_fonts_no_document_defines_are_forgotten() { + let db = vectorcraft_text::FontDb::global(); + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Forgotten Undo")]})).unwrap(); + assert!(db.composite_font("CF Forgotten Undo").is_some()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(db.composite_font("CF Forgotten Undo").is_none()); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(db.composite_font("CF Forgotten Undo").is_some()); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Forgotten Close")]})).unwrap(); + s.execute("file.close", &json!({})).unwrap(); + assert!(db.composite_font("CF Forgotten Close").is_none()); + assert!(db.composite_font("CF Forgotten Undo").is_some()); +} + +/// SVG and legacy `.ai` write type in a composite font as its outlines, since a reader can't find +/// the font by its name. +#[test] +fn exports_outline_type_in_a_composite_font() { + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Export")]})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab1", "size": 20, "font": "CF Export"})).unwrap(); + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap(); + assert!(!svg.contains("CF Export") && !svg.contains(">(); + let svg = vectorcraft_svg::export(&doc, &vectorcraft_svg::ExportOptions::default()); + assert!(!svg.contains("CF Standalone") && !svg.contains(" = missing["fonts"].as_array().unwrap().iter().filter_map(|f| f["family"].as_str()).collect(); + assert_eq!(names, ["No Such Part Font"], "{missing}"); + let fonts = s.execute("text.fonts", &json!({})).unwrap(); + let row = fonts.as_array().unwrap().iter().find(|r| r["family"] == "CF Inventory").cloned().unwrap(); + assert_eq!((&row["missing"], &row["status"]), (&json!(true), &json!("missing")), "{row}"); + assert_eq!(row["resolved"]["family"], vectorcraft_text::FALLBACK_FAMILY, "{row}"); + // A run that starts with a combining mark after a run ending in kana: the mark is Roman. + let boundary = json!({"name": "CF Boundary", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "No Such Part Font"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [boundary]})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 170, "text": "\u{304B}\u{301}", "size": 20, "font": "CF Boundary"})).unwrap()["id"] + .as_u64() + .unwrap(); + let row = + |s: &mut Session| s.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().find(|r| r["family"] == "CF Boundary").cloned(); + assert_eq!(row(&mut s).unwrap()["status"], "exact"); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 5, "size": 30})).unwrap(); + assert_eq!(text(&s, id).runs.len(), 2); + assert_eq!(row(&mut s).unwrap()["status"], "missing"); + // A symbol the Kanji part's font draws but the Symbols part's font lacks. + let db = vectorcraft_text::FontDb::global(); + let (mono, sans) = (db.face("JetBrains Mono", "Regular").unwrap(), db.face("Source Sans 3", "Regular").unwrap()); + let c = ('\u{2190}'..='\u{2BFF}').find(|c| mono.covers(*c) && !sans.covers(*c)).expect("a symbol only JetBrains Mono draws"); + let glyphs = json!({"name": "CF Glyphs", "parts": {"kanji": {"font": "JetBrains Mono"}, "symbols": {"font": "Source Sans 3"}}}); + s.execute("type.compositeFonts.set", &json!({"fonts": [glyphs]})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 130, "text": c.to_string(), "size": 20, "font": "CF Glyphs"})).unwrap(); + let fonts = s.execute("text.fonts", &json!({})).unwrap(); + let row = fonts.as_array().unwrap().iter().find(|r| r["family"] == "CF Glyphs").cloned().unwrap(); + assert_eq!(row["missingGlyphs"], 1, "{row}"); +} + +/// The Glyphs panel's alternates of a character in a composite font come from the font of the +/// part its grapheme cluster falls in. +#[test] +fn glyph_alternates_of_composite_type_come_from_the_characters_part() { + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Glyph Part")]})).unwrap(); + let id = + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Glyph Part"})).unwrap()["id"].as_u64().unwrap(); + let r = s.execute("text.glyphAlternates", &json!({"id": id, "start": 2})).unwrap(); + assert_eq!(r["font"], "Inter", "{r}"); + let r = s.execute("text.glyphAlternates", &json!({"id": id, "start": 0})).unwrap(); + assert_eq!(r["font"], "JetBrains Mono", "{r}"); + // A combining mark is drawn in the part of the character it follows. + let id = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "1\u{301}", "size": 20, "font": "CF Glyph Part"})).unwrap()["id"] + .as_u64() + .unwrap(); + let r = s.execute("text.glyphAlternates", &json!({"id": id, "start": 1})).unwrap(); + assert_eq!(r["font"], "Inter", "{r}"); +} + +/// With two documents defining one name differently, the type is drawn in the front document's. +#[test] +fn the_front_document_defines_a_shared_name() { + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Front")]})).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let mut other = font("CF Front"); + other["parts"]["roman"]["size"] = json!(75); + s.execute("type.compositeFonts.set", &json!({"fonts": [other]})).unwrap(); + let db = vectorcraft_text::FontDb::global(); + assert_eq!(db.composite_font("CF Front").unwrap().parts.roman.size, 75.0); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + assert_eq!(db.composite_font("CF Front").unwrap().parts.roman.size, 50.0); +} + +/// A composite font only a document in the back defines is not available in the front one, where +/// type naming it shows as missing; a click on the back document's tab brings it back. +#[test] +fn a_font_only_a_back_document_defines_is_missing_in_front() { + let db = vectorcraft_text::FontDb::global(); + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Back Only")]})).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + assert!(db.composite_font("CF Back Only").is_none()); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab", "size": 20, "font": "CF Back Only"})).unwrap(); + let fonts = s.execute("text.fonts", &json!({})).unwrap(); + assert!(fonts.as_array().unwrap().iter().any(|f| f["missing"] == true), "{fonts}"); + assert!(s.set_active(0)); + assert!(db.composite_font("CF Back Only").is_some()); +} + +/// A newly opened document measures a missing font without using the previous tab's composite +/// font of the same name. +#[test] +fn opened_document_measures_missing_composite_font_as_missing() { + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Previous Tab")]})).unwrap(); + let id = + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab", "size": 20, "font": "CF Previous Tab"})).unwrap()["id"].as_u64().unwrap(); + let mut doc = (*s.doc().unwrap().doc).clone(); + doc.composite_fonts.clear(); + if let NodeKind::Text(t) = &mut doc.node_mut(NodeId(id)).unwrap().kind { + t.cached_bounds = None; + } + s.add_document(doc, None); + assert!(s.set_active(0)); + assert!(s.set_active(1)); + let actual = text(&s, id); + let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds; + assert_eq!(actual.cached_bounds, Some(expected)); +} + +/// The native file of a document whose composite font `name` sets Roman at full size, with type +/// "Ab12" set in it → (the file, the type's id, its width). +fn full_roman_file(name: &str) -> (Vec, u64, f64) { + let mut s = session(); + let mut full = font(name); + full["parts"]["roman"]["size"] = json!(100); + s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": name})).unwrap()["id"].as_u64().unwrap(); + let width = text(&s, id).cached_bounds.unwrap().width(); + (vectorcraft_format::save_file(&s.doc().unwrap().doc), id, width) +} + +/// Type in a missing font that no composite font is named after keeps the bounds it was measured +/// with when its file was read: opening the document does not lay it out again. +#[test] +fn opening_leaves_type_in_an_unrelated_missing_font_as_measured() { + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Unrelated")]})).unwrap(); + let id = + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab", "size": 20, "font": "No Such Family CF"})).unwrap()["id"].as_u64().unwrap(); + let mut doc = (*s.doc().unwrap().doc).clone(); + let kept = vectorcraft_geom::Rect::new(1.0, 2.0, 3.0, 4.0); + if let NodeKind::Text(t) = &mut doc.node_mut(NodeId(id)).unwrap().kind { + t.cached_bounds = Some(kept); + } + s.add_document(doc, None); + assert_eq!(text(&s, id).cached_bounds, Some(kept)); +} + +/// Text holding an inline graphic whose symbol's art is type in a composite font is measured with +/// the graphic at the size the opened document's own definition gives it. +#[test] +fn opening_measures_inline_graphics_of_composite_type_in_its_own_definition() { + let mut s = session(); + let mut full = font("CF Inline"); + full["parts"]["roman"]["size"] = json!(100); + s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap(); + let art = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Inline"})).unwrap()["id"].as_u64().unwrap(); + s.execute("symbol.new", &json!({"name": "CF Inline Mark", "ids": [art]})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "x", "size": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.insertInline", &json!({"id": id, "at": 0, "symbol": "CF Inline Mark"})).unwrap(); + let width = text(&s, id).cached_bounds.unwrap().width(); + let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc); + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Inline")]})).unwrap(); + let file = crate::cmd::fileio::read_for_open("inline.vectorcraft", &bytes, None, &json!({}), false, false).unwrap(); + crate::cmd::fileio::open_read(&mut s, file).unwrap(); + assert!((text(&s, id).cached_bounds.unwrap().width() - width).abs() < 1e-6); +} + +/// Type read for opening while a composite font of its name was registered is measured again when +/// it opens, even after the document that defined the font has closed in between. +#[test] +fn opening_measures_type_read_in_a_composite_font_closed_since() { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Gone"})).unwrap()["id"].as_u64().unwrap(); + let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Gone")]})).unwrap(); + let file = crate::cmd::fileio::read_for_open("gone.vectorcraft", &bytes, None, &json!({}), false, false).unwrap(); + assert!(s.close_document(1)); + crate::cmd::fileio::open_read(&mut s, file).unwrap(); + let actual = text(&s, id); + let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds; + assert_eq!(actual.cached_bounds, Some(expected)); +} + +/// A file read for opening lays out its type in the composite fonts registered then (the front +/// document's, which defines the name with Roman at half size); once the file opens, its type is +/// measured again in its own. +#[test] +fn an_opened_file_measures_its_type_in_its_own_composite_fonts() { + let (bytes, id, width) = full_roman_file("CF Opened"); + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Opened")]})).unwrap(); + let file = crate::cmd::fileio::read_for_open("opened.vectorcraft", &bytes, None, &json!({}), false, false).unwrap(); + crate::cmd::fileio::open_read(&mut s, file).unwrap(); + let actual = text(&s, id); + assert!((actual.cached_bounds.unwrap().width() - width).abs() < 1e-6); + let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds; + assert_eq!(actual.cached_bounds, Some(expected)); +} + +/// A document replaced while in the back (File › Revert) is measured in its own composite fonts +/// when it comes to the front, not in the front document's. +#[test] +fn a_document_replaced_in_the_back_is_measured_in_its_own_composite_fonts() { + let (bytes, id, width) = full_roman_file("CF Replaced"); + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Replaced")]})).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Replaced")]})).unwrap(); + assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap())); + assert!(s.set_active(0)); + let actual = text(&s, id); + assert!((actual.cached_bounds.unwrap().width() - width).abs() < 1e-6); + let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds; + assert_eq!(actual.cached_bounds, Some(expected)); +} + +/// So is one that comes to the front because the front document closes. +#[test] +fn a_document_replaced_in_the_back_is_measured_when_the_front_one_closes() { + let (bytes, id, width) = full_roman_file("CF Closed"); + let mut s = session(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Closed")]})).unwrap(); + assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap())); + assert!(s.close_document(1)); + let actual = text(&s, id); + assert!((actual.cached_bounds.unwrap().width() - width).abs() < 1e-6); + let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds; + assert_eq!(actual.cached_bounds, Some(expected)); +} + +/// A failed batch takes back the composite fonts it set, in the font database too. +#[test] +fn a_failed_batch_takes_back_its_composite_fonts() { + let db = vectorcraft_text::FontDb::global(); + let mut s = session(); + let steps = json!([ + {"command": "type.compositeFonts.set", "params": {"fonts": [font("CF Failed Batch")]}}, + {"command": "no.such.command"}, + ]); + assert!(s.execute("command.batch", &json!({"commands": steps})).is_err()); + assert!(names(&s).is_empty()); + assert!(db.composite_font("CF Failed Batch").is_none()); +} + +/// A composite font whose edit is refused, because it makes selected type too wide for the canvas, +/// is not left in the font database. +#[test] +fn a_refused_edit_takes_back_its_new_composite_font() { + let db = vectorcraft_text::FontDb::global(); + let mut s = session(); + let x = crate::MAX_COORD - 1000.0; + s.execute("text.create", &json!({"x": x, "y": 50, "text": "MMMMMMMM", "size": 100, "font": "CF Refused Edit"})).unwrap(); + let wide = json!({"name": "CF Refused Edit", "parts": {"kanji": {"font": "Source Sans 3", "size": 400}}}); + let e = s.execute("type.compositeFonts.set", &json!({"fonts": [wide]})).unwrap_err().to_string(); + assert!(e.contains("exceed the canvas"), "{e}"); + assert!(names(&s).is_empty()); + assert!(db.composite_font("CF Refused Edit").is_none()); +} + +/// A loaded composite font cannot replace an installed family used by existing type. +#[test] +fn loaded_composite_font_cannot_take_an_installed_family_name() { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab", "size": 20, "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + let mut doc = (*s.doc().unwrap().doc).clone(); + doc.composite_fonts.push(vectorcraft_doc::CompositeFont::new("Inter", "Source Sans 3", "Regular")); + if let NodeKind::Text(t) = &mut doc.node_mut(NodeId(id)).unwrap().kind { + t.cached_bounds = None; + } + s.add_document(doc, None); + assert!(names(&s).is_empty()); + assert!(vectorcraft_text::FontDb::global().composite_font("Inter").is_none()); + let actual = text(&s, id); + let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds; + assert_eq!(actual.cached_bounds, Some(expected)); +} + +/// A file's composite fonts that Composite Fonts… would refuse (a value out of range, a name used +/// twice) are left out when the file opens. +#[test] +fn unusable_composite_fonts_in_a_file_are_left_out() { + let db = vectorcraft_text::FontDb::global(); + let mut s = session(); + let mut doc = (*s.doc().unwrap().doc).clone(); + let mut wild = vectorcraft_doc::CompositeFont::new("CF Wild", "Source Sans 3", "Regular"); + wild.parts.roman.size = 5000.0; + let good = vectorcraft_doc::CompositeFont::new("CF Kept", "Source Sans 3", "Regular"); + let twice = vectorcraft_doc::CompositeFont::new("cf kept", "Inter", "Regular"); + *doc.composite_fonts = vec![wild, good, twice]; + s.add_document(doc, None); + assert_eq!(names(&s), ["CF Kept"]); + s.execute("document.activate", &json!({"index": 1})).unwrap(); + assert!(db.composite_font("CF Wild").is_none()); + assert_eq!(db.composite_font("CF Kept").unwrap().parts.roman.font, "Source Sans 3"); +} + +/// Export writes the document's composite fonts (all, or those named) to a file; Import reads it: +/// with apply false it only returns them, otherwise they join the document's, replacing a font of +/// the same name, as one undo step. +#[test] +fn composite_fonts_export_and_import() { + let dir = folder("io"); + let path = dir.join("Mixed fonts (日本).vccomposite"); + let path = path.to_str().unwrap(); + let mut s = session(); + assert!(s.execute("type.compositeFonts.export", &json!({"path": path})).is_err(), "nothing to export"); + let mut slash = font("CF IO a/b: \"quoted\" 日本"); + slash["parts"]["kana"] = json!({"font": "Inter", "vScale": 80, "scaleAtCenter": true}); + s.execute("type.compositeFonts.set", &json!({"fonts": [slash, font("CF IO Other")]})).unwrap(); + assert!(s.execute("type.compositeFonts.export", &json!({"path": path, "names": ["CF IO Nope"]})).is_err()); + let r = s + .execute("type.compositeFonts.export", &json!({"path": path, "names": ["cf io a/b: \"quoted\" 日本", "CF IO a/b: \"quoted\" 日本"]})) + .unwrap(); + assert_eq!(r["count"], 1); + let saved = s.doc().unwrap().doc.composite_fonts[0].clone(); + + let mut t = session(); + let mut mine = font("CF IO a/b: \"quoted\" 日本"); + mine["parts"]["roman"]["size"] = json!(90); + t.execute("type.compositeFonts.set", &json!({"fonts": [mine, font("CF IO Kept")]})).unwrap(); + let before = steps(&t); + let read = t.execute("type.compositeFonts.import", &json!({"path": path, "apply": false})).unwrap(); + assert_eq!(read["fonts"].as_array().map(Vec::len), Some(1)); + assert_eq!(steps(&t), before); + t.execute("type.compositeFonts.import", &json!({"path": path})).unwrap(); + assert_eq!(steps(&t), before + 1); + assert_eq!(names(&t), ["CF IO a/b: \"quoted\" 日本", "CF IO Kept"]); + assert_eq!(t.doc().unwrap().doc.composite_fonts[0], saved); + // The same file again changes nothing. + t.execute("type.compositeFonts.import", &json!({"path": path})).unwrap(); + assert_eq!(steps(&t), before + 1); + + // Files that aren't composite fonts, or are too large, are refused. + for (file, bytes) in [ + ("bad.vccomposite", b"not json".to_vec()), + ("empty.vccomposite", br#"{"compositeFonts": []}"#.to_vec()), + ("twice.vccomposite", format!(r#"{{"compositeFonts": [{}, {}]}}"#, font("CF Dup"), font("cf dup")).into_bytes()), + ("large.vccomposite", vec![b' '; (4 << 20) + 1]), + ] { + let p = dir.join(file); + std::fs::write(&p, bytes).unwrap(); + assert!(t.execute("type.compositeFonts.import", &json!({"path": p.to_str().unwrap()})).is_err(), "{file}"); + assert_eq!(steps(&t), before + 1); + } + assert!(t.execute("type.compositeFonts.import", &json!({"path": path, "apply": "no"})).is_err()); + assert!(t.execute("type.compositeFonts.import", &json!({"path": ""})).is_err()); + assert!(t.execute("type.compositeFonts.import", &json!({"path": path, "data": "{}"})).is_err()); + assert!(t.execute("type.compositeFonts.import", &json!({"dataBase64": "%%%"})).is_err()); + + // Without a path, Export gives the file's text, which Import takes as data. + let data = s.execute("type.compositeFonts.export", &json!({"names": ["CF IO Other"]})).unwrap(); + assert_eq!(data["count"], 1); + let mut u = session(); + let r = u.execute("type.compositeFonts.import", &json!({"data": data["data"]})).unwrap(); + assert_eq!(r["imported"], json!(["CF IO Other"])); + assert_eq!(names(&u), ["CF IO Other"]); + // Fonts given are written in place of the document's; bad ones are refused. + let given = s.execute("type.compositeFonts.export", &json!({"fonts": [font("CF IO Given")]})).unwrap(); + assert!(given["data"].as_str().unwrap().contains("CF IO Given")); + assert!(s.execute("type.compositeFonts.export", &json!({"fonts": [font("")]})).is_err()); + assert!(s.execute("type.compositeFonts.export", &json!({"fonts": []})).is_err()); + assert!(s.execute("type.compositeFonts.export", &json!({"path": " "})).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/cmd/compoundshape.rs b/crates/engine/src/cmd/compoundshape.rs new file mode 100644 index 0000000000..52c19a9a52 --- /dev/null +++ b/crates/engine/src/cmd/compoundshape.rs @@ -0,0 +1,288 @@ +//! Pathfinder panel › compound shapes (`object.compoundShape.*`): Make Compound Shape (what +//! Alt-clicking a Shape Mode button does), a member's shape mode, Release and Expand Compound +//! Shape. A compound shape is a group marked so ([`Node::is_compound_shape`]) whose members each +//! have a [`ShapeMode`]; `vectorcraft-effects` draws it as the area they make +//! ([`effects::compound_shape_area`]). + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ShapeMode}; +use vectorcraft_render::effects; + +use super::edit::{roots_of, selected_roots}; +use super::pathops::{Style, pf_leaves, shape_node, style_of}; +use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_multi}; + +const MODE_NAMES: [&str; 4] = ["add", "subtract", "intersect", "exclude"]; + +pub fn specs() -> Vec { + vec![ + cmd!( + "object.compoundShape.make", + "Make Compound Shape", + ["Window", "Pathfinder"], + None, + "{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id}", + has_multi, + make + ), + cmd!( + "object.compoundShape.setMode", + "Shape Mode", + ["Window", "Pathfinder"], + None, + "{mode: \"add\"|\"subtract\"|\"intersect\"|\"exclude\", ids?: [id…] (selected first; default: the selection)} the members of compound shapes that the selected objects are or are in take the shape mode (what clicking a Shape Mode button does with members selected); the backmost member's mode doesn't change the shape → {ids}", + has_member, + set_mode + ), + cmd!( + "object.compoundShape.release", + "Release Compound Shape", + ["Window", "Pathfinder"], + None, + "{ids?: [id…] (selected first; default: the selection)} the selected compound shapes (and those holding the selected objects) become their members again, as they were before Make Compound Shape, selected → {ids}", + has_compound_shape, + release + ), + cmd!( + "object.compoundShape.expand", + "Expand Compound Shape", + ["Window", "Pathfinder"], + None, + "{ids?: [id…] (selected first; default: the selection)} the selected compound shapes (and those holding the selected objects) become the path, or compound path, of the area they draw, painted as they are, selected → {ids}", + has_compound_shape, + expand + ), + ] +} + +/// The innermost compound shape holding `id` (not `id` itself), with the member of it that `id` is +/// or is in. +fn holder(d: &Document, id: NodeId) -> Option<(NodeId, NodeId)> { + let up = d.ancestry(id)?; + up.windows(2).rev().find_map(|w| match w { + [shape, member] if d.node(*shape).is_some_and(Node::is_compound_shape) => Some((*shape, *member)), + _ => None, + }) +} + +/// The compound shape `id` is or is in (the innermost). +fn shape_of(d: &Document, id: NodeId) -> Option { + if d.node(id)?.is_compound_shape() { Some(id) } else { holder(d, id).map(|(shape, _)| shape) } +} + +/// The compound shapes the selection is or is in, outermost only, in paint order. +fn selected_shapes(s: &Session) -> Result> { + let st = s.doc()?; + let mut shapes: Vec = vec![]; + for id in st.selection.in_paint_order(&st.doc) { + if let Some(shape) = shape_of(&st.doc, id).filter(|shape| !shapes.contains(shape)) { + shapes.push(shape); + } + } + Ok(roots_of(&st.doc, shapes)) +} + +/// The members of compound shapes that the selected objects are or are in. +fn selected_members(s: &Session) -> Result> { + let st = s.doc()?; + let mut members: Vec = vec![]; + for id in &st.selection.objects { + if let Some((_, member)) = holder(&st.doc, *id).filter(|(_, m)| !members.contains(m)) { + members.push(member); + } + } + Ok(members) +} + +/// The shape modes of the compound-shape members the selection is or is in (none when it is in +/// none): the Pathfinder panel lights the Shape Mode button they share. +pub fn selected_member_modes(s: &Session) -> Vec { + let Some(st) = s.active() else { return vec![] }; + let members = selected_members(s).unwrap_or_default(); + members.iter().filter_map(|id| st.doc.node(*id)).map(|n| n.extras().shape_mode).collect() +} + +/// The selection is or is in a compound shape. +fn has_compound_shape(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + if st.selection.objects.iter().any(|id| shape_of(&st.doc, *id).is_some()) { Ok(()) } else { Err("select a compound shape".into()) } +} + +/// The selection is or is in a member of a compound shape. +fn has_member(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + if st.selection.objects.iter().any(|id| holder(&st.doc, *id).is_some()) { Ok(()) } else { Err("select members of a compound shape".into()) } +} + +/// The `mode` param: one of [`MODE_NAMES`], or `default` when it is missing (`None`: required). +fn mode_param(p: &Value, cmd: &str, default: Option) -> Result { + match super::object::choice(p, cmd, "mode", &MODE_NAMES)? { + Some(name) => ShapeMode::parse(name), + None => default, + } + .ok_or_else(|| bad(cmd, format!("`mode` must be one of {}", MODE_NAMES.join(", ")))) +} + +fn ids_json(ids: &[NodeId]) -> Value { + json!({ "ids": ids.iter().map(|i| i.0).collect::>() }) +} + +fn make(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.compoundShape.make"; + let mode = mode_param(p, C, Some(ShapeMode::Add))?; + let roots = selected_roots(s)?; + if roots.len() < 2 { + return Err(bad(C, "select at least two objects")); + } + let d = &s.doc()?.doc; + let mut members = Vec::with_capacity(roots.len()); + for id in &roots { + let n = d.node(*id).ok_or(EngineError::NoNode(*id))?; + if !matches!( + n.kind, + NodeKind::Path { guide: false, .. } + | NodeKind::Compound { .. } + | NodeKind::Group { .. } + | NodeKind::Text(_) + | NodeKind::Blend { .. } + | NodeKind::Envelope { .. } + ) { + return Err(bad(C, "compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes")); + } + members.push(n); + } + // The paint and transparency of the topmost member in Add, Intersect or Exclude mode: as they + // all have `mode`, the topmost, or the backmost when they all subtract. + let order: Vec<&Node> = if mode == ShapeMode::Subtract { members } else { members.into_iter().rev().collect() }; + let hook = |c: &Node| effects::outline_object(Some(d), c); + let style = order.into_iter().find_map(|n| top_style(d, n, &hook)); + let id = s.edit("Make Compound Shape", |d, sel| { + let gid = d.alloc_id(); + let id = d.wrap(&roots, |children| { + let children = children + .into_iter() + .map(|c| { + let mut c = Arc::unwrap_or_clone(c); + c.extras_mut().shape_mode = mode; + Arc::new(c) + }) + .collect(); + let mut g = Node::group(gid, children); + g.extras_mut().compound_shape = true; + if let Some(style) = &style { + style.apply(&mut g); + } + g + })?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + +/// The paint and transparency of the frontmost shape `n` adds to a compound shape's area, from the +/// same objects the area takes: a blend, an envelope or an object with a warp gives those of the +/// art it draws, without its geometry effects; a symbol instance those of its symbol's art (with +/// `hook`); type its first style; a compound shape its own; a group those of its frontmost member +/// that has a shape. A shape taken from inside a group, or from the art of a blend, an envelope or +/// a warped group, also takes that object's opacity and blend mode. +fn top_style(d: &Document, n: &Node, hook: effects::OutlineHook) -> Option
, , and ; a trailing .ext is dropped, as in `COMPANY-Logo--####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)", + "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with 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, ,
, , and ; a trailing .ext is dropped, as in `COMPANY-Logo--####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)", has_doc, screens::export_for_screens ), @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Save Export Preset", [], None, - "{name, settings: {formats, settings, preset, name, prefix, counterStart, counterPer, folders, subfolders, includeBleed, antiAlias, folder, fullDocument} (as document.exportForScreens; other keys are left out)} save (or replace) a batch export preset, kept with the preferences; built-in names are refused → {name, created, settings}", + "{name, settings: {formats, settings, preset, name, prefix, counterStart, counterPer, folders, subfolders, includeBleed, includeArtboardFill, antiAlias, folder, fullDocument} (as document.exportForScreens; other keys are left out)} save (or replace) a batch export preset, kept with the preferences; built-in names are refused → {name, created, settings}", always, screens::presets_save ), @@ -85,12 +85,30 @@ pub fn specs() -> Vec { always, screens::presets_delete ), + cmd!( + query "document.exportPresets.import", + "Import Export Presets", + [], + None, + "{path? | data?: file text | dataBase64?, replace?: false (replace saved presets of the same names; else the imported ones get a number)} add the presets of a .vcexportpresets file (as document.exportPresets.export writes) to the saved ones; a built-in name gets a number; a taken name that ends in a number gets the next free one (Web 2 comes in as Web 3); settings that document.exportPresets.save refuses, more than 1000 presets, or a file larger than 4194304 bytes fail the whole file → {imported: [names]}", + always, + screens::presets_import + ), + cmd!( + query "document.exportPresets.export", + "Export Export Presets", + [], + None, + "{names?: [preset names, built-in ones too] (default: every saved preset), path?} write the presets as a .vcexportpresets file (JSON); more than 1000 presets or a file larger than 4194304 bytes is an error → {path, count}; without path → {data: the file's text, count}", + always, + screens::presets_export + ), cmd!( query "command.batch", "Batch", [], None, - "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing or select.allOnArtboard step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", + "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", has_doc, batch::batch ), @@ -99,7 +117,7 @@ pub fn specs() -> Vec { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document (source: datasets; File + Data Set Name for the folder destination and Override Save/Export, with `/`, `\\`, `:`, `<`, `>`, `\"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and `-2`, `-3`… added to a name already used). Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", always, action_batch::action_batch ), diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index a569f1b4c8..b63447e228 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use serde::Deserialize; use serde_json::{Value, json}; -use vectorcraft_cad::{ColorDepth, DxfOptions, DxfVersion, Preserve, RasterFormat}; +use vectorcraft_cad::{ColorDepth, DxfOptions, DxfPreset, DxfVersion, Preserve, RasterFormat}; use vectorcraft_doc::{Document, Unit}; use vectorcraft_geom::Rect; @@ -21,18 +21,24 @@ pub fn specs() -> Vec { "Export DXF", [], None, - "{path?, version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (every stroke as its filled outline), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}", + "{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused", has_doc, export_dxf )] } /// The DXF options `document.formats` lists. -pub(super) const OPTIONS: &[FormatOption] = &[ +pub(crate) const OPTIONS: &[FormatOption] = &[ super::ARTBOARD, super::ARTBOARDS, super::RANGE, super::USE_ARTBOARDS, + FormatOption { + name: "dxfPreset", + ty: "string", + default: "\"custom\"", + description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, PNG images); the options given override it", + }, FormatOption { name: "version", ty: "string", default: "\"2018\"", description: "R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018" }, FormatOption { name: "unit", @@ -64,7 +70,7 @@ pub(super) const OPTIONS: &[FormatOption] = &[ name: "alterPaths", ty: "boolean", default: "false", - description: "Alter Paths for Appearance: every stroke as its filled outline", + description: "Alter Paths for Appearance: strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14", }, FormatOption { name: "outlineText", ty: "boolean", default: "false", description: "type as glyph outlines (always with preserve: appearance)" }, FormatOption { name: "selectedOnly", ty: "boolean", default: "false", description: "only the selected objects, in their layers" }, @@ -120,6 +126,7 @@ impl Unsupported { struct Params { #[serde(flatten)] boards: ArtboardPick, + dxf_preset: Option, version: Option, unit: Option, scale: Option, @@ -150,7 +157,8 @@ fn choice(field: &str, v: Option, read: impl Fn(&str) -> Option, d /// The DXF options in `p` (the region and crop are set per drawing) and the artboard choice. fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> { let q: Params = if p.is_object() { Params::deserialize(p).map_err(|e| bad(C, format!("DXF options: {e}")))? } else { Params::default() }; - let d = DxfOptions::default(); + // The options a preset sets are the defaults of those `p` leaves out. + let d = choice("dxfPreset", q.dxf_preset, DxfPreset::from_id, DxfPreset::Custom, "custom or cnc")?.options(); let scale = q.scale.unwrap_or(d.scale); if !(scale.is_finite() && vectorcraft_cad::SCALE_RANGE.contains(&scale)) { return Err(bad(C, format!("DXF scale must be a positive number up to {}, not {scale}", vectorcraft_cad::SCALE_RANGE.end()))); @@ -181,6 +189,11 @@ pub fn check(p: &Value) -> std::result::Result<(), String> { parse(p).map(|_| ()).map_err(|e| e.to_string()) } +/// The DXF options in `p` (the region and crop left at their defaults). +pub fn options(p: &Value) -> std::result::Result { + parse(p).map(|(o, _)| o).map_err(|e| e.to_string()) +} + /// Encode `doc` as DXF: one drawing whose origin is the chosen artboard's bottom-left corner /// (default the first), or with `use_artboards` one drawing per chosen artboard (default all) /// holding the art over it. diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 1202bde7f8..1108d3e2ca 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -202,13 +202,14 @@ impl RasterOptions { } } - /// The render and encoder settings: `ppi`, else 72 × `scale`, within 0.01–64 pixels per point; + /// The render and encoder settings: `ppi`, else 72 × `scale`, else the document's resolution, + /// within 0.01–64 pixels per point; /// `background`, else `page` (the document's background). - fn settings(&self, page: Option<[u8; 3]>) -> Result { + fn settings(&self, page: Option<[u8; 3]>, document_ppi: f64) -> Result { if let Some(ppi) = self.ppi.filter(|p| !(p.is_finite() && *p > 0.0)) { return Err(bad(C, format!("ppi must be a positive number, not {ppi}"))); } - let ppi = self.ppi.unwrap_or(72.0 * self.scale.unwrap_or(1.0)); + let ppi = self.ppi.unwrap_or_else(|| self.scale.map_or(document_ppi, |scale| 72.0 * scale)); let color_model = parse(self.color_model.as_deref(), jpeg::ColorModel::from_id, "colorModel", "rgb, cmyk or gray")?; let embed_icc = self.embed_icc.unwrap_or(true); Ok(RasterExportOptions { @@ -420,7 +421,10 @@ pub fn encode(doc: &Document, format: &str, p: &Value) -> Result> { /// font; PDF, EPS, SVG, EMF, WMF and the raster formats: type that doesn't fit its frame). pub fn encode_with_warnings(doc: &Document, format: &str, p: &Value) -> Result<(Vec, Vec)> { let f = super::writable(C, Some(format), None)?; - encode_all(doc, f.id, p)?.single(f) + let enc = encode_all(doc, f.id, p)?; + // The error for a version 7 .ai of several artboards names the legacy .ai. + let legacy = f.id == "ai" && super::legacy_ai::wanted(C, f, p)?; + enc.single(&if legacy { super::legacy_ai::named(f) } else { *f }) } /// [`encode`], with every file the export writes. @@ -541,7 +545,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { // New Document → Background Contents: White makes the export opaque, unless `background` // says otherwise (JPEG has no alpha: white either way). let page = (doc.setup.background == vectorcraft_doc::Background::White).then_some([255; 3]); - let mut settings = o.settings(page)?; + let mut settings = o.settings(page, doc.raster_ppi())?; let size = o.pixel_size()?; let format = match f.id { "png" => RasterFormat::Png, @@ -565,6 +569,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { (RasterFormat::Jpeg, Some(m)) => MapKind::from_id(m).ok_or_else(|| bad(C, format!("imageMap `{m}`: none, client or server")))?, _ => MapKind::None, }; + // The artboards' background colors, behind the art (a transparent background too). + let filled = super::export::with_artboard_fills(doc, p, chosen.iter().copied()).map_err(|e| bad(C, e))?; + let doc = &*filled; let mut enc = Encoded::default(); let mut renderer = vectorcraft_render::Renderer::new(); let total = chosen.len() as u64; diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index a05cc08248..ac33326994 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -12,7 +12,7 @@ use vectorcraft_doc::Document; use vectorcraft_eps::{EpsOptions, Level, Overprint, Preview, Raster}; use vectorcraft_geom::{Point, Rect}; -use super::super::flatten::{FlattenOptions, flatten_document}; +use super::super::flatten::{FlattenOptions, expand_transparent_tile_images, flatten_expanded}; use super::super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, str_param}; use super::{ArtboardPick, Encoded, FormatOption}; @@ -32,14 +32,14 @@ pub fn specs() -> Vec { "Export EPS", [], None, - "{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard; with two or more, also the central file {stem}.eps first: the whole document, the bounding box the visible art; none when no art shows) | false (one file, the bounding box the visible art, y up from the first artboard's bottom-left corner, even when artboards are named; the default when none are named), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (the artboards written; naming them without useArtboards works as useArtboards: true)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}", + "{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard; with two or more, also the central file {stem}.eps first: the whole document, the bounding box the visible art; none when no art shows) | false (one file, the bounding box the visible art, y up from the first artboard's bottom-left corner, even when artboards are named; the default when none are named), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (the artboards written; naming them without useArtboards works as useArtboards: true)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}. A key EPS doesn't take, and an unknown key inside flattener, are refused", has_doc, export_eps )] } /// The EPS options `document.formats` lists. -pub(super) const OPTIONS: &[FormatOption] = &[ +pub(crate) const OPTIONS: &[FormatOption] = &[ super::ARTBOARD, super::ARTBOARDS, super::RANGE, @@ -152,6 +152,8 @@ fn parse(p: &Value) -> Result { let overprint = choice("overprints", q.overprints.clone(), Overprint::from_id, d.overprint, "preserve or discard")?; let mut flatten = flattener(&q, &[])?; flatten.preserve_overprints &= overprint == Overprint::Preserve; + // The writer draws colorized images in their ink. + flatten.keeps_colorize = true; let level = q.level.as_ref().map(super::dxf::text); let eps = EpsOptions { level: choice("level", level, Level::from_id, d.level, "2 or 3")?, @@ -298,12 +300,17 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result { if pages.is_empty() { return Err(bad(C, "the document has no artboard")); } + // The artboards' background colors, behind the art (the editing data keeps them as colors). + let filled = super::export::with_artboard_fills(doc, p, pages.iter().filter_map(|(b, ..)| *b)).map_err(|e| bad(C, e))?; + let doc = &*filled; let regions: Vec = pages.iter().map(|(_, region, _)| *region).collect(); - let transparent = doc.layers.iter().any(|l| l.shows_transparency()); - let flat = flatten_document(doc, &set.flatten)?; - let drawn = flat.as_ref().unwrap_or(doc); + let expanded = expand_transparent_tile_images(doc, &set.flatten)?; + let source = expanded.as_ref().unwrap_or(doc); + let transparent = source.layers.iter().any(|l| set.flatten.shows_transparency(source, l)); + let flat = flatten_expanded(source, &set.flatten)?; + let drawn = flat.as_ref().unwrap_or(source); let mut enc = Encoded { warnings, joiner: Some("_"), ..Encoded::default() }; - if transparent && flat.is_some() { + if transparent && (flat.is_some() || expanded.is_some()) { enc.warnings.push("transparency is flattened into opaque art and images (EPS has none): see the flattener preset".into()); } let preview_limit = if saving { SAVE_PREVIEW } else { MAX_PREVIEW }; diff --git a/crates/engine/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index 2a3ff0e78b..0869ad850a 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -72,6 +72,17 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result { write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.warnings })) } +/// The document an export of `st` in format `f` writes ([`export_source`]): a `.ai` or `.ait` +/// file names the view's active artboard ([`DocState::active_artboard`]) as its active one, as a +/// save does. The open document is unchanged. +pub fn export_doc<'a>(st: &'a DocState, f: &Format, p: &Value) -> Result> { + let mut doc = export_source(st, p)?; + if let Some(id) = super::save::moved_active_artboard(st, &doc, f) { + doc.to_mut().opened_artboard = Some(id); + } + Ok(doc) +} + /// The document an export of `st` writes: the whole document, or with `selectedOnly` just the /// selected objects, each in its layers and groups (a clipping group keeps its clipping path). pub fn export_source<'a>(st: &'a DocState, p: &Value) -> Result> { @@ -146,6 +157,21 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document d } +/// `doc` with the background colors of `artboards` drawn behind its art +/// ([`Document::with_artboard_fills`]), what exports and print draw, unless `p` turns +/// `includeArtboardFill` off (Export for Screens › Include Artboard Fill; on by default). +pub(crate) fn with_artboard_fills<'a>( + doc: &'a Document, + p: &Value, + artboards: impl IntoIterator, +) -> std::result::Result, String> { + let include = match p.get("includeArtboardFill") { + None | Some(Value::Null) => true, + Some(v) => v.as_bool().ok_or("`includeArtboardFill` must be true or false")?, + }; + Ok(include.then(|| doc.with_artboard_fills(artboards)).flatten().map_or(Cow::Borrowed(doc), Cow::Owned)) +} + /// `p` without its artboard choice, also inside its SVG options (for documents made of one /// synthetic artboard, and for callers that pick the artboard themselves). pub(super) fn without_artboards(p: &Value) -> Value { @@ -175,7 +201,7 @@ fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(C return Ok((Cow::Owned(doc), display_doc_title)); } let st = s.doc()?; - let doc = export_source(st, p)?; + let doc = export_doc(st, f, p)?; let display_doc_title = super::has_own_title(&doc); Ok((super::titled_for_export(&doc, st.path.as_deref(), f.id).map_or(doc, Cow::Owned), display_doc_title)) } @@ -188,10 +214,11 @@ fn selection(s: &mut Session, cmd: &str) -> Result<(Document, vectorcraft_geom:: } /// The selected objects (their top-most selected ancestors) that are artwork: those on template -/// layers are guides and are left out. +/// layers are guides and are left out. With an object of a dynamic symbol instance's art selected, +/// the instance is exported whole. pub(crate) fn selected_artwork(s: &Session) -> Result> { - let ids = edit::selected_roots(s)?; let st = s.doc()?; + let ids = edit::roots_of(&st.doc, st.selection.in_paint_order(&st.doc)); let is_template = |id| st.doc.node(id).is_some_and(|l| matches!(l.kind, NodeKind::Layer { template: true, .. })); // On a template layer or sublayer, at any depth. let on_template = |id| st.doc.ancestry(id).is_some_and(|a| a.into_iter().any(is_template)); diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 66bd6d3954..5f2c14bfd5 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -5,21 +5,54 @@ use super::{Encoded, EngineError, Result, Session, Value, json}; /// `-`, `Artboard-N` when unnamed, and `-2`, `-3`… after a name already used (compared without /// case: `Icon` and `icon` are one file on most desktop file systems). pub fn artboard_file_names(doc: &vectorcraft_doc::Document, boards: &[usize]) -> Vec { - unique_file_names(boards.iter().map(|&b| (doc.artboards.get(b).map_or("", |a| a.name.as_str()), format!("Artboard-{}", b + 1)))) + unique_file_names(artboard_names(doc, boards)) +} + +/// [`artboard_file_names`] with the dots of a name kept (`example.artboard`), for Export for Screens, +/// which puts every stem through `safe_file_name` after this (trailing periods, device names). +pub(crate) fn artboard_file_names_keeping_dots(doc: &vectorcraft_doc::Document, boards: &[usize]) -> Vec { + unique_file_names_keeping_dots(artboard_names(doc, boards)) +} + +/// Each of `boards`' name, with the file name to use when it has none. +fn artboard_names<'a>(doc: &'a vectorcraft_doc::Document, boards: &'a [usize]) -> impl Iterator { + boards.iter().map(|&b| (doc.artboards.get(b).map_or("", |a| a.name.as_str()), format!("Artboard-{}", b + 1))) } /// File-name parts for `(name, fallback)` pairs (artboards, assets): the name with unsafe /// characters as `-`, the fallback when it is empty, and `-2`, `-3`… after a name already used /// (compared without case). -pub(crate) fn unique_file_names<'a>(names: impl IntoIterator) -> Vec { +fn unique_file_names<'a>(names: impl IntoIterator) -> Vec { distinct_names(names.into_iter().map(|(name, fallback)| { let base: String = name.chars().map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '-' }).collect(); if base.is_empty() { fallback } else { base } })) } +/// [`unique_file_names`] keeping `.` in a name (an artboard called `example.artboard` exports as +/// `example.artboard.png`, #6143). A name of only dots (`.` and `..` name other folders) takes the +/// fallback, and leading dots are dashes (`.draft` would be a hidden file); the caller still runs +/// each stem through `safe_file_name`, which drops trailing periods and guards Windows device names. +pub(crate) fn unique_file_names_keeping_dots<'a>(names: impl IntoIterator) -> Vec { + distinct_names(names.into_iter().map(|(name, fallback)| { + let base: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | '.') { c } else { '-' }).collect(); + if base.trim_matches('.').is_empty() { + return fallback; + } + // A leading dot would hide the file or folder on Unix-like systems: it is a dash, as before. + let rest = base.trim_start_matches('.'); + format!("{}{rest}", "-".repeat(base.len() - rest.len())) + })) +} + /// `names` with `-2`, `-3`… after a name already used (compared without case). pub(super) fn distinct_names(names: impl IntoIterator) -> Vec { + distinct_names_by(names, str::to_lowercase) +} + +/// `names` with `-2`, `-3`… after a name already used, two names matching when `key` gives the same +/// key for them. +pub(super) fn distinct_names_by(names: impl IntoIterator, key: impl Fn(&str) -> String) -> Vec { let mut taken = std::collections::HashSet::new(); // The next number to try for each base: a name repeated many times doesn't search the numbers // taken before it. @@ -28,8 +61,8 @@ pub(super) fn distinct_names(names: impl IntoIterator) -> Vec &'static [&'static str] { + READ_ALIASES.iter().find(|(id, _)| *id == f.id).map_or(f.extensions, |(_, exts)| *exts) +} + +/// The readable format of extension `ext` (any case, leading dot allowed): [`format`]'s when it +/// reads, else the one [`READ_ALIASES`] gives it (`.dib` is BMP). +pub fn readable_format(ext: &str) -> Option<&'static Format> { + let k = ext.trim_start_matches('.').to_ascii_lowercase(); + format(&k).filter(|f| f.read).or_else(|| READ_ALIASES.iter().find(|(_, exts)| exts.contains(&k.as_str())).and_then(|(id, _)| format(id))) +} + +/// The readable format a file name's extension names ([`readable_format`]). +pub fn readable_format_for_name(name: &str) -> Option<&'static Format> { + Some(extension(name)).filter(|e| !e.is_empty()).and_then(|e| readable_format(&e)) +} + /// One dialog filter per readable format. fn format_filters() -> impl Iterator { - FORMATS.iter().filter(|f| f.read).map(|f| (f.label, f.extensions)) + FORMATS.iter().filter(|f| f.read).map(|f| (f.label, read_extensions(f))) } /// Open-dialog filters: "All readable files" first, then one per readable format, then swatch -/// libraries (which open in the library panel), Libraries panel libraries, flattener, PDF and print -/// presets (imported), scripts (checked without running them) and plug-ins (installed). +/// libraries (which open in the library panel), Libraries panel libraries, flattener, PDF, print +/// and export presets (imported), scripts (checked without running them) and plug-ins (installed). pub fn open_filters() -> impl Iterator { std::iter::once(("All readable files", OPEN_EXTS)) .chain(format_filters()) @@ -610,6 +687,7 @@ pub fn open_filters() -> impl Iterator impl Iterator { std::iter::once(("All placeable files", PLACE_EXTS)) .chain(format_filters().filter(|(_, exts)| exts.iter().all(|ext| PLACE_EXTS.contains(ext)))) .chain(std::iter::once(("Text", TEXT_EXTS))) .chain(std::iter::once(("RTF", RTF_EXTS))) - .chain(std::iter::once(("Word", DOCX_EXTS))) + .chain(std::iter::once(("Word", WORD_EXTS))) } /// A format by id or extension (any case, leading dot allowed; `jpeg` finds `jpg`): a built-in @@ -689,6 +767,25 @@ pub fn file_stem(name: &str) -> String { std::path::Path::new(name).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| name.to_string()) } +/// The name an imported preset `base` takes: `base` if `taken` doesn't claim it, else for a name +/// that ends in a space and a number ("Logo Package 2") the first free name with a higher number +/// ("Logo Package 3"), and for any other name the first free "base 2", "base 3"… ([`unique_name`]). +pub(crate) fn import_name(base: &str, taken: impl Fn(&str) -> bool) -> String { + if !taken(base) { + return base.to_string(); + } + let numbered = base + .rsplit_once(' ') + .filter(|(stem, n)| !stem.trim().is_empty() && !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) + .and_then(|(stem, n)| Some((stem, n.parse::().ok()?))); + match numbered { + Some((stem, n)) => { + (n.saturating_add(1)..=u64::MAX).map(|i| format!("{stem} {i}")).find(|c| !taken(c)).unwrap_or_else(|| unique_name(base, &taken)) + } + None => unique_name(base, taken), + } +} + /// What a `format` export of `doc`, whose file is `path`, writes when it isn't `doc` itself: a /// document that only has the Untitled-N name New gave it is titled after its file, as its tab is /// (the title PDF, PNG and SVG metadata carry). A title of its own stays, and native files keep diff --git a/crates/engine/src/cmd/fileio/heifread.rs b/crates/engine/src/cmd/fileio/heifread.rs new file mode 100644 index 0000000000..4867022ded --- /dev/null +++ b/crates/engine/src/cmd/fileio/heifread.rs @@ -0,0 +1,627 @@ +//! HEIC and HEIF images for File › Open and File › Place, decoded with heic-rs when the engine's +//! `heif` feature is on (the default). The image is bounded before decoding and converted to RGBA +//! for the common PNG storage path. A build without the feature still recognizes the files and +//! refuses them with a message. + +#[cfg(all(test, feature = "heif"))] +pub(super) use decoder::{active_sps, picture_bytes, sps_signal, sps_size}; +#[cfg(feature = "heif")] +pub(super) use decoder::{decode, quarter_turned, with_exif}; + +/// The brands heic-rs 0.1.4 reads: HEVC-coded images and image sequences (ISO/IEC 23008-12 annex +/// B) and the general image and sequence brands. +const BRANDS: [&[u8; 4]; 7] = [b"heic", b"heix", b"heim", b"heis", b"hevc", b"mif1", b"msf1"]; + +/// Recognize a HEIF file by its `ftyp` box: one of [`BRANDS`] as the major brand or a compatible +/// one, and no AVIF brand (`avif`, `avis`), as heic-rs refuses a file that lists one. The box is +/// read as JP2 boxes are ([`super::jp2read::boxes`]): ISO BMFF sizes, the 64-bit one included. +pub(super) fn is_heif(bytes: &[u8]) -> bool { + let Some((b"ftyp", ftyp)) = super::jp2read::boxes(bytes).next() else { return false }; + let Some(major) = ftyp.get(..4).and_then(|b| <&[u8; 4]>::try_from(b).ok()) else { return false }; + if ftyp.len() < 8 { + return false; + } + let compatible = ftyp.get(8..).unwrap_or_default().as_chunks::<4>().0; + let brands = || std::iter::once(major).chain(compatible); + !brands().any(|brand| matches!(brand, b"avif" | b"avis")) && brands().any(|brand| BRANDS.contains(&brand)) +} + +/// Without the `heif` feature every HEIF file is refused. +#[cfg(not(feature = "heif"))] +pub(super) fn decode(_bytes: &[u8], _max_alloc: u64) -> Result { + Err("HEIC and HEIF images can't be opened in this build".into()) +} + +/// Without the `heif` feature no image is decoded, so none is turned. +#[cfg(not(feature = "heif"))] +pub(super) fn quarter_turned(_bytes: &[u8]) -> bool { + false +} + +/// Without the `heif` feature no resolution is read. +#[cfg(not(feature = "heif"))] +pub(super) fn with_exif(_bytes: &[u8], _read: impl FnOnce(&[u8]) -> Option) -> Option { + None +} + +#[cfg(feature = "heif")] +mod decoder { + use heic_rs::context::Context; + use heic_rs::{DecodeOptions, Error, MatrixCoefficients, Nclx, PixelLayout, Range}; + + /// The message for a file that isn't a readable HEIF image. + const UNREADABLE: &str = "the HEIC or HEIF file can't be read"; + /// The message for an image sequence, an overlay, an image that isn't HEVC-coded, a grid whose + /// tiles are cropped, turned or mirrored, or an HEVC coding tool the decoder doesn't implement. + const UNSUPPORTED: &str = "the HEIC or HEIF file holds a kind of image that can't be read"; + + /// Decode the primary image within `max_alloc` bytes, counting the decoder's planes, the RGBA + /// output and the copy that rotating or cropping makes, with the container's rotation, mirror + /// and crop applied. An embedded RGB ICC profile, or `nclx` Display P3 primaries with the sRGB + /// curve, is converted to sRGB; other `nclx` values are read as sRGB. A panic inside the + /// decoder is reported as an unreadable file. + pub(in super::super) fn decode(bytes: &[u8], max_alloc: u64) -> Result { + crate::guard::catch_panic(|| decode_unguarded(bytes, max_alloc)).unwrap_or_else(|_| Err(UNREADABLE.into())) + } + + /// Whether the container's rotations of the primary image add up to an odd number of quarter + /// turns, so its width and height swap. The decoder applies every `irot` the item lists. + pub(in super::super) fn quarter_turned(bytes: &[u8]) -> bool { + let turned = || { + let ctx = Context::open(bytes).ok()?; + let props = ctx.props(ctx.meta.primary).ok()?; + let quarters = props.transforms.iter().filter(|t| matches!(t, heic_rs::props::Transform::Rotate(r) if r.swaps_axes())).count(); + Some(quarters % 2 == 1) + }; + crate::guard::catch_panic(turned).ok().flatten().unwrap_or(false) + } + + /// `read` of the primary image's EXIF block, a TIFF structure inside `bytes`, for its + /// resolution tags. + pub(in super::super) fn with_exif(bytes: &[u8], read: impl FnOnce(&[u8]) -> Option) -> Option { + let find = || { + let ctx = Context::open(bytes).ok()?; + ctx.exif(ctx.meta.primary).ok().flatten() + }; + crate::guard::catch_panic(find).ok().flatten().and_then(read) + } + + fn decode_unguarded(bytes: &[u8], max_alloc: u64) -> Result { + let refused = |e: Error| match e { + Error::Unsupported(_) | Error::MissingBox("hvcC" | "meta") => UNSUPPORTED.to_string(), + _ => UNREADABLE.to_string(), + }; + let info = heic_rs::probe(bytes).map_err(refused)?; + let ctx = Context::open(bytes).map_err(refused)?; + if unsupported_items(&ctx).ok_or(UNREADABLE)? { + return Err(UNSUPPORTED.into()); + } + // The stored size, before a crop: the size the decoder holds. + let too_large = || format!("an image of {} × {} pixels is too large to draw", info.coded_width, info.coded_height); + let declared = u64::from(info.coded_width).checked_mul(u64::from(info.coded_height)).ok_or_else(too_large)?; + // A grid is composed at the size its own data gives, which need not match `ispe`. + let grid = grid_pixels(&ctx).ok_or(UNREADABLE)?; + // A single picture is converted at the size its stream gives, which need not match `ispe` + // either. + let coded = declared.max(grid).max(stream_pixels(&ctx).ok_or(UNREADABLE)?); + let shown = u64::from(info.width).checked_mul(u64::from(info.height)).ok_or_else(too_large)?; + // The RGBA output, and a second RGBA image when the decoder rotates, mirrors or crops it, + // which is no larger than the first. + let output = coded.checked_mul(8).ok_or_else(too_large)?; + let pictures = picture_bytes_in(&ctx).ok_or(UNREADABLE)?; + // An alpha grid is composed into a frame of 16-bit planes (at most three samples a pixel), + // and so is the image's grid when it is decoded with a color description of its tiles or + // its stream. A single picture is converted in place. + let composed = if grid > 0 { coded.checked_mul(if info.has_alpha { 12 } else { 6 }).ok_or_else(too_large)? } else { 0 }; + if coded == 0 || shown == 0 || output.checked_add(pictures).and_then(|n| n.checked_add(composed)).is_none_or(|n| n > max_alloc) { + return Err(too_large()); + } + let max_pixels = max_alloc / 4; + let decoded = match tile_nclx(&ctx).or_else(|| stream_nclx(&ctx)) { + Some(nclx) => decode_with_nclx(&ctx, nclx, max_pixels), + None => heic_rs::decode(bytes, &DecodeOptions::default().with_layout(PixelLayout::Rgba8).with_max_pixels(Some(max_pixels))), + } + .map_err(|e| match e { + Error::PixelLimit { .. } | Error::BoxTooLarge { .. } => too_large(), + e => refused(e), + })?; + let mut img = image::RgbaImage::from_raw(decoded.width, decoded.height, decoded.data).ok_or(UNREADABLE)?; + if let Some(profile) = source_profile(&ctx) { + for pixel in img.pixels_mut() { + let [r, g, b, a] = pixel.0; + let device = [r, g, b].map(|v| f32::from(v) / 255.0); + if let Some(rgb) = profile.to_srgb_into(&device, vectorcraft_color::cms::Intent::RelativeColorimetric) { + let [r, g, b] = rgb.map(|v| (v * 255.0).round() as u8); + pixel.0 = [r, g, b, a]; + } + } + } + Ok(img) + } + + /// The primary image and its alpha image, when it has one. + fn primary_and_alpha(ctx: &Context<'_>) -> Option> { + let primary = ctx.meta.primary; + Some(std::iter::once(primary).chain(ctx.alpha_item(primary).ok()?)) + } + + /// Whether the primary image or its alpha image is neither an HEVC-coded item (`hvc1`, `hev1`) + /// nor a grid of them, or is a grid with a tile that carries a crop, rotation or mirror. heic-rs + /// 0.1.4 decodes any item with an `hvcC` whatever its type, and composes a grid from its tiles + /// as coded, without their transforms: an encoder that pads tiles smaller than its coding block + /// (64 × 64 for x265) and crops them back with `clap` gets the wrong pixels. + fn unsupported_items(ctx: &Context<'_>) -> Option { + let hevc = |id: u32| ctx.meta.item(id).is_some_and(|info| info.is_hevc()); + for item in primary_and_alpha(ctx)? { + let Some((_, tiles)) = ctx.grid(item).ok()? else { + if !hevc(item) { + return Some(true); + } + continue; + }; + for tile in tiles { + if !hevc(tile) || !ctx.props(tile).ok()?.transforms.is_empty() { + return Some(true); + } + } + } + Some(false) + } + + /// The pixels of the larger of the primary image's grid and its alpha image's grid, at the + /// output size each grid gives; 0 when neither is a grid. + fn grid_pixels(ctx: &Context<'_>) -> Option { + let mut largest = 0u64; + for item in primary_and_alpha(ctx)? { + if let Some((grid, _)) = ctx.grid(item).ok()? { + largest = largest.max(u64::from(grid.output_width) * u64::from(grid.output_height)); + } + } + Some(largest) + } + + /// The pixels of the larger of the primary image and its alpha image when either is a single + /// picture, at the size of its largest sequence parameter set (before its conformance window); + /// 0 when both are grids. `None` when a size can't be read. + fn stream_pixels(ctx: &Context<'_>) -> Option { + let mut largest = 0u64; + for item in primary_and_alpha(ctx)? { + if ctx.grid(item).ok()?.is_some() { + continue; + } + // An item without `hvcC` isn't decoded: heic-rs refuses the file. + let Some(hvcc) = ctx.props(item).ok()?.hvcc else { continue }; + for nal in hvcc.parameter_sets().into_iter().filter(|nal| nal_type(nal) == Some(SPS)) { + let (width, height, _) = sps_size(nal)?; + largest = largest.max(width.checked_mul(height)?); + } + } + Some(largest) + } + + /// The first tile's `nclx` when the primary image is a grid without an `nclx` of its own and + /// its tiles carry one. heic-rs 0.1.4 converts a grid's samples to RGB with the grid item's + /// `nclx` alone, and with its BT.709 limited-range default when the grid has none + /// (tbraun96/heic-rs#6). + fn tile_nclx(ctx: &Context<'_>) -> Option { + let primary = ctx.meta.primary; + if ctx.props(primary).ok()?.nclx.is_some() { + return None; + } + let (_, tiles) = ctx.grid(primary).ok()??; + ctx.props(*tiles.first()?).ok()?.nclx + } + + /// The color description in the HEVC stream's video usability information (ITU-T H.265 + /// E.2.1) of the primary image, or of its grid's first tile, when neither carries an `nclx` + /// (a file whose only color box is an ICC profile, or one without a color box). heic-rs 0.1.4 + /// reads only the container's `nclx` and otherwise converts with BT.709 limited range. + fn stream_nclx(ctx: &Context<'_>) -> Option { + let primary = ctx.meta.primary; + if ctx.props(primary).ok()?.nclx.is_some() { + return None; + } + let coded = match ctx.grid(primary).ok()? { + Some((_, tiles)) => *tiles.first()?, + None => primary, + }; + let props = ctx.props(coded).ok()?; + if props.nclx.is_some() { + return None; + } + let hvcc = props.hvcc?; + let data = ctx.item_data(coded).ok()?; + let slices = hvcc.split_nals(&data).ok()?; + active_sps(&hvcc.parameter_sets(), &slices).and_then(sps_signal) + } + + /// The SPS the first slice of `slices` uses: the one its PPS names (ITU-T H.265 7.4.3.3.1). + pub(in super::super) fn active_sps<'a>(parameter_sets: &[&'a [u8]], slices: &[&[u8]]) -> Option<&'a [u8]> { + let slice = slices.iter().find(|nal| nal_type(nal).is_some_and(|t| t < 32))?; + let bits = &mut Bits { data: &payload(slice), at: 0 }; + // first_slice_segment_in_pic_flag, no_output_of_prior_pics_flag in an IRAP picture (types 16 + // to 23), slice_pic_parameter_set_id. + bits.skip(1)?; + if nal_type(slice).is_some_and(|t| (16..=23).contains(&t)) { + bits.skip(1)?; + } + let pps_id = bits.exp_golomb()?; + // pps_pic_parameter_set_id, pps_seq_parameter_set_id. + let pps_ids = |nal: &[u8]| { + let bits = &mut Bits { data: &payload(nal), at: 0 }; + Some((bits.exp_golomb()?, bits.exp_golomb()?)) + }; + let sps_id = parameter_sets.iter().filter(|nal| nal_type(nal) == Some(PPS)).find_map(|nal| pps_ids(nal).filter(|(id, _)| *id == pps_id))?.1; + let sps_ids = |nal: &[u8]| { + let rbsp = sps_payload(nal)?; + sps_head(&mut Bits { data: &rbsp, at: 0 }).map(|(_, id, ..)| id) + }; + parameter_sets.iter().copied().find(|nal| sps_ids(nal) == Some(sps_id)) + } + + /// The primary image decoded as heic-rs 0.1.4 decodes it (a grid's tiles one after another), + /// with its samples converted to RGBA with `nclx`, the alpha image applied and the image's + /// rotation, mirror and crop applied. + fn decode_with_nclx(ctx: &Context<'_>, nclx: Nclx, max_pixels: u64) -> heic_rs::Result { + use heic_rs::hevc::Frame; + + fn coded(ctx: &Context<'_>, id: u32) -> heic_rs::Result { + let props = ctx.props(id)?; + let hvcc = props.hvcc.as_ref().ok_or(Error::MissingBox("hvcC"))?; + let data = ctx.item_data(id)?; + let frame = heic_rs::hevc::decode_still(&hvcc.parameter_sets(), &hvcc.split_nals(&data)?)?; + frame.validate()?; + Ok(frame) + } + fn item(ctx: &Context<'_>, id: u32, max_pixels: u64) -> heic_rs::Result { + match ctx.grid(id)? { + Some((grid, tiles)) => { + // The tiles decode in parallel on native, as heic-rs's own decode does. + #[cfg(not(target_arch = "wasm32"))] + let frames = { + use rayon::prelude::*; + tiles.par_iter().map(|&t| coded(ctx, t)).collect::>>()? + }; + #[cfg(target_arch = "wasm32")] + let frames = tiles.iter().map(|&t| coded(ctx, t)).collect::>>()?; + heic_rs::grid::compose(&grid, &frames, max_pixels) + } + None => coded(ctx, id), + } + } + + let primary = ctx.meta.primary; + let props = ctx.props(primary)?; + let frame = item(ctx, primary, max_pixels)?; + let alpha = ctx.alpha_item(primary)?.map(|a| item(ctx, a, max_pixels)).transpose()?; + // `None`: rayon's global pool on native, where heic-rs is built with `parallel`. + let image = heic_rs::color::convert(&frame, alpha.as_ref(), nclx, PixelLayout::Rgba8, max_pixels, None)?; + heic_rs::transform::apply_all(image, &props.transforms) + } + + /// The bytes heic-rs 0.1.4 allocates for the coded pictures of `bytes` it decodes (see + /// [`picture_bytes_in`]); `None` when they can't be read. + #[cfg(test)] + pub(in super::super) fn picture_bytes(bytes: &[u8]) -> Option { + picture_bytes_in(&Context::open(bytes).ok()?) + } + + /// The bytes heic-rs 0.1.4 allocates for the coded pictures it decodes: the primary image's, + /// or each tile of its grid, and its alpha image's the same way. Each picture is sized by the + /// largest of its sequence parameter sets (the size the decoder allocates, rounded up to whole + /// 64-sample coding blocks), not by the container, and takes three sets of 16-bit planes: the + /// picture, a filtered copy and the frame returned. `None` when an item's sizes can't be read. + fn picture_bytes_in(ctx: &Context<'_>) -> Option { + let mut total = 0u64; + for item in primary_and_alpha(ctx)? { + let coded = match ctx.grid(item).ok()? { + Some((_, tiles)) => tiles, + None => vec![item], + }; + for id in coded { + let props = ctx.props(id).ok()?; + // An item without `hvcC` isn't decoded: heic-rs refuses the file. + let Some(hvcc) = props.hvcc else { continue }; + // The slices pick their SPS through the PPS, so the largest one is counted. Every + // SPS must be read. + let mut largest = None; + for nal in hvcc.parameter_sets().into_iter().filter(|nal| nal_type(nal) == Some(SPS)) { + let (width, height, chroma) = sps_size(nal)?; + let blocks = |n: u64| n.div_ceil(64) * 64; + // Bytes a sample position takes in one set of planes: luma and the two chroma + // planes. + let planes = match chroma { + 0 => 2, + 1 => 3, + 2 => 4, + _ => 6, + }; + let picture = blocks(width).checked_mul(blocks(height))?.checked_mul(planes * 3)?; + largest = largest.max(Some(picture)); + } + total = total.checked_add(largest?)?; + } + } + Some(total) + } + + /// The NAL unit type of an HEVC sequence parameter set. + const SPS: u8 = 33; + + /// The type of an HEVC NAL unit, from its header. + fn nal_type(nal: &[u8]) -> Option { + nal.first().map(|b| (b >> 1) & 0x3f) + } + + /// The NAL unit type of an HEVC picture parameter set. + const PPS: u8 = 34; + + /// A NAL unit's payload, without its two-byte header and the emulation prevention bytes (the 03 + /// of 00 00 03), up to its first 4,096 bytes. + fn payload(nal: &[u8]) -> Vec { + let mut rbsp = Vec::with_capacity(256); + let mut zeros = 0; + for &b in nal.get(2..).unwrap_or_default().iter().take(4096) { + if b == 3 && zeros >= 2 { + zeros = 0; + continue; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + rbsp.push(b); + } + rbsp + } + + /// An SPS NAL unit's [`payload`]; `None` for another NAL unit. + fn sps_payload(nal: &[u8]) -> Option> { + (nal_type(nal) == Some(SPS)).then(|| payload(nal)) + } + + /// The fields of an SPS (ITU-T H.265 7.3.2.2) up to the picture height: + /// `sps_max_sub_layers_minus1`, `sps_seq_parameter_set_id`, the width, the height and + /// `chroma_format_idc`. + fn sps_head(bits: &mut Bits<'_>) -> Option<(u64, u64, u64, u64, u64)> { + // sps_video_parameter_set_id, sps_max_sub_layers_minus1, sps_temporal_id_nesting_flag. + bits.skip(4)?; + let sub_layers = bits.read(3)?; + bits.skip(1)?; + // profile_tier_level (7.3.3): the general profile, tier and level, then the sub-layers'. + bits.skip(96)?; + let mut present = Vec::new(); + for _ in 0..sub_layers { + present.push((bits.read(1)?, bits.read(1)?)); + } + if sub_layers > 0 { + bits.skip(2 * (8 - sub_layers as usize))?; + } + for (profile, level) in present { + bits.skip(88 * profile as usize + 8 * level as usize)?; + } + let id = bits.exp_golomb()?; + let chroma = bits.exp_golomb()?; + if chroma == 3 { + bits.skip(1)?; + } + let width = bits.exp_golomb()?; + let height = bits.exp_golomb()?; + Some((sub_layers, id, width, height, chroma)) + } + + /// The picture width, height and `chroma_format_idc` of an HEVC sequence parameter set NAL + /// unit, before its conformance window; `None` for another NAL unit. + pub(in super::super) fn sps_size(nal: &[u8]) -> Option<(u64, u64, u64)> { + let rbsp = sps_payload(nal)?; + let (_, _, width, height, chroma) = sps_head(&mut Bits { data: &rbsp, at: 0 })?; + Some((width, height, chroma)) + } + + /// The video signal type of an HEVC sequence parameter set NAL unit's VUI (ITU-T H.265 E.2.1) + /// as an `nclx`: the full-range flag and, when the VUI describes them, the color primaries, + /// transfer characteristics and matrix coefficients (otherwise 2, unspecified). `None` when the + /// SPS has no VUI, the VUI has no video signal type, or the SPS can't be read that far. + pub(in super::super) fn sps_signal(nal: &[u8]) -> Option { + let rbsp = sps_payload(nal)?; + let bits = &mut Bits { data: &rbsp, at: 0 }; + let (sub_layers, ..) = sps_head(bits)?; + skip_to_vui(bits, sub_layers)?; + // vui_parameters_present_flag, then aspect_ratio_info_present_flag (an Extended_SAR + // aspect_ratio_idc of 255 adds its 32-bit ratio) and overscan_info_present_flag. + if bits.read(1)? == 0 { + return None; + } + if bits.read(1)? == 1 && bits.read(8)? == 255 { + bits.skip(32)?; + } + if bits.read(1)? == 1 { + bits.skip(1)?; + } + // video_signal_type_present_flag: video_format, video_full_range_flag and the color + // description. + if bits.read(1)? == 0 { + return None; + } + bits.skip(3)?; + let range = if bits.read(1)? == 1 { Range::Full } else { Range::Limited }; + let (primaries, transfer, matrix) = if bits.read(1)? == 1 { (bits.read(8)?, bits.read(8)?, bits.read(8)?) } else { (2, 2, 2) }; + let code = |v: u64| u16::try_from(v).ok(); + let matrix_code = code(matrix)?; + Some(Nclx { primaries: code(primaries)?, transfer: code(transfer)?, matrix: MatrixCoefficients::from_code(matrix_code), matrix_code, range }) + } + + /// Skips the fields of an SPS after [`sps_head`], up to `vui_parameters_present_flag`. + fn skip_to_vui(bits: &mut Bits<'_>, sub_layers: u64) -> Option<()> { + // conformance_window_flag and its four offsets. + if bits.read(1)? == 1 { + for _ in 0..4 { + bits.exp_golomb()?; + } + } + // bit_depth_luma_minus8, bit_depth_chroma_minus8. + bits.exp_golomb()?; + bits.exp_golomb()?; + let poc_bits = bits.exp_golomb()?.checked_add(4).filter(|&n| n <= 16)?; + // sps_sub_layer_ordering_info_present_flag, then three values for each sub-layer given. + let ordered = if bits.read(1)? == 1 { sub_layers + 1 } else { 1 }; + for _ in 0..ordered * 3 { + bits.exp_golomb()?; + } + // The coding and transform block sizes and the transform hierarchy depths. + for _ in 0..6 { + bits.exp_golomb()?; + } + // scaling_list_enabled_flag, sps_scaling_list_data_present_flag. + if bits.read(1)? == 1 && bits.read(1)? == 1 { + skip_scaling_lists(bits)?; + } + // amp_enabled_flag, sample_adaptive_offset_enabled_flag. + bits.skip(2)?; + // pcm_enabled_flag: the PCM sample depths, block sizes and loop filter flag. + if bits.read(1)? == 1 { + bits.skip(8)?; + bits.exp_golomb()?; + bits.exp_golomb()?; + bits.skip(1)?; + } + skip_reference_picture_sets(bits)?; + // long_term_ref_pics_present_flag: each picture's POC bits and used flag. + if bits.read(1)? == 1 { + let count = bits.exp_golomb()?; + if count > 32 { + return None; + } + for _ in 0..count { + bits.skip(poc_bits as usize + 1)?; + } + } + // sps_temporal_mvp_enabled_flag, strong_intra_smoothing_enabled_flag. + bits.skip(2) + } + + /// Skips `scaling_list_data()` (ITU-T H.265 7.3.4). + fn skip_scaling_lists(bits: &mut Bits<'_>) -> Option<()> { + for size in 0..4 { + // The 32 × 32 lists are given for matrices 0 and 3 only. + for _ in 0..if size == 3 { 2 } else { 6 } { + if bits.read(1)? == 0 { + // scaling_list_pred_matrix_id_delta. + bits.exp_golomb()?; + } else { + // scaling_list_dc_coef_minus8, then each scaling_list_delta_coef (se(v) codes, + // as long as ue(v) codes). + if size > 1 { + bits.exp_golomb()?; + } + for _ in 0..if size == 0 { 16 } else { 64 } { + bits.exp_golomb()?; + } + } + } + } + Some(()) + } + + /// Skips `num_short_term_ref_pic_sets` and each `st_ref_pic_set()` (ITU-T H.265 7.3.7) of an + /// SPS. A set predicted from the one before it has one or two flags for each of that set's + /// pictures and one more. + fn skip_reference_picture_sets(bits: &mut Bits<'_>) -> Option<()> { + let sets = bits.exp_golomb()?; + if sets > 64 { + return None; + } + // NumDeltaPocs of each set read so far. + let mut pictures: Vec = Vec::new(); + for index in 0..sets { + let predicted = index != 0 && bits.read(1)? == 1; + let count = if predicted { + // delta_rps_sign, abs_delta_rps_minus1. + bits.skip(1)?; + bits.exp_golomb()?; + let mut count = 0; + for _ in 0..=*pictures.last()? { + // used_by_curr_pic_flag, and use_delta_flag when it is 0. + if bits.read(1)? == 1 || bits.read(1)? == 1 { + count += 1; + } + } + count + } else { + let (negative, positive) = (bits.exp_golomb()?, bits.exp_golomb()?); + if negative > 16 || positive > 16 { + return None; + } + // Each picture's delta_poc_s0_minus1 or delta_poc_s1_minus1 and its used flag. + for _ in 0..negative + positive { + bits.exp_golomb()?; + bits.skip(1)?; + } + negative + positive + }; + pictures.push(count); + } + Some(()) + } + + /// A big-endian bit reader over an RBSP. + struct Bits<'a> { + data: &'a [u8], + at: usize, + } + + impl Bits<'_> { + fn bit(&mut self) -> Option { + let byte = self.data.get(self.at / 8)?; + let bit = (byte >> (7 - self.at % 8)) & 1; + self.at += 1; + Some(u64::from(bit)) + } + + fn read(&mut self, n: u32) -> Option { + (0..n).try_fold(0u64, |v, _| Some(v << 1 | self.bit()?)) + } + + fn skip(&mut self, n: usize) -> Option<()> { + self.at = self.at.checked_add(n)?; + (self.at <= self.data.len() * 8).then_some(()) + } + + /// An unsigned Exp-Golomb code, ue(v), of at most 32 leading zeros. + fn exp_golomb(&mut self) -> Option { + let mut zeros = 0; + while self.bit()? == 0 { + zeros += 1; + if zeros > 32 { + return None; + } + } + Some((1u64 << zeros) - 1 + self.read(zeros)?) + } + } + + /// `nclx` color primaries for Display P3 (SMPTE EG 432-1) and transfer characteristics for + /// the sRGB curve (IEC 61966-2-1), ITU-T H.273. + const P3_PRIMARIES: u16 = 12; + const SRGB_TRANSFER: u16 = 13; + + /// The profile the decoded RGB values are in when it isn't sRGB: the primary item's RGB ICC + /// profile, else Display P3 when its `nclx` names P3 primaries with the sRGB curve. A grid + /// without its own `colr` takes its first tile's, as cameras write it on the tiles. A profile + /// that can't be read, or isn't RGB, is left out and the values are read as sRGB. Without any + /// `colr`, the HEVC stream's color description ([`stream_nclx`]) is read the same way. + fn source_profile(ctx: &Context<'_>) -> Option { + use vectorcraft_color::cms::{self, IccProfile, ProfileKind}; + + let id = ctx.meta.primary; + let own = ctx.props(id).ok()?; + let described = |p: &heic_rs::props::ItemProps<'_>| p.icc.is_some() || p.nclx.is_some(); + let tile = || ctx.grid(id).ok().flatten().and_then(|(_, tiles)| tiles.first().and_then(|&t| ctx.props(t).ok())).filter(described); + let props = if described(&own) { Some(own) } else { tile() }; + if let Some(icc) = props.as_ref().and_then(|p| p.icc) { + return IccProfile::from_bytes(None, icc).ok().filter(|p| p.kind == ProfileKind::Rgb); + } + let nclx = match props { + Some(props) => props.nclx?, + None => stream_nclx(ctx)?, + }; + (nclx.primaries == P3_PRIMARIES && nclx.transfer == SRGB_TRANSFER).then(|| cms::icc::builtin_rgb(cms::DISPLAY_P3)).flatten() + } +} diff --git a/crates/engine/src/cmd/fileio/jp2read.rs b/crates/engine/src/cmd/fileio/jp2read.rs new file mode 100644 index 0000000000..9e0752c2c5 --- /dev/null +++ b/crates/engine/src/cmd/fileio/jp2read.rs @@ -0,0 +1,279 @@ +//! JPEG 2000 JP2 and codestream images for File › Open and File › Place. The decoded image is +//! bounded before allocation and converted to RGBA for the common PNG storage path. + +use hayro_jpeg2000::{ColorSpace, DecodeSettings, DecoderContext, Image}; +use vectorcraft_color::cms::{IccProfile, Intent}; + +/// Recognize a JP2 signature box or the start of a raw codestream. The decoder checks the rest. +pub(super) fn is_jpeg2000(bytes: &[u8]) -> bool { + bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") || bytes.starts_with(b"\xff\x4f") +} + +/// Boxes at one JP2 nesting level. Invalid lengths stop the walk at that level. +pub(super) fn boxes(b: &[u8]) -> impl Iterator { + let mut at = 0usize; + std::iter::from_fn(move || { + let header = b.get(at..at.checked_add(8)?)?; + let size = u32::from_be_bytes(header.get(..4)?.try_into().ok()?); + let (length, head) = match size { + 0 => (b.len().checked_sub(at)?, 8usize), + 1 => (usize::try_from(u64::from_be_bytes(b.get(at.checked_add(8)?..at.checked_add(16)?)?.try_into().ok()?)).ok()?, 16usize), + n => (n as usize, 8usize), + }; + if length < head { + return None; + } + let end = at.checked_add(length)?; + let data = b.get(at.checked_add(head)?..end)?; + let ty = header.get(4..8)?; + at = end; + Some((ty, data)) + }) +} + +/// The decoder ignores JPX layers and composition and silently uses the last top-level jp2c. +fn unsupported_jpx_content(bytes: &[u8]) -> bool { + fn association_has_content(data: &[u8], depth: usize) -> bool { + if depth >= 16 { + return true; + } + boxes(data).any(|(ty, child)| { + matches!(ty, b"jp2c" | b"jpch" | b"jplh" | b"comp" | b"ftbl") || (ty == b"asoc" && association_has_content(child, depth + 1)) + }) + } + let mut codestreams = 0u8; + for (ty, data) in boxes(bytes) { + match ty { + b"jp2c" => { + codestreams = codestreams.saturating_add(1); + if codestreams > 1 { + return true; + } + } + b"jpch" | b"jplh" | b"comp" | b"ftbl" => return true, + b"asoc" if association_has_content(data, 0) => return true, + _ => {} + } + } + false +} + +/// The largest embedded ICC profile read. +const MAX_PROFILE: usize = 4 * 1024 * 1024; +/// A codestream numbers its tiles 0 to 65,534 (Isot in SOT, ITU-T T.800 A.4.2). +const MAX_TILES: u64 = 65_535; +/// Bytes the decoder keeps for each component of each tile before decoding any of them. +const TILE_COMPONENT_BYTES: u64 = 256; + +/// SIZ follows SOC in the codestream; Lsiz includes its two length bytes. Returns the component +/// count, the image size and the tile count. +fn codestream_size(bytes: &[u8]) -> Option<(u64, u32, u32, u64)> { + let stream = if bytes.starts_with(b"\xff\x4f") { bytes } else { boxes(bytes).find_map(|(ty, data)| (ty == b"jp2c").then_some(data))? }; + if stream.get(..4)? != b"\xff\x4f\xff\x51" { + return None; + } + let length = u16::from_be_bytes(stream.get(4..6)?.try_into().ok()?) as usize; + let count = u16::from_be_bytes(stream.get(40..42)?.try_into().ok()?) as usize; + if count == 0 || length != 38usize.checked_add(count.checked_mul(3)?)? || stream.get(4..4usize.checked_add(length)?)?.len() != length { + return None; + } + let be32 = |range: std::ops::Range| stream.get(range).and_then(|v| v.try_into().ok()).map(u32::from_be_bytes); + let width = be32(8..12)?.checked_sub(be32(16..20)?)?; + let height = be32(12..16)?.checked_sub(be32(20..24)?)?; + // Tiles across and down (T.800 B-5): the grid from the tile offset, in whole tiles. + let tiles = |grid: u32, offset: u32, tile: u32| match (grid.checked_sub(offset), tile) { + (Some(span), 1..) => Some(u64::from(span).div_ceil(u64::from(tile))), + _ => None, + }; + let across = tiles(be32(8..12)?, be32(32..36)?, be32(24..28)?)?; + let down = tiles(be32(12..16)?, be32(36..40)?, be32(28..32)?)?; + Some((count as u64, width, height, across.checked_mul(down)?)) +} + +/// One `jp2h` header with at most one palette, component mapping and channel definition box, so +/// the checks below read the boxes the decoder uses. +fn single_header_boxes(bytes: &[u8]) -> bool { + let mut headers = boxes(bytes).filter(|(ty, _)| *ty == b"jp2h"); + let (Some((_, header)), None) = (headers.next(), headers.next()) else { + return false; + }; + [b"pclr", b"cmap", b"cdef"].iter().all(|kind| boxes(header).filter(|(ty, _)| ty == kind).count() <= 1) +} + +/// The number of channel definitions in a JP2 `cdef` box, `None` without one. Only color channels +/// 1 to n, in any order, followed by at most one opacity channel for the whole image are read; +/// any other layout (premultiplied opacity, opacity before a color, an unassociated channel) gives +/// `Some(0)`, which no image matches. +fn channel_definitions(bytes: &[u8]) -> Option { + if bytes.starts_with(b"\xff\x4f") { + return None; + } + let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data))?; + let cdef = boxes(header).find_map(|(ty, data)| (ty == b"cdef").then_some(data))?; + let count = cdef.get(..2).and_then(|n| n.try_into().ok()).map_or(0, |n: [u8; 2]| usize::from(u16::from_be_bytes(n))); + let Some(entries) = cdef.get(2..).filter(|rest| count > 0 && rest.len() == count * 6) else { + return Some(0); + }; + // (channel, type, association) by channel. + let mut defs: Vec<[u16; 3]> = + entries.as_chunks::<6>().0.iter().map(|&[a, b, c, d, e, f]| [[a, b], [c, d], [e, f]].map(u16::from_be_bytes)).collect(); + defs.sort_unstable(); + let opacity = defs.last().is_some_and(|&[_, kind, association]| kind == 1 && association == 0); + let colors = defs.len() - usize::from(opacity); + let mut seen = vec![false; colors]; + let layout_ok = defs.iter().enumerate().all(|(i, &[channel, kind, association])| { + usize::from(channel) == i + && (i >= colors + || (kind == 0 + && usize::from(association).checked_sub(1).and_then(|slot| seen.get_mut(slot)).is_some_and(|s| !std::mem::replace(s, true)))) + }); + Some(if layout_ok { defs.len() as u64 } else { 0 }) +} + +/// The column count of a JP2 palette (`pclr`), `Ok(None)` without one. A component mapping (`cmap`) +/// beside it needs one entry per column, each naming a codestream component and, when it maps +/// through the palette, a palette column; anything else is `Err`. +fn palette_columns(bytes: &[u8], components: u64) -> Result, ()> { + if bytes.starts_with(b"\xff\x4f") { + return Ok(None); + } + let Some(header) = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)) else { + return Ok(None); + }; + let Some(palette) = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then_some(data)) else { + return Ok(None); + }; + let columns = palette.get(2).copied().ok_or(())?; + // Each column's descriptor: unsigned, 1 to 31 bits, as codestream samples are. + let depths = palette.get(3..3 + usize::from(columns)).ok_or(())?; + if columns == 0 || depths.iter().any(|&d| d & 0x80 != 0 || (d & 0x7f) + 1 > 31) { + return Err(()); + } + // Without a mapping the decoder maps every column from the first component. + let Some(mapping) = boxes(header).find_map(|(ty, data)| (ty == b"cmap").then_some(data)) else { + return Ok(Some(u64::from(columns))); + }; + if mapping.len() != usize::from(columns) * 4 { + return Err(()); + } + for &[c0, c1, kind, column] in mapping.as_chunks::<4>().0 { + let valid = u64::from(u16::from_be_bytes([c0, c1])) < components + && match kind { + 0 => true, + 1 => column < columns, + _ => false, + }; + if !valid { + return Err(()); + } + } + Ok(Some(u64::from(columns))) +} + +/// Decode within the raster allocation allowance, counting source samples, RGBA output, and +/// decoder intermediates. The decoder may need multiple full-sized component planes. +pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result { + if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && unsupported_jpx_content(bytes) { + return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()); + } + if bytes.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") && !single_header_boxes(bytes) { + return Err("the JPEG 2000 file can't be read".into()); + } + let (codestream_channels, declared_w, declared_h, tile_count) = codestream_size(bytes).ok_or("the JPEG 2000 file can't be read")?; + if tile_count == 0 || tile_count > MAX_TILES { + return Err("the JPEG 2000 file can't be read".into()); + } + let declared_pixels = u64::from(declared_w).checked_mul(u64::from(declared_h)); + if declared_w == 0 + || declared_h == 0 + || declared_pixels.and_then(|n| n.checked_mul(codestream_channels)).and_then(|n| n.checked_mul(4)).is_none_or(|n| n > max_alloc) + || tile_count.checked_mul(codestream_channels).and_then(|n| n.checked_mul(TILE_COMPONENT_BYTES)).is_none_or(|n| n > max_alloc) + { + return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw")); + } + // The decoder copies an embedded profile (after a 3-byte `colr` header) when it reads the file. + let header = boxes(bytes).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap_or_default(); + if boxes(header).any(|(ty, data)| ty == b"colr" && data.len() > MAX_PROFILE + 3) { + return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()); + } + let palette = palette_columns(bytes, codestream_channels).map_err(|()| "the JPEG 2000 file can't be read")?; + // The decoder keeps each palette value in 8 bytes and each row in its own list. + let palette_rows = boxes(header).find_map(|(ty, data)| (ty == b"pclr").then(|| data.get(..2)).flatten()); + if let (Some(columns), Some(&[r0, r1])) = (palette, palette_rows) + && u64::from(u16::from_be_bytes([r0, r1])) * (columns * 8 + 24) > max_alloc + { + return Err(format!("an image of {declared_w} × {declared_h} pixels is too large to draw")); + } + let image = Image::new(bytes, &DecodeSettings::default()).map_err(|_| "the JPEG 2000 file can't be read")?; + let (w, h) = (image.width(), image.height()); + let color = image.color_space(); + let channels = match color { + ColorSpace::Gray => 1, + ColorSpace::RGB => 3, + ColorSpace::CMYK => 4, + ColorSpace::Icc { num_channels: 1 | 3 | 4, profile } if profile.len() <= MAX_PROFILE => color.num_channels(), + _ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()), + }; + let stride = u64::from(channels) + u64::from(image.has_alpha()); + // The decoder sizes its output by the palette's columns and writes one channel per mapping + // entry, so the columns, the entries and the output channels must all match. + if palette.is_some_and(|columns| columns != stride) { + return Err("the JPEG 2000 file can't be read".into()); + } + // The decoder reorders the channels by their definitions (`cdef`) and drops any channel without + // one, so a definition is needed for every channel it writes. + if channel_definitions(bytes).is_some_and(|count| count != stride || count != palette.unwrap_or(codestream_channels)) { + return Err("the JPEG 2000 file can't be read".into()); + } + let plane_channels = codestream_channels.max(stride).max(palette.unwrap_or(0)); + let too_large = || format!("an image of {w} × {h} pixels is too large to draw"); + let pixels = u64::from(w).checked_mul(u64::from(h)).ok_or_else(too_large)?; + let size = pixels.checked_mul(stride).ok_or_else(too_large)?; + let rgba_size = pixels.checked_mul(4).ok_or_else(too_large)?; + // hayro 0.3.5 keeps a f32 plane per component, including alpha, and a second + // f32 coefficient plane per component. Palette mapping or channel definitions + // can temporarily clone the component planes. Reserve another 8 bytes per + // pixel for IDWT and code-block scratch while samples and RGBA coexist. + let plane_bytes = pixels.checked_mul(plane_channels).and_then(|n| n.checked_mul(4)).ok_or_else(too_large)?; + let scratch_bytes = plane_bytes.checked_mul(2).and_then(|n| n.checked_add(pixels.checked_mul(8)?)).ok_or_else(too_large)?; + let working = + size.checked_add(rgba_size).and_then(|n| n.checked_add(plane_bytes)).and_then(|n| n.checked_add(scratch_bytes)).ok_or_else(too_large)?; + if w == 0 || h == 0 || working > max_alloc { + return Err(too_large()); + } + let len = usize::try_from(size).map_err(|_| too_large())?; + let mut samples = vec![0; len]; + image.decode_into(&mut samples, &mut DecoderContext::default()).map_err(|_| "the JPEG 2000 file can't be read")?; + let profile = match color { + ColorSpace::Icc { profile, .. } => { + Some(IccProfile::from_bytes(None, profile).map_err(|_| "the JPEG 2000 file has an unsupported color space or JPX content")?) + } + _ => None, + }; + let cms = vectorcraft_color::cms::active(); + let mut rgba = Vec::with_capacity(usize::try_from(rgba_size).map_err(|_| too_large())?); + for sample in samples.chunks_exact(stride as usize) { + let at = |i: usize| sample.get(i).copied().unwrap_or(0); + let rgb = match (color, profile.as_ref()) { + (ColorSpace::Gray, _) => [at(0); 3], + (ColorSpace::RGB, _) => [at(0), at(1), at(2)], + (ColorSpace::CMYK, _) => { + cms.cmyk_to_srgb([at(0), at(1), at(2), at(3)].map(|v| f32::from(v) / 255.0), false).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) + } + (ColorSpace::Icc { .. }, Some(profile)) => { + let mut values = [0.0f32; 4]; + for (dst, src) in values.iter_mut().zip(sample.iter().take(usize::from(channels))) { + *dst = f32::from(*src) / 255.0; + } + profile + .to_srgb_into(&values[..usize::from(channels)], Intent::RelativeColorimetric) + .ok_or("the JPEG 2000 file has an unsupported color space or JPX content")? + .map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8) + } + _ => return Err("the JPEG 2000 file has an unsupported color space or JPX content".into()), + }; + let [r, g, b] = rgb; + rgba.extend_from_slice(&[r, g, b, if image.has_alpha() { at(usize::from(channels)) } else { 255 }]); + } + image::RgbaImage::from_raw(w, h, rgba).ok_or_else(|| "the JPEG 2000 file can't be read".into()) +} diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index c7c467dc8c..9bf7a311a0 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -14,13 +14,16 @@ //! Images are the exception (`transparentImages`): an image with see-through pixels, opacity or a //! blending mode written opaque is a box hiding the art under it (version 7 images have no alpha //! channel, §8.1). With `flatten` (the default) each becomes an opaque image of itself and the art -//! under it, rendered from the document as it is, clipped to the area where it changes what shows; +//! under it, rendered from the document as it is, clipped to the area where it changes what shows +//! (a smooth outline of its rendered pixels, not a staircase of them); //! the art under it stays as it was. An image in a group with opacity or a blending mode is //! flattened the same way, and a pattern fill that paints a transparent image (see-through //! pixels, or opacity or a blending mode on the image, the fill, the shape or a group it is in) is //! expanded into its tiles first so its images flatten too. With `omit` the images with //! see-through pixels, opacity or a blending mode of their own are left out, and pattern fills stay -//! as the writer draws them (their tiles opaque over white). An image that can't be decoded is +//! as the writer draws them (their tiles opaque over white). A colorized image is flattened or +//! left out the same way, unless its pixels are all black or white: the writer writes that one as +//! a 1-bit image mask in its color, which keeps its white pixels clear. An image that can't be decoded is //! missing from the images that flattening and expanding raster effects draw, and the warnings //! then carry the raster exports' note once. //! @@ -28,7 +31,7 @@ //! layer's hidden objects go to a hidden layer of their own just above it, with `omit` they are //! left out, with `visible` they show where they are. Type is written as text the format's reader //! lays out again, in the fonts it names; `outlineText` writes its outlines instead (as type that -//! 8-bit text can't hold always is). +//! 8-bit text can't hold and type with rotated characters always are). use std::sync::Arc; @@ -41,7 +44,7 @@ use super::super::{Affine, EngineError, NodeId, Result, bad}; use super::{ArtboardPick, Encoded, Format}; /// Does `p` ask a save in `f` for a legacy `.ai` file of version 7 (`aiVersion: "7"`)? An unknown -/// version is an error, and so is version 7 for a `.ait` template, which is PDF-compatible only. +/// version is an error, and so is version 7 for a `.ait` template, which is never a legacy file. pub(super) fn wanted(cmd: &str, f: &Format, p: &Value) -> Result { let legacy = match p.get("aiVersion") { None | Some(Value::Null) => false, @@ -51,11 +54,17 @@ pub(super) fn wanted(cmd: &str, f: &Format, p: &Value) -> Result { Some(v) => return Err(bad(cmd, format!("aiVersion {v}: \"pdf\" (PDF-compatible, the default) or \"7\" (legacy .ai, version 7)"))), }; if legacy && f.id == "ait" { - return Err(bad(cmd, "aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible")); + return Err(bad(cmd, "aiVersion 7 writes legacy .ai files, not .ait templates")); } Ok(legacy) } +/// `f` (the `.ai` format, whose label names the PDF-compatible file) named, in its errors, as the +/// legacy `.ai` file. +pub(super) fn named(f: &Format) -> Format { + Format { label: "legacy .ai (version 7)", ..*f } +} + /// What a legacy `.ai` does with the images it can't hold (`transparentImages`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum SeeThrough { @@ -109,7 +118,7 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result } let mode = see_through(cmd, p)?; let (hidden, outline_text) = (hidden_objects(cmd, p)?, outline_text(cmd, p)?); - let picked: ArtboardPick = super::encode::options(f, p)?; + let picked: ArtboardPick = super::encode::options(&named(f), p)?; let boards = picked.resolve(n).map_err(|e| bad(cmd, e))?.unwrap_or_else(|| (0..n).collect()); let mut enc = Encoded { warnings: vec![FIDELITY.to_string()], ..Encoded::default() }; if boards.len() > 1 { @@ -161,21 +170,22 @@ fn expand_appearances(d: &mut Document) { } } -/// Expand every layer's pattern fills that paint a transparent image into their tiles, so those -/// images flatten like any other transparent image. The writer would otherwise draw them opaque -/// over white. +/// Expand every layer's pattern fills that paint an image with see-through pixels, a colorize paint, +/// opacity or blending into their tiles, so those images can be flattened. fn expand_image_patterns(d: &mut Document) -> Result<()> { let keys = super::super::flatten::see_through_images(d); let layers: Vec = d.layers.iter().map(|l| l.id).collect(); for id in layers { - super::super::expand::expand_transparent_image_patterns(d, id, &keys)?; + super::super::expand::expand_transparent_image_patterns(d, id, &keys, &|_, _| true)?; } Ok(()) } /// The images of `d` a legacy `.ai` can't hold, in paint order with their places in it (as -/// [`Document::walk`] counts). These are the images with see-through pixels, and the images -/// that have opacity or a blending mode of their own or, with `flatten`, of a group they are in. +/// [`Document::walk`] counts). These have see-through pixels or a colorize paint (except the +/// colorized images the writer writes as image masks, clear pixels included, +/// [`vectorcraft_eps::writes_image_mask`]), or +/// have opacity or a blending mode of their own or, with `flatten`, of a group they are in. /// With `flatten` only visible images are returned, because a hidden one (which the hidden objects /// option may write) is written over white. With `omit` all of them are returned. fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> { @@ -184,7 +194,10 @@ fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> { let mut at = 0; d.walk(|n| { if let NodeKind::Image(im) = &n.kind - && (keys.contains(&im.key) || n.opacity < 1.0 || n.blend != BlendMode::Normal || (mode == SeeThrough::Flatten && transparent(d, n.id))) + && (((keys.contains(&im.key) || n.extras().colorize.is_some()) && !vectorcraft_eps::writes_image_mask(d, n)) + || n.opacity < 1.0 + || n.blend != BlendMode::Normal + || (mode == SeeThrough::Flatten && transparent(d, n.id))) { out.push((at, n.id)); } @@ -241,8 +254,11 @@ const MAX_PPI: f64 = 600.0; const MIN_PPI: f64 = 72.0; /// A rendered pixel channel changes when it changes by more than this. const CHANGED: u8 = 2; -/// The clip outline follows cells of about this many points. -const CELL: f64 = 2.0; +/// The clip outline follows the rendered pixels, in blocks of them when there would be more than +/// this many: a huge image's clip would have millions of anchors. +const MAX_CELLS: usize = 4 << 20; +/// How far (in cells) the clip outline may stray from the staircase it smooths. +const SMOOTH: f64 = 0.35; /// The image `id` (the `at`th node in paint order of `src`) flattened: `src` drawn up to and /// including it, over white, cropped and clipped to the cells where drawing it changes the @@ -276,18 +292,21 @@ fn flattened(src: &Document, at: usize, id: NodeId) -> Result> { if w == 0 || h == 0 || shown.pixels.len() != w * h * 4 || under.pixels.len() != shown.pixels.len() { return Ok(None); } - // The cells where it changes anything. - let c = (CELL * scale).round().max(1.0) as usize; + // The cells where it changes anything: its pixels, or blocks of them for a huge image. + let c = if w * h <= MAX_CELLS { 1 } else { ((w * h) as f64 / MAX_CELLS as f64).sqrt().ceil() as usize }; let (cw, ch) = (w.div_ceil(c), h.div_ceil(c)); - let mut cells = vec![false; cw * ch]; + let mut changed = vec![false; cw * ch]; for (k, (a, b)) in shown.pixels.as_chunks::<4>().0.iter().zip(under.pixels.as_chunks::<4>().0).enumerate() { if a.iter().zip(b).any(|(a, b)| a.abs_diff(*b) > CHANGED) { let (x, y) = (k % w, k / w); - if let Some(cell) = cells.get_mut(y / c * cw + x / c) { + if let Some(cell) = changed.get_mut(y / c * cw + x / c) { *cell = true; } } } + // Grown by a cell, so the clip takes in the whole anti-aliased edge: where the image changes + // nothing it is the art under it, so a clip a little too large shows nothing more. + let cells = grown(&changed, cw, ch); let marked = || cells.iter().enumerate().filter(|(_, on)| **on).map(|(k, _)| (k % cw, k / cw)); let (Some(x0), Some(x1), Some(y0), Some(y1)) = (marked().map(|p| p.0).min(), marked().map(|p| p.0).max(), marked().map(|p| p.1).min(), marked().map(|p| p.1).max()) @@ -304,12 +323,16 @@ fn flattened(src: &Document, at: usize, id: NodeId) -> Result> { let crop = vectorcraft_render::Rendered { width: (px1 - px0) as u32, height: (py1 - py0) as u32, pixels }; let png = crop.to_png().map_err(EngineError::Other)?; let at = |x: usize, y: usize| Point::new(region.x0 + (x.min(w)) as f64 / scale, region.y0 + (y.min(h)) as f64 / scale); + // A cell corner, in cells, as a point of the page. + let (wf, hf, cf) = (w as f64, h as f64, c as f64); + let page = |(x, y): (f64, f64)| Point::new(region.x0 + (x * cf).clamp(0.0, wf) / scale, region.y0 + (y * cf).clamp(0.0, hf) / scale); let mut clip = PathData::new(vec![]); for comp in vectorcraft_trace::trace_mask(&cells, cw, ch) { for lp in std::iter::once(&comp.outer).chain(&comp.holes) { - let pts: Vec<(i32, i32)> = corners(&lp.pts); - let anchors = pts.iter().map(|&(x, y)| Anchor::corner(at(x.max(0) as usize * c, y.max(0) as usize * c))).collect(); - clip.subpaths.push(SubPath::new(anchors, true)); + let anchors: Vec = smoothed(&lp.pts).into_iter().map(|p| Anchor::corner(page(p))).collect(); + if anchors.len() >= 3 { + clip.subpaths.push(SubPath::new(anchors, true)); + } } } let xf = Affine::translate(at(px0, py0).to_vec2()) * Affine::scale(1.0 / scale); @@ -331,17 +354,64 @@ fn up_to(n: &Node, last: usize, i: &mut usize) -> Option { Some(n) } -/// A loop's corners: its points without those in the middle of a straight run. -fn corners(pts: &[(i32, i32)]) -> Vec<(i32, i32)> { +/// `mask` (`w × h` cells) with every cell next to a set one set too. +fn grown(mask: &[bool], w: usize, h: usize) -> Vec { + let set = |x: usize, y: usize| mask.get(y * w + x).copied().unwrap_or(false); + let mut out = vec![false; mask.len()]; + for (k, cell) in out.iter_mut().enumerate() { + let (x, y) = (k % w, k / w); + *cell = (y.saturating_sub(1)..(y + 2).min(h)).any(|y| (x.saturating_sub(1)..(x + 2).min(w)).any(|x| set(x, y))); + } + out +} + +/// A loop of cell corners (a staircase) as a smooth outline, in cells: the middle of each cell +/// edge along it, so that a run of one-cell steps becomes the sloped line it stands for, without +/// the points that lie (within [`SMOOTH`]) on a straight line between their neighbours. +fn smoothed(pts: &[(i32, i32)]) -> Vec<(f64, f64)> { + let mut mids = Vec::with_capacity(pts.len()); + for (k, &(ax, ay)) in pts.iter().enumerate() { + let Some(&(bx, by)) = pts.get(k + 1).or(pts.first()) else { break }; + let (dx, dy) = ((bx - ax).signum(), (by - ay).signum()); + let steps = (bx - ax).unsigned_abs().max((by - ay).unsigned_abs()); + for i in 0..steps as i32 { + let (x, y) = (ax + dx * i, ay + dy * i); + mids.push((f64::from(x) + 0.5 * f64::from(dx), f64::from(y) + 0.5 * f64::from(dy))); + } + } + simplify_closed(&mids, SMOOTH) +} + +/// The points of closed polyline `pts` that Douglas–Peucker keeps with tolerance `tol`. +fn simplify_closed(pts: &[(f64, f64)], tol: f64) -> Vec<(f64, f64)> { let n = pts.len(); - let get = |k: usize| pts.get(k % n.max(1)).copied(); - (0..n) - .filter_map(|k| { - let (a, b, c) = (get(k + n - 1)?, get(k)?, get(k + 1)?); - let straight = (a.0 == b.0 && b.0 == c.0) || (a.1 == b.1 && b.1 == c.1); - (!straight).then_some(b) - }) - .collect() + if n < 4 { + return pts.to_vec(); + } + let d2 = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).powi(2) + (a.1 - b.1).powi(2); + let Some(&first) = pts.first() else { return vec![] }; + // Split at the first point and the point farthest from it: two open runs. + let far = (1..n).max_by(|&i, &j| d2(first, pts[i]).total_cmp(&d2(first, pts[j]))).unwrap_or(n / 2); + let mut keep = vec![false; n]; + keep[0] = true; + keep[far] = true; + let mut todo = vec![(0, far), (far, n)]; + while let Some((a, b)) = todo.pop() { + if b <= a + 1 { + continue; + } + let (p, q) = (pts[a], pts[b % n]); + let (ux, uy) = (q.0 - p.0, q.1 - p.1); + let len = ux.hypot(uy); + let dist = |r: (f64, f64)| if len > 0.0 { ((r.0 - p.0) * uy - (r.1 - p.1) * ux).abs() / len } else { d2(p, r).sqrt() }; + let Some((m, dm)) = (a + 1..b).map(|i| (i, dist(pts[i]))).max_by(|x, y| x.1.total_cmp(&y.1)) else { continue }; + if dm > tol { + keep[m] = true; + todo.push((a, m)); + todo.push((m, b)); + } + } + pts.iter().zip(&keep).filter(|(_, k)| **k).map(|(p, _)| *p).collect() } fn note(warnings: &mut Vec, w: &str) { diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index ecb1c30993..697f3c1d73 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -9,7 +9,7 @@ use vectorcraft_render::effects::pixel::LoadedTexture; use super::super::{Result, Session, bad, bool_or, clipboard, parse_range, str_param}; use super::pdfimport::LoadOptions; -use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, format_for_name, psdread, read_file}; +use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, psdread, read_file, readable_format_for_name}; use crate::cmd::links::Resolved; use crate::{EngineError, Prefs}; @@ -29,6 +29,8 @@ pub struct Loaded { /// A PDF, or a `.ai` or `.ait` that holds a PDF, read through the editor's own copy of its art /// that it carries (its layers), not from its PDF part alone. pub editing_data: bool, + /// Whether the native source declared a PDF; other formats carry no native save preference. + pub native_pdf_compatible: Option, } impl Loaded { @@ -67,7 +69,7 @@ pub fn file_name(name: &str) -> String { /// The readable format of a file: from its content (magic bytes) when that tells, else from the /// extension of `name`. pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { - let by_name = format_for_name(name).filter(|f| f.read); + let by_name = readable_format_for_name(name); if vectorcraft_affinity::is_affinity(bytes) { return format("affinity"); } @@ -97,6 +99,15 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if psdread::is_psd(bytes) { return format(if psdread::is_psb(bytes) { "psb" } else { "psd" }); } + if super::pxrread::is_pxr(bytes) { + return format("pxr"); + } + if super::jp2read::is_jpeg2000(bytes) { + return format("jpeg2000"); + } + if super::heifread::is_heif(bytes) { + return format("heif"); + } if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) { return Some(f); } @@ -159,14 +170,18 @@ pub fn load(name: &str, bytes: &[u8]) -> Result { /// of its art, which it carries: its layers and hidden objects as they were, and the art outside /// its artboard (its PDF part has only what is on the artboards), as an EPS of the editor is read. /// Anything else as it was. `unit`: the size in points of a unit of the PDF part's user space (its -/// first page's `UserUnit`) → (document, warnings, whether its layers were read). -fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warnings: Vec, unit: f64) -> (Document, Vec, bool) { - if opts.pages.is_some() || !opts.layers || !opts.editing_data { - return (doc, warnings, false); - } - let Some(private) = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref()) else { return (doc, warnings, false) }; +/// first page's `UserUnit`) → (document, warnings, whether its layers were read). `layers`: the +/// editor's copy ([`editing_copy`]), as far as it was decoded and read. +fn through_editing_data( + layers: Option, + opts: &LoadOptions, + doc: Document, + warnings: Vec, + unit: f64, +) -> (Document, Vec, bool) { + let Some(layers) = layers else { return (doc, warnings, false) }; let outlined = opts.text_as == vectorcraft_pdf::TextAs::Outlines; - let (doc, mut warnings, read) = vectorcraft_eps::layered_ai(&private, doc, warnings, outlined, opts.trust_editing_data, unit); + let (doc, mut warnings, read) = vectorcraft_eps::layered_ai_from(layers, doc, warnings, outlined, opts.trust_editing_data, unit); // The layers weren't read (or couldn't be): the notes of reading the PDF part still hold. if !read { return (doc, warnings, false); @@ -183,18 +198,98 @@ fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warning (doc, warnings, true) } -/// A `.ai` saved without PDF compatibility (its PDF part is a placeholder page) from the editor's -/// own copy of its art alone: `None` when the file has none (or pages are picked, or layers or the -/// editing data are off), an error when it can't be read. -fn from_editing_data_alone(bytes: &[u8], opts: &LoadOptions) -> Option)>> { +/// A `.ai` saved without PDF compatibility (its PDF part is a placeholder page), `opened`, from the +/// editor's own copy of its art alone: `None` when the file has none (or the pages picked don't +/// name every page, or layers or the editing data are off), an error when it can't be read. +fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option)>> { + if !every_page(opened.page_count(), opts) || !opts.layers || !opts.editing_data { + return None; + } + let private = opened.illustrator_data()?; + Some(editing_copy_alone(&private)) +} + +/// [`from_editing_data_alone`] of `private`, the editor's copy already read. +fn editing_copy_alone(private: &[u8]) -> Result<(Document, Vec)> { + vectorcraft_eps::ai_alone(private) + .map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})"))) +} + +/// Does a file opened with `opts` read the editor's own copy of its art: no pages picked, and +/// layers and the editing data on? +fn reads_editing_copy(opts: &LoadOptions) -> bool { + opts.pages.is_none() && opts.layers && opts.editing_data +} + +/// May a file opened with `opts` open from the editor's own copy of its art without its PDF part +/// being imported ([`vectorcraft_eps::ai_layers_alone`]): it reads the editor's copy, on the pages' +/// trim boxes (the crop box asked for, as a file with the editor's copy opens on them), with its +/// type as text? +fn reads_layers_alone(opts: &LoadOptions) -> bool { + reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines +} + +/// The editor's own copy of its art that `opened` carries (as [`vectorcraft_pdf::illustrator_data`] +/// reads it), when `opts` read it ([`reads_editing_copy`]). +fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option> { + reads_editing_copy(opts).then(|| opened.illustrator_data()).flatten() +} + +/// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's +/// error) from the editor's own copy of its art alone, as a file saved without PDF compatibility +/// is read, its first note saying why: `None` when pages are picked, layers or the editing data +/// are off, or the file has no editing data that reads. Its type is outlines when `opts` asks. +fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: &EngineError) -> Option<(Document, Vec)> { if opts.pages.is_some() || !opts.layers || !opts.editing_data { return None; } - let private = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref())?; - Some( - vectorcraft_eps::ai_alone(&private) - .map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})"))), - ) + let private = vectorcraft_pdf::illustrator_data_without_pdf_part(bytes, opts.password.as_deref())?; + let (doc, warnings) = vectorcraft_eps::ai_alone_on_page(&private.data, private.trim, private.user_unit).ok()?; + let notes = std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect(); + Some(outlined_if_asked(doc, notes, opts)) +} + +/// Is `w` a note on the PDF part as a page, which says nothing was skipped: that the art off the +/// artboards is in the editing data alone, or that art past the page was clipped to it? +fn is_page_note(w: &str) -> bool { + w == vectorcraft_pdf::OFF_ARTBOARD_NOTE || w == vectorcraft_pdf::PAST_PAGE_NOTE +} + +/// The document read from the editing data alone with its type as outlines when `opts` asks for +/// them (`textAs: outlines`): the page that would have them has none to give. Threaded type first +/// flows through its frames (the editing data gives a story in its first frame), and the outlined +/// frames leave their threads. Each outline group keeps its type's transparency, opacity mask and +/// effects. +pub(super) fn outlined_if_asked(mut doc: Document, warnings: Vec, opts: &LoadOptions) -> (Document, Vec) { + if opts.text_as != vectorcraft_pdf::TextAs::Outlines { + return (doc, warnings); + } + if !doc.text_threads.is_empty() { + crate::cmd::threads::reflow(&Document::new(1.0, 1.0), &mut doc); + } + let threaded = crate::cmd::threads::frames(&doc); + let mut texts = Vec::new(); + doc.walk(|n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)) { + texts.push(n.clone()); + } + }); + for t in texts { + let Some(o) = crate::cmd::flatten::outlined_text(&t) else { continue }; + let o = Node { visible: t.visible, locked: t.locked, ..doc.reid(&o) }; + if let Some(slot) = doc.node_mut(t.id) { + *slot = o; + } + } + crate::cmd::threads::leave_threads(&mut doc, &threaded); + (doc, warnings) +} + +/// Does `doc` hold no art: only layers, with nothing in them? +fn draws_nothing(doc: &Document) -> bool { + let mut art = false; + doc.walk(|n| art |= !n.is_layer()); + !art } /// Is `e` the error of a file whose pages are only a placeholder @@ -203,28 +298,35 @@ pub(crate) fn is_placeholder(e: &EngineError) -> bool { e.to_string() == vectorcraft_pdf::PdfError::PlaceholderOnly.to_string() } -/// Do `opts` read every page of the PDF `bytes`: no `pages`, or a range that names each one? -fn every_page(bytes: &[u8], opts: &LoadOptions) -> bool { +/// Do `opts` read every page of a PDF of `count` pages: no `pages`, or a range that names each one? +fn every_page(count: usize, opts: &LoadOptions) -> bool { let Some(range) = &opts.pages else { return true }; - vectorcraft_pdf::info(bytes, opts.password.as_deref()).is_ok_and(|i| parse_range(range, i.pages.len()).is_ok_and(|p| p.len() == i.pages.len())) + parse_range(range, count).is_ok_and(|p| p.len() == count) } -/// A page read from a PDF or `.ai` (`read`, as [`super::page_document`] reads it) → (document, -/// notes, false); for a `.ai` saved without PDF compatibility (its page only a placeholder), the -/// file `name` read as `document.open` reads it with `password`, from its editing copy alone → -/// (document, notes, true). +/// Page `page_index` (0-based) read from a PDF or `.ai` (`read`, as [`super::page_document`] reads +/// it) → (document, notes, false); for a `.ai` saved without PDF compatibility (its page only a +/// placeholder), the file `name` read as `document.open` reads it with `opts`' password, from its +/// editing copy alone → (document, notes, true). So too, read with `opts` but every page, for the +/// first page of a `.ai` or PDF whose PDF part can't be read and whose editing copy reads; the +/// error of any other page stays. pub(crate) fn page_or_editing_data( name: &str, bytes: &[u8], - password: Option<&str>, + opts: &LoadOptions, + page_index: usize, read: Result<(Document, Vec)>, ) -> Result<(Document, Vec, bool)> { match read { Ok((doc, notes)) => Ok((doc, notes, false)), Err(e) if is_placeholder(&e) => { - let l = load_with(name, bytes, &LoadOptions { password: password.map(str::to_string), ..Default::default() })?; + let l = load_with(name, bytes, &LoadOptions { password: opts.password.clone(), ..Default::default() })?; Ok((l.doc, l.warnings, true)) } + Err(e) if page_index == 0 => match load_with(name, bytes, &LoadOptions { pages: None, ..opts.clone() }) { + Ok(l) if l.editing_data => Ok((l.doc, l.warnings, true)), + _ => Err(e), + }, Err(e) => Err(e), } } @@ -236,9 +338,12 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result None => err(format!("can't open `{name}`: not a format VectorCraft reads (see document.formats)")), })?; let title = file_name(name); + // The File Info a PDF, `.ai` or `.ait` gives. + let mut file_info = None; let mut converted = false; let mut preview_only = false; let mut editing_data = false; + let mut native_pdf_compatible = None; let (mut doc, mut warnings, restored) = match format.id { // EPS, .ps and PostScript .ai: the document our EPS files carry, else the PostScript read. _ if matches!(format.id, "eps" | "ps") || vectorcraft_pdf::is_postscript(bytes) => { @@ -251,6 +356,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result } "vectorcraft" | "template" => { let (d, info, warnings) = native_file(bytes)?; + native_pdf_compatible = Some(info.pdf_compatible); converted = info.is_old() || super::extension(name) == vectorcraft_format::LEGACY_EXTENSION; (d, warnings, false) } @@ -262,35 +368,93 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result restore_or_import(editing, || import_svg(&text, folder.as_deref()))? } "pdf" | "ai" | "ait" => { + // The file is read and checked once, for the document it carries, its pages, the + // editor's copy and its File Info. + let opened = vectorcraft_pdf::open_pdf(bytes, opts.password.as_deref()); // Saved with Preserve Editing: the document it carries, unless some pages are picked. - let editing = opts - .pages - .is_none() - .then(|| vectorcraft_pdf::editing_with(bytes, opts.password.as_deref())) + let editing = (opts.pages.is_none() && opts.native) + .then(|| opened.as_ref().ok().and_then(|o| o.editing())) .flatten() .map(|e| (e.intact, move || Some(e.data))); - restore_or_import(editing, || match super::pdfimport::import(bytes, opts, format.id != "pdf") { - Ok(r) => { - // Pages of text alone: the editing copy alone where it reads, as for a file - // saved without its PDF part (#1387: else the page, which is the art). - let alone = r.only_text.then(|| from_editing_data_alone(bytes, opts)).flatten().and_then(|read| read.ok()); - let (doc, warnings, read) = match alone { - Some((doc, warnings)) => (doc, warnings, true), - None => through_editing_data(bytes, opts, r.document, r.warnings, r.user_unit), - }; - editing_data = read; - Ok((doc, warnings)) + let imported = || match &opened { + Ok(o) => super::pdfimport::import(bytes, o, opts, format.id != "pdf"), + Err(e) => Err(err(e)), + }; + let mut read = restore_or_import(editing, || { + // Type all from the text document and nothing that needs the PDF part: the layers + // alone, the PDF part not imported. Else what was read of the layers is kept for + // reading them with the PDF part. + let mut layers = None; + if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?))) + { + let pages = o.trim_pages(); + match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit) { + Ok((mut doc, warnings)) => { + doc.setup.bleed = pages.bleed; + editing_data = true; + return Ok((doc, warnings)); + } + Err(read) => layers = Some(read), + } } - // Saved without its PDF part: the editing copy is all the file has (`pages` that - // name every page read it as the whole file). - Err(e) if is_placeholder(&e) => { - let whole = LoadOptions { pages: None, ..opts.clone() }; - from_editing_data_alone(bytes, if every_page(bytes, opts) { &whole } else { opts }) + match imported() { + Ok(r) => { + // The editor's copy, read once the import is done with the pages, unless + // its layers were read before it. + let private = layers.is_none().then(|| opened.as_ref().ok().and_then(|o| editing_copy(o, opts))).flatten(); + // Pages of text alone: the editing copy alone where it reads, as for a file + // saved without its PDF part (#1387: else the page, which is the art). So too + // pages that draw nothing at all: there is no page art to check the layers + // against, and the empty page would lose all of it. + // A page is empty only when nothing on it was skipped (an image that can't be + // decoded draws nothing either): its notes are at most the page's own. + let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w)); + let copy_alone = || match &private { + Some(private) => Some(editing_copy_alone(private)), + None if layers.is_some() => opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p)), + None => None, + }; + let alone = (r.only_text || empty) + .then(copy_alone) + .flatten() + .and_then(|read| read.ok()) + .map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts)); + let (doc, warnings, read) = match alone { + Some((doc, warnings)) => (doc, warnings, true), + None => { + let layers = layers.or_else(|| private.as_deref().map(vectorcraft_eps::AiLayers::decode)); + through_editing_data(layers, opts, r.document, r.warnings, r.user_unit) + } + }; + editing_data = read; + Ok((doc, warnings)) + } + // Saved without its PDF part: the editing copy is all the file has (`pages` that + // name every page read it as the whole file). + Err(e) if is_placeholder(&e) => opened + .as_ref() + .ok() + .and_then(|o| from_editing_data_alone(o, opts)) .unwrap_or(Err(e)) - .inspect(|_| editing_data = true) + .map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts)) + .inspect(|_| editing_data = true), + // A PDF part that can't be read (a stream the import refuses): the editing copy + // alone where it reads, else the error. + Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e), } - Err(e) => Err(e), - })? + })?; + // The File Info of a file read from its pages or its editing copy. + if !read.2 { + file_info = opened.as_ref().ok().map(|o| o.file_info()); + } + // A restored document opens on the artboard that the editing copy beside it names as + // active, as a file read from that copy does (the restored document never holds one). + if read.2 + && let Some(private) = opened.as_ref().ok().and_then(|o| o.illustrator_data()) + { + read.0.opened_artboard = vectorcraft_eps::ai_opened_artboard(&private, &read.0); + } + read } "dxf" => { let (doc, warnings) = super::dxfimport::import(bytes, &opts.dxf)?; @@ -312,17 +476,21 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result // it carries, opens with the File Info it gives (a PostScript `.ai` gives none). if matches!(format.id, "pdf" | "ai" | "ait") && !restored - && let Some(info) = vectorcraft_pdf::file_info(bytes, opts.password.as_deref()) + && let Some(info) = file_info { super::super::fileinfo::read_pdf(&mut doc.metadata, info); } // Threaded type read from a file flows through its frames (the threaded type of a restored // document keeps its text as saved), and every frame of a thread takes its first frame's - // Optical Margin Alignment setting. + // Optical Margin Alignment setting and writing direction. When that changes the direction of a + // frame of a restored document, the story flows through that frame's thread again. Threaded + // frames keep their size: Auto Size is off for them. if !doc.text_threads.is_empty() && !restored { crate::cmd::threads::reflow(&Document::new(1.0, 1.0), &mut doc); } else if !doc.text_threads.is_empty() { + crate::cmd::threads::keep_frame_sizes(&mut doc); crate::cmd::threads::share_optical_margin(&mut doc); + crate::cmd::threads::share_orientation(&mut doc); // A frame whose first paragraph continues from the frame before draws it without the // paragraph's first-line indent and list marker. crate::cmd::threads::mark_continued(&mut doc); @@ -336,7 +504,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result doc.title = title; } warnings.extend(doc.images.values().filter_map(|b| size_note(&b.bytes))); - Ok(Loaded { doc, format, warnings, restored, converted, preview_only, editing_data }) + Ok(Loaded { doc, format, warnings, restored, converted, preview_only, editing_data, native_pdf_compatible }) } /// Import SVG text, reading the files its images link to (relative links from `folder`, the SVG's @@ -396,13 +564,14 @@ impl ReadFile { /// The first half of [`open_bytes_with`], which needs no session (an app may do it on another /// thread): read and decode the file, read its linked files and lay out its type → what -/// [`open_read`] opens. The linked files are looked for from `path`, where the file was read from, +/// [`open_read`] opens. Type in the file's composite fonts is measured again once the document +/// opens and its composite fonts are registered. The linked files are looked for from `path`, where the file was read from, /// and modified ones are read again when `update_links` (Preferences › File Handling › Update /// Links set to Automatically; see [`crate::cmd::links::resolve`]). pub fn read_for_open(name: &str, bytes: &[u8], path: Option, p: &Value, update_links: bool, low_res_proxy_eps: bool) -> Result { let opts = LoadOptions::from_params("document.open", p)?; let mut loaded = load_with(name, bytes, &opts)?; - let links = crate::cmd::links::resolve(&mut loaded.doc, path.as_deref(), update_links, low_res_proxy_eps); + let links = crate::cmd::links::resolve(&mut loaded.doc, crate::cmd::links::LinkBase::file(path.as_deref()), update_links, low_res_proxy_eps); Session::refresh_text_bounds(&mut loaded.doc); Ok(ReadFile { loaded, opts, path, links }) } @@ -422,14 +591,15 @@ pub fn open_template(s: &mut Session, name: &str, bytes: &[u8], path: Option<&st "only this Affinity file's embedded preview could be read: use File › Open to see it with its warning, or export SVG or PDF from Affinity first", )); } - let links = crate::cmd::links::resolve(&mut loaded.doc, path, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps); + let base = crate::cmd::links::LinkBase::file(path); + let links = crate::cmd::links::resolve(&mut loaded.doc, base, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps); open_loaded(s, loaded, links, path.map(str::to_string), &LoadOptions::default(), true) } /// Make a loaded file the new active document; `links` is what became of its linked files, and /// `opts` are the options it was read with. fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option, opts: &LoadOptions, as_template: bool) -> Result { - let Loaded { mut doc, format, warnings, restored, converted, .. } = loaded.with_grid_prefs(&s.prefs); + let Loaded { mut doc, format, warnings, restored, converted, native_pdf_compatible, .. } = loaded.with_grid_prefs(&s.prefs); // EPS now has an ordinary Save path. Its preview, partial-program and damaged-editing // fallbacks must ask before overwriting the richer source they could not fully read. let losses: Vec = warnings @@ -461,11 +631,15 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option Option { /// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]). /// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read /// either, become RGBA too, whether they store their channels together or one plane per channel. +/// A PCX file is recognized by its header ([`super::pcxread::is_pcx`]) and read by +/// [`super::pcxread::decode`], which refuses an image past [`MAX_RASTER_ALLOC`] before decoding. +/// A Pixar picture file is recognized by its magic number ([`super::pxrread::is_pxr`]) and read by +/// [`super::pxrread::decode`], which does the same. +/// A HEIC or HEIF file is recognized by its `ftyp` brands ([`super::heifread::is_heif`]) and read +/// by [`super::heifread::decode`], which does the same. /// A Targa file, which starts with no signature, is recognized by its header /// ([`super::tgaread::is_targa`]) and becomes RGBA with the transparency it stores /// ([`super::tgaread::fix_alpha`]). An image stored as PNG whose decoded samples, or whose pixels @@ -576,16 +757,34 @@ pub fn raster_image(bytes: &[u8]) -> Result { let cms = vectorcraft_color::cms::active(); return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, ppi); } + if super::jp2read::is_jpeg2000(bytes) { + return as_png(super::jp2read::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi); + } + if super::heifread::is_heif(bytes) { + // The EXIF resolution describes the stored pixels; a quarter turn swaps its axes. + let ppi = ppi.map(|(x, y)| if super::heifread::quarter_turned(bytes) { (y, x) } else { (x, y) }); + return as_png(super::heifread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi); + } + if super::pxrread::is_pxr(bytes) { + return as_png(super::pxrread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi); + } let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?; if reader.format().is_none() && super::tgaread::is_targa(bytes) { reader.set_format(image::ImageFormat::Tga); } + if reader.format().is_none() && super::pcxread::is_pcx(bytes) { + return as_png(super::pcxread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi); + } let mut limits = image::Limits::default(); limits.max_alloc = Some(MAX_RASTER_ALLOC); reader.limits(limits); let kind = reader.format().ok_or_else(|| err("not an image VectorCraft reads (see document.formats)"))?; let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?; + // A photo whose EXIF orientation turns or flips it (a camera held upright) is stored as it is + // seen, so it places the way it was taken (#4284); the others keep their own bytes. + let turned = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff") && exif_orientation(bytes).is_some(); let kept = match f.id { + _ if turned => None, "png" | "jpg" | "gif" | "webp" => Some(bytes.to_vec()), "tiff" => vectorcraft_doc::cmyk::stored_cmyk_tiff(bytes, ppi), _ => None, @@ -604,13 +803,16 @@ pub fn raster_image(bytes: &[u8]) -> Result { Some(read) => read.map_err(err)?, None => { use image::ImageDecoder as _; - let decoder = reader.into_decoder().map_err(err)?; + let mut decoder = reader.into_decoder().map_err(err)?; // The allowance counts the decoded samples and the RGBA pixels they become (#1717). let (w, h) = decoder.dimensions(); if decoder.total_bytes() > MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC { return Err(err(format!("an image of {w} × {h} pixels is too large to draw"))); } - image::DynamicImage::from_decoder(decoder).map_err(err)?.to_rgba8() + let orientation = decoder.orientation().unwrap_or(image::metadata::Orientation::NoTransforms); + let mut img = image::DynamicImage::from_decoder(decoder).map_err(err)?; + img.apply_orientation(orientation); + img.to_rgba8() } }, }; @@ -620,6 +822,14 @@ pub fn raster_image(bytes: &[u8]) -> Result { as_png(img, ppi) } +/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when +/// it leaves them as stored, or the image has none. +pub(crate) fn exif_orientation(bytes: &[u8]) -> Option { + use image::ImageDecoder as _; + let mut decoder = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?; + decoder.orientation().ok().filter(|o| *o != image::metadata::Orientation::NoTransforms) +} + /// `img` stored as a PNG that keeps the file's resolution. fn as_png(img: image::RgbaImage, ppi: Option<(f64, f64)>) -> Result { let size = img.dimensions(); diff --git a/crates/engine/src/cmd/fileio/mesh3d.rs b/crates/engine/src/cmd/fileio/mesh3d.rs new file mode 100644 index 0000000000..50a919d834 --- /dev/null +++ b/crates/engine/src/cmd/fileio/mesh3d.rs @@ -0,0 +1,260 @@ +//! 3D objects as mesh files, for a 3D asset of Window › Asset Export (`assets.export3D`): OBJ with +//! its MTL materials, glTF 2.0 (one `.gltf` file, its buffer embedded as a data URI), USDA and +//! USDZ (the USDA layer in an uncompressed ZIP, its data on a 64-byte boundary). +//! +//! Each solid of the object ([`vectorcraft_render::effects::three_d_meshes`]) is its own mesh, with a +//! material in the color it is painted (solids of one color share it). Positions are y up and +//! about the point the object turns about: in points in OBJ and USD (whose layer says how many +//! meters a unit is), in meters in glTF, as its specification asks. glTF and USD colors are linear, +//! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since +//! an open solid or a turned plane is seen from both sides. +//! +//! Formats: glTF 2.0 , USD +//! (USDZ: ). + +use std::fmt::Write as _; + +use serde_json::{Value, json}; +use vectorcraft_render::effects::SolidMesh; + +/// The formats a 3D asset exports to, as `assets.set3DFormat` names them: USDA first, the default. +pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"]; +/// The format a new 3D asset exports to. +pub const DEFAULT_FORMAT_3D: &str = "usda"; +/// The meters in a point (1/72 inch). +const METERS_PER_POINT: f64 = 0.0254 / 72.0; + +/// The label of `format` for menus: `USDA`, `USDZ`, `glTF`, `OBJ`. +pub fn format_3d_label(format: &str) -> &'static str { + match format { + "usdz" => "USDZ", + "gltf" => "glTF", + "obj" => "OBJ", + _ => "USDA", + } +} + +/// `stem` as an OBJ file name: whitespace and `#` become `_`, so the `mtllib` line names the MTL +/// file as one word. +fn obj_stem(stem: &str) -> String { + stem.chars().map(|c| if c.is_whitespace() || c == '#' { '_' } else { c }).collect() +} + +/// The names of the files [`mesh_files`] writes for `stem` in `format`. +pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result, String> { + match format { + "obj" => { + let stem = obj_stem(stem); + Ok(vec![format!("{stem}.obj"), format!("{stem}.mtl")]) + } + "gltf" | "usda" | "usdz" => Ok(vec![format!("{stem}.{format}")]), + _ => { + let key = "format"; + Err(format!("`{key}` must be one of {}", FORMATS_3D.join(", "))) + } + } +} + +/// The files of a 3D object named `stem` in `format` ([`FORMATS_3D`]): `(file name, bytes)`, the +/// OBJ with its MTL after it. +pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result)>, String> { + let names = mesh_file_names(stem, format)?; + let bytes = match format { + "obj" => { + let (obj, mtl) = obj(&obj_stem(stem), parts); + vec![obj.into_bytes(), mtl.into_bytes()] + } + "gltf" => vec![gltf(stem, parts).into_bytes()], + "usda" => vec![usda(stem, parts).into_bytes()], + _ => vec![super::zip::store_aligned(&[(format!("{stem}.usda"), usda(stem, parts).into_bytes())], 64)?], + }; + Ok(names.into_iter().zip(bytes).collect()) +} + +/// The distinct colors of `parts` in order, and each part's index among them. +fn materials(parts: &[SolidMesh]) -> (Vec<[f32; 4]>, Vec) { + let mut colors: Vec<[f32; 4]> = vec![]; + let index = parts + .iter() + .map(|p| { + colors.iter().position(|c| *c == p.color).unwrap_or_else(|| { + colors.push(p.color); + colors.len() - 1 + }) + }) + .collect(); + (colors, index) +} + +/// An sRGB channel (0..1) as linear light. +fn linear(c: f32) -> f32 { + if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } +} + +/// A number as text: the shortest decimal that reads back as the same value. +fn num(v: f64) -> String { + format!("{v}") +} + +fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) { + let (colors, material) = materials(parts); + let mut o = String::new(); + let _ = writeln!(o, "mtllib {stem}.mtl"); + let _ = writeln!(o, "o {stem}"); + for p in parts { + for v in &p.mesh.positions { + let _ = writeln!(o, "v {} {} {}", num(v[0]), num(v[1]), num(v[2])); + } + } + for p in parts { + for n in &p.mesh.normals { + let _ = writeln!(o, "vn {} {} {}", num(n[0]), num(n[1]), num(n[2])); + } + } + let mut base = 1usize; + for (k, p) in parts.iter().enumerate() { + let _ = writeln!(o, "g Solid_{}", k + 1); + let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1); + for t in &p.mesh.triangles { + let [a, b, c] = t.map(|i| i as usize + base); + let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}"); + } + base += p.mesh.positions.len(); + } + let mut m = String::new(); + for (k, c) in colors.iter().enumerate() { + let _ = writeln!(m, "newmtl Material_{}", k + 1); + let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2]))); + let _ = writeln!(m, "d {}", num(f64::from(c[3]))); + let _ = writeln!(m, "illum 1"); + } + (o, m) +} + +fn gltf(stem: &str, parts: &[SolidMesh]) -> String { + let (colors, material) = materials(parts); + let mut buffer: Vec = vec![]; + let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]); + let mut view = |buffer: &mut Vec, bytes: Vec, target: u32| -> usize { + views.push(json!({ "buffer": 0, "byteOffset": buffer.len(), "byteLength": bytes.len(), "target": target })); + buffer.extend(bytes); + views.len() - 1 + }; + for (k, p) in parts.iter().enumerate() { + let floats = |v: &[[f64; 3]], scale: f64| v.iter().flatten().flat_map(|x| ((x * scale) as f32).to_le_bytes()).collect::>(); + let (lo, hi) = p.mesh.bounds().unwrap_or_default(); + let positions = view(&mut buffer, floats(&p.mesh.positions, METERS_PER_POINT), 34962); + let normals = view(&mut buffer, floats(&p.mesh.normals, 1.0), 34962); + let indices = view(&mut buffer, p.mesh.triangles.iter().flatten().flat_map(|i| i.to_le_bytes()).collect(), 34963); + let count = p.mesh.positions.len(); + let at = accessors.len(); + accessors.push(json!({ + "bufferView": positions, "componentType": 5126, "count": count, "type": "VEC3", + "min": lo.map(|v| (v * METERS_PER_POINT) as f32), "max": hi.map(|v| (v * METERS_PER_POINT) as f32), + })); + accessors.push(json!({ "bufferView": normals, "componentType": 5126, "count": count, "type": "VEC3" })); + accessors.push(json!({ "bufferView": indices, "componentType": 5125, "count": p.mesh.triangles.len() * 3, "type": "SCALAR" })); + primitives.push(json!({ + "attributes": { "POSITION": at, "NORMAL": at + 1 }, + "indices": at + 2, + "material": material.get(k).copied().unwrap_or(0), + })); + } + let materials: Vec = colors + .iter() + .enumerate() + .map(|(k, c)| { + let mut m = json!({ + "name": format!("Material_{}", k + 1), + "pbrMetallicRoughness": { + "baseColorFactor": [linear(c[0]), linear(c[1]), linear(c[2]), c[3]], + "metallicFactor": 0.0, + "roughnessFactor": 1.0, + }, + "doubleSided": true, + }); + if c[3] < 1.0 { + m["alphaMode"] = json!("BLEND"); + } + m + }) + .collect(); + let doc = json!({ + "asset": { "version": "2.0", "generator": "VectorCraft" }, + "scene": 0, + "scenes": [{ "nodes": [0] }], + "nodes": [{ "name": stem, "mesh": 0 }], + "meshes": [{ "name": stem, "primitives": primitives }], + "materials": materials, + "buffers": [{ + "byteLength": buffer.len(), + "uri": format!("data:application/octet-stream;base64,{}", vectorcraft_format::base64_encode(&buffer)), + }], + "bufferViews": views, + "accessors": accessors, + }); + serde_json::to_string_pretty(&doc).unwrap_or_default() +} + +/// `name` as a USD prim name: letters, digits and `_`, not starting with a digit. +fn prim_name(name: &str) -> String { + let mut out: String = name.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect(); + if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) { + out.insert(0, '_'); + } + out +} + +fn usda(stem: &str, parts: &[SolidMesh]) -> String { + let (colors, material) = materials(parts); + let root = prim_name(stem); + let triple = |v: [f64; 3]| format!("({}, {}, {})", num(v[0]), num(v[1]), num(v[2])); + let list = |items: Vec| items.join(", "); + let mut u = String::new(); + let _ = writeln!(u, "#usda 1.0"); + let _ = writeln!(u, "(\n defaultPrim = \"{root}\"\n metersPerUnit = {}\n upAxis = \"Y\"\n)\n", METERS_PER_POINT); + let _ = writeln!(u, "def Xform \"{root}\"\n{{"); + for (k, p) in parts.iter().enumerate() { + let (lo, hi) = p.mesh.bounds().unwrap_or_default(); + let m = material.get(k).copied().unwrap_or(0) + 1; + let _ = writeln!(u, " def Mesh \"Solid_{}\" (\n prepend apiSchemas = [\"MaterialBindingAPI\"]\n )\n {{", k + 1); + let _ = writeln!(u, " uniform bool doubleSided = 1"); + let _ = writeln!(u, " float3[] extent = [{}, {}]", triple(lo), triple(hi)); + let _ = writeln!(u, " int[] faceVertexCounts = [{}]", list(vec!["3".to_string(); p.mesh.triangles.len()])); + let _ = writeln!(u, " int[] faceVertexIndices = [{}]", list(p.mesh.triangles.iter().flatten().map(u32::to_string).collect())); + let _ = writeln!(u, " rel material:binding = "); + let _ = writeln!( + u, + " normal3f[] normals = [{}] (\n interpolation = \"vertex\"\n )", + list(p.mesh.normals.iter().map(|n| triple(*n)).collect()) + ); + let _ = writeln!(u, " point3f[] points = [{}]", list(p.mesh.positions.iter().map(|v| triple(*v)).collect())); + let c = p.color; + let _ = writeln!( + u, + " color3f[] primvars:displayColor = [({}, {}, {})] (\n interpolation = \"constant\"\n )", + linear(c[0]), + linear(c[1]), + linear(c[2]) + ); + let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]); + let _ = writeln!(u, " uniform token subdivisionScheme = \"none\"\n }}\n"); + } + let _ = writeln!(u, " def Scope \"Materials\"\n {{"); + for (k, c) in colors.iter().enumerate() { + let m = k + 1; + let _ = writeln!(u, " def Material \"Material_{m}\"\n {{"); + let _ = writeln!(u, " token outputs:surface.connect = \n"); + let _ = writeln!(u, " def Shader \"Surface\"\n {{"); + let _ = writeln!(u, " uniform token info:id = \"UsdPreviewSurface\""); + let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2])); + let _ = writeln!(u, " float inputs:opacity = {}", c[3]); + let _ = writeln!(u, " float inputs:roughness = 1"); + let _ = writeln!(u, " token outputs:surface\n }}\n }}"); + } + let _ = writeln!(u, " }}\n}}"); + u +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/fileio/mesh3d/tests.rs b/crates/engine/src/cmd/fileio/mesh3d/tests.rs new file mode 100644 index 0000000000..7c467fafad --- /dev/null +++ b/crates/engine/src/cmd/fileio/mesh3d/tests.rs @@ -0,0 +1,130 @@ +use serde_json::Value; +use vectorcraft_render::effects::{Mesh, SolidMesh}; + +use super::*; + +/// A 10 × 10 square facing the viewer: two triangles, each with corners of its own. +fn square(color: [f32; 4]) -> SolidMesh { + let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]]; + let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] }; + SolidMesh { mesh, color } +} + +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 0.5]; + +fn text(files: &[(String, Vec)], name: &str) -> String { + let (_, bytes) = files.iter().find(|(n, _)| n == name).unwrap_or_else(|| panic!("no {name}")); + String::from_utf8(bytes.clone()).unwrap() +} + +#[test] +fn obj_numbers_corners_across_solids_and_names_its_materials() { + let files = mesh_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap(); + assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box.obj", "Box.mtl"]); + let obj = text(&files, "Box.obj"); + assert!(obj.starts_with("mtllib Box.mtl\no Box\n")); + assert_eq!(obj.lines().filter(|l| l.starts_with("v ")).count(), 18); + assert_eq!(obj.lines().filter(|l| l.starts_with("vn ")).count(), 18); + // The third solid's last triangle uses corners 13 to 18; red solids share Material_1. + assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 16//16 17//17 18//18")); + assert_eq!(obj.lines().filter(|l| l.starts_with("usemtl ")).collect::>(), ["usemtl Material_1", "usemtl Material_2", "usemtl Material_1"]); + let mtl = text(&files, "Box.mtl"); + assert_eq!(mtl.matches("newmtl").count(), 2); + assert!(mtl.contains("newmtl Material_2\nKd 0 0 1\nd 0.5\n"), "{mtl}"); +} + +#[test] +fn gltf_holds_its_buffer_and_every_accessor_fits_it() { + let files = mesh_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap(); + let g: Value = serde_json::from_str(&text(&files, "Box.gltf")).unwrap(); + assert_eq!(g["asset"]["version"], "2.0"); + let uri = g["buffers"][0]["uri"].as_str().unwrap(); + let data = vectorcraft_format::base64_decode(uri.strip_prefix("data:application/octet-stream;base64,").unwrap()).unwrap(); + assert_eq!(g["buffers"][0]["byteLength"].as_u64(), Some(data.len() as u64)); + for v in g["bufferViews"].as_array().unwrap() { + assert!(v["byteOffset"].as_u64().unwrap() + v["byteLength"].as_u64().unwrap() <= data.len() as u64); + assert_eq!(v["byteOffset"].as_u64().unwrap() % 4, 0); + } + let prims = g["meshes"][0]["primitives"].as_array().unwrap(); + assert_eq!(prims.len(), 2); + assert_eq!((prims[0]["material"].as_u64(), prims[1]["material"].as_u64()), (Some(0), Some(1))); + // Positions are meters: the 10 pt square is 10/72 inch across. + let pos = &g["accessors"][prims[0]["attributes"]["POSITION"].as_u64().unwrap() as usize]; + let width = pos["max"][0].as_f64().unwrap() - pos["min"][0].as_f64().unwrap(); + assert!((width - 10.0 * 0.0254 / 72.0).abs() < 1e-7, "{width}"); + let index = &g["accessors"][prims[0]["indices"].as_u64().unwrap() as usize]; + assert_eq!((index["componentType"].as_u64(), index["count"].as_u64()), (Some(5125), Some(6))); + // Translucent paint blends; colors are linear. + assert_eq!(g["materials"][1]["alphaMode"], "BLEND"); + assert!(g["materials"][0].get("alphaMode").is_none()); + assert_eq!(g["materials"][0]["doubleSided"], true); +} + +#[test] +fn usda_is_y_up_in_points_with_a_material_for_each_color() { + let files = mesh_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap(); + let u = text(&files, "My Box.usda"); + assert!(u.starts_with("#usda 1.0\n")); + assert!(u.contains("defaultPrim = \"My_Box\"") && u.contains("upAxis = \"Y\"") && u.contains("def Xform \"My_Box\""), "{u}"); + assert!(u.contains(&format!("metersPerUnit = {}", 0.0254 / 72.0))); + assert_eq!(u.matches("def Mesh").count(), 2); + assert_eq!(u.matches("def Material").count(), 2); + assert!(u.contains("int[] faceVertexCounts = [3, 3]")); + assert!(u.contains("rel material:binding = ")); + // sRGB 0.5 is about 0.214 linear. + assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}"); + assert_eq!(u.matches('{').count(), u.matches('}').count()); +} + +#[test] +fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() { + let files = mesh_files("Box", "usdz", &[square(RED)]).unwrap(); + let (name, zip) = &files[0]; + assert_eq!(name, "Box.usdz"); + // The local header: 30 bytes, the name, then the extra field. + let u16_at = |at: usize| u16::from_le_bytes([zip[at], zip[at + 1]]) as usize; + assert_eq!(&zip[..4], &[0x50, 0x4b, 0x03, 0x04]); + assert_eq!(u16_at(8), 0, "stored, not deflated"); + let start = 30 + u16_at(26) + u16_at(28); + assert_eq!(start % 64, 0); + let layer = mesh_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1; + assert_eq!(&zip[start..start + layer.len()], layer.as_slice()); + let archive = super::super::zip::Archive::open(zip, 8).unwrap(); + assert_eq!(archive.read("Box.usda", usize::MAX).unwrap(), Some(layer)); +} + +#[test] +fn an_obj_names_its_mtl_file_without_spaces_or_comment_marks() { + let files = mesh_files("Box #1", "obj", &[square(RED)]).unwrap(); + assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box__1.obj", "Box__1.mtl"]); + assert!(text(&files, "Box__1.obj").starts_with("mtllib Box__1.mtl\n")); + assert_eq!(mesh_file_names("Box #1", "obj").unwrap(), ["Box__1.obj", "Box__1.mtl"]); + assert_eq!(mesh_file_names("Box #1", "usda").unwrap(), ["Box #1.usda"]); +} + +#[test] +fn obj_and_usda_keep_coordinates_a_32_bit_float_would_merge() { + let mut part = square(RED); + part.mesh.positions[0] = [20_000_000.0, 0.0, 0.0]; + part.mesh.positions[1] = [20_000_001.0, 0.0, 0.0]; + let obj = text(&mesh_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj"); + assert!(obj.contains("v 20000000 0 0\nv 20000001 0 0\n"), "{obj}"); + let usda = text(&mesh_files("Box", "usda", &[part]).unwrap(), "Box.usda"); + assert!(usda.contains("(20000001, 0, 0)")); +} + +#[test] +fn an_unknown_format_is_refused() { + assert!(mesh_files("Box", "fbx", &[square(RED)]).is_err()); + assert!(mesh_file_names("Box", "").is_err()); + assert_eq!(mesh_file_names("Box", "obj").unwrap(), ["Box.obj", "Box.mtl"]); +} + +#[test] +fn prim_names_are_usd_identifiers() { + assert_eq!(prim_name("Logo 2"), "Logo_2"); + assert_eq!(prim_name("3D"), "_3D"); + assert_eq!(prim_name(""), "_"); + assert_eq!(prim_name("é/x"), "__x"); +} diff --git a/crates/engine/src/cmd/fileio/naming.rs b/crates/engine/src/cmd/fileio/naming.rs index 9e18e8212e..12cf26ca0b 100644 --- a/crates/engine/src/cmd/fileio/naming.rs +++ b/crates/engine/src/cmd/fileio/naming.rs @@ -70,9 +70,11 @@ pub fn render(template: &str, p: &NameParts<'_>) -> String { let mut out = String::with_capacity(t.len() + 16); let mut rest = t; while let Some(c) = rest.chars().next() { - // Bracketed tokens; an unknown one stays as written, with `-` for its brackets. + // Bracketed tokens; an unknown one stays as written, with `-` for its brackets. A token's + // name has no `<`, so the search for its `>` stops at the next `<`: each part of the + // pattern is searched once, not once for every `<` before it. if c == '<' - && let Some(end) = rest.find('>') + && let Some(end) = rest.get(1..).and_then(|r| r.find(['<', '>'])).map(|i| i + 1).filter(|&i| rest.as_bytes().get(i) == Some(&b'>')) && let Some(value) = rest.get(1..end).and_then(|name| token(name, p)) { out.push_str(&value); @@ -100,13 +102,19 @@ pub fn render(template: &str, p: &NameParts<'_>) -> String { /// `YYYY-MM-DD` (or `YYYYMMDD`) as `[year, month, day, 0, 0, 0]`; `None` when it isn't a date. pub fn parse_date(s: &str) -> Option<[i64; 6]> { - let digits: String = s.trim().chars().filter(|c| *c != '-').collect(); + let s = s.trim(); + let digits: String = match s.len() { + 8 => s.to_string(), + 10 if s.as_bytes()[4] == b'-' && s.as_bytes()[7] == b'-' => s.chars().filter(|c| *c != '-').collect(), + _ => return None, + }; if digits.len() != 8 || !digits.bytes().all(|b| b.is_ascii_digit()) { return None; } let num = |a: usize, b: usize| digits.get(a..b).and_then(|t| t.parse::().ok()); let (y, m, d) = (num(0, 4)?, num(4, 6)?, num(6, 8)?); - ((1..=12).contains(&m) && (1..=31).contains(&d)).then_some([y, m, d, 0, 0, 0]) + chrono::NaiveDate::from_ymd_opt(i32::try_from(y).ok()?, u32::try_from(m).ok()?, u32::try_from(d).ok()?)?; + Some([y, m, d, 0, 0, 0]) } #[cfg(test)] @@ -149,6 +157,24 @@ mod tests { assert_eq!(render("#", &NameParts { counter: 12345, ..parts() }), "12345"); } + /// Many `<` without a `>`, or before one far away, are each looked at once. + #[test] + fn unmatched_brackets_are_read_in_one_pass() { + let p = parts(); + let n = 200_000; + assert_eq!(render(&"<".repeat(n), &p), "-".repeat(n)); + assert_eq!(render(&format!("{}", "<".repeat(n)), &p), format!("{}Dark", "-".repeat(n))); + assert_eq!(render(">", &p), "-aDark-"); + } + + #[test] + fn dates_are_strict_about_hyphens_and_days() { + for bad in ["2026-1-011", "2-0-2-6-1-0-1-6", "2026--10--16", "2026-02-31", "2026-10-16-", "202610-16"] { + assert_eq!(parse_date(bad), None, "{bad}"); + } + assert_eq!(parse_date("2024-02-29"), Some([2024, 2, 29, 0, 0, 0])); + } + #[test] fn dates_parse() { assert_eq!(parse_date("2026-10-16"), Some([2026, 10, 16, 0, 0, 0])); diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index d7dbbe5a69..4e2e9a85fd 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -35,6 +35,12 @@ pub const OPTIONS: &[FormatOption] = &[ default: "false", description: "embed a PNG preview of the first artboard (at most 256 pixels on its longer side) for file browsers", }, + FormatOption { + name: "precision", + ty: "integer", + default: "null", + description: "round path anchors and handles to this many decimal places, 0 to 9 (a smaller file; colors, transforms and type are kept exactly); null writes them exactly. Only the save that gives it rounds", + }, SEPARATE_ARTBOARDS, SEPARATE_RANGE, INCLUDE_LINKED, @@ -42,7 +48,7 @@ pub const OPTIONS: &[FormatOption] = &[ FormatOption { name: "pdfCompatible", ty: "boolean", - default: "false", + default: "true", description: "also carry a PDF of every artboard, for apps that read PDF (a larger file)", }, ]; @@ -99,6 +105,12 @@ pub const AI_OPTIONS: &[FormatOption] = &[ default: "true", description: "compress the PDF's content and the native document it carries (the PDF option compression.compressText)", }, + FormatOption { + name: "editingData", + ty: "boolean", + default: "true", + description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, linear and radial gradients, patterns on a grid of tiles, swatches, artboards and which one is active, the transparency of objects and layers, objects' opacity masks, clipping groups and layers clipped by a path, embedded images with their pixels, linked images as placed files with a preview, point type, area type and type on a path as text, and symbols and their instances, with other type, other patterns, other clipping objects, other symbol instances and live objects as plain filled and stroked paths, freeform gradients, gradients along or across a stroke and gradients of more than 256 stops as their average color, gradients that dither or mix perceptually as classic ones, and gradient stops linked to global process colors as their colors (written only with every artboard, as Preserve Editing is)", + }, FormatOption { name: "aiVersion", ty: "string", @@ -109,7 +121,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[ name: "transparentImages", ty: "string", default: "\"flatten\"", - description: "with aiVersion 7, the images version 7 can't hold (see-through pixels, opacity or a blending mode): flatten (the default: each becomes an opaque image of itself and the art under it, clipped to where it changes what shows; that art stays as it is) or omit (left out)", + description: "with aiVersion 7, the images version 7 can't hold (see-through pixels, opacity, a blending mode, or a colorize color unless every pixel is black or white): flatten (the default: each becomes an opaque image of itself and the art under it, clipped to where it changes what shows; that art stays as it is) or omit (left out)", }, FormatOption { name: "hiddenObjects", @@ -121,7 +133,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[ name: "outlineText", ty: "boolean", default: "false", - description: "with aiVersion 7, type as its outlines instead of text (which apps reading the file set in the fonts it names: they need them installed); type 8-bit text can't hold (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is always outlines", + description: "with aiVersion 7, type as its outlines instead of text (which apps reading the file set in the fonts it names: they need them installed); type 8-bit text can't hold (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) and type with rotated characters are always outlines", }, ]; @@ -131,9 +143,10 @@ struct NativeOptions { compress: Option, version: Option, preview: bool, + precision: Option, include_linked: bool, embed_profiles: Option, - pdf_compatible: bool, + pdf_compatible: Option, } /// What [`save_options`] leaves to [`encode`] (rendering and encoding take time). @@ -151,13 +164,30 @@ pub(super) fn save_options(cmd: &str, f: &Format, doc: &Document, p: &Value) -> compress: o.compress.unwrap_or(false), version: o.version.unwrap_or(vectorcraft_format::VERSION), include_linked: o.include_linked, + precision: o.precision.map(|v| precision(cmd, &v)).transpose()?, ..SaveOptions::default() }; if o.embed_profiles.unwrap_or(true) { so.profiles = embedded_profiles(doc); } so.check().map_err(|e| bad(cmd, e.to_string()))?; - Ok((so, Extras { preview: o.preview, pdf: o.pdf_compatible })) + let pdf = o.pdf_compatible.unwrap_or(true); + so.pdf_compatible = Some(pdf); + Ok((so, Extras { preview: o.preview, pdf })) +} + +/// The `precision` option `v`: a whole number of decimal places, 0 to +/// [`vectorcraft_format::MAX_PRECISION`]. Any other value, a string included, gets the range message. +fn precision(cmd: &str, v: &Value) -> Result { + let (key, min, max) = ("precision", 0u8, vectorcraft_format::MAX_PRECISION); + if let Some(x) = v.as_f64() + && x.fract() == 0.0 + && (f64::from(min)..=f64::from(max)).contains(&x) + { + return Ok(x as u8); + } + let x = v.as_f64().map_or_else(|| v.to_string(), |x| x.to_string()); + Err(bad(cmd, format!("`{key}` must be a whole number between {min} and {max} (got {x})"))) } /// The `.vectorcraft` file of `doc` with the options in `p`. @@ -177,13 +207,21 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp } else { std::borrow::Cow::Borrowed(doc) }; + // With a precision, the preview and PDF show the rounded art the file holds. + let drawn = match so.precision { + Some(decimals) if extras.preview || extras.pdf => Cow::Owned(rounded(&full, so.version, decimals)), + _ => Cow::Borrowed(full.as_ref()), + }; if extras.preview { - so.preview = preview_png(&full)?; + so.preview = preview_png(&drawn)?; } - if extras.pdf { - // Every artboard as PDF pages (no editing data: the file is the native document). - so.pdf = Some(super::pdf::encode(cmd, &full, &json!({ "range": "all", "preserveEditing": false }))?.0); + if extras.pdf && !drawn.artboards.is_empty() { + // Every artboard as PDF pages (no editing data: the file is the native document), dated by + // the document's File Info, so the same document and dates give the same bytes. + let at = drawn.metadata.modified.or(drawn.metadata.created); + so.pdf = Some(super::pdf::encode_at(cmd, &drawn, &json!({ "range": "all", "preserveEditing": false }), at)?.0); } + drop(drawn); let native = match full { Cow::Owned(full) if so.include_linked && so.version >= vectorcraft_format::VERSION => { // Include available bytes without replacing missing, relinkable placed objects. @@ -197,6 +235,20 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string())) } +/// `doc` with its path geometry rounded to `decimals` places, as [`vectorcraft_format::save_to`] +/// writes it for `version`: placed documents become groups of their art for older versions. +fn rounded(doc: &Document, version: u32, decimals: u8) -> Document { + let mut d = if version < vectorcraft_format::VERSION && doc.has_placed() { + let mut d = doc.with_placed_art().into_owned(); + d.placed_as_groups(); + d + } else { + doc.clone() + }; + d.round_geometry(decimals.min(vectorcraft_format::MAX_PRECISION)); + d +} + /// The ICC files of the profiles `doc` is tagged with that were loaded from files (the built-in /// ones are there wherever VectorCraft runs). fn embedded_profiles(doc: &Document) -> BTreeMap> { @@ -230,8 +282,8 @@ pub(super) fn ai_options(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Re let mut q = p.clone(); if let Some(o) = q.as_object_mut() { // AI carries the current native format without a separate preview. Its compression - // and PDF-content flags are still validated as booleans. - o.retain(|k, _| !matches!(k.as_str(), "version" | "preview")); + // and PDF-content flags are still validated as booleans. Its coordinates are written exactly. + o.retain(|k, _| !matches!(k.as_str(), "version" | "preview" | "precision")); if o.get("pdfCompatible").is_some_and(Value::is_null) { o.remove("pdfCompatible"); } diff --git a/crates/engine/src/cmd/fileio/pcxread.rs b/crates/engine/src/cmd/fileio/pcxread.rs new file mode 100644 index 0000000000..aabbbc2642 --- /dev/null +++ b/crates/engine/src/cmd/fileio/pcxread.rs @@ -0,0 +1,166 @@ +//! Reading PCX files (`.pcx`) for File › Open and File › Place, from the ZSoft PCX Technical +//! Reference Manual (release 5). [`is_pcx`] recognizes a file by the first fields of its 128-byte +//! header, and [`decode`] reads its run-length encoded scan lines into RGBA pixels: 1-bit with two +//! colors; 1-bit in two to four planes and 4-bit with up to 16 colors; 2-bit CGA pictures in the +//! four colors their CGA palette settings pick; 8-bit with the +//! 256-color palette after the image data (gray levels without one); and 24-bit color in three +//! 8-bit planes. The file is untrusted: every read is checked. + +/// The size of the header, after which the image data starts. +const HEADER: usize = 128; + +/// The message for a file whose header or image data ends early. +const TRUNCATED: &str = "the PCX file is cut short"; + +/// The message for a header whose window or line length can't hold its image. +const DAMAGED: &str = "the PCX file's header is damaged"; + +/// The 16 colors of the EGA palette, which files of versions 0 and 3 use instead of the header's. +const EGA: [[u8; 3]; 16] = [ + [0x00, 0x00, 0x00], + [0x00, 0x00, 0xaa], + [0x00, 0xaa, 0x00], + [0x00, 0xaa, 0xaa], + [0xaa, 0x00, 0x00], + [0xaa, 0x00, 0xaa], + [0xaa, 0x55, 0x00], + [0xaa, 0xaa, 0xaa], + [0x55, 0x55, 0x55], + [0x55, 0x55, 0xff], + [0x55, 0xff, 0x55], + [0x55, 0xff, 0xff], + [0xff, 0x55, 0x55], + [0xff, 0x55, 0xff], + [0xff, 0xff, 0x55], + [0xff, 0xff, 0xff], +]; + +/// Does `bytes` start with a PCX header? The manufacturer byte is `0x0A`, the version 0, 2, 3, 4 +/// or 5, the encoding 1 (run-length) and the bits per pixel of each plane 1, 2, 4 or 8. +pub(super) fn is_pcx(bytes: &[u8]) -> bool { + matches!(bytes, [0x0a, 0 | 2 | 3 | 4 | 5, 1, 1 | 2 | 4 | 8, ..]) +} + +/// The resolution in the header's HDpi and VDpi fields; `None` when either is 0 or the header is +/// cut short. +pub(super) fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { + let le = |at: usize| Some(u16::from_le_bytes([*bytes.get(at)?, *bytes.get(at + 1)?])); + let (x, y) = (le(12)?, le(14)?); + (x > 0 && y > 0).then(|| (f64::from(x), f64::from(y))) +} + +/// The pixels of PCX file `bytes`, which [`is_pcx`] accepts, refused when they or the decoded +/// scan lines take more than `max_alloc` bytes (the pixels counted as RGBA) before anything is +/// decoded. +pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result { + let head = bytes.get(..HEADER).ok_or(TRUNCATED)?; + let le = |at: usize| usize::from(u16::from_le_bytes([head[at], head[at + 1]])); + let (version, bits, planes) = (head[1], head[3], head[65]); + let (x_min, y_min, x_max, y_max) = (le(4), le(6), le(8), le(10)); + let line = le(66); + if !matches!((bits, planes), (1, 1..=4) | (2 | 4, 1) | (8, 1 | 3)) { + return Err(format!("PCX files with {bits}-bit pixels in {planes} planes can't be read")); + } + if x_max < x_min || y_max < y_min { + return Err(DAMAGED.into()); + } + let (w, h) = (x_max - x_min + 1, y_max - y_min + 1); + // Each plane's line holds the row's pixels, padded to an even number of bytes. + if line * 8 < w * usize::from(bits) { + return Err(DAMAGED.into()); + } + let scan = line * usize::from(planes); + let rgba = w as u64 * h as u64 * 4; + if rgba > max_alloc || scan as u64 * h as u64 > max_alloc { + return Err(format!("an image of {w} × {h} pixels is too large to draw")); + } + // An 8-bit image's 256-color palette is its last 769 bytes, `0x0C` and then the colors; the + // image data ends before it. A `0x0C` there is image data instead when the image data runs to + // the end of the file. + let candidate = bytes.len().checked_sub(769).filter(|at| *at >= HEADER && (bits, planes) == (8, 1) && bytes.get(*at) == Some(&0x0c)); + let body = bytes.get(HEADER..).unwrap_or_default(); + let (tail, decoded) = match candidate { + Some(at) => match unpack(body, scan * h) { + Ok((data, used)) if used == body.len() => (None, Ok((data, used))), + _ => (Some(at), unpack(bytes.get(HEADER..at).unwrap_or_default(), scan * h)), + }, + None => (None, unpack(body, scan * h)), + }; + let (data, used) = decoded?; + // A palette marker right after the image data with fewer than 768 colors after it is a palette + // cut short. + let after = bytes.get(HEADER + used..).unwrap_or_default(); + if tail.is_none() && (bits, planes) == (8, 1) && after.first() == Some(&0x0c) && after.len() < 769 { + return Err(TRUNCATED.into()); + } + let palette: Vec<[u8; 3]> = match (bits, planes) { + (8, 1) => match tail.and_then(|at| bytes.get(at + 1..)) { + Some(colors) => colors.as_chunks::<3>().0.to_vec(), + None => (0..=255).map(|v| [v; 3]).collect(), + }, + // A 1-bit image takes the header palette's first two colors; versions without a palette, + // and headers whose two colors are the same (left unset), give black and white. + (1, 1) if matches!(version, 0 | 3) || head[16..19] == head[19..22] => vec![[0; 3], [255; 3]], + // A 2-bit image is a CGA picture, whose header holds CGA palette settings instead of colors. + (2, 1) => cga(head[16], head[19]), + _ if matches!(version, 0 | 3) => EGA.to_vec(), + _ => head[16..64].as_chunks::<3>().0.to_vec(), + }; + let mut img = image::RgbaImage::new(w as u32, h as u32); + for (y, row) in data.chunks_exact(scan).enumerate() { + let plane = |p: usize| row.get(p * line..(p + 1) * line).unwrap_or_default(); + for x in 0..w { + let rgb = if bits == 8 && planes == 3 { + [0, 1, 2].map(|p| plane(p).get(x).copied().unwrap_or(0)) + } else { + // Plane p gives bits p × bits and up of the color index. + let index = (0..usize::from(planes)).fold(0, |index, p| { + let at = x * usize::from(bits); + let byte = plane(p).get(at / 8).copied().unwrap_or(0); + let value = (byte >> (8 - usize::from(bits) - at % 8)) & (0xff >> (8 - bits)); + index | usize::from(value) << (p * usize::from(bits)) + }); + palette.get(index).copied().unwrap_or([0; 3]) + }; + img.put_pixel(x as u32, y as u32, image::Rgba([rgb[0], rgb[1], rgb[2], 255])); + } + } + Ok(img) +} + +/// The four colors of a CGA picture from header bytes 16 and 19. The top four bits of `background` +/// are the EGA color of index 0. The top three bits of `settings` are the color burst, palette and +/// intensity bits (C, P, I), which pick the other three: with color burst on (C = 0), P = 0 gives +/// green, red and brown and P = 1 gives cyan, magenta and light gray; with it off (C = 1) they are +/// cyan, red and light gray. I = 1 gives the bright version of each (brown becomes yellow). +fn cga(background: u8, settings: u8) -> Vec<[u8; 3]> { + let foreground: [usize; 3] = match settings >> 6 { + 0 => [2, 4, 6], + 1 => [3, 5, 7], + _ => [3, 4, 7], + }; + let bright = if settings & 0x20 != 0 { 8 } else { 0 }; + let ega = |i: usize| EGA.get(i).copied().unwrap_or([0; 3]); + let mut colors = vec![ega(usize::from(background >> 4))]; + colors.extend(foreground.map(|i| ega(i + bright))); + colors +} + +/// `len` bytes of run-length encoded image data: a byte with its top two bits set repeats the +/// next byte as many times as its other six bits count, and any other byte stands for itself. +/// Runs may cross the end of a scan line. Also returns how many bytes of `data` were read. +fn unpack(data: &[u8], len: usize) -> Result<(Vec, usize), String> { + let mut out = Vec::with_capacity(len); + let mut bytes = data.iter(); + while out.len() < len { + let &b = bytes.next().ok_or(TRUNCATED)?; + if b & 0xc0 == 0xc0 { + let &v = bytes.next().ok_or(TRUNCATED)?; + let n = usize::from(b & 0x3f).min(len - out.len()); + out.resize(out.len() + n, v); + } else { + out.push(b); + } + } + Ok((out, data.len() - bytes.len())) +} diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 7902a0fed1..2387088b3f 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -21,7 +21,7 @@ const C: &str = "document.exportPdf"; pub use vectorcraft_pdf::DEFAULT_PRESET; /// The PDF options `document.formats` lists; `document.exportPdf` documents every field. -pub(super) const OPTIONS: &[FormatOption] = &[ +pub(crate) const OPTIONS: &[FormatOption] = &[ super::ARTBOARD, super::ARTBOARDS, super::RANGE, @@ -50,13 +50,26 @@ pub(super) const OPTIONS: &[FormatOption] = &[ default: "true", description: "embed the native document so VectorCraft reopens the PDF editable (the default preset's choice)", }, + FormatOption { name: "thumbnails", ty: "boolean", default: "false", description: "each page drawn as a /Thumb image, 106 px on its long side" }, + FormatOption { + name: "fastWebView", + ty: "boolean", + default: "false", + description: "a linearized file: the first page shows while the rest downloads", + }, + FormatOption { + name: "viewAfterSaving", + ty: "boolean", + default: "false", + description: "in the desktop app's document.exportPdf, the written file opens in the system viewer", + }, FormatOption { name: "compression", ty: "object", default: "null", description: "{color, gray, mono, compressText} (see document.exportPdf)" }, FormatOption { name: "marks", ty: "object", default: "null", description: "printer's marks (see document.exportPdf)" }, FormatOption { name: "bleed", ty: "object", default: "null", - description: "{useDocument, top, bottom, left, right} in points: the page grows by the bleed (BleedBox) around its artboard (TrimBox)", + description: "{useDocument, top, bottom, left, right} in points: the page grows by the bleed (BleedBox) around its artboard (TrimBox); a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning", }, FormatOption { name: "output", @@ -109,7 +122,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), @@ -118,7 +131,7 @@ pub fn specs() -> Vec { "PDF Settings", [], None, - "{preset?, includeDocument?: false, …options of document.exportPdf} → {settings (the preset with the options applied), presets: [name…], changed: [{option: \"compression.compressText\", value}] (what differs from the preset), warnings}; includeDocument also exports the active document in memory and adds its warnings (knockout groups approximated, effects left out…)", + "{preset?, includeDocument?: false, …options of document.exportPdf} → {settings (the preset with the options applied), presets: [name…], changed: [{option: \"compression.compressText\", value}] (what differs from the preset), warnings}; includeDocument also exports the active document in memory and adds its warnings (knockout groups approximated, effects left out…). A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", always, pdf_settings ), @@ -240,9 +253,13 @@ pub fn expand_preset<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result Result { + options_at(cmd, doc, p, vectorcraft_doc::metadata::output_time()) +} + +/// [`options`] modified at `now` (Unix seconds) instead of the time of writing. +fn options_at(cmd: &str, doc: &Document, p: &Value, now: Option) -> Result { let pick = if p.is_object() { ArtboardPick::deserialize(p).map_err(|e| bad(cmd, format!("PDF options: {e}")))? } else { ArtboardPick::default() }; let artboards = pick.resolve(doc.artboards.len()).map_err(|e| bad(cmd, e))?; - let now = vectorcraft_doc::metadata::output_time(); Ok(PdfOptions { settings: settings(cmd, p)?, artboards, @@ -257,13 +274,22 @@ pub fn options(cmd: &str, doc: &Document, p: &Value) -> Result { pub const EDITING_NEEDS_EVERY_ARTBOARD: &str = "Preserve editing was left out: it needs a PDF of every artboard, in order (reopened, this one would show the others too)"; +/// The warning for a PDF/X file that leaves out the document's bleed +/// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]). +pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings"; + /// Encode `doc` as PDF with the options in `p` → (bytes, warnings). Raster effects are rendered /// to images at the document's raster effects resolution. Preserve Editing embeds `doc` itself /// when the PDF has every artboard (a PDF of some reopens as just those). pub fn encode(cmd: &str, doc: &Document, p: &Value) -> Result<(Vec, Vec)> { + encode_at(cmd, doc, p, None) +} + +/// [`encode`] modified at `modified` (Unix seconds) when given, instead of the time of writing. +pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option) -> Result<(Vec, Vec)> { // Keep the editable object tree independent of preview fallbacks used by the drawn pages. let (full, mut warnings) = crate::cmd::place::document::full_documents(doc); - let (bytes, drawn_warnings) = encode_carrying(cmd, &full, p, || Ok(vectorcraft_format::save(doc, false)))?; + let (bytes, drawn_warnings) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?; warnings.extend(drawn_warnings); warnings.extend(overflow_warning(cmd, &full, p)?); Ok((bytes, warnings)) @@ -281,16 +307,48 @@ fn overflow_warning(cmd: &str, doc: &Document, p: &Value) -> Result Result>) -> Result<(Vec, Vec)> { - let mut opts = options(cmd, doc, p)?; +/// native document with its save options, whose pages may be left blank), and `private()`, the +/// editing copy of the art for other apps with what it couldn't hold, on every page. +pub(super) fn encode_carrying( + cmd: &str, + doc: &Document, + p: &Value, + native: impl FnOnce() -> Result>, + private: impl FnOnce() -> Result)>>, +) -> Result<(Vec, Vec)> { + encode_carrying_at(cmd, doc, p, None, native, private) +} + +/// [`encode_carrying`] modified at `modified` (Unix seconds) when given, instead of the time of +/// writing. +fn encode_carrying_at( + cmd: &str, + doc: &Document, + p: &Value, + modified: Option, + native: impl FnOnce() -> Result>, + private: impl FnOnce() -> Result)>>, +) -> Result<(Vec, Vec)> { + let mut opts = options_at(cmd, doc, p, modified.or_else(vectorcraft_doc::metadata::output_time))?; + // The pages' background colors, behind the art (the editing data keeps them as colors). + let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect()); + let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?; + let doc = &*filled; if opts.settings.thumbnails { opts.thumbnails = thumbnails(doc, &opts).map_err(|e| pdf_error(cmd, e))?; } let mut warnings = vec![]; + // The status bar shows the first warning, so this one goes ahead of the flattening note. + if opts.settings.leaves_out_bleed(doc) { + warnings.push(BLEED_LEFT_OUT.to_string()); + } if opts.settings.preserve_editing { if opts.artboards.as_ref().is_none_or(|v| v.iter().copied().eq(0..doc.artboards.len())) { opts.native = Some(native()?); + if let Some((data, lost)) = private()? { + opts.private_data = Some(data); + warnings.extend(lost); + } } else { opts.settings.preserve_editing = false; warnings.push(EDITING_NEEDS_EVERY_ARTBOARD.to_string()); @@ -317,9 +375,9 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution"; /// `doc` with its transparency flattened for a PDF 1.3 file (asked for, or PDF/X-1a and PDF/X-3, /// whose files have none), with `flattenerPreset` (default High Resolution) and `p`'s `flattener` -/// options over it; images with see-through pixels count as transparency, rasterized areas are -/// clipped to their regions, and discarded overprints are dropped. `None` when nothing changes (or -/// the file keeps transparency). +/// options over it; images with see-through pixels and colorized images, including those in +/// pattern tiles, count as transparency. Rasterized areas are clipped to their regions, and +/// discarded overprints are dropped. `None` when nothing changes (or the file keeps transparency). fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result> { if !set.pdf13() { return Ok(None); diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 80575c23f8..9550cf90f4 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -7,7 +7,7 @@ use vectorcraft_doc::{ColorMode, Document}; use vectorcraft_pdf::{Choice, CropTo, ImportOptions, PdfError, TextAs}; use super::super::colormgmt::Grays; -use super::super::{Result, Session, bad, f64_or, parse_range, str_param}; +use super::super::{Result, Session, bad, check_numbers, number_or, parse_range, text_param}; use super::{err, source}; /// The `document.open` options besides the file. The PDF ones (pages, box, password, text, @@ -39,6 +39,9 @@ pub struct LoadOptions { /// A `.ai` opens from its editing copy even where that draws differently from its PDF part /// (which can be older than it), with a warning, instead of from the PDF part. pub trust_editing_data: bool, + /// A PDF or `.ai` saved with Preserve Editing opens from the VectorCraft document it carries; + /// off, it opens as another app would open it, from the editing copy of its art or its pages. + pub native: bool, } impl Default for LoadOptions { @@ -54,6 +57,7 @@ impl Default for LoadOptions { dxf: Default::default(), editing_data: true, trust_editing_data: false, + native: true, } } } @@ -71,16 +75,17 @@ impl LoadOptions { Some(Value::Number(n)) => Some(n.to_string()), Some(v) => return Err(bad(cmd, format!("pages must be a range such as \"2-3\" or a page number, not {v}"))), }; - let crop = choice(cmd, "cropTo", str_param(p, "cropTo").or_else(|| str_param(p, "crop")))?; - let password = str_param(p, "password").filter(|s| !s.is_empty()).map(str::to_string); - let color_mode = match str_param(p, "colorMode").map(str::to_ascii_lowercase).as_deref() { + let (crop_to, crop_alias) = (text_param(p, "cropTo", cmd)?, text_param(p, "crop", cmd)?); + let crop = choice(cmd, "cropTo", crop_to.or(crop_alias))?; + let password = text_param(p, "password", cmd)?.filter(|s| !s.is_empty()).map(str::to_string); + let color_mode = match text_param(p, "colorMode", cmd)?.map(str::to_ascii_lowercase).as_deref() { None => None, Some("rgb") => Some(ColorMode::Rgb), Some("cmyk") => Some(ColorMode::Cmyk), Some(m) => return Err(bad(cmd, format!("colorMode must be rgb or cmyk, not `{m}`"))), }; let grays = Grays::param(cmd, p)?; - let text_as = choice(cmd, "textAs", str_param(p, "textAs"))?; + let text_as = choice(cmd, "textAs", text_param(p, "textAs", cmd)?)?; let layers = match p.get("layers").filter(|v| !v.is_null()) { None => true, Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "layers must be true or false"))?, @@ -91,28 +96,25 @@ impl LoadOptions { Some(v) => (v.as_bool().ok_or_else(|| bad(cmd, "editingData must be true, false or \"always\""))?, false), }; let dxf = super::dxfimport::options(cmd, p.get("dxf"))?; - Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data }) + Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data, native: true }) } /// Does the document read only part of the file, or read it differently (a page range, another - /// box, a password, without its hidden layers)? Writing it back would lose the rest, so Save - /// doesn't (it asks for a name). + /// box, a password, without its hidden layers, without the VectorCraft document it carries)? + /// Writing it back would lose the rest, so Save doesn't (it asks for a name). pub fn is_partial(&self) -> bool { - self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers + self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native } /// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible /// `.ai`, or a PDF saved with its editing data, asked for its crop box opens on its trim boxes, /// its editor's artboards, with the bleed round them (its crop box takes the bleed in). - fn import_options(&self, bytes: &[u8], editor_document: bool) -> Result { + fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result { let pages = match &self.pages { None => None, - Some(range) => { - let count = vectorcraft_pdf::info(bytes, self.password.as_deref()).map_err(err)?.pages.len(); - Some(parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?) - } + Some(range) => Some(parse_range(range, opened.page_count()).map_err(|e| err(format!("pages: {e}")))?), }; - let is_ai = self.crop == CropTo::Crop && vectorcraft_pdf::has_illustrator_data(bytes, self.password.as_deref()); + let is_ai = self.crop == CropTo::Crop && opened.has_illustrator_data(); Ok(ImportOptions { pages, crop: if is_ai { CropTo::Trim } else { self.crop }, @@ -136,24 +138,33 @@ fn choice(cmd: &str, key: &str, id: Option<&str>) -> Result .ok_or_else(|| bad(cmd, format!("{key} must be one of {}", T::IDS.join(", ")))) } -/// Import the pages `o` pick → the document, import notes and what else the import tells. +/// Import the pages `o` pick of `opened`, the PDF `bytes` already read +/// ([`vectorcraft_pdf::open_pdf`]) → the document, import notes and what else the import tells. /// `editor_document`: a `.ai` file. -pub(super) fn import(bytes: &[u8], o: &LoadOptions, editor_document: bool) -> Result { - vectorcraft_pdf::import_with_report(bytes, &o.import_options(bytes, editor_document)?).map_err(err) +pub(super) fn import( + bytes: &[u8], + opened: &vectorcraft_pdf::Opened, + o: &LoadOptions, + editor_document: bool, +) -> Result { + let options = o.import_options(opened, editor_document)?; + vectorcraft_pdf::import_opened(bytes, opened, &options).map_err(err) } /// Page `page` (0-based) of a PDF as a document of one artboard (its `o.crop` box) and one /// layer of what it shows, with the same text choice as Open, and the import notes. pub fn page_document(bytes: &[u8], page: usize, o: &LoadOptions) -> Result<(Document, Vec)> { - let opts = ImportOptions { - pages: Some(vec![page]), - crop: o.crop, - password: o.password.clone(), - text_as: o.text_as, - layers: false, - ..Default::default() - }; - vectorcraft_pdf::import_with_report(bytes, &opts).map(|r| (r.document, r.warnings)).map_err(err) + vectorcraft_pdf::import_with_report(bytes, &page_options(page, o)).map(|r| (r.document, r.warnings)).map_err(err) +} + +/// [`page_document`] of `opened`, the PDF `bytes` already read. +fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opened, page: usize, o: &LoadOptions) -> Result<(Document, Vec)> { + vectorcraft_pdf::import_opened(bytes, opened, &page_options(page, o)).map(|r| (r.document, r.warnings)).map_err(err) +} + +/// The import options of [`page_document`]. +fn page_options(page: usize, o: &LoadOptions) -> ImportOptions { + ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() } } const INFO: &str = "document.pdfInfo"; @@ -162,17 +173,20 @@ const INFO: &str = "document.pdfInfo"; pub(super) fn pdf_info(_: &mut Session, p: &Value) -> Result { let bytes = source(p, INFO)?.bytes; let o = LoadOptions::from_params(INFO, p)?; + check_numbers(p, &["thumbnailSize"], INFO)?; // Programs whose header is only `%!` are PostScript too, as `clipboard.importEps` reads them. if bytes.starts_with(b"%!") || vectorcraft_pdf::is_postscript(&bytes) { return postscript_info(&bytes, p); } - let info = match vectorcraft_pdf::info(&bytes, o.password.as_deref()) { - Ok(i) => i, + // The file is read once, for its pages and the thumbnail. + let opened = match vectorcraft_pdf::open_pdf(&bytes, o.password.as_deref()) { + Ok(opened) => opened, Err(e @ (PdfError::NeedsPassword | PdfError::WrongPassword)) => { return Ok(json!({"pages": 0, "needsPassword": true, "wrongPassword": e == PdfError::WrongPassword, "pageInfo": []})); } Err(e) => return Err(err(e)), }; + let info = opened.info(); let r4 = |r: vectorcraft_geom::Rect| json!([r.x0, r.y0, r.x1, r.y1]); let pages: Vec = info .pages @@ -184,7 +198,7 @@ pub(super) fn pdf_info(_: &mut Session, p: &Value) -> Result { .collect(); let mut out = json!({"pages": pages.len(), "needsPassword": false, "pageInfo": pages}); if let Some(page) = thumbnail_page(p, info.pages.len(), "PDF")? { - let (doc, _) = page_document(&bytes, page, &o)?; + let (doc, _) = opened_page_document(&bytes, &opened, page, &o)?; out["thumbnail"] = json!(thumbnail(&doc, p)?); } Ok(out) @@ -217,7 +231,7 @@ fn postscript_info(bytes: &[u8], p: &Value) -> Result { /// A PNG of `doc`'s first artboard, `thumbnailSize` px (default 160, from 16 to 1024) on its longer /// side, base64. fn thumbnail(doc: &Document, p: &Value) -> Result { - let size = f64_or(p, "thumbnailSize", 160.0).clamp(16.0, 1024.0); + let size = number_or(p, "thumbnailSize", 160.0, INFO)?.clamp(16.0, 1024.0); let r = doc.artboards.first().map(|a| a.rect).ok_or_else(|| err("the page has no area"))?; let png = super::encode(doc, "png", &json!({"scale": size / r.width().max(r.height()).max(1.0)}))?; Ok(vectorcraft_format::base64_encode(&png)) diff --git a/crates/engine/src/cmd/fileio/ppi.rs b/crates/engine/src/cmd/fileio/ppi.rs index 1c04db9c88..9539a81c7e 100644 --- a/crates/engine/src/cmd/fileio/ppi.rs +++ b/crates/engine/src/cmd/fileio/ppi.rs @@ -1,5 +1,7 @@ //! Image resolution metadata (pixels per inch): PNG `pHYs`, JPEG JFIF density or EXIF, TIFF and -//! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo. Place +//! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo, a PCX +//! header's HDpi and VDpi, JP2 capture and display resolution boxes, or a HEIF image's EXIF +//! resolution tags. Place //! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it //! as a `pHYs` chunk. @@ -21,12 +23,56 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { bmp(bytes) } else if super::psdread::is_psd(bytes) { super::psdread::resolution(bytes) + } else if super::pcxread::is_pcx(bytes) { + super::pcxread::resolution(bytes) + } else if super::jp2read::is_jpeg2000(bytes) { + jp2(bytes) + } else if super::heifread::is_heif(bytes) { + super::heifread::with_exif(bytes, tiff) } else { None }; r.filter(|(x, y)| [*x, *y].iter().all(|v| v.is_finite() && (1.0..=100_000.0).contains(v))) } +fn jp2_axis(n: u16, d: u16, e: i8) -> Option { + if d == 0 { + return None; + } + let ppi = f64::from(n) / f64::from(d) * 10f64.powi(i32::from(e)) * INCH_M; + (ppi.is_finite() && (1.0..=100_000.0).contains(&ppi)).then_some(ppi) +} + +/// JP2 resolution is independent on each axis. A valid display (`resd`) value, the resolution the +/// image is meant to be reproduced at, wins over a capture (`resc`) value whichever box comes first; +/// the capture value is used for an axis with no valid display value. Within one box type, later +/// boxes replace earlier valid values for that axis; an invalid later axis leaves the earlier value intact. +fn jp2(b: &[u8]) -> Option<(f64, f64)> { + if !b.starts_with(b"\0\0\0\x0cjP \r\n\x87\n") { + return Some((72.0, 72.0)); + } + // [capture, display], each (x, y). + let mut found = [(None, None); 2]; + for (_, header) in super::jp2read::boxes(b).filter(|(ty, _)| *ty == b"jp2h") { + for (_, res) in super::jp2read::boxes(header).filter(|(ty, _)| *ty == b"res ") { + for (ty, data) in super::jp2read::boxes(res).filter(|(ty, _)| *ty == b"resc" || *ty == b"resd") { + let Some([vn0, vn1, vd0, vd1, hn0, hn1, hd0, hd1, ve, he]): Option<[u8; 10]> = data.get(..10).and_then(|v| v.try_into().ok()) else { + continue; + }; + let (x, y) = &mut found[usize::from(ty == b"resd")]; + if let Some(value) = jp2_axis(u16::from_be_bytes([hn0, hn1]), u16::from_be_bytes([hd0, hd1]), he as i8) { + *x = Some(value); + } + if let Some(value) = jp2_axis(u16::from_be_bytes([vn0, vn1]), u16::from_be_bytes([vd0, vd1]), ve as i8) { + *y = Some(value); + } + } + } + } + let [(cx, cy), (dx, dy)] = found; + Some((dx.or(cx).unwrap_or(72.0), dy.or(cy).unwrap_or(72.0))) +} + /// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either). fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> { b.get(at..at.checked_add(n)?) diff --git a/crates/engine/src/cmd/fileio/progress.rs b/crates/engine/src/cmd/fileio/progress.rs index d2e0393484..2d23ef6cdb 100644 --- a/crates/engine/src/cmd/fileio/progress.rs +++ b/crates/engine/src/cmd/fileio/progress.rs @@ -14,7 +14,7 @@ use std::rc::Rc; use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use vectorcraft_doc::cancel::{self, CancelToken, ProgressSink}; @@ -26,6 +26,9 @@ pub struct Progress { total: AtomicU64, /// The steps are files (Export for Screens), not artboards. files: bool, + /// The last report came from a plug-in ([`vectorcraft_plugins::host::PROGRESS_STEP`]): its + /// steps are its own, shown as a share of the work. + share: AtomicBool, } impl Progress { @@ -43,6 +46,11 @@ impl Progress { self.files } + /// Are the steps a plug-in's own, which only a share of the work done describes? + pub fn counts_share(&self) -> bool { + self.share.load(Ordering::Relaxed) + } + /// `(steps done, steps in all)`; `total` is 0 while the export can't say (one file made in one go). pub fn counts(&self) -> (u64, u64) { let total = self.total.load(Ordering::Relaxed); @@ -68,7 +76,8 @@ impl Progress { /// Run `f` with `progress`'s token in effect on this thread and the steps reported to it. pub fn scope(progress: &Arc, f: impl FnOnce() -> R) -> R { let to = Arc::clone(progress); - let sink: ProgressSink = Rc::new(move |done, total, _| { + let sink: ProgressSink = Rc::new(move |done, total, what| { + to.share.store(what == vectorcraft_plugins::host::PROGRESS_STEP, Ordering::Relaxed); to.total.store(total, Ordering::Relaxed); to.done.store(done, Ordering::Relaxed); }); @@ -94,4 +103,14 @@ mod tests { assert!(matches!(r, Err(crate::EngineError::Cancelled)), "{:?}", r.err()); assert!(!cancel::is_cancelled(), "the scope ended"); } + + /// A plug-in's reports count as a share of the work, not as artboards or files. + #[test] + fn a_plugin_s_reports_count_as_a_share_of_the_work() { + let p = Progress::new(); + scope(&p, || cancel::progress(1, 4, "artboard")); + assert_eq!((p.counts(), p.counts_share()), ((1, 4), false)); + scope(&p, || cancel::progress(3, 8, vectorcraft_plugins::host::PROGRESS_STEP)); + assert_eq!((p.counts(), p.counts_share()), ((3, 8), true)); + } } diff --git a/crates/engine/src/cmd/fileio/pxrread.rs b/crates/engine/src/cmd/fileio/pxrread.rs new file mode 100644 index 0000000000..fc3a32f155 --- /dev/null +++ b/crates/engine/src/cmd/fileio/pxrread.rs @@ -0,0 +1,276 @@ +//! Reading Pixar picture files (`.pxr`) for File › Open and File › Place, from "The Format of +//! Stored Pictures" in the Pixar Image Computer manuals (release 1.2, December 1986). [`is_pxr`] +//! recognizes a file by the magic number at the start of its 512-byte header, and [`decode`] reads +//! its tiles into RGBA pixels: any subset of the R, G, B and A channels, 8 or 12 bits a sample, +//! dumped or run-length encoded, with alpha matted to black or unassociated. The file is +//! untrusted: every read is checked. +//! +//! Display rules for what the format leaves open: a picture whose only color channel is R is +//! gray; a missing color channel is 0 and a missing A is opaque; a null tile is transparent when +//! the picture has A and black otherwise. The x and y offsets are not read. + +/// The size of the header, after which the tile pointer table starts. +const HEADER: usize = 512; + +/// The first four bytes of every picture: the magic number `0x0000E880`, least significant byte +/// first. +const MAGIC: [u8; 4] = [0x80, 0xe8, 0x00, 0x00]; + +/// The message for a file whose header, tile table or tile data ends early, or that holds a tile +/// whose writing was not finished. +const TRUNCATED: &str = "the Pixar file is cut short"; + +/// The message for a header whose sizes, channels, storage mode or alpha mode the format doesn't +/// define. +const DAMAGED: &str = "the Pixar file's header is damaged"; + +/// The message for a tile pointer into the header or the tile pointer table, and for encoded tile +/// data with a packet the format doesn't define, or one that runs past the end of its scan line. +const BAD_DATA: &str = "the Pixar file's image data is damaged"; + +/// The channel bits of the picture format field (header byte 424): R, G, B and A, stored in this +/// order in each pixel. +const CHANNELS: [u16; 4] = [8, 4, 2, 1]; + +/// Does `bytes` start with a Pixar picture header's magic number? +pub(super) fn is_pxr(bytes: &[u8]) -> bool { + bytes.starts_with(&MAGIC) +} + +/// How one tile's samples are stored and how they become pixels. +struct Layout { + /// The channel indices (0 R, 1 G, 2 B, 3 A) the file stores, in the order it stores them. + stored: Vec, + /// Is a sample 12 bits in two bytes, rather than 8 bits in one? + wide: bool, + /// The bytes of one stored sample. + sample: usize, + /// Is the only color channel R, so the picture is gray? + gray: bool, + /// Are R, G and B matted to black (multiplied by A)? + matted: bool, + /// Does the picture store A? + alpha: bool, +} + +impl Layout { + /// The display value of the sample at `at` in `bytes`. A 12-bit sample is the low 12 bits of a + /// two-byte value, where 0 is 0.0, 2048 is 1.0, 2049 to 3071 are past 1.0 and 3072 to 4095 are + /// below 0.0; values outside 0.0 to 1.0 are clamped. + fn sample(&self, bytes: &[u8], at: usize) -> Result { + if !self.wide { + return bytes.get(at).copied().ok_or_else(|| TRUNCATED.to_string()); + } + let pair = bytes.get(at..at + 2).ok_or(TRUNCATED)?; + let v = u32::from(u16::from_le_bytes([pair[0], pair[1]]) & 0x0fff); + let v = if v >= 3072 { 0 } else { v.min(2048) }; + Ok(((v * 255 + 1024) / 2048) as u8) + } + + /// The RGBA pixel of the samples for `channels` read from `bytes` at `at`, combined with + /// `base` (the channels not read, such as a packet's common A). + fn pixel(&self, bytes: &[u8], at: usize, channels: &[usize], mut base: [u8; 4]) -> Result<[u8; 4], String> { + for (i, &c) in channels.iter().enumerate() { + base[c] = self.sample(bytes, at + i * self.sample)?; + } + Ok(base) + } + + /// The color a pixel of stored samples is shown in: gray from R, and straight color from color + /// matted to black (0 where A is 0). + fn shown(&self, [r, g, b, a]: [u8; 4]) -> [u8; 4] { + let [r, g, b] = if self.gray { [r; 3] } else { [r, g, b] }; + if !self.alpha { + return [r, g, b, 255]; + } + if !self.matted { + return [r, g, b, a]; + } + let unmatte = |c: u8| if a == 0 { 0 } else { ((u32::from(c) * 255 + u32::from(a) / 2) / u32::from(a)).min(255) as u8 }; + [unmatte(r), unmatte(g), unmatte(b), a] + } +} + +/// The pixels of Pixar picture `bytes`, which [`is_pxr`] accepts, refused when they take more +/// than `max_alloc` bytes as RGBA before anything is decoded. +pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result { + let head = bytes.get(..HEADER).ok_or(TRUNCATED)?; + let le = |at: usize| u16::from_le_bytes([head[at], head[at + 1]]); + let (h, w, tile_h, tile_w) = (le(416), le(418), le(420), le(422)); + let (format, storage, block, alpha_mode) = (le(424), le(426), le(428), le(430)); + // Sizes must be positive; the format field holds only the four channel bits; the storage modes + // are 0 to 3 and the alpha modes 0 and 1. + if w == 0 || h == 0 || tile_w == 0 || tile_h == 0 { + return Err(DAMAGED.into()); + } + if format == 0 || format > 15 || storage > 3 || alpha_mode > 1 { + return Err(DAMAGED.into()); + } + let (w, h, tile_w, tile_h) = (usize::from(w), usize::from(h), usize::from(tile_w), usize::from(tile_h)); + if w as u64 * h as u64 * 4 > max_alloc { + return Err(format!("an image of {w} × {h} pixels is too large to draw")); + } + let stored: Vec = CHANNELS.iter().enumerate().filter(|(_, bit)| format & **bit != 0).map(|(i, _)| i).collect(); + let wide = storage % 2 == 1; + let layout = + Layout { gray: format & 0b1110 == 0b1000, matted: alpha_mode == 0, alpha: format & 1 != 0, sample: if wide { 2 } else { 1 }, wide, stored }; + let (across, down) = (w.div_ceil(tile_w), h.div_ceil(tile_h)); + // A table end past the largest address is past the end of the file too. + let table_end = across.checked_mul(down).and_then(|n| n.checked_mul(8)).and_then(|n| n.checked_add(HEADER)).ok_or(TRUNCATED)?; + let table = bytes.get(HEADER..table_end).ok_or(TRUNCATED)?; + let empty = if layout.alpha { [0; 4] } else { [0, 0, 0, 255] }; + let mut img = image::RgbaImage::from_pixel(w as u32, h as u32, image::Rgba(empty)); + // The encoded data read in all, which a file whose tiles each hold their own data stays within. + let mut left = bytes.len(); + for (n, entry) in table.as_chunks::<8>().0.iter().enumerate() { + let pointer = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]) as usize; + let length = i32::from_le_bytes([entry[4], entry[5], entry[6], entry[7]]); + if pointer == 0 { + continue; + } + // A tile that starts past the end of the file; every offset read from here stays near the + // file's length, so it fits a 32-bit address. + if length == -1 || pointer >= bytes.len() { + return Err(TRUNCATED.into()); + } + // Tile data follows the tile pointer table; a pointer into the header or the table would + // read them as pixels. + if pointer < table_end { + return Err(BAD_DATA.into()); + } + let (x0, y0) = (n % across * tile_w, n / across * tile_h); + // The part of the tile inside the picture; the pixels of border tiles past its edges are + // stored and skipped. + let tile = Tile { w: tile_w, h: tile_h, shown_w: tile_w.min(w - x0), shown_h: tile_h.min(h - y0) }; + let mut put = |x: usize, y: usize, px: [u8; 4]| { + img.put_pixel((x0 + x) as u32, (y0 + y) as u32, image::Rgba(layout.shown(px))); + }; + if storage >= 2 { + dumped(bytes, pointer, tile, &layout, &mut put)?; + } else { + encoded(bytes, pointer, tile, usize::from(block), &layout, &mut left, &mut put)?; + } + } + Ok(img) +} + +/// A tile's size, and the size of its part inside the picture (the pixels that are drawn). +#[derive(Clone, Copy)] +struct Tile { + w: usize, + h: usize, + shown_w: usize, + shown_h: usize, +} + +/// Read a dumped tile at `at`: its pixels row by row, each pixel's samples in channel order. The +/// whole tile must be in the file; only its part inside the picture is read. +fn dumped(bytes: &[u8], at: usize, tile: Tile, layout: &Layout, put: &mut impl FnMut(usize, usize, [u8; 4])) -> Result<(), String> { + let size = layout.stored.len() * layout.sample; + let end = tile.w.checked_mul(tile.h).and_then(|n| n.checked_mul(size)).and_then(|n| n.checked_add(at)).ok_or(TRUNCATED)?; + if end > bytes.len() { + return Err(TRUNCATED.into()); + } + for y in 0..tile.shown_h { + for x in 0..tile.shown_w { + put(x, y, layout.pixel(bytes, at + (y * tile.w + x) * size, &layout.stored, [0, 0, 0, 255])?); + } + } + Ok(()) +} + +/// Read an encoded tile at `at`: each scan line is a series of packets, each headed by a 16-bit +/// value whose top 4 bits are its kind and whose low 12 bits are its count less one. +/// +/// - 0 ends the disk block: reading goes on at the next multiple of `block` bytes in the file. +/// - 1 dumps count + 1 pixels with every channel. +/// - 2 holds count + 1 runs, each a length byte (pixels less one) and one pixel with every channel. +/// - 3 dumps count + 1 pixels' color channels after one A sample they share. +/// - 4 holds count + 1 runs of color channels, each a length byte and one pixel, after one A +/// sample they share. +/// +/// No packet runs past the end of its scan line, and a block end never follows another one (an +/// empty block). Reading stops after the last scan line inside the picture, pixels past its right +/// edge are skipped, and the bytes read count against `left`, the encoded data left to read in +/// the whole file: tiles that share their data are refused once it is used up. +fn encoded( + bytes: &[u8], + mut at: usize, + tile: Tile, + block: usize, + layout: &Layout, + left: &mut usize, + put: &mut impl FnMut(usize, usize, [u8; 4]), +) -> Result<(), String> { + let all = &layout.stored; + let colors: Vec = all.iter().copied().filter(|c| *c != 3).collect(); + let mut block_ended = false; + for y in 0..tile.shown_h { + let mut x = 0; + while x < tile.w { + let start = at; + let head = bytes.get(at..at + 2).ok_or(TRUNCATED)?; + let head = u16::from_le_bytes([head[0], head[1]]); + let (kind, count) = (head >> 12, usize::from(head & 0x0fff) + 1); + if kind == 0 { + if block == 0 || block_ended { + return Err(BAD_DATA.into()); + } + block_ended = true; + at = (at / block + 1) * block; + if at >= bytes.len() { + return Err(TRUNCATED.into()); + } + *left = left.checked_sub(at - start).ok_or(BAD_DATA)?; + continue; + } + block_ended = false; + at += 2; + let shared = matches!(kind, 3 | 4); + if shared && (!layout.alpha || colors.is_empty()) { + return Err(BAD_DATA.into()); + } + let (channels, base) = if shared { + let a = layout.sample(bytes, at)?; + at += layout.sample; + (&colors, [0, 0, 0, a]) + } else { + (all, [0, 0, 0, 255]) + }; + let size = channels.len() * layout.sample; + match kind { + 1 | 3 => { + if x + count > tile.w { + return Err(BAD_DATA.into()); + } + let end = at + count * size; + if end > bytes.len() { + return Err(TRUNCATED.into()); + } + for i in 0..count.min(tile.shown_w.saturating_sub(x)) { + put(x + i, y, layout.pixel(bytes, at + i * size, channels, base)?); + } + at = end; + x += count; + } + 2 | 4 => { + for _ in 0..count { + let run = usize::from(*bytes.get(at).ok_or(TRUNCATED)?) + 1; + if x + run > tile.w { + return Err(BAD_DATA.into()); + } + let px = layout.pixel(bytes, at + 1, channels, base)?; + at += 1 + size; + for i in 0..run.min(tile.shown_w.saturating_sub(x)) { + put(x + i, y, px); + } + x += run; + } + } + _ => return Err(BAD_DATA.into()), + } + *left = left.checked_sub(at - start).ok_or(BAD_DATA)?; + } + } + Ok(()) +} diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index da1a4f5ac2..c4db832d24 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -96,7 +96,8 @@ pub struct SavePlan { /// stamps; `None`: the time it is written. pub modified: Option>, /// Warnings about the params themselves: each native option (`compress`, `version`, - /// `preview`) given beside the path that the format doesn't read. + /// `preview`, `precision`) given beside the path, and each key of `options`, that the format + /// doesn't read, naming the file the save writes. pub notes: Vec, } @@ -134,8 +135,9 @@ pub fn templates_folder(prefs: &Prefs) -> Option { pub fn templates_dialog_folder(prefs: &Prefs) -> Option { let folder = std::path::PathBuf::from(templates_folder(prefs)?); if !folder.is_dir() { - // Best effort: a folder that can't be made leaves the nearest one that exists. - let _ = std::fs::create_dir_all(&folder); + // Best effort: a folder that can't be made (or automation may not write) leaves the + // nearest one that exists. + let _ = super::create_dir(&folder.to_string_lossy()); } folder.ancestors().find(|a| a.is_dir()).map(|a| a.to_string_lossy().into_owned()).or_else(home_folder) } @@ -248,11 +250,6 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result { if let Some((key, top, inner)) = disagreeing_option(p, is_svg(format)).map_err(|e| bad(cmd, e))? { return Err(bad(cmd, format!("`{key}: {top}` and `options.{key}: {inner}` disagree: give the option once"))); } - let notes = NATIVE_OPTIONS - .iter() - .filter(|k| p.get(**k).is_some_and(|v| !v.is_null()) && !reads_option(format, k)) - .map(|k| format!("`{k}` was not used: {} files don't read it", format.label)) - .collect(); let mut given: Map = match p.get("options") { Some(Value::Object(o)) => o.iter().filter(|(k, _)| reads_option(format, k)).map(|(k, v)| (k.clone(), v.clone())).collect(), None | Some(Value::Null) => Map::new(), @@ -265,7 +262,7 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result { given = svg; } else { // So do PDF options (as the Save PDF dialog and document.exportPdf name them) and the - // native ones (compress, version, preview). + // native ones (compress, version, preview, precision). if let Some(o) = p.as_object() { given.extend( o.iter().filter(|(k, v)| !v.is_null() && k.as_str() != "path" && reads_option(format, k)).map(|(k, v)| (k.clone(), v.clone())), @@ -273,7 +270,18 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result { } } // None given: the ones the document was last saved with in this format. - let options = if given.is_empty() && format.id == st.format { remembered_save_options(st) } else { given }; + let mut options = if given.is_empty() && format.id == st.format { remembered_save_options(st) } else { given }; + // Remember the effective choice, including the encoder's default, so another document's + // later save cannot change what this one writes. Invalid non-null values still reach validation. + if matches!(format.id, "vectorcraft" | "template") { + let pdf = match options.get("pdfCompatible") { + None | Some(Value::Null) => Some(native_pdf_preference(s, Some(st)).unwrap_or(true)), + _ => None, + }; + if let Some(pdf) = pdf { + options.insert("pdfCompatible".into(), json!(pdf)); + } + } // Save writes the document's own file; the other modes only where they are told to. let path = path.or_else(|| (mode == SaveMode::Save && !st.converted && !st.recovered && format.id == st.format).then(|| st.path.clone()).flatten()); @@ -292,11 +300,19 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result { if let Some(path) = &path { super::check_not_lossy_overwrite(st, path, p, cmd)?; } + let written = written_as(cmd, format, &Value::Object(options.clone())); + let top = NATIVE_OPTIONS.iter().filter(|k| p.get(**k).is_some_and(|v| !v.is_null())).map(|k| k.to_string()); + let nested = p.get("options").and_then(Value::as_object).into_iter().flatten().filter(|(_, v)| !v.is_null()).map(|(k, _)| k); + let notes = top + .filter(|k| !reads_option(format, k)) + .chain(nested.filter(|k| !reads_option(format, k)).map(|k| format!("options.{k}"))) + .map(|k| format!("`{k}` was not used: {} files don't read it", written.label)) + .collect(); Ok(SavePlan { mode, path, format, options, name, folder, modified, notes }) } /// The native save options, which a save also takes beside the path. -const NATIVE_OPTIONS: [&str; 3] = ["compress", "version", "preview"]; +const NATIVE_OPTIONS: [&str; 4] = ["compress", "version", "preview", "precision"]; /// The first option `p` gives both beside the path and in `options` with different values, as /// `(key, top-level value, options value)`. For an SVG save (`svg`), an SVG option's value on @@ -331,6 +347,15 @@ fn same_value(a: &Value, b: &Value) -> bool { } } +/// Native documents and templates share only their PDF choice. Other source formats use the +/// application's last native choice, keeping an AI file's separate PDF option out of it. +fn native_pdf_preference(s: &Session, st: Option<&DocState>) -> Option { + st.filter(|d| matches!(d.format, "vectorcraft" | "template")) + .and_then(|d| d.save_options.get("pdfCompatible")) + .and_then(Value::as_bool) + .or_else(|| s.prefs.native_save_options.get("pdfCompatible").and_then(Value::as_bool)) +} + /// The options `st` was last saved with, their artboards (`artboard`, `artboards` and `range`) /// following the artboards they named ([`DocState::save_artboards`]): an artboard deleted since is /// left out, and one that moved is named by its new number. When none of the artboards the save @@ -445,22 +470,34 @@ fn is_svg(f: &Format) -> bool { } /// The document as written: native files carry the view to reopen at and the Layers panel's open -/// rows and transparency grid visibility. +/// rows and transparency grid visibility; a `.ai` file names the view's active artboard +/// ([`DocState::active_artboard`]) as its active one. fn doc_to_save(st: &DocState, f: &Format) -> Arc { if !is_native(f) { return st.doc.clone(); } let open = st.layers_open.saved(&st.doc); - if st.doc.last_view == st.view && st.doc.layers_open == open && st.doc.transparency_grid == st.transparency_grid { + let active = moved_active_artboard(st, &st.doc, f); + if st.doc.last_view == st.view && st.doc.layers_open == open && st.doc.transparency_grid == st.transparency_grid && active.is_none() { return st.doc.clone(); } let mut d = (*st.doc).clone(); + if active.is_some() { + d.opened_artboard = active; + } d.last_view = st.view.clone(); d.transparency_grid = st.transparency_grid; d.layers_open = open; Arc::new(d) } +/// The artboard a `.ai` or `.ait` file written from `st` (`doc`, the document it writes) names as +/// its active one, when that is not already the one `doc` opened on: the view's active artboard +/// ([`DocState::active_artboard`]), if `doc` has it. +pub(super) fn moved_active_artboard(st: &DocState, doc: &Document, f: &Format) -> Option { + st.active_artboard.filter(|id| matches!(f.id, "ai" | "ait") && doc.artboards.iter().any(|a| a.id == *id) && doc.opened_artboard != Some(*id)) +} + /// What a format loses against a native file (reported whenever a save writes it). fn fidelity_warning(f: &Format) -> Option { (!is_native(f)).then(|| { @@ -574,6 +611,28 @@ fn blank_pages(doc: &Document) -> Document { /// Why a `.ai` file saved without PDF content looks empty elsewhere. const NOT_PDF_COMPATIBLE: &str = "saved without PDF content: VectorCraft opens it as before, other apps show empty pages"; +/// The same, for a file that carries the editing copy of its art. +const NOT_PDF_COMPATIBLE_EDITING: &str = + "saved without PDF content: VectorCraft and apps that read its editing data open it, other apps show empty pages"; + +/// `f` (`.ai` or `.ait`) named, in its option errors, as a file saved without PDF content. +fn without_pdf(f: &Format) -> Format { + let label = if f.id == "ait" { "non-PDF-compatible .ait template" } else { "non-PDF-compatible .ai" }; + Format { label, ..*f } +} + +/// `f` named, in its errors and notes, as the file a save with options `p` writes: a version 7 +/// `.ai` as the legacy `.ai`, and a `.ai` or `.ait` with `pdfCompatible: false` as one saved +/// without PDF content. +fn written_as(cmd: &str, f: &Format, p: &Value) -> Format { + if f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false) { + super::legacy_ai::named(f) + } else if matches!(f.id, "ai" | "ait") && !bool_or(p, "pdfCompatible", true) { + without_pdf(f) + } else { + *f + } +} /// `e`, an error of the export encoders, under the save command `cmd` instead of /// `document.export`. @@ -584,8 +643,39 @@ fn named_for_save(cmd: &str, e: crate::EngineError) -> crate::EngineError { } } -/// The shared Save and Export encoder for PDF-compatible `.ai` files (and `.ait` templates, the -/// same file). +/// Refuse the artboards a `.ai` or `.ait` save is given (`artboard`, `artboards`, or a `range` +/// that isn't empty) when one of them is not in `doc`, with the error an export gives. The save +/// then writes every artboard, or a legacy `.ai` file's `range`, whatever `artboard` and +/// `artboards` name. An empty `artboards` list is not refused: the save writes every artboard. +fn named_artboards_exist(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<()> { + let n = doc.artboards.len(); + // The encoders refuse a document without artboards themselves. + if n == 0 { + return Ok(()); + } + // The encoders refuse a value of the wrong type themselves, each with its own label. + let Ok(mut picked) = super::encode::options::(&written_as(cmd, f, p), p) else { + return Ok(()); + }; + picked.range = picked.range.filter(|r| !r.trim().is_empty()); + if picked.range.is_none() && picked.artboards.as_ref().is_some_and(Vec::is_empty) { + return Ok(()); + } + picked.resolve(n).map_err(|e| bad(cmd, e))?; + Ok(()) +} + +/// The `.ai` option `editingData`: whether the file also carries the editing copy of the art that +/// other apps read (default on). +#[derive(Default, serde::Deserialize)] +#[serde(default, rename_all = "camelCase")] +struct AiEditingData { + editing_data: Option, +} + +/// The shared Save and Export encoder for `.ai` files (and `.ait` templates, the same file): +/// PDF-compatible by default, without PDF content (`pdfCompatible: false`), or legacy version 7 +/// `.ai` files (`aiVersion: "7"`). pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result { if super::legacy_ai::wanted(cmd, f, p)? { return super::legacy_ai::encode(cmd, f, doc, p); @@ -604,8 +694,9 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res } } } - let native_options = super::native::ai_options(cmd, f, doc, ¶ms)?; let pdf_compatible = bool_or(¶ms, "pdfCompatible", true); + let f = &if pdf_compatible { *f } else { without_pdf(f) }; + let native_options = super::native::ai_options(cmd, f, doc, ¶ms)?; if !pdf_compatible { let picked: ArtboardPick = super::encode::options(f, ¶ms)?; let picked = picked.resolve(doc.artboards.len()).map_err(|e| bad(cmd, e))?; @@ -613,16 +704,46 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res return Err(bad(cmd, "pdfCompatible: false needs every artboard to keep the editable artwork")); } } - let pages = doc.without_edit_modes(); + let edited = doc.without_edit_modes(); // Resolve placed files only for the drawn pages. Missing files become preview images there; // the native attachment keeps the original placed objects and their relinkable metadata. - let (pages, placed_warnings) = - if pdf_compatible { crate::cmd::place::document::full_documents(&pages) } else { (std::borrow::Cow::Owned(blank_pages(&pages)), Vec::new()) }; + let (pages, placed_warnings) = if pdf_compatible { + crate::cmd::place::document::full_documents(&edited) + } else { + (std::borrow::Cow::Owned(blank_pages(&edited)), Vec::new()) + }; let native = || super::native::ai_native(cmd, doc, &native_options); - let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, ¶ms, native)?; + let other_apps: AiEditingData = super::encode::options(f, ¶ms)?; + let carries_editing = std::cell::Cell::new(false); + let private = || { + if !other_apps.editing_data.unwrap_or(true) { + return Ok(None); + } + // The art with placed files resolved as the pages draw them, also when the pages are blank. + let resolved; + let (art, mut resolved_warnings): (&Document, Vec) = if pdf_compatible { + (&pages, Vec::new()) + } else { + let (d, w) = crate::cmd::place::document::full_documents(&edited); + resolved = d; + (&resolved, w) + }; + // With the artboards' background colors, as the pages draw them. + let art = super::export::with_artboard_fills(art, ¶ms, 0..art.artboards.len()).map_err(|e| bad(cmd, e))?; + let o = vectorcraft_eps::AiEditingOptions { + title: doc.title.clone(), + created: doc.metadata.created.or_else(vectorcraft_doc::metadata::output_time), + }; + let (data, lost) = vectorcraft_eps::ai_private_data(&art, &o).map_err(|e| bad(cmd, e))?; + // Placed files that weren't found are written as their previews here too. + resolved_warnings.extend(lost); + carries_editing.set(true); + Ok(Some((data, resolved_warnings))) + }; + let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, ¶ms, native, private)?; warnings.extend(placed_warnings); if !pdf_compatible { - warnings.push(NOT_PDF_COMPATIBLE.to_string()); + warnings.push(if carries_editing.get() { NOT_PDF_COMPATIBLE_EDITING } else { NOT_PDF_COMPATIBLE }.to_string()); } Ok(Encoded { warnings, ..Encoded::one(bytes) }) } @@ -656,7 +777,8 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option Result { +pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; let job = save_job(s, plan)?; let uid = s.doc()?.uid; @@ -915,12 +1049,15 @@ fn can_revert(s: &Session) -> std::result::Result<(), String> { fn revert(s: &mut Session, _: &Value) -> Result { let index = s.active_index().ok_or(crate::EngineError::NoDocument)?; let path = s.doc()?.path.clone().ok_or_else(|| bad("file.revert", "the document has never been saved"))?; - let Loaded { mut doc, .. } = load(&path, &read_file(&path)?)?.with_grid_prefs(&s.prefs); + let Loaded { mut doc, native_pdf_compatible, .. } = load(&path, &read_file(&path)?)?.with_grid_prefs(&s.prefs); doc.template = false; // Back to the saved file: its recovery copy has nothing left to recover. let uid = s.doc()?.uid; crate::cmd::recovery::forget(s, uid); s.replace_document(index, doc); + if let Some(pdf) = native_pdf_compatible { + s.doc_mut()?.save_options.insert("pdfCompatible".into(), json!(pdf)); + } Ok(json!({ "path": path })) } @@ -932,14 +1069,25 @@ fn format_options(s: &mut Session, p: &Value) -> Result { let f = format(id) .filter(|f| f.write || SAVE_FORMATS.contains(&f.id) || TEMPLATE_FORMATS.contains(&f.id)) .ok_or_else(|| bad(C, format!("`{id}` is no writable format (see document.formats)")))?; - let saved = st.filter(|d| d.format == f.id).map(remembered_save_options); + // A document not yet saved as a native file starts from the native options used last. + let saved = st + .filter(|d| d.format == f.id) + .map(remembered_save_options) + .filter(|m| !m.is_empty()) + .or_else(|| (f.id == "vectorcraft" && !s.prefs.native_save_options.is_empty()).then(|| s.prefs.native_save_options.clone())); // A native save compresses as Use Compression says, unless told otherwise. let prefs = with_compression_pref(&s.prefs, &json!({})); + let native_pdf = matches!(f.id, "vectorcraft" | "template").then(|| native_pdf_preference(s, st)).flatten(); let mut v = f.to_json(); if let Some(options) = v["options"].as_object_mut() { for (name, o) in options.iter_mut() { let default = prefs.get(name).filter(|_| matches!(f.id, "vectorcraft" | "template")).unwrap_or(&o["default"]); o["value"] = saved.as_ref().and_then(|m| m.get(name)).unwrap_or(default).clone(); + if name == "pdfCompatible" + && let Some(pdf) = native_pdf + { + o["value"] = json!(pdf); + } } } v["saveFormats"] = @@ -954,7 +1102,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version or preview given flat), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: false for native (also carry a PDF of every artboard) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly; separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified", has_doc, |s, p| save(s, SaveMode::Save, p) ), @@ -963,7 +1111,7 @@ pub(super) fn specs() -> Vec { "Save As…", ["File"], Some("Cmd+Shift+S"), - "{…as document.save} {path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own; ait, a .ait template, is written by file.saveAsTemplate), options?, svg?, modified?} the document takes on the new path, name and format (except a template, which is always a copy) → {path, format, bytes, warnings}; no path → {dataBase64, format, name, folder?, warnings}", + "{…as document.save} {path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own; ait, a .ait template, is written by file.saveAsTemplate), options?, svg?, precision?, modified?} the document takes on the new path, name and format (except a template, which is always a copy) → {path, format, bytes, warnings}; no path → {dataBase64, format, name, folder?, warnings}", has_doc, |s, p| save(s, SaveMode::SaveAs, p) ), @@ -972,7 +1120,7 @@ pub(super) fn specs() -> Vec { "Save a Copy…", ["File"], Some("Cmd+Alt+S"), - "{…as document.save} {path?, format?, options?} write a copy; the document keeps its path, title and modified state → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" copy.\", folder?, warnings}", + "{…as document.save} {path?, format?, options?, precision?} write a copy; the document keeps its path, title and modified state → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" copy.\", folder?, warnings}", has_doc, |s, p| save(s, SaveMode::Copy, p) ), @@ -981,7 +1129,7 @@ pub(super) fn specs() -> Vec { "Save as Template…", ["File"], None, - "{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" template.\", folder: the Templates folder (preference templatesFolder), warnings}", + "{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \" template.\", folder: the Templates folder (preference templatesFolder), warnings}", has_doc, |s, p| save(s, SaveMode::Template, p) ), @@ -1008,7 +1156,7 @@ pub(super) fn specs() -> Vec { "Format Options", [], None, - "{format?: a writable format id or ait (default: the document's own)} → {id, label, extensions, mime, read, write, raster, options: {name: {type, default, description, value}}, saveFormats: [{id, label, extensions}]}; value = the document's option as last saved in that format, else the default", + "{format?: a writable format id or ait (default: the document's own)} → {id, label, extensions, mime, read, write, raster, options: {name: {type, default, description, value}}, saveFormats: [{id, label, extensions}]}; value = the document's option as last saved in that format, else (native, for a document not yet saved as one) as the last native save used it, else the default", always, format_options ), @@ -1062,6 +1210,13 @@ mod tests_folders { std::fs::write(base.join("blocked"), b"x").unwrap(); prefs.templates_folder = base.join("blocked").join("Templates").to_string_lossy().into_owned(); assert_eq!(super::templates_dialog_folder(&prefs).map(PathBuf::from), Some(base.clone())); + // Automation that may not write there makes no folder. + let outside = base.join("Outside").join("Templates"); + prefs.templates_folder = outside.to_string_lossy().into_owned(); + std::fs::create_dir_all(base.join("Allowed")).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&base], &[&base.join("Allowed")]).unwrap().unwrap(); + crate::file_access::confine(Some(&roots), || super::templates_dialog_folder(&prefs)); + assert!(!outside.exists(), "not made"); let _ = std::fs::remove_dir_all(&base); } } diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index db934aeab7..8a149c6245 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -16,13 +16,13 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::Document; use vectorcraft_geom::Rect; -use super::super::{NodeId, Result, Session, bad, str_param}; +use super::super::{EngineError, NodeId, Result, Session, bad, bool_or, str_param}; use super::encode::single_artboard; use super::export::{export_crop, isolated, selected_artwork, without_artboards}; use super::naming::{self, NameParts}; use super::{ - ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names, create_dir, distinct_names, encode_with_warnings, unique_file_names, - with_black_output, writable, write_file, + ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names_keeping_dots, create_dir, distinct_names_by, encode_with_warnings, merge, + unique_file_names_keeping_dots, with_black_output, writable, write_file, }; const C: &str = "document.exportForScreens"; @@ -174,7 +174,13 @@ pub(super) fn file_part(s: &str) -> String { /// every platform. Spaces between the device name and the period are dropped (`CON .png` becomes /// `CON-.png`). pub(crate) fn safe_file_name(s: &str) -> String { - let name = file_part(s); + name_without_device(&file_part(s)) +} + +/// [`safe_file_name`] without [`file_part`]: drops trailing periods and spaces and puts `-` after a +/// Windows device name, and keeps every other character, so a source file name with `\` or `:` keeps +/// it where the file system allows it. +pub(super) fn name_without_device(name: &str) -> String { let name = name.trim_end_matches(['.', ' ']); let (base, rest) = name.split_at(name.find('.').unwrap_or(name.len())); // Windows ignores spaces before the extension, so `CON .png` is the CON device too. @@ -277,7 +283,7 @@ impl Row { /// The settings the Asset Export panel shares with the dialog: what is exported, not which art /// or where to. -pub(crate) const SHARED_KEYS: [&str; 6] = ["formats", "preset", "settings", "prefix", "subfolders", "antiAlias"]; +pub const SHARED_KEYS: [&str; 6] = ["formats", "preset", "settings", "prefix", "subfolders", "antiAlias"]; /// What `document.exportForScreens` reads besides the formats. #[derive(Default, Deserialize)] @@ -289,6 +295,8 @@ struct ScreenParams { zip: bool, full_document: bool, include_bleed: bool, + /// Include Artboard Fill: the artboards' background colors behind the art (default on). + include_artboard_fill: Option, subfolders: bool, preset: Option, prefix: Option, @@ -309,6 +317,9 @@ struct ScreenParams { /// Where files go: `none` (all in the folder), `rows` (the rows' sub-folders, as /// `subfolders`), `format` (a folder per extension), `item`, or `itemFormat`. folders: Option, + /// Export PDFs As: `single` (the artboards a PDF row writes are the pages of one file) or + /// `multiple` (a file per artboard, the default). + pdfs: Option, } /// How exported files are sorted into folders. @@ -389,6 +400,8 @@ struct Naming { /// The counter counts files rather than items. per_file: bool, folders: Folders, + /// Export PDFs As › Single file. + single_pdf: bool, } impl Naming { @@ -406,9 +419,14 @@ impl Naming { Some("file") => true, Some(c) => return Err(bad(C, format!("counterPer `{c}`: item or file"))), }; + let single_pdf = match o.pdfs.as_deref() { + None | Some("multiple") => false, + Some("single") => true, + Some(m) => return Err(bad(C, format!("pdfs `{m}`: single or multiple"))), + }; let filename = safe_name(&super::file_stem(title)).unwrap_or_else(|| "Untitled".into()); let pattern = o.name.clone().filter(|n| !n.trim().is_empty()); - Ok(Self { pattern, prefix, filename, when, counter_start: o.counter_start.unwrap_or(1), per_file, folders }) + Ok(Self { pattern, prefix, filename, when, counter_start: o.counter_start.unwrap_or(1), per_file, folders, single_pdf }) } /// The sub-folder (`None` for the export folder itself) and the file name of the file row `r` @@ -478,14 +496,42 @@ pub(crate) fn check_settings(s: &Session, p: &Value) -> Result<()> { rows_of(s, p, ScreenParams::of(p)?.preset.as_deref()).map(|_| ()) } +/// `name` the way a case-insensitive file system compares names: lower-cased, then each character +/// upper-cased where its upper case is one character. Names with the same lower case give the +/// same key, and so do `ΟΣ`, `ος` and `οσ` (`ΟΣ`); `ᾈ` and `ᾀ` give `ᾀ`, and `ß` stays `ß`. +/// Dotless `ı` stays `ı`, as NTFS and Unicode case folding outside Turkic languages keep it apart +/// from `i` and `I`. +fn fold(name: &str) -> String { + name.to_lowercase() + .chars() + .map(|c| { + if c == 'ı' { + return c; + } + let mut upper = c.to_uppercase(); + match (upper.next(), upper.next()) { + (Some(u), None) => u, + _ => c, + } + }) + .collect() +} + /// The file names (and bytes) an export wrote, or the files it returns. #[derive(Default)] struct Output { - /// Lower-case relative names already used, with what wrote each (two identical rows write - /// one file; different files that would share a name get `-2`, `-3`…). + /// Relative names already used, by their [`fold`]ed spelling, with what wrote each (two + /// identical rows write one file; different files that would share a name get `-2`, `-3`…). taken: std::collections::HashMap, - /// Sub-folders already made. + /// Each sub-folder as the first file in it spells it, by its [`fold`]ed name. + folders: std::collections::HashMap, + /// Sub-folders already made, by their [`fold`]ed names. made: HashSet, + /// For each [`fold`]ed name asked for, the number to try next: many files given one name + /// would otherwise try `-2`, `-3`… from the start each time. + next: std::collections::HashMap, + /// Each [`fold`]ed name asked for with the file (`key`) that got a name from it. + claimed: HashSet<(String, String)>, /// `(relative name, bytes)` kept to return or zip (empty when written to a folder). kept: Vec<(String, Vec)>, /// The paths written. @@ -493,13 +539,26 @@ struct Output { } impl Output { - /// The name the file `key` writes as `name` takes: `name`, else (with `number`) `name-2`, - /// `name-3`… when another file has it; `None` when the same file (`key`) was written as `name` - /// already, or, without `number`, when any file was (the first row wins, as Export for Screens - /// always did when no name pattern is given). - fn claim(&mut self, name: &str, key: &str, number: bool) -> Option { - let (base, ext) = name.rsplit_once('.').map_or((name, ""), |(b, e)| (b, e)); - for n in 1.. { + /// The name the file `key` writes as `name` takes: `name`, else `name-2`, `name-3`… when + /// another file has it, with or without a name pattern; `None` when the same file (`key`) was + /// written as `name` already. Names are compared without case, and a sub-folder keeps the + /// spelling of the first file put in it. + fn claim(&mut self, name: &str, key: &str) -> Option { + let name = match name.rsplit_once('/') { + Some((dir, file)) => { + let dir = self.folders.entry(fold(dir)).or_insert_with(|| dir.to_string()); + format!("{dir}/{file}") + } + None => name.to_string(), + }; + let asked = (fold(&name), key.to_string()); + // The same file under the same name again: it has its name already. + if self.claimed.contains(&asked) { + return None; + } + let (base, ext) = name.rsplit_once('.').map_or((name.as_str(), ""), |(b, e)| (b, e)); + let start = self.next.get(&asked.0).copied().unwrap_or(1); + for n in start.. { let candidate = if n == 1 { name.to_string() } else if ext.is_empty() { @@ -507,11 +566,13 @@ impl Output { } else { format!("{base}-{n}.{ext}") }; - match self.taken.get(&candidate.to_lowercase()) { - Some(k) if k == key || !number => return None, + match self.taken.get(&fold(&candidate)) { + Some(k) if k == key => return None, Some(_) => continue, None => { - self.taken.insert(candidate.to_lowercase(), key.to_string()); + self.taken.insert(fold(&candidate), key.to_string()); + self.next.insert(asked.0.clone(), n + 1); + self.claimed.insert(asked); return Some(candidate); } } @@ -531,7 +592,7 @@ impl Output { match folder { Some(dir) if !keep => { if let Some((sub, _)) = name.rsplit_once('/') - && self.made.insert(sub.to_lowercase()) + && self.made.insert(fold(sub)) { create_dir(&format!("{dir}/{sub}"))?; } @@ -569,7 +630,7 @@ pub struct ScreenExportPreset { /// What a preset keeps: the formats, their settings, the naming and the folders; not which art /// (it changes with the document) nor where to (unless given). -pub const PRESET_KEYS: [&str; 13] = [ +pub const PRESET_KEYS: [&str; 14] = [ "formats", "settings", "preset", @@ -580,6 +641,7 @@ pub const PRESET_KEYS: [&str; 13] = [ "folders", "subfolders", "includeBleed", + "includeArtboardFill", "antiAlias", "folder", "fullDocument", @@ -614,7 +676,7 @@ fn find_preset(s: &Session, name: &str) -> Option { } /// `p` over the settings of its `exportPreset`, when it names one (its own keys win). -fn with_preset(s: &Session, p: &Value) -> Result { +pub(super) fn with_preset(s: &Session, p: &Value) -> Result { let Some(name) = str_param(p, "exportPreset") else { return Ok(p.clone()) }; let preset = find_preset(s, name).ok_or_else(|| bad(C, format!("no export preset `{name}` (see document.exportPresets.list)")))?; let mut merged = preset.settings; @@ -624,24 +686,47 @@ fn with_preset(s: &Session, p: &Value) -> Result { Ok(Value::Object(merged)) } -pub(super) fn presets_list(s: &mut Session, _: &Value) -> Result { +/// The rows of `document.exportPresets.list`: the built-in presets, then `saved`, each +/// `{name, builtIn, settings}`. +pub fn preset_list(saved: &[ScreenExportPreset]) -> Value { let row = |p: &ScreenExportPreset, built_in: bool| json!({"name": p.name, "builtIn": built_in, "settings": p.settings}); - let rows: Vec = - builtin_presets().iter().map(|p| row(p, true)).chain(s.prefs.screen_export_presets.iter().map(|p| row(p, false))).collect(); - Ok(json!({ "presets": rows })) + Value::Array(builtin_presets().iter().map(|p| row(p, true)).chain(saved.iter().map(|p| row(p, false))).collect()) +} + +pub(super) fn presets_list(s: &mut Session, _: &Value) -> Result { + Ok(json!({ "presets": preset_list(&s.prefs.screen_export_presets) })) +} + +/// The [`PRESET_KEYS`] of `given`, refused as an error of command `cmd` when an export would +/// refuse them. +fn preset_settings(s: &Session, cmd: &str, given: &Map) -> Result> { + let settings: Map = given.iter().filter(|(k, _)| PRESET_KEYS.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + // Refuse what an export would refuse, now rather than when the preset is used. + check_settings(s, &Value::Object(settings.clone())).map_err(|e| bad(cmd, e.to_string()))?; + Folders::of(&ScreenParams::of(&Value::Object(settings.clone()))?).map_err(|e| bad(cmd, e.to_string()))?; + let mut settings = settings; + remove_passwords(&mut settings); + Ok(settings) +} + +/// The longest export preset name kept (characters), as for asset names (`assets::MAX_NAME`). +const MAX_PRESET_NAME: usize = 255; + +/// `name` trimmed and at most [`MAX_PRESET_NAME`] characters long (`None` when empty), as +/// `assets::clean_name` keeps an asset name. +fn preset_name(name: &str) -> Option { + let n: String = name.trim().chars().take(MAX_PRESET_NAME).collect(); + (!n.is_empty()).then_some(n) } pub(super) fn presets_save(s: &mut Session, p: &Value) -> Result { const SAVE: &str = "document.exportPresets.save"; - let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(SAVE, "give the preset a name"))?.to_string(); + let name = str_param(p, "name").and_then(preset_name).ok_or_else(|| bad(SAVE, "give the preset a name"))?; if builtin_presets().iter().any(|b| b.name == name) { return Err(bad(SAVE, format!("`{name}` is a built-in preset: save under another name"))); } let given = p.get("settings").and_then(Value::as_object).ok_or_else(|| bad(SAVE, "settings is an object of document.exportForScreens params"))?; - let settings: Map = given.iter().filter(|(k, _)| PRESET_KEYS.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); - // Refuse what an export would refuse, now rather than when the preset is used. - check_settings(s, &Value::Object(settings.clone())).map_err(|e| bad(SAVE, e.to_string()))?; - Folders::of(&ScreenParams::of(&Value::Object(settings.clone()))?).map_err(|e| bad(SAVE, e.to_string()))?; + let settings = preset_settings(s, SAVE, given)?; let preset = ScreenExportPreset { name: name.clone(), settings }; let created = match s.prefs.screen_export_presets.iter_mut().find(|q| q.name == name) { Some(slot) => { @@ -670,12 +755,185 @@ pub(super) fn presets_delete(s: &mut Session, p: &Value) -> Result { Ok(json!({ "deleted": name })) } +/// What `document.exportPresets.export` writes and `document.exportPresets.import` reads. +#[derive(Serialize, Deserialize)] +struct PresetFile { + format: String, + #[serde(default)] + presets: Vec, +} + +/// The `format` of an export presets file, also its extension. +pub const PRESET_FILE_FORMAT: &str = "vcexportpresets"; + +/// The extensions of export presets files (opening one imports it). +pub const PRESET_FILE_EXTS: &[&str] = &[PRESET_FILE_FORMAT]; + +/// The most presets one file imports. +const MAX_IMPORT: usize = 1000; + +/// The most bytes in an export presets file. +const MAX_PRESET_FILE_BYTES: usize = 4 << 20; + +pub(super) fn presets_export(s: &mut Session, p: &Value) -> Result { + const EXPORT: &str = "document.exportPresets.export"; + // A file holds no more presets than an import reads. + let too_many = || bad(EXPORT, format!("more than {MAX_IMPORT} presets")); + let presets = match p.get("names") { + Some(Value::Array(names)) if names.len() > MAX_IMPORT => return Err(too_many()), + Some(Value::Array(names)) => { + let find = |n: &Value| { + let n = n.as_str().ok_or_else(|| bad(EXPORT, "`names` lists preset names"))?; + find_preset(s, n).ok_or_else(|| bad(EXPORT, format!("no export preset `{n}` (see document.exportPresets.list)"))) + }; + names.iter().map(find).collect::>>()? + } + None | Some(Value::Null) => s.prefs.screen_export_presets.clone(), + Some(_) => return Err(bad(EXPORT, "`names` is a list of preset names")), + }; + if presets.is_empty() { + return Err(bad(EXPORT, "no saved export presets to export (name built-in ones in `names`)")); + } + if presets.len() > MAX_IMPORT { + return Err(too_many()); + } + let count = presets.len(); + let text = serde_json::to_string_pretty(&PresetFile { format: PRESET_FILE_FORMAT.into(), presets }).map_err(|e| bad(EXPORT, e.to_string()))?; + if text.len() > MAX_PRESET_FILE_BYTES { + return Err(bad(EXPORT, format!("export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes"))); + } + match str_param(p, "path") { + Some(path) => { + write_file(path, text.as_bytes())?; + Ok(json!({"path": path, "count": count})) + } + None => Ok(json!({"data": text, "count": count})), + } +} + +pub(super) fn presets_import(s: &mut Session, p: &Value) -> Result { + const IMPORT: &str = "document.exportPresets.import"; + let bytes = match (str_param(p, "path"), str_param(p, "data"), str_param(p, "dataBase64")) { + (Some(path), ..) => super::read_file_head(path, MAX_PRESET_FILE_BYTES + 1)?, + (None, Some(text), _) => { + if text.len() > MAX_PRESET_FILE_BYTES { + return Err(bad(IMPORT, format!("export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes"))); + } + text.as_bytes().to_vec() + } + (None, None, Some(b64)) => { + if b64.bytes().filter(|b| !b.is_ascii_whitespace()).count() > MAX_PRESET_FILE_BYTES.div_ceil(3) * 4 { + return Err(bad(IMPORT, format!("export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes"))); + } + vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(IMPORT, "bad dataBase64"))? + } + _ => return Err(bad(IMPORT, "give `path`, `data` or `dataBase64`")), + }; + if bytes.len() > MAX_PRESET_FILE_BYTES { + return Err(bad(IMPORT, format!("export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes"))); + } + let file: PresetFile = serde_json::from_slice(&bytes).map_err(|e| bad(IMPORT, format!("not an export presets file: {e}")))?; + if file.format != PRESET_FILE_FORMAT { + return Err(bad(IMPORT, format!("not an export presets file (format `{}`)", file.format))); + } + if file.presets.len() > MAX_IMPORT { + return Err(bad(IMPORT, format!("more than {MAX_IMPORT} presets"))); + } + // Settings a hand-edited file may carry are refused as document.exportPresets.save refuses + // them, before any preset is added. + let mut presets = vec![]; + for q in file.presets { + let settings = preset_settings(s, IMPORT, &q.settings).map_err(|e| match e { + EngineError::BadParams { msg, .. } => bad(IMPORT, format!("`{}`: {msg}", q.name)), + e => e, + })?; + let name = preset_name(&q.name).unwrap_or_else(|| "Export Preset".to_string()); + presets.push((name, settings)); + } + let replace = bool_or(p, "replace", false); + let saved = &mut s.prefs.screen_export_presets; + let saved_before = saved.len(); + // A built-in name, or a saved one that stays, gets a number. + let mut taken: std::collections::HashSet = + builtin_presets().into_iter().map(|b| b.name).chain(saved.iter().map(|q| q.name.clone())).collect(); + let mut imported = vec![]; + for (base, settings) in presets { + if replace && let Some(slot) = saved.iter_mut().take(saved_before).find(|q| q.name == base) { + slot.settings = settings; + imported.push(base); + continue; + } + let mut name = super::import_name(&base, |n| taken.contains(n)); + if name.chars().count() > MAX_PRESET_NAME { + // A number after a long name stays within the limit: the name is cut to leave room for + // a space and the longest number. + let short: String = base.chars().take(MAX_PRESET_NAME - 21).collect(); + let short = short.trim_end(); + name = super::import_name(short, |n| n == short || taken.contains(n)); + } + taken.insert(name.clone()); + saved.push(ScreenExportPreset { name: name.clone(), settings }); + imported.push(name); + } + Ok(json!({ "imported": imported })) +} + +/// `settings` (a document's export settings) with export preset `name` applied as the Asset +/// Export panel applies one: its formats (or mobile/density `preset`), its format settings over +/// the ones there, its prefix (none when it has none), its folders (`folders`, or `subfolders`) +/// with Create Sub-folders on for a folder per row, and its anti-aliasing. +pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map, name: &str) -> Result<()> { + let preset = find_preset(s, name).ok_or_else(|| bad(cmd, format!("no export preset `{name}` (see document.exportPresets.list)")))?.settings; + if let Some(formats) = preset.get("formats") { + settings.insert("formats".into(), formats.clone()); + settings.remove("preset"); + } else if let Some(p) = preset.get("preset") { + settings.insert("preset".into(), p.clone()); + settings.remove("formats"); + } + if let Some(given) = preset.get("settings").and_then(Value::as_object) { + let all = settings.entry("settings").or_insert_with(|| json!({})); + if !all.is_object() { + *all = json!({}); + } + if let Some(all) = all.as_object_mut() { + for (id, o) in given { + match (all.get_mut(id).and_then(Value::as_object_mut), o.as_object()) { + (Some(mine), Some(o)) => mine.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))), + _ => _ = all.insert(id.clone(), o.clone()), + } + } + } + } + match preset.get("prefix") { + Some(prefix) => _ = settings.insert("prefix".into(), prefix.clone()), + None => _ = settings.remove("prefix"), + } + // Its `folders` (Export for Screens shows it; empty is none, as an export reads it), else its + // `subfolders` (a folder per row or none). Create Sub-folders is on for a folder per row, as + // the dialog sets it. + let folders = preset + .get("folders") + .and_then(Value::as_str) + .map(|f| if f.is_empty() { "none" } else { f }) + .or_else(|| preset.get("subfolders").and_then(Value::as_bool).map(|b| if b { "rows" } else { "none" })); + if let Some(f) = folders { + settings.insert("folders".into(), json!(f)); + settings.insert("subfolders".into(), json!(f == "rows")); + } + if let Some(aa) = preset.get("antiAlias") { + settings.insert("antiAlias".into(), aa.clone()); + } + Ok(()) +} + /// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF /// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard, /// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and -/// so do different files the `name` pattern gives one name. The reply's `warnings` lists every -/// warning the encoders give for the files, each once. +/// so do different files that would share a name, with or without the `name` pattern. The reply's +/// `warnings` lists every warning the encoders give for the files, each once. pub(crate) fn export(s: &mut Session, p: &Value) -> Result { + check_passwords(p)?; let o = ScreenParams::of(p)?; let rows = rows_of(s, p, o.preset.as_deref())?; o.one_source()?; @@ -698,7 +956,9 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result { let crop = rows.iter().any(|r| r.format.id != "pdf"); let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?; // Appearance of Black › Printing / Exporting for RGB raster rows. - let rows = rows.into_iter().map(|r| Row { options: with_black_output(s, &r.options), ..r }).collect(); + // Include Artboard Fill off: the encoders leave the background colors out. + let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) }; + let rows = rows.into_iter().map(|r| Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }).collect(); let export = ScreenExport { cmd: C, o, rows, naming, items }; match &mut s.screens_hand_off { Some(slot) => { @@ -765,11 +1025,14 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> let mut out = Output::default(); // The encoders' warnings for every file, each once. let mut warnings: Vec = Vec::new(); + // Include Bleed: a grown artboard already holds the bleed. Assets, layers and a selection are + // written on a page of their own bounds, which it doesn't grow. + let bleed_on_page = o.include_bleed && o.assets.is_none() && o.layers.is_none() && o.selection.is_none(); let mut write = |doc: &Document, format: &str, options: &Value| -> Result> { // The steps are the files: an encoder's own steps (artboards, pages) are not reported. let (bytes, notes) = vectorcraft_doc::cancel::quiet(|| encode_with_warnings(doc, format, options))?; for w in notes { - if !warnings.contains(&w) { + if !(bleed_on_page && w == super::pdf::BLEED_LEFT_OUT) && !warnings.contains(&w) { warnings.push(w); } } @@ -781,15 +1044,34 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> // One step per item and row, the files a name collision skips included. let steps = (items.len() * rows.len()) as u64; let mut step = 0u64; + // Export PDFs As › Single file: with several artboards, a PDF row writes them all as the pages + // of one file, named as the document, with the first of them. + let artboards: Option> = items.iter().map(|i| i.artboard).collect::>>().filter(|a| naming.single_pdf && a.len() > 1); for (index, item) in items.iter().enumerate() { for r in &rows { vectorcraft_doc::cancel::check()?; vectorcraft_doc::cancel::progress(step, steps, &format!("Exporting file {} of {steps}", step + 1)); step += 1; - let (sub, file) = naming.file(item, index, files, r); + let single = artboards.as_ref().filter(|_| r.format.id == "pdf"); + if single.is_some() && index > 0 { + continue; + } + let document = single.map(|_| Item { + name: naming.filename.clone(), + stem: naming.filename.clone(), + doc: item.doc.clone(), + artboard: None, + region: item.region, + every_artboard: None, + }); + let (sub, file) = naming.file(document.as_ref().unwrap_or(item), index, files, r); let name = sub.map_or_else(|| file.clone(), |d| format!("{d}/{file}")); - let Some(name) = out.claim(&name, &format!("{}|{}", item.stem, r.key), o.name.is_some()) else { continue }; - let bytes = if let (Some(all), "pdf") = (&item.every_artboard, r.format.id) { + let Some(name) = out.claim(&name, &format!("{}|{}", item.stem, r.key)) else { continue }; + let bytes = if let Some(boards) = single { + let mut options = r.options.clone(); + options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::>().join(", ")); + write(&item.doc, "pdf", &options)? + } else if let (Some(all), "pdf") = (&item.every_artboard, r.format.id) { // One page per artboard. let mut options = r.options.clone(); options["range"] = json!("all"); @@ -801,6 +1083,10 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> .entry(b) .or_insert_with(|| { let mut d = single_artboard(&item.doc, item.region, &item.name); + // It keeps its background color. + if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) { + a.color = from.color; + } super::save::keep_art_on(&mut d, item.region); Arc::new(d) }) @@ -900,10 +1186,11 @@ fn items( } isolated(doc, &doc.paint_order(ids.iter().copied()), name).map(|(d, r)| (Arc::new(d), r)) }; - // Each item's stem follows Windows' file-naming rules, and no two items share one. - let safe = |stems: Vec| distinct_names(stems.iter().map(|s| safe_file_name(s))); + // Each item's stem follows Windows' file-naming rules, and no two items share one, compared as + // the item folders are (`fold`). + let safe = |stems: Vec| distinct_names_by(stems.iter().map(|s| safe_file_name(s)), fold); let named = |pieces: Vec<(String, Arc, Option, Rect)>, fallback: &str| -> Vec { - let stems = safe(unique_file_names(pieces.iter().map(|(n, ..)| (n.as_str(), fallback.to_string())))); + let stems = safe(unique_file_names_keeping_dots(pieces.iter().map(|(n, ..)| (n.as_str(), fallback.to_string())))); pieces .into_iter() .zip(stems) @@ -929,6 +1216,9 @@ fn items( let mut pieces = vec![]; for id in ids { let a = doc.asset(*id).ok_or_else(|| bad(C, format!("no asset {id} (see assets.list)")))?; + if a.format_3d.is_some() { + return Err(bad(C, format!("asset {id} is a 3D asset: assets.export3D writes it"))); + } let (d, r) = alone(&a.nodes, &a.name).ok_or_else(|| bad(C, format!("asset `{}` has no art to export", a.name)))?; pieces.push((a.name.clone(), d, Some(0), r)); } @@ -977,7 +1267,7 @@ fn items( if boards.is_empty() { return Err(bad(C, "the document has no artboard")); } - let stems = safe(artboard_file_names(doc, &boards)); + let stems = safe(artboard_file_names_keeping_dots(doc, &boards)); Ok(boards .into_iter() .zip(stems) @@ -1000,9 +1290,61 @@ fn remember(s: &mut Session, p: &Value) { let _ = store_settings(s, settings); } +/// The PDF passwords an export may be given (`security` of a PDF row or of `settings.pdf`). +const PASSWORD_KEYS: [&str; 2] = ["openPassword", "permissionsPassword"]; + +/// Left where [`remove_passwords`] took a password out: an export of these settings is refused +/// until a password is given again ([`check_passwords`]), rather than written unprotected. +const PASSWORD_REQUIRED: &str = "passwordRequired"; + +/// `settings` without the PDF passwords anywhere in them: settings kept in the document (which +/// native saves write) or in the preferences hold the export's choices, never its secrets, as +/// the PDF settings themselves are saved without them. Where one was given, [`PASSWORD_REQUIRED`] +/// says so. +fn remove_passwords(settings: &mut Map) { + let mut removed = false; + for key in PASSWORD_KEYS { + removed |= settings.remove(key).is_some_and(|v| v.as_str().is_none_or(|p| !p.is_empty())); + } + if removed { + settings.insert(PASSWORD_REQUIRED.into(), Value::Bool(true)); + } + for v in settings.values_mut() { + remove_passwords_in(v); + } +} + +/// Refuse export params `v` that hold settings whose PDF passwords were left out +/// ([`PASSWORD_REQUIRED`]) without a password given again. +fn check_passwords(v: &Value) -> Result<()> { + match v { + Value::Object(m) => { + let given = PASSWORD_KEYS.iter().any(|k| m.get(*k).and_then(Value::as_str).is_some_and(|p| !p.is_empty())); + if m.get(PASSWORD_REQUIRED) == Some(&Value::Bool(true)) && !given { + return Err(bad( + C, + "the PDF security settings were saved without their passwords: give openPassword or permissionsPassword again, or security without passwordRequired to export unprotected", + )); + } + m.values().try_for_each(check_passwords) + } + Value::Array(items) => items.iter().try_for_each(check_passwords), + _ => Ok(()), + } +} + +fn remove_passwords_in(v: &mut Value) { + match v { + Value::Object(m) => remove_passwords(m), + Value::Array(items) => items.iter_mut().for_each(remove_passwords_in), + _ => {} + } +} + /// Make `settings` the document's export settings. Not an undo step (like the settings of any /// export); the document has changed only if they differ. -pub(crate) fn store_settings(s: &mut Session, settings: Map) -> Result<()> { +pub(crate) fn store_settings(s: &mut Session, mut settings: Map) -> Result<()> { + remove_passwords(&mut settings); let st = s.doc_mut()?; if st.doc.export_settings != settings { Arc::make_mut(&mut st.doc).export_settings = settings; @@ -1018,7 +1360,26 @@ pub(super) fn export_settings(s: &mut Session, _: &Value) -> Result { #[cfg(test)] mod tests { - use super::{ScreenSize, safe_file_name}; + use super::{Output, ScreenSize, safe_file_name}; + + /// Files given one name are numbered in turn, each numbering going on from the last one (so + /// thousands of them don't each try every number used before), and a file asking again for + /// the name it got is told it has it. + #[test] + fn taken_names_are_numbered_from_the_last_number() { + let mut out = Output::default(); + assert_eq!(out.claim("a.png", "1").as_deref(), Some("a.png")); + assert_eq!(out.claim("A.png", "2").as_deref(), Some("A-2.png")); + assert_eq!(out.claim("a-3.png", "x").as_deref(), Some("a-3.png")); + assert_eq!(out.claim("a.png", "3").as_deref(), Some("a-4.png")); + assert_eq!(out.claim("a.png", "2"), None); + assert_eq!(out.claim("a.png", "1"), None); + assert_eq!(out.claim("sub/a.png", "1").as_deref(), Some("sub/a.png")); + for k in 0..20_000 { + assert!(out.claim("same.png", &k.to_string()).is_some()); + } + assert_eq!(out.claim("same.png", "last").as_deref(), Some("same-20001.png")); + } #[test] fn size_parse_refuses_signs_and_exponents() { @@ -1040,4 +1401,22 @@ mod tests { assert_eq!(safe_file_name("lpt9 .png"), "lpt9-.png"); assert_eq!(safe_file_name("My CON .png"), "My CON .png"); } + + /// The settings an export leaves in the document keep its PDF security choices but not its + /// passwords, in a row or in `settings.pdf`. + #[test] + fn stored_settings_leave_out_pdf_passwords() { + let mut s = crate::Session::new(); + s.execute("file.new", &serde_json::json!({"width": 100, "height": 100})).unwrap(); + let given = serde_json::json!({ + "formats": [{"format": "pdf", "security": {"openPassword": "open sesame", "permissionsPassword": "owner", "printing": "low"}}], + "settings": {"pdf": {"security": {"openPassword": "open sesame", "copy": false}}}, + }); + super::store_settings(&mut s, given.as_object().unwrap().clone()).unwrap(); + let kept = serde_json::Value::Object(s.doc().unwrap().doc.export_settings.clone()); + assert!(!kept.to_string().contains("Password"), "{kept}"); + assert_eq!(kept["formats"][0]["security"]["printing"], "low"); + assert_eq!(kept["settings"]["pdf"]["security"]["copy"], false); + assert_eq!(kept["formats"][0]["security"]["passwordRequired"], true); + } } diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index e0909cb570..56bfd0f7b6 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -169,13 +169,15 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result> = chosen.then(|| boards.iter().flatten().filter_map(|b| doc.artboards.get(*b)).map(|a| a.rect).collect()); let overflow = crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, regions.as_deref()); // Render effects SVG cannot represent faithfully, including source-model Darkness shadows. - let flat = crate::cmd::rasterfx::flatten_pixel_effects(doc); + let flat = crate::cmd::rasterfx::flatten_pixel_effects_for(doc, opts.profile != vectorcraft_svg::Profile::Tiny12); let doc = flat.as_ref().unwrap_or(doc); let mut enc = Encoded { warnings, ..Encoded::default() }; for artboard in boards { diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index f2b770682e..84513cd2c9 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -366,20 +366,21 @@ fn templates_open_untitled() { #[test] fn open_exts_cover_every_readable_format() { for f in FORMATS.iter().filter(|f| f.read) { - for e in f.extensions { + for e in read_extensions(f) { assert!(OPEN_EXTS.contains(e), "OPEN_EXTS lacks .{e} ({})", f.label); } } for e in OPEN_EXTS { - assert!(format(e).is_some_and(|f| f.read), ".{e} in OPEN_EXTS is no readable format"); + assert!(readable_format(e).is_some(), ".{e} in OPEN_EXTS is no readable format"); } let filters: Vec<_> = open_filters().collect(); assert_eq!(filters[0], ("All readable files", OPEN_EXTS)); assert_eq!( filters.len(), - 9 + FORMATS.iter().filter(|f| f.read).count(), - "and swatch libraries, libraries, flattener, PDF and print presets, shortcut sets, scripts, plug-ins" + 10 + FORMATS.iter().filter(|f| f.read).count(), + "and swatch libraries, libraries, flattener, PDF, print and export presets, shortcut sets, scripts, plug-ins" ); + assert!(filters.contains(&("Export presets", SCREEN_EXPORT_PRESET_EXTS)), "File › Open imports export presets"); assert!(filters.contains(&("Scripts", crate::cmd::scripts::EXTS)), "File › Open checks scripts"); assert_eq!(filters.last(), Some(&("Plug-ins", crate::cmd::plugin::EXTS)), "File › Open installs plug-ins"); } @@ -458,7 +459,7 @@ fn formats_query_lists_readers_writers_and_options() { ); assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string())); let png = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "png").unwrap(); - assert_eq!(png["options"]["scale"]["default"], 1); + assert_eq!(png["options"]["scale"]["default"], Value::Null); assert_eq!(r["openExtensions"].as_array().unwrap().len(), OPEN_EXTS.len()); } @@ -679,7 +680,9 @@ fn a_native_save_streams_the_bytes_the_encoder_makes() { s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); for (name, compress) in [("a.vectorcraft", false), ("b.vectorcraft", true), ("c.vctemplate", true)] { let path = d.join(name).to_string_lossy().to_string(); - let p = json!({"path": path, "compress": compress}); + // A PDF-compatible file's PDF is dated to the second it is written, so the byte comparison + // uses files without one. + let p = json!({"path": path, "compress": compress, "pdfCompatible": false}); let r = s.execute("file.saveCopy", &p).unwrap(); let written = std::fs::read(&path).unwrap(); assert_eq!(r["bytes"], written.len(), "{r}"); @@ -689,6 +692,17 @@ fn a_native_save_streams_the_bytes_the_encoder_makes() { assert_eq!(written, job.encode().unwrap().files[0].1, "{name}"); assert_eq!(vectorcraft_format::load(&written).unwrap().template, name.ends_with("vctemplate")); } + // A save with the default options streams a file that carries its PDF. + let path = d.join("d.vectorcraft").to_string_lossy().to_string(); + let p = json!({"path": path}); + let r = s.execute("file.saveCopy", &p).unwrap(); + let written = std::fs::read(&path).unwrap(); + assert_eq!(r["bytes"], written.len(), "{r}"); + assert!(vectorcraft_format::pdf_content(&written).is_some()); + let plan = save_plan(&s, SaveMode::Copy, &p).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + assert!(job.streams()); + assert!(vectorcraft_format::pdf_content(&job.encode().unwrap().files[0].1).is_some()); // A writer that fails: the save fails with its error. let plan = save_plan(&s, SaveMode::Copy, &json!({"path": "/x/y.vectorcraft"})).unwrap(); let job = save_job(&mut s, plan).unwrap(); @@ -703,8 +717,8 @@ fn a_native_save_streams_the_bytes_the_encoder_makes() { } /// An option given beside the path (an SVG option flat or in `svg`) and in `options` with different -/// values is refused before anything is written; `compress`, `version` or `preview` beside the path of a format that doesn't -/// read it is named in the warnings. +/// values is refused before anything is written; `compress`, `version`, `preview` or `precision` beside the path of a format +/// that doesn't read it is named in the warnings. #[test] fn a_save_refuses_disagreeing_options_and_names_unread_native_ones() { let d = tmp_dir("save-options"); @@ -751,6 +765,16 @@ fn a_save_refuses_disagreeing_options_and_names_unread_native_ones() { let r = s.execute("file.saveCopy", &json!({"path": d.join("a.ai").to_string_lossy(), "compress": false, "version": 3})).unwrap(); let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); assert!(w.iter().any(|w| w.starts_with("`version` was not used")) && !w.iter().any(|w| w.starts_with("`compress`")), "{w:?}"); + // `precision` is read by native files and templates only. + for name in ["p.svg", "p.pdf", "p.ai", "p.eps"] { + let r = s.execute("file.saveCopy", &json!({"path": d.join(name).to_string_lossy(), "precision": 2})).unwrap(); + let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(w.iter().any(|w| w.starts_with("`precision` was not used:")), "{name}: {w:?}"); + } + for name in ["p.vectorcraft", "p.vctemplate"] { + let r = s.execute("file.saveCopy", &json!({"path": d.join(name).to_string_lossy(), "precision": 2})).unwrap(); + assert_eq!(r["warnings"], json!([]), "{name}: {r}"); + } let _ = std::fs::remove_dir_all(&d); } @@ -837,3 +861,33 @@ fn a_failed_save_does_not_stamp_the_documents_dates() { s.execute("edit.undo", &json!({})).unwrap(); assert!(!s.doc().unwrap().is_dirty()); } + +/// #4284: a photo whose EXIF orientation says the camera was turned places upright: its pixels +/// turned as the orientation says, its width and height swapped. One without keeps its own bytes. +#[test] +fn a_photo_places_the_way_its_exif_orientation_says() { + // 16 × 8, red on the left half. + let mut rgb = image::RgbImage::from_pixel(16, 8, image::Rgb([255, 255, 255])); + for y in 0..8 { + for x in 0..8 { + rgb.put_pixel(x, y, image::Rgb([220, 0, 0])); + } + } + let mut jpg = Vec::new(); + image::DynamicImage::ImageRgb8(rgb).write_to(&mut Cursor::new(&mut jpg), image::ImageFormat::Jpeg).unwrap(); + // An EXIF segment with Orientation 6: turn a quarter clockwise to show. + let exif: Vec = + [b"Exif\0\0".as_slice(), b"II", &[0x2a, 0, 8, 0, 0, 0], &[1, 0], &[0x12, 0x01, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0], &[0, 0, 0, 0]].concat(); + let mut turned = jpg[..2].to_vec(); + turned.extend([0xff, 0xe1]); + turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes()); + turned.extend(&exif); + turned.extend(&jpg[2..]); + let plain = raster_image(&jpg).unwrap(); + assert_eq!((plain.width, plain.height, plain.blob.bytes.as_slice()), (16, 8, jpg.as_slice()), "a photo as taken keeps its bytes"); + let img = raster_image(&turned).unwrap(); + assert_eq!((img.width, img.height), (8, 16), "turned a quarter"); + let px = image::load_from_memory(&img.blob.bytes).unwrap().to_rgb8(); + let red = |p: &image::Rgb| p[0] > 150 && p[1] < 80; + assert!(red(px.get_pixel(4, 3)) && !red(px.get_pixel(4, 12)), "the left half is on top"); +} diff --git a/crates/engine/src/cmd/fileio/tests_affinity.rs b/crates/engine/src/cmd/fileio/tests_affinity.rs index ae8f6cc452..05ca07019f 100644 --- a/crates/engine/src/cmd/fileio/tests_affinity.rs +++ b/crates/engine/src/cmd/fileio/tests_affinity.rs @@ -98,7 +98,9 @@ fn templates_and_libraries_cannot_silently_extract_preview_content() { let original = s.doc().unwrap().doc.clone(); for name in ["test.af", "renamed.svg"] { let p = json!({"name":name, "dataBase64":vectorcraft_format::base64_encode(&file(&png()))}); - for cmd in ["file.newFromTemplate", "swatch.library.load", "graphicStyle.loadLibrary"] { + for cmd in + ["file.newFromTemplate", "swatch.library.load", "graphicStyle.loadLibrary", "charStyle.load", "paraStyle.load", "textStyle.loadAll"] + { let e = s.execute(cmd, &p).unwrap_err().to_string(); assert!(e.contains("File › Open"), "{cmd}: {e}"); } @@ -300,6 +302,176 @@ mod native { } } + /// A version-12 document holding an open curve with an 8 px stroke whose pressure curve (`LDeP`) + /// is made of `records`. + fn pressure_document(records: Vec>) -> Vec { + pressure_documents(records, 1) + } + + /// [`pressure_document`] with `copies` curves, all linking the first one's fill and stroke. + fn pressure_documents(records: Vec>, copies: u32) -> Vec { + let mut style = Some(( + solid(24, rgba(0.0, 0.0, 0.0, 1.0)), + F::Def( + 27, + vec![tag(b"LDsc")], + vec![ + (tag(b"LDeL"), F::Def(28, vec![tag(b"LSty")], vec![(tag(b"Wght"), F::F64(8.0))])), + (tag(b"LDSc"), F::Bool(false)), + (tag(b"LDeP"), F::Obj(tag(b"CrvD"), vec![(tag(b"Data"), F::Pos(vec![F::U32(0), F::Bool(false), F::Records(18, records)]))])), + ], + ), + )); + let lines = (0..copies) + .map(|i| { + let (fill, line) = style.take().unwrap_or((F::Ref(24), F::Ref(27))); + F::Def( + if i == 0 { 20 } else { 1000 + i }, + vec![tag(b"PCrv"), tag(b"VNod"), tag(b"Node")], + vec![ + ( + tag(b"Crvs"), + F::Obj( + tag(b"PCvD"), + vec![( + tag(b"Data"), + F::Pos(vec![ + F::U8(0), + F::U32(1), + F::Bool(false), + F::Records(18, vec![node(0.0, 0.0, 1, 0), node(100.0, 0.0, 1, 0)]), + ]), + )], + ), + ), + (tag(b"LIFl"), F::Shared(vec![fill])), + (tag(b"LILn"), F::Shared(vec![line])), + ], + ) + }) + .collect(); + let spread = F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 200.0, 100.0])), (tag(b"Chld"), F::Shared(lines))]); + let doc = synth::stream(&[ + (tag(b"UVCn"), F::Obj(tag(b"UVCn"), vec![(tag(b"UPPI"), F::F64(72.0))])), + (tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))])), + ]); + synth::container(&[("doc.dat", &doc, Method::Zstd)], Some(&png())) + } + + /// The width profile of the only stroked path in `d`. + fn stroke_of(d: &vectorcraft_doc::Document) -> vectorcraft_doc::appearance::StrokeLayer { + let mut found = None; + d.walk(|n| { + if let Some(AppearanceItem::Stroke(k)) = n.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + found = Some(k.clone()); + } + }); + found.unwrap_or_else(|| panic!("no stroke in {:?}", d.layers)) + } + + #[test] + fn a_pressure_curve_becomes_the_strokes_width_profile() { + // Thin at the start, full width from half way: anchor (0, 0), handles (0.25, 0.5) and + // (0.5, 1), anchor (0.5, 1), then straight on to anchor (1, 1). + let curve = vec![node(0.0, 0.0, 4, 0), node(0.25, 0.5, 0, 1), node(0.5, 1.0, 0, 2), node(0.5, 1.0, 4, 0), node(1.0, 1.0, 4, 0)]; + let r = load("pressure.af", &pressure_document(curve)).unwrap(); + assert!(!r.preview_only); + assert!(r.warnings.iter().all(|w| !w.contains("pressure")), "{:?}", r.warnings); + let k = stroke_of(&r.doc); + assert_eq!(k.width, 8.0); + let profile = k.profile.unwrap_or_else(|| panic!("the pressure curve is read: {:?}", r.warnings)); + assert_eq!(profile.points.first(), Some(&(0.0, 0.0, 0.0))); + assert_eq!(profile.points.last(), Some(&(1.0, 1.0, 1.0))); + assert!(profile.points.windows(2).all(|w| w[0].0 <= w[1].0), "positions go forward: {:?}", profile.points); + let (left, right) = profile.at(0.25); + assert!(left > 0.25 && left < 1.0 && left == right, "{left} {right}"); + assert_eq!(profile.at(0.75), (1.0, 1.0)); + + // Widths past the full weight are held at it. + let huge = vec![node(0.0, 0.0, 4, 0), node(0.5, 1e300, 4, 0), node(1.0, 0.0, 4, 0)]; + let profile = stroke_of(&load("huge.af", &pressure_document(huge)).unwrap().doc).profile.unwrap(); + assert!(profile.points.iter().all(|p| (0.0..=1.0).contains(&p.1)), "{:?}", profile.points); + assert_eq!(profile.at(0.5), (1.0, 1.0)); + + // Each segment is sampled inside too: anchors at full width whose handles dip to nothing + // still narrow the stroke, with 256 segments. + let mut dips = vec![node(0.0, 1.0, 4, 0)]; + for i in 1..=256 { + let (a, b) = (f64::from(i - 1) / 256.0, f64::from(i) / 256.0); + dips.extend([node(a + (b - a) / 3.0, 0.0, 0, 1), node(b - (b - a) / 3.0, 0.0, 0, 2), node(b, 1.0, 4, 0)]); + } + let profile = stroke_of(&load("dips.af", &pressure_document(dips)).unwrap().doc).profile.unwrap(); + assert!(profile.points.iter().any(|p| p.1 < 0.5), "{:?}", profile.points); + + // A curve of more than 256 segments is left out, with a warning. + let long: Vec> = (0..=300).map(|i| node(f64::from(i) / 300.0, f64::from(i % 2), 4, 0)).collect(); + let r = load("long.af", &pressure_document(long)).unwrap(); + assert!(stroke_of(&r.doc).profile.is_none()); + assert!(r.warnings.iter().any(|w| w.contains("pressure curve can't be read")), "{:?}", r.warnings); + + // A pressure curve at full width all along leaves the stroke plain. + let flat = vec![node(0.0, 1.0, 4, 0), node(1.0, 1.0, 4, 0)]; + let r = load("flat.af", &pressure_document(flat)).unwrap(); + assert!(stroke_of(&r.doc).profile.is_none()); + assert!(r.warnings.iter().all(|w| !w.contains("pressure")), "{:?}", r.warnings); + } + + #[test] + fn a_dip_between_the_samples_of_a_long_pressure_curve_is_kept() { + // 256 segments at full width, except one whose handles sit at widths 0 and 2: its width is + // 1 at its middle and end but 0.71875 a quarter of the way along. + let mut curve = vec![node(0.0, 1.0, 4, 0)]; + for i in 1..=256 { + let (a, b) = (f64::from(i - 1) / 256.0, f64::from(i) / 256.0); + let (h1, h2) = if i == 100 { (0.0, 2.0) } else { (1.0, 1.0) }; + curve.extend([node(a + (b - a) / 3.0, h1, 0, 1), node(b - (b - a) / 3.0, h2, 0, 2), node(b, 1.0, 4, 0)]); + } + let profile = stroke_of(&load("dip.af", &pressure_document(curve)).unwrap().doc).profile.unwrap_or_else(|| panic!("the dip is kept")); + let narrowest = profile.points.iter().map(|p| p.1).fold(1.0, f64::min); + assert!((narrowest - 0.71).abs() < 0.02, "{narrowest}"); + } + + #[test] + fn a_pressure_curve_just_under_full_width_is_kept() { + let curve = vec![node(0.0, 0.9995, 4, 0), node(1.0, 0.9995, 4, 0)]; + let profile = stroke_of(&load("near.af", &pressure_document(curve)).unwrap().doc).profile.unwrap_or_else(|| panic!("the curve is kept")); + assert_eq!(profile.at(0.5), (0.9995, 0.9995)); + } + + #[test] + fn pressure_curves_stay_within_the_points_of_one_document() { + // One 256-segment curve linked from 2100 strokes: more than a million points in all. + let mut curve = vec![node(0.0, 1.0, 4, 0)]; + for i in 1..=256 { + let (a, b) = (f64::from(i - 1) / 256.0, f64::from(i) / 256.0); + curve.extend([node(a + (b - a) / 3.0, 0.0, 0, 1), node(b - (b - a) / 3.0, 0.0, 0, 2), node(b, 1.0, 4, 0)]); + } + let r = load("many.af", &pressure_documents(curve, 2100)).unwrap(); + let mut profiles = Vec::new(); + r.doc.walk(|n| { + if let Some(AppearanceItem::Stroke(k)) = n.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + profiles.push(k.profile.as_ref().map_or(0, |p| p.points.len())); + } + }); + assert_eq!(profiles.len(), 2100); + assert!(profiles.iter().sum::() <= 1 << 20, "{}", profiles.iter().sum::()); + assert!(profiles.iter().filter(|n| **n > 0).count() > 1000); + assert!(profiles.contains(&0)); + assert!(r.warnings.iter().any(|w| w.contains("pressure points one document may hold")), "{:?}", r.warnings); + + // Curves at full width count too, so linking one from many strokes can't repeat its work + // without bound. + let flat: Vec> = (0..=768).map(|i| node(f64::from(i) / 768.0, 1.0, if i % 3 == 0 { 4 } else { 0 }, (i % 3) as u8)).collect(); + let r = load("flat-many.af", &pressure_documents(flat, 2100)).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("pressure points one document may hold")), "{:?}", r.warnings); + + // So do curves that can't be read: 768 segments, more than a curve may have. + let long: Vec> = (0..=768).map(|i| node(f64::from(i) / 768.0, f64::from(i % 2), 4, 0)).collect(); + let r = load("long-many.af", &pressure_documents(long, 2100)).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("pressure curve can't be read")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("pressure points one document may hold")), "{:?}", r.warnings); + } + #[test] fn native_documents_save_reopen_export_place_and_template() { let bytes = document(Method::Zstd); diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 3f0dce5c15..489da992a7 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -6,7 +6,7 @@ use std::io::Write as _; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_doc::{Node, NodeId, NodeKind}; use vectorcraft_testkit::ai; use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; @@ -82,6 +82,235 @@ fn an_illustrator_ai_file_opens_from_its_editing_data() { assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]); } +/// Opening a `.ai` or a PDF whose PDF part reads, or a `.ai` saved without PDF compatibility, +/// reads and checks the file once, on any thread, for the document it may carry, its pages, its +/// editing data and its File Info, with pages picked or not. +#[test] +fn an_ai_or_pdf_file_is_read_once_when_it_opens() { + let ai_file = ai::ai(&compressed(&ai::sample_data()), ai::page_pdf()); + let pdf_file = pdf_with(&[PdfPage::new(100.0, 100.0, "0 0 1 rg 10 10 50 50 re f")], &[], None); + let placeholder = ai::ai(&compressed(&ai::sample_data()), PLACEHOLDER); + for (name, file) in [("art.ai", &ai_file), ("art.pdf", &pdf_file), ("placeholder.ai", &placeholder)] { + for opts in [LoadOptions::default(), LoadOptions { pages: Some("1".into()), ..Default::default() }] { + let before = vectorcraft_pdf::reads_of(file); + let loaded = load_with(name, file, &opts).unwrap(); + assert_eq!(vectorcraft_pdf::reads_of(file) - before, 1, "{name}, pages {:?}", opts.pages); + let editing_data = name == "placeholder.ai" || (name == "art.ai" && opts.pages.is_none()); + assert_eq!(loaded.editing_data, editing_data, "{name}, pages {:?}", opts.pages); + } + } +} + +#[test] +fn an_ai_file_opens_with_its_artboard_options_raster_settings_and_author() { + let document = "%_/Document :\n%_/Dictionary :\n%_/Dictionary :\n%_150 /Int (dpi.) ,\n%_1 /Bool (mask) ,\n%_; (AI Auto Rasterize) ,\n\ + %_/Array :\n%_/Dictionary :\n%_3 /Int (DisplayMark) ,\n%_1.33 /Real (PAR) ,\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n\ + %_200 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_(Board) /UnicodeString (Name) ,\n%_; ,\n%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + // The sample (it holds binary samples) with `insert` before the first `at`. + let before = |data: Vec, at: &[u8], insert: &str| { + let i = data.windows(at.len()).position(|w| w == at).unwrap(); + [&data[..i], insert.as_bytes(), &data[i..]].concat() + }; + let data = before(before(ai::sample_data(), b"%%EndComments", "%%For: (Ann Lee) (Studio)\n"), b"%AI5_BeginLayer", document); + let mut s = Session::new(); + let r = open(&mut s, "art.ai", &ai::ai(&data, ai::page_pdf()), json!({})).unwrap(); + check_sample(&s); + let d = &s.doc().unwrap().doc; + assert!(r["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("weren't read")), "{r}"); + let b = &d.artboards[0]; + assert_eq!((b.name.as_str(), b.show_center_mark, b.show_cross_hairs, b.show_video_safe_areas), ("Board", true, true, false)); + assert_eq!(b.video_ruler_pixel_aspect_ratio, 1.33); + assert_eq!((d.raster_effects_ppi, d.raster_effects.clipping_mask), (150.0, true)); + assert_eq!(d.metadata.author, "Ann Lee"); +} + +#[test] +fn an_ai_file_opens_with_its_active_artboard() { + let board = |x: i32, name: &str| { + format!( + "%_/Dictionary :\n%_{x} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_({name}) /UnicodeString (Name) ,\n%_; ,\n", + x + 200 + ) + }; + let document = format!( + "%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}%_; (ArtboardArray) ,\n%_1 /Int (CropAreaActive) ,\n%_; /NotRecorded ,\n%_;\n", + board(0, "One"), + board(300, "Two") + ); + let data = ai::sample_data(); + let at = data.windows(15).position(|w| w == b"%AI5_BeginLayer").unwrap(); + let data = [&data[..at], document.as_bytes(), &data[at..]].concat(); + let mut s = Session::new(); + let r = open(&mut s, "art.ai", &ai::ai(&compressed(&data), PLACEHOLDER), json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.artboards.iter().map(|a| a.name.as_str()).collect(); + assert_eq!(names, ["One", "Two"], "{r}"); + assert_eq!(d.opened_artboard, Some(d.artboards[1].id), "{r}"); +} + +/// A `.ai` or `.ait` file VectorCraft wrote reopens, restored from the document it carries, on the +/// artboard its editing copy names as active; without the copy, on the first artboard. +#[test] +fn a_restored_ai_file_opens_on_the_artboard_active_when_saved() { + let mut doc = vectorcraft_doc::Document::new(100.0, 100.0); + let first = doc.artboards[0].clone(); + for (i, id) in [(1.0, 7), (2.0, 9)] { + let x0 = i * 150.0; + doc.artboards.push(vectorcraft_doc::Artboard { id, rect: vectorcraft_geom::Rect::new(x0, 0.0, x0 + 100.0, 100.0), ..first.clone() }); + } + let mut s = Session::new(); + // The view's artboard, one the document doesn't have, none, and the first. + for (active, opened, reopened) in + [(Some(7), None, Some(7)), (Some(99), Some(9), Some(9)), (None, Some(9), Some(9)), (Some(first.id), Some(9), None)] + { + for (cmd, format) in [("document.save", "ai"), ("file.saveAsTemplate", "ait")] { + let mut d = doc.clone(); + d.opened_artboard = opened; + s.add_document(d, None); + s.doc_mut().unwrap().active_artboard = active; + let saved = s.execute(cmd, &json!({"format": format})).unwrap(); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let r = open(&mut s, &format!("again.{format}"), &bytes, json!({})).unwrap(); + assert_eq!(r["restored"], json!(true), "{r}"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.artboards.iter().map(|a| a.id).collect::>(), [first.id, 7, 9]); + assert_eq!(d.opened_artboard, reopened, "{format} {active:?} {opened:?}"); + } + } + // A file saved without its PDF part still has the editing copy. + s.add_document(doc.clone(), None); + s.doc_mut().unwrap().active_artboard = Some(7); + let saved = s.execute("document.save", &json!({"format": "ai", "options": {"pdfCompatible": false}})).unwrap(); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let r = open(&mut s, "again.ai", &bytes, json!({})).unwrap(); + assert_eq!(r["restored"], json!(true), "{r}"); + assert_eq!(s.doc().unwrap().doc.opened_artboard, Some(7), "{r}"); + // Without the editing copy, the file reopens on the first artboard. + s.add_document(doc.clone(), None); + s.doc_mut().unwrap().active_artboard = Some(7); + let saved = s.execute("document.save", &json!({"format": "ai", "options": {"editingData": false}})).unwrap(); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let r = open(&mut s, "again.ai", &bytes, json!({})).unwrap(); + assert_eq!(r["restored"], json!(true), "{r}"); + assert_eq!(s.doc().unwrap().doc.opened_artboard, None, "{r}"); +} + +/// A `.ai` save names the view's active artboard in its editing copy, else the one the document +/// opened on, else the first; the file read from that copy opens on it. +#[test] +fn an_ai_save_names_its_active_artboard() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 60, "height": 40, "artboards": 3})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let ids: Vec = s.doc().unwrap().doc.artboards.iter().map(|a| a.id).collect(); + let opts = LoadOptions { native: false, ..Default::default() }; + let active = |s: &mut Session, format: &str| { + let cmd = if format == "ait" { "file.saveAsTemplate" } else { "file.saveCopy" }; + let saved = s.execute(cmd, &json!({"format": format})).unwrap(); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let l = load::load_with(&format!("a.{format}"), &bytes, &opts).unwrap(); + assert!(l.editing_data && !l.restored, "{:?}", l.warnings); + assert_eq!(l.doc.artboards.len(), 3); + l.doc.opened_artboard.and_then(|id| l.doc.artboards.iter().position(|a| a.id == id)).unwrap_or(0) + }; + assert_eq!(active(&mut s, "ai"), 0); + // The view's. + s.doc_mut().unwrap().active_artboard = Some(ids[2]); + assert_eq!((active(&mut s, "ai"), active(&mut s, "ait")), (2, 2)); + // The one the document opened on, when the view names none or an artboard it doesn't have. + Arc::make_mut(&mut s.doc_mut().unwrap().doc).opened_artboard = Some(ids[1]); + for view in [None, Some(99)] { + s.doc_mut().unwrap().active_artboard = view; + assert_eq!(active(&mut s, "ai"), 1, "{view:?}"); + } + // The view's first artboard over the one the document opened on. + s.doc_mut().unwrap().active_artboard = Some(ids[0]); + assert_eq!(active(&mut s, "ai"), 0); + assert_eq!(s.doc().unwrap().doc.opened_artboard, Some(ids[1]), "the document is unchanged"); +} + +/// A `.ai` export (`document.serialize`, `document.export`, with or without `selectedOnly`) names +/// the view's active artboard in its editing copy, as a save does. +#[test] +fn an_ai_export_names_its_active_artboard() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 60, "height": 40, "artboards": 3})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let ids: Vec = s.doc().unwrap().doc.artboards.iter().map(|a| a.id).collect(); + s.doc_mut().unwrap().active_artboard = Some(ids[2]); + let opts = LoadOptions { native: false, ..Default::default() }; + for (cmd, selected) in [("document.serialize", false), ("document.serialize", true), ("document.export", false)] { + let out = s.execute(cmd, &json!({"format": "ai", "selectedOnly": selected})).unwrap(); + let bytes = vectorcraft_format::base64_decode(out["dataBase64"].as_str().unwrap()).unwrap(); + let l = load::load_with("a.ai", &bytes, &opts).unwrap(); + assert!(l.editing_data && !l.restored, "{cmd}: {:?}", l.warnings); + let active = l.doc.opened_artboard.and_then(|id| l.doc.artboards.iter().position(|a| a.id == id)); + assert_eq!(active, Some(2), "{cmd} {selected}"); + } + assert_eq!(s.doc().unwrap().doc.opened_artboard, None, "the document is unchanged"); +} + +#[test] +fn an_ai_unread_group_keeps_its_layers_and_live_neighbor() { + let live = format!("0 0 1 0 k\n{}f", ai::rect(10.0, 10.0, 14.0, 14.0)); + let unread = format!("u\n0 0 1 0 k\n{}f\nZZ\nU\n{}", ai::rect(50.0, 10.0, 54.0, 14.0), ai::named("Unread")); + let data = ai::editing_data(200.0, 100.0, &(ai::layer("Live", &live) + &ai::layer("Mixed", &unread))); + let page = "0 0 1 0 k 10 10 4 4 re f 1 0 0 0 k 50 10 4 4 re f"; + let mut session = Session::new(); + let result = open(&mut session, "unread.ai", &ai::ai(&compressed(data.as_bytes()), page), json!({})).unwrap(); + let doc = &session.doc().unwrap().doc; + assert_eq!(names(&doc.layers), ["Live", "Mixed"], "{result}"); + assert!(matches!(doc.layers[0].children().unwrap()[0].kind, NodeKind::Path { .. }), "{result}"); + assert!(matches!(doc.layers[1].children().unwrap()[0].kind, NodeKind::Group { .. }), "{result}"); + assert_eq!(doc.layers[1].children().unwrap()[0].name.as_deref(), Some("Unread"), "{result}"); + let replacement = &doc.layers[1].children().unwrap()[0].children().unwrap()[0]; + assert!( + matches!(replacement.appearance.items.first(), Some(vectorcraft_doc::AppearanceItem::Fill(fill)) + if fill.paint == vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0))), + "{result}" + ); + assert!(result["warnings"].to_string().contains("`ZZ` (1)"), "{result}"); +} + +#[test] +fn a_differing_object_keeps_the_layers_with_a_note() { + let square = |cmyk: &str, x: f64| format!("{cmyk} k\n{}f\n", ai::rect(x, 40.0, x + 16.0, 56.0)); + let front = square("0 0 0 1", 90.0) + &square("0 0 1 0", 160.0); + let data = ai::editing_data(200.0, 100.0, &(ai::layer("Back", &square("0 0 1 0", 20.0)) + &ai::layer("Front", &front))); + let page = "0 0 1 0 k 20 40 16 16 re f 1 0 0 0 k 90 40 16 16 re f 0 0 1 0 k 160 40 16 16 re f"; + let mut session = Session::new(); + let result = open(&mut session, "differs.ai", &ai::ai(&compressed(data.as_bytes()), page), json!({})).unwrap(); + let doc = &session.doc().unwrap().doc; + assert_eq!(names(&doc.layers), ["Back", "Front"], "{result}"); + let front = doc.layers[1].children().unwrap(); + assert!(matches!(front[0].kind, NodeKind::Group { .. }) && matches!(front[1].kind, NodeKind::Path { .. }), "{result}"); + let replacement = &front[0].children().unwrap()[0]; + assert!( + matches!(replacement.appearance.items.first(), Some(vectorcraft_doc::AppearanceItem::Fill(fill)) + if fill.paint == vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0))), + "{result}" + ); + assert!( + result["warnings"].to_string().contains("objects that drew differently from the file's own page came in as its art: Front (1)"), + "{result}" + ); + // An export to the file's own path is refused unless it is given `acknowledgeLoss`. + let d = std::env::temp_dir().join(format!("vc-aidiffers-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + let path = d.join("differs.ai"); + let file = ai::ai(&compressed(data.as_bytes()), page); + std::fs::write(&path, &file).unwrap(); + let path = path.to_string_lossy().to_string(); + let mut s = Session::new(); + s.execute("document.open", &json!({"path": path})).unwrap(); + let e = s.execute("document.export", &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains("left things out") && e.contains("objects that drew differently"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), file); + s.execute("document.export", &json!({"path": path, "acknowledgeLoss": true})).unwrap(); + assert_ne!(std::fs::read(&path).unwrap(), file); + std::fs::remove_dir_all(d).ok(); +} + /// A palette of three swatches and a color group `Inks` holding a fourth. const INKS_PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\n0.04 0.3 0 0 81.96 21 -8 (Pink ink) 0 2 Xx\n(Pink ink)\nPc\n\ 0.06 0.98 1 0 (Red ink) 0 x\n(Red ink)\nPc\n1 (Inks) 1 Pg\n0.02 0.1 1 0 (Yellow ink) 0 x\n(Yellow ink)\nPc\nPB\n%AI5_EndPalette\n"; @@ -115,6 +344,36 @@ fn an_ai_file_opens_with_the_swatches_of_its_palette() { ); } +/// A `.ai` opens with the graphic styles of its style list, in the list's order, and an object read +/// as itself with a listed style is linked to it. +#[test] +fn an_ai_file_opens_with_the_graphic_styles_of_its_style_list() { + let style = |name: &str, xa: &str| { + format!( + "/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n" + ) + }; + let styles = format!( + "%AI9_BeginArtStyles\n{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Red)\n(Blue)\n%AI9_EndArtStyleList\n", + style("Blue", "0 0 0 0 0 0 1 Xa\n"), + style("Red", "0 0 0 0 1 0 0 Xa\n") + ); + let hidden = ai::rect(10.0, 50.0, 40.0, 90.0).replace('\n', "\n%_"); + let art = format!("0 Ae\nu\n0 0 0 0 1 0 0 Xa\n{}f\nU\n%_{hidden}f\n1 (Red) XW\n", ai::rect(10.0, 50.0, 40.0, 90.0)); + let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("Art", &art))); + let mut s = Session::new(); + let r = open(&mut s, "styles.ai", &ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + assert_eq!(names(&doc.layers), ["Art"], "opened from the editing data: {r}"); + let styles: Vec<(&str, u32)> = doc.graphic_styles.iter().map(|g| (g.name.as_str(), g.id)).collect(); + assert_eq!(styles, [("Red", 1), ("Blue", 2)]); + let square = &doc.layers[0].children().unwrap()[0]; + assert_eq!(square.extras().graphic_style, Some(1), "{square:#?}"); +} + /// A `.ai` whose editing data has a palette and no layers, as a swatch library is saved, opens as its /// PDF part with the swatches and color groups of its palette in place of the default swatches. #[test] @@ -154,6 +413,71 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() { assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}"); } +/// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the +/// library the styles of its list, in the list's order, not the default styles; the file opens with +/// them too. +#[test] +fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() { + let style = |name: &str, xa: &str| { + format!( + "/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n" + ) + }; + let styles = format!( + "%AI9_BeginArtStyles\n{}{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n%AI9_EndArtStyleList\n", + style("Blue", "0 0 0 0 0 0 1 Xa\n"), + style("Green", "0 0 0 0 0 1 0 Xa\n"), + style("Red", "0 0 0 0 1 0 0 Xa\n") + ); + let data = ai::editing_data(200.0, 100.0, &styles); + let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f"); + let mut s = Session::new(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "fills.ai"}); + let r = s.execute("graphicStyle.loadLibrary", &p).unwrap(); + assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(3)), "{r}"); + let lib = s.execute("graphicStyle.library", &json!({"library": r["library"]})).unwrap(); + let names: Vec<&str> = lib["styles"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Red", "Green", "Blue"], "{lib}"); + let r = open(&mut s, "fills.ai", &file, json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + let styles: Vec<(&str, u32)> = doc.graphic_styles.iter().map(|g| (g.name.as_str(), g.id)).collect(); + assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3)], "{r}"); +} + +/// A `.ai` symbol library (symbols and their list, no layers) opens with its symbols, and Other +/// Library… in the Symbols panel lists them in the list's order. +#[test] +fn a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols() { + let symbol = |name: &str, x: f64| { + format!( + "%AI14_BeginSymbol\n({name})\n0 A\n0 Xw\n0 Ae\nu\n0 1 1 0 1 0 0 Xa\n{x} 0 m\n{x} 4 L\n{} 4 L\n{} 0 L\nf\nU\n\ + %_/ArtDictionary :\n%_5 /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n", + x + 4.0, + x + 4.0 + ) + }; + let symbols = format!( + "%AI5_Begin_NonPrinting\n{}{}{}%AI5_End_NonPrinting--\n%AI24_BeginSymbolList\n(Star)\n(Leaf)\n(Arrow)\n%AI24_EndSymbolList\n", + symbol("Arrow", 0.0), + symbol("Leaf", 10.0), + symbol("Star", 20.0) + ); + let data = ai::editing_data(200.0, 100.0, &symbols); + let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f"); + let mut s = Session::new(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "shapes.ai"}); + let r = s.execute("symbol.loadLibrary", &p).unwrap(); + assert_eq!((&r["name"], &r["count"]), (&json!("shapes"), &json!(3)), "{r}"); + let lib = s.execute("symbol.library", &json!({"library": r["library"]})).unwrap(); + let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Star", "Leaf", "Arrow"], "{lib}"); + let r = open(&mut s, "shapes.ai", &file, json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + let names: Vec<&str> = doc.symbols.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, ["Star", "Leaf", "Arrow"], "{r}"); +} + /// A 1-bit RGB image opens from the editing data in the colors its PDF part shows. #[test] fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() { @@ -175,6 +499,24 @@ fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() { assert_eq!(found, [[[255, 0, 0], [0, 255, 0], [0, 0, 255]]], "{r}"); } +/// A stroke of width 0 (`0 w`) in the editing data is the thinnest line the device draws: the +/// opened `.ai` shows a hairline where the same path without its stroke shows nothing. +#[test] +fn a_zero_width_stroke_in_the_editing_data_draws_a_hairline() { + let drawn = |art: &str| { + let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", art)); + let file = ai::ai(&compressed(data.as_bytes()), ""); + let mut s = Session::new(); + let r = open(&mut s, "zero.ai", &file, json!({})).unwrap(); + assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}"); + let v = s.execute("document.export", &json!({"format": "png", "background": "transparent"})).unwrap(); + let png = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + image::load_from_memory(&png).unwrap().to_rgba8().pixels().filter(|p| p.0[3] > 0).count() + }; + assert!(drawn("0 1 1 0 1 0 0 XA\n0 w\n20 20 m\n180 80 L\nS\n") > 0, "the hairline draws"); + assert_eq!(drawn("0 1 1 0 1 0 0 XA\n0 w\n20 20 m\n180 80 L\nN\n"), 0, "the unstroked path draws nothing"); +} + /// A page of a square and a line of type, as a `.ai`'s PDF part draws them. const SQUARE_AND_TYPE: &str = "0 g 10 10 40 40 re f BT /F1 12 Tf 100 50 Td (Hi) Tj ET"; @@ -326,6 +668,167 @@ fn editing_data_that_cant_be_read_keeps_the_pdf_parts_notes() { assert_eq!(r["warnings"], json!([vectorcraft_pdf::PAST_PAGE_NOTE, unread]), "{r}"); } +/// Decode parameters the import refuses, for the page's content stream (#4366). +const REFUSED_CONTENT: &str = "/DecodeParms << /Predictor 12 /Columns 0 >>"; + +/// A `.ai` and a PDF saved with the editing data, carrying `private`, whose page's content stream +/// the import refuses. +fn refused_files(private: &[u8], page: &str) -> [(&'static str, Vec); 2] { + [("art.ai", ai::ai_with_content(private, page, REFUSED_CONTENT)), ("art.pdf", ai::pdf_with_content(private, page, REFUSED_CONTENT))] +} + +/// The note of a file opened from its editing data because its PDF part fails with `e`. +fn unread_pdf_part(e: &str) -> String { + format!("the PDF part couldn't be read ({e}): the file opened from its editing data") +} + +/// #4366: a `.ai`, or a PDF saved with the editing data, whose PDF part can't be read opens from +/// its editing data, with a first note saying why. Pages picked, layers off or the editing data +/// off keep the error, and so does editing data that can't be read. +#[test] +fn a_file_whose_pdf_part_cant_be_read_opens_from_its_editing_data() { + let mut s = Session::new(); + for (name, file) in refused_files(&compressed(&ai::sample_data()), ai::page_pdf()) { + let e = open(&mut s, name, &file, json!({"editingData": false})).unwrap_err().to_string(); + assert!(e.contains("a page's content in it (object 4) has decode parameters that can't be applied"), "{name}: {e}"); + let r = open(&mut s, name, &file, json!({})).unwrap(); + assert_eq!(r["format"], json!(&name[4..]), "{name}: {r}"); + assert_eq!(r["warnings"], json!([unread_pdf_part(&e)]), "{name}: {r}"); + check_sample(&s); + assert!(load(name, &file).unwrap().editing_data, "{name}"); + for p in [json!({"pages": "1"}), json!({"layers": false})] { + assert_eq!(open(&mut s, name, &file, p.clone()).unwrap_err().to_string(), e, "{name}: {p}"); + } + } + for (name, file) in refused_files(b"%AI12_CompressedData not zlib", ai::page_pdf()) { + let plain = open(&mut s, name, &file, json!({"editingData": false})).unwrap_err().to_string(); + assert_eq!(open(&mut s, name, &file, json!({})).unwrap_err().to_string(), plain, "{name}"); + } +} + +/// A file saved in units of 10 points (`/UserUnit 10`, as in +/// `an_ai_file_with_a_user_unit_opens_at_its_size_in_points`) whose PDF part can't be read opens +/// from its editing data at its size in points. +#[test] +fn a_file_whose_pdf_part_cant_be_read_opens_at_its_size_in_points() { + let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 1 1 0 1 0 0 Xa\n{}f\n", ai::rect(20.0, 20.0, 60.0, 50.0)))); + let file = ai::ai_with_entries_and_content(&compressed(data.as_bytes()), "1 0 0 rg 20 20 40 30 re f", "/UserUnit 10", REFUSED_CONTENT); + let near = |r: vectorcraft_geom::Rect, want: [f64; 4]| [r.x0, r.y0, r.x1, r.y1].iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01); + let mut s = Session::new(); + let r = open(&mut s, "large.ai", &file, json!({})).unwrap(); + assert!(r["warnings"][0].as_str().unwrap().starts_with("the PDF part couldn't be read ("), "{r}"); + let doc = &s.doc().unwrap().doc; + assert!(near(doc.artboards[0].rect, [0.0, 0.0, 2000.0, 1000.0]), "{:?}", doc.artboards[0].rect); + let art = doc.art_bounds().unwrap(); + assert!(near(art, [200.0, 500.0, 600.0, 800.0]), "{art:?}"); + // On a page turned a quarter, the same. + let file = ai::ai_with_entries_and_content(&compressed(data.as_bytes()), "", "/UserUnit 10 /Rotate 90", REFUSED_CONTENT); + open(&mut s, "turned.ai", &file, json!({})).unwrap(); + assert!(near(s.doc().unwrap().doc.artboards[0].rect, [0.0, 0.0, 2000.0, 1000.0]), "{:?}", s.doc().unwrap().doc.artboards[0].rect); + // A page cropped to the art: its box has the art's size in those units. + let art = format!("0 1 1 0 1 0 0 Xa\n{}f\n", ai::rect(20.0, 20.0, 60.0, 50.0)); + let cropped = ai::editing_data_in([20.0, 20.0, 60.0, 50.0], [0.0, 0.0, 200.0, 100.0], &ai::layer("Art", &art)); + let file = ai::ai_with_entries_and_content(&compressed(cropped.as_bytes()), "", "/UserUnit 10 /TrimBox [20 20 60 50]", REFUSED_CONTENT); + open(&mut s, "cropped.ai", &file, json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + assert!(near(doc.artboards[0].rect, [0.0, 0.0, 2000.0, 1000.0]), "{:?}", doc.artboards[0].rect); + assert!(near(doc.art_bounds().unwrap(), [200.0, 500.0, 600.0, 800.0]), "{:?}", doc.art_bounds()); + // Saved in points, it opens as it is. + let file = ai::ai_with_entries_and_content(&compressed(data.as_bytes()), "", "", REFUSED_CONTENT); + open(&mut s, "points.ai", &file, json!({})).unwrap(); + assert!(near(s.doc().unwrap().doc.artboards[0].rect, [0.0, 0.0, 200.0, 100.0])); +} + +/// Type asked for as outlines in a file whose PDF part can't be read: the editing data's type, +/// outlined, as for a file saved without its PDF part. +#[test] +fn a_file_whose_pdf_part_cant_be_read_outlines_its_type_when_asked() { + let [(name, file), _] = refused_files(&typed_data(), ""); + let mut s = Session::new(); + let r = open(&mut s, name, &file, json!({})).unwrap(); + assert_eq!(texts_and_paths(&s).0, 1, "by default the editing data's type is type: {r}"); + let r = open(&mut s, name, &file, json!({"textAs": "outlines"})).unwrap(); + let (texts, paths) = texts_and_paths(&s); + assert_eq!(texts, 0, "no type left: {r}"); + assert!(paths > 0, "the outlines are there: {r}"); +} + +/// An image whose data is cut short in the editing data of a file whose PDF part can't be read is +/// left out, and both notes say so. +#[test] +fn a_file_whose_pdf_part_cant_be_read_notes_an_image_left_out() { + let data = String::from_utf8_lossy(&ai::sample_data()).replace("] 0 0 2 1 2 1 8 3", "] 0 0 6000 6000 6000 6000 8 3"); + let [(name, file), _] = refused_files(&compressed(data.as_bytes()), ai::page_pdf()); + let mut s = Session::new(); + let e = open(&mut s, name, &file, json!({"editingData": false})).unwrap_err().to_string(); + let r = open(&mut s, name, &file, json!({})).unwrap(); + assert_eq!(r["warnings"], json!([unread_pdf_part(&e), "an image whose data is cut short was left out"]), "{r}"); +} + +/// A copied file whose PDF part can't be read pastes the objects of its editing data when asked +/// for them, with the note; without `editingData` its page can't be read. +#[test] +fn a_copied_file_whose_pdf_part_cant_be_read_pastes_from_its_editing_data() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for (name, file) in refused_files(&compressed(&ai::sample_data()), ai::page_pdf()) { + let (r, pasted) = paste(&mut s, &file, true); + assert_eq!(r["count"], 7, "{name}: {r}"); + let pasted: Vec = pasted.iter().map(|n| n.name.clone().unwrap_or_default()).collect(); + assert_eq!(pasted, ["Pair", "Ring", "Window", "Shaded", "", "Sub", ""], "{name}"); + assert!(r["warnings"][0].as_str().unwrap().starts_with("the PDF part couldn't be read (cannot read PDF: "), "{name}: {r}"); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file)}); + let e = s.execute("clipboard.importPdf", &p).unwrap_err().to_string(); + assert!(e.contains("decode parameters"), "{name}: {e}"); + } +} + +/// A file whose PDF part can't be read places its first artboard from its editing data, with the +/// note; any other page keeps the error. +#[test] +fn a_file_whose_pdf_part_cant_be_read_places_from_its_editing_data() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + for (name, file) in refused_files(&compressed(&ai::sample_data()), ai::page_pdf()) { + let data = vectorcraft_format::base64_encode(&file); + let r = s.execute("file.place", &json!({"name": name, "dataBase64": data, "link": false})).unwrap(); + assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(200.0), Some(100.0)), "{name}: {r}"); + assert!(r["warnings"][0].as_str().unwrap().starts_with("the PDF part couldn't be read ("), "{name}: {r}"); + let placed = s.doc().unwrap().doc.layers[0].children().unwrap().last().unwrap().clone(); + assert_eq!(names(&placed.children().unwrap()[1..]), ["Pair", "Ring", "Window"], "{name}: after the clipping path"); + for off in [json!({"editingData": false}), json!({"layers": false})] { + let mut p = json!({"name": name, "dataBase64": data, "link": false}); + p.as_object_mut().unwrap().extend(off.as_object().unwrap().clone()); + let e = s.execute("file.place", &p).unwrap_err().to_string(); + assert!(e.contains("decode parameters"), "{name}: {off}: {e}"); + } + } + let [(name, file), _] = refused_files(&typed_data(), ""); + let data = vectorcraft_format::base64_encode(&file); + let r = s.execute("file.place", &json!({"name": name, "dataBase64": data, "link": false, "textAs": "outlines", "crop": "bounding"})).unwrap(); + assert!(r["warnings"][0].as_str().unwrap().starts_with("the PDF part couldn't be read ("), "{r}"); + let placed = s.doc().unwrap().doc.layers[0].children().unwrap().last().unwrap().clone(); + let mut texts = 0; + placed.walk(&mut |n| texts += usize::from(matches!(n.kind, NodeKind::Text(_)))); + assert_eq!(texts, 0, "placed with its type outlined: {r}"); + // Two artboards: the second can't be placed. + let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_/Dictionary :\n%_0 -50 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 -150 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let art = format!("0 g\n{}f\n{}f\n", ai::rect(10.0, 10.0, 50.0, 50.0), ai::rect(10.0, -140.0, 70.0, -100.0)); + let paged = ai::editing_data(100.0, 100.0, &(boards.to_string() + &ai::layer("Art", &art))); + let [(name, file), _] = refused_files(&compressed(paged.as_bytes()), ai::page_pdf()); + let data = vectorcraft_format::base64_encode(&file); + let size = |s: &mut Session, page: u64| { + let r = s.execute("file.place.info", &json!({"name": name, "dataBase64": data, "page": page, "crop": "bounding"})); + r.map(|r| (r["width"].as_f64(), r["height"].as_f64())).map_err(|e| e.to_string()) + }; + assert_eq!(size(&mut s, 1), Ok((Some(40.0), Some(40.0)))); + let second = size(&mut s, 2); + assert!(second.as_ref().is_err_and(|e| e.contains("decode parameters")), "{second:?}"); +} + /// A copied `.ai` whose editing data can't be read, or isn't there, pastes its page as a PDF /// does: the same objects as without `editingData`. #[test] @@ -360,32 +863,107 @@ fn what_the_reader_doesnt_read_opens_as_before_with_a_warning() { assert!(r["warnings"].to_string().contains("symbols") && r["warnings"].to_string().contains("PDF part"), "{r}"); } -/// A `.ai` whose document data has a variable library opens with a note that its variables and -/// data sets weren't read, whether its layers are read or it comes in as its PDF part. +/// A `.ai` whose document data has a variable library opens with its variables, data sets, active +/// data set and lock, whether its layers are read or it comes in as its PDF part: `variable.list` +/// and `dataset.list` report them. A variable of unknown kind can't be bound. What of the library +/// can't be read is noted. With its layers read, the object a variable is bound to comes in bound, +/// and selecting a data set changes it; the bindings to objects the file doesn't have are noted. #[test] -fn an_ai_file_with_a_variable_library_says_its_variables_werent_read() { - const NOTE: &str = "the file's variables and data sets weren't read (variables: 2, data sets: 3): the Variables panel doesn't list them"; - let library = ai::variable_library(&["Name", "Number"], &["One", "Two", "Three"]); - let square = format!("0 1 1 0 1 0 0 Xa\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0)); - let notes = - |r: &Value| r["warnings"].as_array().unwrap().iter().filter(|w| w.as_str().unwrap().contains("variables")).cloned().collect::>(); +fn an_ai_file_opens_its_variable_library() { + let library = ai::variable_library_data(&ai::sample_variable_sets("variableAndTypes", &[])); + let square = format!("0 1 1 0 1 0 0 Xa\n{}f\n{}", ai::rect(10.0, 50.0, 40.0, 90.0), ai::named("path_x5F_1")); + let notes = |r: &Value| { + r["warnings"].as_array().map_or(vec![], |w| w.iter().filter(|w| w.as_str().unwrap().contains("variable")).cloned().collect::>()) + }; + let skipped = |n: usize| { + json!(format!("the file's variable bindings weren't all read (bindings skipped: {n}): those objects aren't bound to their variables")) + }; + let check = |s: &mut Session, bound: usize| { + let r = s.execute("variable.list", &json!({})).unwrap(); + assert_eq!( + r, + json!({"variables": [ + {"name": "v_text", "kind": "text", "bindings": 0}, + {"name": "v_visible", "kind": "visibility", "bindings": bound}, + {"name": "v_file", "kind": "image", "bindings": 0}, + {"name": "v_graph", "kind": "graph", "bindings": 0}, + {"name": "v_unbound", "kind": "unknown", "bindings": 0}, + ], "locked": true}) + ); + let r = s.execute("dataset.list", &json!({})).unwrap(); + assert_eq!(r["active"], "ds_two", "{r}"); + let names: Vec<&str> = r["datasets"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["ds_one", "ds_two", "ds_three"]); + assert_eq!( + r["datasets"][1]["values"], + json!({"v_text": {"text": "line one\nline two & < é"}, "v_visible": {"visible": false}, "v_file": {"image": ai::SAMPLE_MISSING_FILE}}) + ); + }; let mut s = Session::new(); let layered = ai::editing_data(200.0, 100.0, &format!("{library}{}", ai::layer("Art", &square))); let file = ai::ai(&compressed(layered.as_bytes()), "1 0 0 rg 10 50 30 40 re f"); let r = open(&mut s, "variables.ai", &file, json!({})).unwrap(); assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}"); - assert_eq!(notes(&r), [json!(NOTE)], "{r}"); - let r = s.execute("variable.list", &json!({})).unwrap(); - assert_eq!(r["variables"], json!([]), "{r}"); - // Its layers can't be read (a symbol): it comes in as its PDF part, with the note. + // The library's text and image variables are bound to objects the file doesn't have. + assert_eq!(notes(&r), [skipped(2)], "{r}"); + check(&mut s, 1); + let id = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id; + assert_eq!(s.doc().unwrap().doc.variables.objects_of("v_visible"), [id]); + s.execute("dataset.select", &json!({"name": "ds_two"})).unwrap(); + assert!(!s.doc().unwrap().doc.node(id).unwrap().visible, "ds_two hides the square"); + s.execute("dataset.select", &json!({"name": "ds_one"})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).unwrap().visible, "ds_one shows it"); + let e = s.execute("variable.bind", &json!({"variable": "v_unbound", "ids": [id.0]})).unwrap_err(); + assert!(e.to_string().contains("a variable of unknown kind can't be bound to objects"), "{e}"); + // Its layers can't be read (a symbol): it comes in as its PDF part, with the library and none + // of its bindings. let symbols = ai::editing_data(200.0, 100.0, &format!("{library}{}", ai::layer("Art", "/SymbolInstance :\n(Dot) /SymbolRef ,\n;\n"))); let r = open(&mut s, "symbols.ai", &ai::ai(&compressed(symbols.as_bytes()), ai::page_pdf()), json!({})).unwrap(); assert!(r["warnings"].to_string().contains("PDF part"), "{r}"); - assert_eq!(notes(&r), [json!(NOTE)], "{r}"); - // Without a library, no note. + assert_eq!(notes(&r), [skipped(3)], "{r}"); + check(&mut s, 0); + // A graph value isn't read: the note says how many entries were left out. + let graph = ai::xml_element("v_graph", &[], &[ai::xml_text(ai::XmlValue::Str("a,b"))]); + let partly = ai::variable_library_data(&ai::sample_variable_sets("none", &[graph])); + let layered = ai::editing_data(200.0, 100.0, &format!("{partly}{}", ai::layer("Art", &square))); + let r = open(&mut s, "graph.ai", &ai::ai(&compressed(layered.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap(); + assert_eq!( + notes(&r), + [json!("the file's variable library was partly read (entries skipped: 1): the Variables panel lists the rest"), skipped(2)], + "{r}" + ); + // Without a library, no note and no variables. let plain = ai::editing_data(200.0, 100.0, &ai::layer("Art", &square)); let r = open(&mut s, "plain.ai", &ai::ai(&compressed(plain.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap(); assert!(notes(&r).is_empty(), "{r}"); + assert_eq!(s.execute("variable.list", &json!({})).unwrap()["variables"], json!([])); +} + +/// An Objects on Path group in a `.ai` file opens as one: its record names the group's children by +/// their ids in the opened document. +#[test] +fn an_ai_file_opens_its_objects_on_path_group_live() { + let ids = ["9b1c0e7a-0000-4000-8000-000000000001", "9b1c0e7a-0000-4000-8000-000000000002", "9b1c0e7a-0000-4000-8000-000000000003"]; + let options = ai::on_path_options(2, 4, std::f64::consts::FRAC_PI_2, ""); + let record = ai::on_path_record("Adobe Align On Path", &ids, &options); // brand-ok: the record's name in the files + let group = format!( + "0 Ae\nu\n/ConstraintGroup :\n128 /GroupType ,\n;\n0 0 1 0 0 0 1 XA\n10 50 m\n190 50 L\nS\n{}0 1 1 0 1 0 0 Xa\n{}f\n{}{}f\n{}U\n", + ai::on_path_member(ids[0], None, 0.0), + ai::rect(5.0, 45.0, 15.0, 55.0), + ai::on_path_member(ids[1], Some(0), 0.0), + ai::rect(185.0, 45.0, 195.0, 55.0), + ai::on_path_member(ids[2], Some(1), 0.0), + ); + let data = ai::editing_data(200.0, 100.0, &format!("{record}{}", ai::layer("Art", &group))); + let mut s = Session::new(); + let r = open(&mut s, "on-path.ai", &ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 5 45 10 10 re f 185 45 10 10 re f"), json!({})).unwrap(); + assert_eq!(r["format"], json!("ai"), "{r}"); + let doc = &s.doc().unwrap().doc; + let g = &doc.layers[0].children().unwrap()[0]; + let rec = g.extras().objects_on_path.as_deref().expect("an Objects on Path group"); + let kids: Vec = g.children().unwrap().iter().map(|c| c.id).collect(); + assert!(kids.contains(&rec.path) && rec.members.iter().all(|m| kids.contains(&m.id)), "{rec:?} {kids:?}"); + assert_eq!((rec.members.len(), rec.pivot, rec.rotate.round()), (2, 4, 90.0)); } /// A page showing only a placeholder line, as a `.ai` saved without PDF compatibility has. @@ -482,7 +1060,7 @@ fn an_ai_file_saved_without_its_pdf_part_places_from_its_editing_data() { assert_eq!(size(1), Ok((Some(40.0), Some(40.0)))); assert_eq!(size(2), Ok((Some(60.0), Some(40.0)))); let third = size(3); - assert!(third.as_ref().is_err_and(|e| e.contains("has 2 page(s)")), "{third:?}"); + assert!(third.as_ref().is_err_and(|e| e.contains("has 2 pages")), "{third:?}"); let e = s.execute("file.place", &json!({"name": "damaged.ai", "dataBase64": damaged})).unwrap_err().to_string(); assert!(e.contains("without PDF compatibility") && e.contains("zlib"), "{e}"); let e = s.execute("file.place", &json!({"name": "plain.ai", "dataBase64": plain})).unwrap_err().to_string(); @@ -535,6 +1113,234 @@ fn an_ai_file_whose_pdf_part_is_only_text_still_opens_from_editing_data_that_rea check_sample(&s); } +#[test] +fn an_ai_file_whose_pdf_part_is_cropped_to_its_art_opens_from_its_layers() { + // A 400 × 200 pt artboard with two red bars across (100, 50)–(300, 150). The PDF part's page + // is that art's box, 200 × 100 pt (the editing data's bounding box), not the artboard. + let red = "0 1 1 0 1 0 0 Xa\n"; + let art = ai::layer("Art", &format!("{red}{}f\n{red}{}f\n", ai::rect(100.0, 50.0, 180.0, 150.0), ai::rect(220.0, 50.0, 300.0, 150.0))); + let data = ai::editing_data_in([100.0, 50.0, 300.0, 150.0], [0.0, 0.0, 400.0, 200.0], &art); + let page = "1 0 0 rg 0 0 80 100 re f 120 0 80 100 re f"; + let mut s = Session::new(); + let r = open(&mut s, "cropped.ai", &ai::ai(&compressed(data.as_bytes()), page), json!({})).unwrap(); + assert!(!r["warnings"].to_string().contains("weren't read"), "{r}"); + let doc = &s.doc().unwrap().doc; + assert_eq!(names(&doc.layers), ["Art"]); + assert_eq!(doc.artboards.len(), 1); + assert_eq!(doc.artboards[0].rect, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 200.0), "the file's artboard, not its page"); + let bars = doc.layers[0].children().unwrap(); + assert_eq!(bars.len(), 2); + let b = bars[0].geometric_bounds().unwrap(); + assert!((b.x0 - 100.0).abs() < 0.01 && (b.y0 - 50.0).abs() < 0.01, "where the artboard has it: {b:?}"); +} + +#[test] +fn an_ai_file_whose_pdf_part_draws_nothing_opens_from_its_editing_data() { + // A PDF-compatible `.ai` whose PDF part is a page with nothing on it (no notice text either), + // with or without the boxes that say where its art is: its editing data is the art. + for boxed in ["", "/ArtBox [0 0 200 100] /TrimBox [0 0 200 100]"] { + let mut s = Session::new(); + let r = open(&mut s, "blank.ai", &ai::ai_with(&compressed(&ai::sample_data()), "", boxed), json!({})).unwrap(); + assert_eq!(r["warnings"], json!([]), "{boxed:?}: {r}"); + check_sample(&s); + // The PDF part alone, as asked: its empty page. + open(&mut s, "blank.ai", &ai::ai_with(&compressed(&ai::sample_data()), "", boxed), json!({"editingData": false})).unwrap(); + let layers = &s.doc().unwrap().doc.layers; + assert!(layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())), "{boxed:?}"); + } + // Editing data that can't be read leaves the empty page, as before. + let mut s = Session::new(); + open(&mut s, "blank.ai", &ai::ai(b"%AI24_ZStandard_Data\0\0\0\0\0\0\0\0", ""), json!({})).unwrap(); + assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]); +} + +/// A page that draws nothing only because what it holds couldn't be read (an image that can't be +/// decoded) isn't an empty page: its notes stay, and the editing data isn't taken in its place +/// unchecked. +#[test] +fn a_page_whose_content_was_skipped_is_not_taken_for_an_empty_one() { + let broken = "q 100 0 0 50 0 0 cm BI /W 2 /H 2 /CS /RGB /BPC 8 /F /DCT ID notajpeg EI Q"; + let mut s = Session::new(); + let r = open(&mut s, "broken.ai", &ai::ai(&compressed(&ai::sample_data()), broken), json!({})).unwrap(); + let warnings = r["warnings"].to_string(); + assert_ne!(r["warnings"], json!([]), "the skipped image is told: {r}"); + assert!(!warnings.contains("saved without PDF compatibility"), "{r}"); +} + +/// Editing data with one layer, "Art", holding one left-aligned story, "Hi", 14 pt Helvetica, +/// anchored at the canvas centre (the template box's centre), as the editing data's text document +/// gives it; compressed. +fn typed_data() -> Vec { + let story = "<< /0 << /0 (Hi\r) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 3 >> ] >> \ + /6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 /53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> >> >> >> /1 3 >> ] >> >> \ + /1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8191.5 8191.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \ + << /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 3 >> >> ] >> ] >> ] >> ] >> ] >> ] >> >>"; + let document = format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n/1 << /1 [ {story} ] /2 << /1 12.0 >> >>\n" + ); + let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n2 /TextAntialiasing ,\n;\n"; + let data = format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\ + %AI5_NumLayers: 1\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n", + ai::layer("Art", text), + lines.join("\n") + ); + compressed(data.as_bytes()) +} + +/// How many text objects and how many paths the open document holds. +fn texts_and_paths(s: &Session) -> (usize, usize) { + let (mut texts, mut paths) = (0, 0); + s.doc().unwrap().doc.walk(|c| { + texts += usize::from(matches!(c.kind, NodeKind::Text(_))); + paths += usize::from(matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })); + }); + (texts, paths) +} + +/// Type asked for as outlines on a page that draws nothing: the editing data's type, outlined (the +/// page has none to give). +#[test] +fn an_empty_page_with_type_as_outlines_outlines_the_editing_datas_type() { + let file = ai::ai(&typed_data(), ""); + let mut s = Session::new(); + let r = open(&mut s, "typed.ai", &file, json!({})).unwrap(); + assert_eq!(texts_and_paths(&s).0, 1, "by default the editing data's type is type: {r}"); + let r = open(&mut s, "typed.ai", &file, json!({"textAs": "outlines"})).unwrap(); + let (texts, paths) = texts_and_paths(&s); + assert_eq!(texts, 0, "no type left: {r}"); + assert!(paths > 0, "the outlines are there: {r}"); + assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "the editing data's layers"); +} + +/// A story of a `.ai` file's text document with no character or paragraph runs is set in +/// `[Normal Character Style]` and `[Normal Paragraph Style]`; the base attributes give only what +/// those styles leave out. +#[test] +fn an_ai_story_without_runs_takes_the_normal_styles() { + let story = "<< /0 << /0 (Hi\r) >> \ + /1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8191.5 8191.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \ + << /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 3 >> >> ] >> ] >> ] >> ] >> ] >> ] >> >>"; + let char_sheets = "/5 << /0 [ << /0 << /0 ([Normal Character Style]) /6 << /0 0 /1 9.0 \ + /53 << /99 /SimplePaint /0 << /0 1 /1 [ 1.0 0.0 0.0 1.0 ] >> >> >> >> >> ] >>"; + let para_sheets = "/6 << /0 [ << /0 << /0 ([Normal Paragraph Style]) /5 << /1 6.0 /9 false >> >> >> ] >>"; + let document = format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> {char_sheets} {para_sheets} \ + /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\ + /1 << /1 [ {story} ] /2 << /1 12.0 /53 << /99 /SimplePaint /0 << /0 0 /1 [ 1.0 1.0 ] >> >> >> /3 << /1 2.0 /9 true >> >>\n" + ); + let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n2 /TextAntialiasing ,\n;\n"; + let data = format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\ + %AI5_NumLayers: 1\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n", + ai::layer("Art", text), + lines.join("\n") + ); + let mut s = Session::new(); + let r = open(&mut s, "plain.ai", &ai::ai(&compressed(data.as_bytes()), ""), json!({})).unwrap(); + let mut texts = vec![]; + s.doc().unwrap().doc.walk(|c| { + if let NodeKind::Text(t) = &c.kind { + texts.push((**t).clone()); + } + }); + let [t] = texts.as_slice() else { panic!("one text object: {r}") }; + assert_eq!(t.plain_text(), "Hi"); + let style = &t.runs[0].style; + assert_eq!(style.size, 9.0, "{r}"); + assert_eq!(style.fill, vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))); + assert_eq!((t.para.first_line_indent, t.para.hyphenate), (6.0, false)); +} + +/// Type asked for as outlines in a `.ai` saved without PDF compatibility (its page only a +/// placeholder): the editing data's type, outlined, as for an empty page. +#[test] +fn a_file_saved_without_its_pdf_part_with_type_as_outlines_outlines_its_type() { + let file = ai::ai(&typed_data(), PLACEHOLDER); + let mut s = Session::new(); + let r = open(&mut s, "typed.ai", &file, json!({})).unwrap(); + assert_eq!(texts_and_paths(&s).0, 1, "by default the editing data's type is type: {r}"); + let r = open(&mut s, "typed.ai", &file, json!({"textAs": "outlines"})).unwrap(); + let (texts, paths) = texts_and_paths(&s); + assert_eq!(texts, 0, "no type left: {r}"); + assert!(paths > 0, "the outlines are there: {r}"); + assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "the editing data's layers"); +} + +/// Type of the editing data outlined keeps its transparency, opacity mask and effects, and is +/// shown and locked as the type was. +#[test] +fn outlined_type_of_the_editing_data_keeps_its_transparency_and_effects() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + let mut doc = s.doc().unwrap().doc.as_ref().clone(); + let shadow = vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: json!({}), visible: true }; + { + let t = doc.node_mut(id).unwrap(); + t.opacity = 0.5; + t.blend = vectorcraft_color::BlendMode::Multiply; + t.isolate = true; + t.locked = true; + t.name = Some("Title".into()); + t.appearance.effects = vec![shadow.clone()]; + } + let opts = LoadOptions { text_as: vectorcraft_pdf::TextAs::Outlines, ..Default::default() }; + let (doc, _) = load::outlined_if_asked(doc, vec![], &opts); + let mut outlines = vec![]; + doc.walk(|n| { + if n.extras().type_outlines { + outlines.push(n.clone()); + } + }); + let [o] = &outlines[..] else { panic!("one group of outlines: {outlines:?}") }; + assert_eq!((o.opacity, o.blend, o.isolate), (0.5, vectorcraft_color::BlendMode::Multiply, true)); + assert_eq!(o.appearance.effects, [shadow]); + assert!(o.locked && o.visible); + assert_eq!(o.name.as_deref(), Some("Title")); +} + +/// Threaded type of the editing data, its story all in its first frame as the editing data gives +/// it, outlined: each frame's outlines show the text that flows into it. +#[test] +fn outlined_threaded_type_of_the_editing_data_shows_the_text_of_every_frame() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + let story = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame. ".repeat(4); + let a = + s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + // As the editing data gives it: the first frame holds the story, the second nothing yet. + let mut doc = s.doc().unwrap().doc.as_ref().clone(); + let runs = |id: u64| match &doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("area type"), + }; + let (shown, flowed) = (runs(a), runs(b)); + let empty: Vec<_> = flowed.iter().take(1).map(|r| vectorcraft_doc::TextRun { text: String::new(), ..r.clone() }).collect(); + for (id, put) in [(a, [shown, flowed].concat()), (b, empty)] { + if let NodeKind::Text(t) = &mut doc.node_mut(NodeId(id)).unwrap().kind { + t.runs = put; + t.cached_bounds = None; + t.cached_baselines.clear(); + } + } + let opts = LoadOptions { text_as: vectorcraft_pdf::TextAs::Outlines, ..Default::default() }; + let (doc, _) = load::outlined_if_asked(doc, vec![], &opts); + let mut right = 0; + doc.walk(|n| { + if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && n.geometric_bounds().is_some_and(|r| r.x0 >= 190.0) { + right += 1; + } + }); + assert!(right > 0, "the second frame's text is outlined where it flows"); + assert!(doc.text_threads.is_empty(), "outlined frames are in no thread: {:?}", doc.text_threads); +} + #[test] fn editing_data_false_opens_only_what_the_page_prints() { let mut s = Session::new(); @@ -646,10 +1452,16 @@ fn half_outlined_line(y: f64, rest: &str, mode: u8) -> String { /// text document (a line starting at (14, 65)), then `more` of a story the text document doesn't /// have. Without `story` the file has no text document. fn half_outlined_ai(story: Option<&str>, more: usize, type_content: &str) -> Vec { + half_outlined_ai_on(story, more, type_content, "", |page| page) +} + +/// [`half_outlined_ai`] with the editing data's comments `head` before its art, whose page is +/// `page_of` the 200 × 100 pt page it draws on (other boxes, more entries). +fn half_outlined_ai_on(story: Option<&str>, more: usize, type_content: &str, head: &str, page_of: impl FnOnce(PdfPage) -> PdfPage) -> Vec { let text = |story: u32| format!("/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n{story} /StoryIndex ,\n;\n"); let texts: String = std::iter::once(text(0)).chain((0..more).map(|_| text(99))).collect(); let mut body = - format!("%AI3_TemplateBox: 100 50 100 50\n{}", ai::layer("Art", &format!("0.5 g\n{}f\n{texts}", ai::rect(120.0, 20.0, 160.0, 60.0)))); + format!("{head}%AI3_TemplateBox: 100 50 100 50\n{}", ai::layer("Art", &format!("0.5 g\n{}f\n{texts}", ai::rect(120.0, 20.0, 160.0, 60.0)))); if let Some(story) = story { // The story's one line starts at the canvas center (8191.5, the template box's center) moved // to (14, 65): its y runs down the page. @@ -680,7 +1492,7 @@ fn half_outlined_ai(story: Option<&str>, more: usize, type_content: &str) -> Vec }; let cmap = "begincmap\n1 begincodespacerange\n<00> \nendcodespacerange\n1 beginbfchar\n<41> \nendbfchar\nendcmap\n"; pdf_with( - &[page], + &[page_of(page)], &[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len()), &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None, ) @@ -708,6 +1520,99 @@ fn texts(s: &Session) -> Vec { art.iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(t.plain_text()) } else { None }).collect() } +/// A `.ai` saved without its PDF part whose layer `Art` holds a story in two area type frames +/// (art x 10 to 90 and 110 to 190, y 10 to 90), then a band across the first frame (y 30 to 70), +/// made a wrap object with no offset when `wrap` is set. +fn wrapped_thread_ai(wrap: bool) -> Vec { + ai::ai(&wrapped_thread_data(wrap.then_some(0.0)), PLACEHOLDER) +} + +/// The editing data of [`wrapped_thread_ai`], compressed, with the band a wrap object of `offset` +/// when one is given. +fn wrapped_thread_data(offset: Option) -> Vec { + // The template box is centred at (100, 50), the canvas centre 8191.5: y runs down the canvas. + let canvas = |x: f64, y: f64| (x + 8091.5, 8241.5 - y); + let rect = |x0: f64, y0: f64, x1: f64, y1: f64| { + let corners = [canvas(x0, y1), canvas(x0, y0), canvas(x1, y0), canvas(x1, y1), canvas(x0, y1)]; + let segments: Vec = + corners.windows(2).map(|w| format!("{} {} {} {} {} {} {} {}", w[0].0, w[0].1, w[0].0, w[0].1, w[1].0, w[1].1, w[1].0, w[1].1)).collect(); + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", segments.join(" ")) + }; + let story = "Words keep flowing from the first frame into the second one, line after line, until the story ends here. ".repeat(3); + let n = story.chars().count() + 1; + let document = format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ {} {} ] >> >>\n\ + /1 << /1 [ << /0 << /0 ({story}\r) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 {n} >> ] >> \ + /6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /1 10.0 >> >> >> /1 {n} >> ] >> >> /1 << /0 [ << /0 0 >> << /0 1 >> ] >> >> ] /2 << /1 12.0 >> >>\n", + rect(10.0, 10.0, 90.0, 90.0), + rect(110.0, 10.0, 190.0, 90.0) + ); + let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + let frame = |f: u32| format!("/AI11Text :\n0 /FreeUndo ,\n{f} /FrameIndex ,\n0 /StoryIndex ,\n;\n"); + let dict = offset + .map(|o| format!("%_/ArtDictionary :\n%_{o} /Real (AI11TextWrapOffset) ,\n%_0 /Bool (AI11TextWrapInvert) ,\n%_;\n%_\n")) + .unwrap_or_default(); + let art = format!("{}{}0.5 g\n{}f\n{dict}", frame(0), frame(1), ai::rect(10.0, 30.0, 90.0, 70.0)); + let body = format!( + "%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", + ai::layer("Art", &art), + lines.join("\n") + ); + compressed(ai::editing_data(200.0, 100.0, &body).as_bytes()) +} + +/// The wrap offset of the first frame of `doc`'s threaded type, as its text resolves it. +fn first_frame_wrap_offset(doc: &vectorcraft_doc::Document) -> f64 { + match &doc.node(doc.text_threads[0][0]).unwrap().kind { + NodeKind::Text(t) => t.wrap[0].wrap.offset, + _ => panic!("area type"), + } +} + +/// A `.ai` in units of 10 points whose threaded area type flows around a wrap object of a 2 unit +/// offset opens with the type flowing round it 20 pt off, its PDF part read or not, and when its +/// PDF part can't be read. The default graphic styles of a file without its own aren't scaled. +#[test] +fn wrapped_type_in_units_of_ten_points_flows_round_the_wrap_at_its_size_in_points() { + let private = wrapped_thread_data(Some(2.0)); + let page = "0.5 g 10 30 80 40 re f"; + let refused = ai::ai_with_entries_and_content(&private, page, "/UserUnit 10", REFUSED_CONTENT); + // On the trim boxes the PDF part is imported, and the refused stream stops it. + let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }; + let files = [(ai::ai_with(&private, page, "/UserUnit 10"), LoadOptions::default()), (refused, trim)]; + for (file, opts) in &files { + let loaded = load_with("thread.ai", file, opts).unwrap(); + assert!(loaded.editing_data, "{:?}", loaded.warnings); + assert!((first_frame_wrap_offset(&loaded.doc) - 20.0).abs() < 0.01, "{:?}", loaded.warnings); + } + let loaded = load_with("thread.ai", &files[1].0, &files[1].1).unwrap(); + assert!(loaded.warnings.iter().any(|w| w.starts_with("the PDF part couldn't be read")), "{:?}", loaded.warnings); + // The file has no graphic styles of its own: the default ones aren't scaled either way. + let read = load_with("thread.ai", &files[0].0, &files[0].1).unwrap(); + assert_eq!(loaded.doc.graphic_styles, read.doc.graphic_styles); +} + +/// Threaded area type below a wrap object flows around it when the file opens: the text the wrap +/// object pushes out of the first frame goes on in the second. +#[test] +fn wrap_threaded_area_after_open() { + let second = |wrap: bool| { + let mut s = Session::new(); + let r = open(&mut s, "thread.ai", &wrapped_thread_ai(wrap), json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.text_threads.len(), 1, "{r}"); + let text = |id: NodeId| match &doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.clone(), + _ => panic!("area type"), + }; + let (first, second) = (text(doc.text_threads[0][0]), text(doc.text_threads[0][1])); + assert_eq!(first.wrap.len(), usize::from(wrap), "{r}"); + second.plain_text().chars().count() + }; + let (plain, wrapped) = (second(false), second(true)); + assert!(wrapped > plain, "the second frame holds more of the story: {plain} → {wrapped}"); +} + /// The note that glyphs were kept as outlines is dropped when the type comes from the editing data's /// text document, and stays with the PDF part alone. #[test] @@ -729,6 +1634,77 @@ fn type_from_the_text_document_opens_without_the_pdf_parts_note_on_outlines() { assert!(!r["warnings"].as_array().unwrap().contains(&without_outlines_note(1)), "{r}"); } +/// A `.ai` whose text document makes all of its type, with nothing unread, opens from its layers +/// without its PDF part being imported: a page that draws more than the layers isn't compared with +/// them. On its trim box it takes the pages' bleed, and pages in units of 10 points draw it ten +/// times as large, as when its PDF part is imported. With type the text document can't make, +/// editing data on a large canvas, its type asked for as outlines, another box or pages picked, the +/// PDF part is imported as before. +#[test] +fn type_all_from_the_text_document_opens_without_importing_the_pdf_part() { + let line = half_outlined_line(65.0, "rst draft", 0); + // The page draws a red square the layers don't have. + let differs = half_outlined_ai(Some("first draft"), 0, &format!("{line} 1 0 0 rg 20 20 30 30 re f")); + let mut s = Session::new(); + let before = vectorcraft_pdf::imports_of(&differs); + let loaded = load_with("draft.ai", &differs, &LoadOptions::default()).unwrap(); + assert_eq!(vectorcraft_pdf::imports_of(&differs), before, "{:?}", loaded.warnings); + assert!(loaded.editing_data, "{:?}", loaded.warnings); + assert!(!loaded.warnings.iter().any(|w| w.contains("differently")), "{:?}", loaded.warnings); + let r = open(&mut s, "draft.ai", &differs, json!({})).unwrap(); + assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}"); + assert_eq!(texts(&s), ["first draft"], "{r}"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the square and the type, without the page's red square: {r}"); + // A 10 pt bleed round the trim box, the art drawn in the trim box. + let bled = half_outlined_ai_on(Some("first draft"), 0, &line, "", |p| PdfPage { + media: [0.0, 0.0, 220.0, 120.0], + bleed: Some([0.0, 0.0, 220.0, 120.0]), + trim: Some([10.0, 10.0, 210.0, 110.0]), + content: format!("1 0 0 1 10 10 cm {}", p.content), + ..p + }); + let before = vectorcraft_pdf::imports_of(&bled); + let loaded = load_with("bled.ai", &bled, &LoadOptions::default()).unwrap(); + assert_eq!(vectorcraft_pdf::imports_of(&bled), before); + assert_eq!(loaded.doc.setup.bleed, [10.0; 4]); + // Pages of 10 pt units. + let large = half_outlined_ai_on(Some("first draft"), 0, &line, "", |p| PdfPage { entries: format!("{} /UserUnit 10", p.entries), ..p }); + let before = vectorcraft_pdf::imports_of(&large); + let loaded = load_with("large.ai", &large, &LoadOptions::default()).unwrap(); + assert_eq!(vectorcraft_pdf::imports_of(&large), before); + let board = loaded.doc.artboards[0].rect; + assert!((board.width() - 2000.0).abs() < 0.01 && (board.height() - 1000.0).abs() < 0.01, "{board:?}"); + // Opened on the trim boxes with the PDF part imported and compared, as before, both files have + // the same artboards and bleed. + for file in [&bled, &large] { + let alone = load_with("draft.ai", file, &LoadOptions::default()).unwrap(); + let compared = load_with("draft.ai", file, &LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }).unwrap(); + assert!(compared.editing_data, "{:?}", compared.warnings); + let boards = |d: &vectorcraft_doc::Document| d.artboards.iter().map(|a| a.rect).collect::>(); + assert_eq!(boards(&alone.doc), boards(&compared.doc)); + assert_eq!(alone.doc.setup.bleed, compared.doc.setup.bleed); + assert_eq!(names(&alone.doc.layers), names(&compared.doc.layers)); + // The file has no graphic styles of its own: the default ones aren't scaled. + assert_eq!(alone.doc.graphic_styles, compared.doc.graphic_styles); + } + // The PDF part is imported, once. + let unmade = half_outlined_ai(Some("first draft"), 1, &line); + // Editing data on a large canvas reads at its own scale when the file has no PDF part. + let canvas = half_outlined_ai_on(Some("first draft"), 0, &line, "%AI24_LargeCanvasScale: 2\n", |p| p); + let cases = [ + (&unmade, LoadOptions::default()), + (&canvas, LoadOptions::default()), + (&differs, LoadOptions { text_as: vectorcraft_pdf::TextAs::Outlines, ..Default::default() }), + (&differs, LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }), + (&differs, LoadOptions { pages: Some("1".into()), ..Default::default() }), + ]; + for (file, opts) in cases { + let before = vectorcraft_pdf::imports_of(file); + load_with("draft.ai", file, &opts).unwrap(); + assert_eq!(vectorcraft_pdf::imports_of(file) - before, 1, "{opts:?}"); + } +} + /// A text object that takes the page's type lacks the glyphs next to it that the page kept as /// outlines: a note counts such objects, in place of the PDF part's notes. Stroked glyphs that /// come in with the stroked type keep the PDF part's notes. diff --git a/crates/engine/src/cmd/fileio/tests_artboard_fill.rs b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs new file mode 100644 index 0000000000..9a7684686a --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_artboard_fill.rs @@ -0,0 +1,158 @@ +//! Artboard background colors in output (#4937): raster, PDF, SVG and EPS exports, Export for +//! Screens and print draw each artboard's color behind its art, inside the artboard; +//! `includeArtboardFill: false` (Include Artboard Fill) leaves it out; the editing data keeps it as +//! the artboard's color, not as art. + +use serde_json::{Value, json}; + +use super::*; + +const RED: [u8; 4] = [255, 0, 0, 255]; + +/// Two 60×40 pt artboards, a 20 pt square (white fill, black stroke) on the first, which is red. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 60, "height": 40, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 0, "color": "#ff0000"})).unwrap(); + s +} + +fn b64(v: &Value) -> Vec { + vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap() +} + +fn with(mut p: Value, more: &Value) -> Value { + if let (Some(o), Some(m)) = (p.as_object_mut(), more.as_object()) { + o.extend(m.iter().map(|(k, v)| (k.clone(), v.clone()))); + } + p +} + +/// The pixels of the PNG `document.export` writes of the active document with `p`, on transparency. +fn png(s: &mut Session, p: Value) -> image::RgbaImage { + let v = s.execute("document.export", &with(json!({"format": "png", "background": "transparent"}), &p)).unwrap(); + image::load_from_memory(&b64(&v)).unwrap().to_rgba8() +} + +/// The file `document.export` writes with `p`. +fn file(s: &mut Session, p: Value) -> Vec { + b64(&s.execute("document.export", &p).unwrap()) +} + +/// The file `bytes` named `name`, opened in a new session. +fn opened(name: &str, bytes: &[u8]) -> Session { + let mut s = Session::new(); + s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + s +} + +/// What the file `bytes` named `name` shows near its top-left corner, opened and drawn. +fn corner(name: &str, bytes: &[u8]) -> [u8; 4] { + png(&mut opened(name, bytes), json!({"artboard": 0})).get_pixel(2, 2).0 +} + +#[test] +fn raster_exports_paint_the_color_behind_the_art() { + let mut s = session(); + let on = png(&mut s, json!({"artboard": 0})); + assert_eq!(on.get_pixel(2, 2).0, RED, "a transparent background still shows the color"); + assert_eq!(on.get_pixel(20, 20).0, [255, 255, 255, 255], "the art over it"); + assert_eq!(png(&mut s, json!({"artboard": 0, "includeArtboardFill": false})).get_pixel(2, 2)[3], 0, "left out"); + assert_eq!(png(&mut s, json!({"artboard": 1})).get_pixel(2, 2)[3], 0, "an artboard without a color"); + let jpg = file(&mut s, json!({"format": "jpg", "artboard": 0, "quality": 100})); + let px = image::load_from_memory(&jpg).unwrap().to_rgb8().get_pixel(2, 2).0; + assert!(px[0] > 240 && px[1] < 16 && px[2] < 16, "JPEG too: {px:?}"); + for bad in [json!("no"), json!(1)] { + assert!(s.execute("document.export", &json!({"format": "png", "includeArtboardFill": bad})).is_err(), "{bad}"); + } + assert_eq!(s.doc().unwrap().doc.layers.len(), 1, "the document gains no layer"); +} + +#[test] +fn the_color_fills_its_artboard_alone_behind_the_art() { + let s = session(); + let doc = &s.doc().unwrap().doc; + let board = doc.artboards[0].rect; + let filled = doc.with_artboard_fills([0, 1]).unwrap(); + let img = vectorcraft_render::Renderer::new().render_region(&filled, board.inflate(10.0, 10.0), 1.0, false); + let rgba = img.to_straight(); + let px = |x: usize, y: usize| rgba[(y * img.width as usize + x) * 4..][..4].to_vec(); + assert_eq!(px(5, 5)[3], 0, "outside the artboard"); + assert_eq!(px(15, 15), RED, "inside it"); + assert_eq!(px(30, 30), [255, 255, 255, 255], "the art over it"); +} + +#[test] +fn pdf_and_svg_show_the_color_and_their_editing_data_keeps_it_as_the_artboards() { + let mut s = session(); + for (format, name) in [("pdf", "a.pdf"), ("svg", "a.svg")] { + let p = json!({"format": format, "artboard": 0, "preserveEditing": false}); + assert_eq!(corner(name, &file(&mut s, p.clone())), RED, "{format}"); + assert_eq!(corner(name, &file(&mut s, with(p, &json!({"includeArtboardFill": false}))))[3], 0, "{format}"); + } + let reopened = opened("a.pdf", &file(&mut s, json!({"format": "pdf", "preserveEditing": true}))); + let (back, doc) = (&reopened.doc().unwrap().doc, &s.doc().unwrap().doc); + assert_eq!(back.artboards[0].color, doc.artboards[0].color); + assert_eq!(back.layers.len(), doc.layers.len(), "no art made of it"); +} + +#[test] +fn the_ai_editing_copy_for_other_apps_draws_the_color_as_the_pages_do() { + let mut s = session(); + let opts = LoadOptions { native: false, ..Default::default() }; + for (more, fill) in [(json!({}), true), (json!({"includeArtboardFill": false}), false)] { + let l = load::load_with("a.ai", &file(&mut s, with(json!({"format": "ai"}), &more)), &opts).unwrap(); + assert!(l.editing_data && !l.restored, "{more}: {:?}", l.warnings); + let names: Vec = l.doc.layers.iter().filter_map(|l| l.name.clone()).collect(); + assert_eq!(names.iter().any(|n| n == "Artboard Fill"), fill, "{more}: {names:?}"); + } +} + +#[test] +fn eps_and_postscript_print_draw_the_color() { + let mut s = session(); + // The only red the document has, the first artboard's color: RGB, or CMYK PostScript's (its + // values depend on the color conversion the platform offers, so only its hue is checked). + let red = |t: &str| { + t.lines().any(|l| { + let mut w: Vec<&str> = l.split_whitespace().collect(); + let Some(op) = w.pop() else { return false }; + let v: Vec = w.iter().filter_map(|n| n.parse().ok()).collect(); + match (op, v.as_slice()) { + ("rg" | "setrgbcolor", [r, g, b]) => *r > 0.9 && *g < 0.1 && *b < 0.1, + ("k" | "setcmykcolor", [c, m, y, k]) => *c < 0.1 && *m > 0.8 && *y > 0.8 && *k < 0.1, + _ => false, + } + }) + }; + let eps = |s: &mut Session, more: Value| { + String::from_utf8_lossy(&file(s, with(json!({"format": "eps", "useArtboards": true, "artboard": 0}), &more))).into_owned() + }; + assert!(red(&eps(&mut s, json!({}))), "EPS"); + assert!(!red(&eps(&mut s, json!({"includeArtboardFill": false}))), "EPS without it"); + let ps = |s: &mut Session, more: Value| { + String::from_utf8_lossy(&b64(&s.execute("file.print", &with(json!({"format": "postscript"}), &more)).unwrap())).into_owned() + }; + assert!(red(&ps(&mut s, json!({}))), "print"); + assert!(!red(&ps(&mut s, json!({"includeArtboardFill": false}))), "print without it"); +} + +#[test] +fn export_for_screens_includes_the_fill_unless_unchecked() { + let mut s = session(); + let screens = |s: &mut Session, more: Value| { + let p = with(json!({"artboards": [0], "formats": [{"format": "png"}], "settings": {"png": {"background": "transparent"}}}), &more); + s.execute("document.exportForScreens", &p).unwrap() + }; + let corner = |r: &Value| image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8().get_pixel(2, 2).0; + assert_eq!(corner(&screens(&mut s, json!({}))), RED, "on by default"); + assert_eq!(corner(&screens(&mut s, json!({"includeArtboardFill": false})))[3], 0, "unchecked"); + assert_eq!(s.execute("document.exportSettings", &json!({})).unwrap()["settings"]["includeArtboardFill"], false, "remembered"); + assert!(s.execute("document.exportForScreens", &json!({"includeArtboardFill": "no", "formats": [{"format": "png"}]})).is_err()); + // A document row's artboard keeps its color, as a color. + let r = screens(&mut s, json!({"formats": [{"format": "vectorcraft"}]})); + let back = vectorcraft_format::load(&b64(&r["files"][0])).unwrap(); + assert_eq!(back.artboards[0].color, s.doc().unwrap().doc.artboards[0].color); + assert_eq!(back.layers.len(), 1, "not as art"); +} diff --git a/crates/engine/src/cmd/fileio/tests_batch.rs b/crates/engine/src/cmd/fileio/tests_batch.rs index b889eb2d4f..f4e38e293d 100644 --- a/crates/engine/src/cmd/fileio/tests_batch.rs +++ b/crates/engine/src/cmd/fileio/tests_batch.rs @@ -222,3 +222,231 @@ fn export_presets_save_use_and_delete() { assert!(s.execute(bad.0, &bad.1).is_err(), "{bad:?}"); } } + +/// Export presets go to a file and come back from one: a name in use gets a number unless +/// `replace`, a built-in name is never replaced, and a file in another format or with a setting an +/// export refuses adds nothing. +#[test] +fn export_presets_export_and_import() { + let mut s = session(2); + assert!(s.execute("document.exportPresets.export", &json!({})).is_err(), "nothing saved to export"); + let web = json!({"name": "ACME-", "folders": "item", "formats": [{"format": "jpg", "quality": 80}]}); + s.execute("document.exportPresets.save", &json!({"name": "Web JPG", "settings": web})).unwrap(); + let out = s.execute("document.exportPresets.export", &json!({})).unwrap(); + assert_eq!(out["count"], 1); + let data = out["data"].as_str().unwrap().to_string(); + assert_eq!(serde_json::from_str::(&data).unwrap()["format"], "vcexportpresets"); + // Into a session with no saved presets: the preset as it was saved, and it exports. + let mut other = session(2); + let r = other.execute("document.exportPresets.import", &json!({ "data": data })).unwrap(); + assert_eq!(r["imported"], json!(["Web JPG"])); + assert_eq!(other.prefs.screen_export_presets, s.prefs.screen_export_presets); + assert_eq!(names(&export(&mut other, json!({"exportPreset": "Web JPG", "range": "2"}))), ["Artboard-2/ACME-Artboard 2.jpg"]); + // Again: a second copy with a number; with replace, the saved one changes. + let r = other.execute("document.exportPresets.import", &json!({ "data": data })).unwrap(); + assert_eq!(r["imported"], json!(["Web JPG 2"])); + s.execute("document.exportPresets.save", &json!({"name": "Web JPG", "settings": {"formats": [{"format": "png"}]}})).unwrap(); + let changed = s.execute("document.exportPresets.export", &json!({"names": ["Web JPG"]})).unwrap()["data"].clone(); + let r = other.execute("document.exportPresets.import", &json!({"data": changed, "replace": true})).unwrap(); + assert_eq!(r["imported"], json!(["Web JPG"])); + let saved: Vec<(&str, &Value)> = + other.prefs.screen_export_presets.iter().map(|p| (p.name.as_str(), &p.settings["formats"][0]["format"])).collect(); + assert_eq!(saved, [("Web JPG", &json!("png")), ("Web JPG 2", &json!("jpg"))]); + // A built-in preset exports by name and comes back under a new name; the built-in one stays. + let path = std::env::temp_dir().join(format!("vc-export-presets-{}.vcexportpresets", std::process::id())); + let path = path.to_string_lossy().to_string(); + let out = s.execute("document.exportPresets.export", &json!({"names": ["Logo Package"], "path": path})).unwrap(); + assert_eq!((out["path"].as_str(), out["count"].as_u64()), (Some(path.as_str()), Some(1))); + let r = other.execute("document.exportPresets.import", &json!({"path": path, "replace": true})).unwrap(); + assert_eq!(r["imported"], json!(["Logo Package 2"])); + let builtin = screens::builtin_presets(); + assert_eq!(other.prefs.screen_export_presets.last().map(|p| &p.settings), builtin.first().map(|p| &p.settings)); + let _ = std::fs::remove_file(&path); + // Refused files add nothing. + let before = other.prefs.screen_export_presets.clone(); + let preset = |settings: Value| { + json!({"format": "vcexportpresets", "presets": [{"name": "Fine", "settings": {"formats": [{"format": "png"}]}}, {"name": "Bad", "settings": settings}]}).to_string() + }; + for bad in [ + json!({"data": "{\"format\": \"vcflattener\", \"presets\": []}"}), + json!({"data": "not json"}), + json!({"data": preset(json!({"formats": [{"format": "txt"}]}))}), + json!({"data": preset(json!({"folders": "sideways"}))}), + json!({"dataBase64": "%%"}), + json!({}), + ] { + assert!(other.execute("document.exportPresets.import", &bad).is_err(), "{bad}"); + } + assert_eq!(other.prefs.screen_export_presets, before); + assert!(s.execute("document.exportPresets.export", &json!({"names": ["Never saved"]})).is_err()); + // `names` that is not a list of names is an error, not every saved preset. + for bad in [json!({"names": "Web JPG"}), json!({"names": [3]}), json!({"names": {"Web JPG": true}})] { + assert!(s.execute("document.exportPresets.export", &bad).is_err(), "{bad}"); + } + // One file imports at most 1,000 presets; names repeated in a file are numbered in turn. + let many = |n: usize| { + let one = json!({"name": "Same", "settings": {"formats": [{"format": "png"}]}}); + json!({"format": "vcexportpresets", "presets": vec![one; n]}).to_string() + }; + assert!(other.execute("document.exportPresets.import", &json!({"data": many(1001)})).is_err(), "more than 1,000"); + assert_eq!(other.prefs.screen_export_presets, before); + let r = other.execute("document.exportPresets.import", &json!({"data": many(1000)})).unwrap(); + let imported = r["imported"].as_array().unwrap(); + assert_eq!((imported.len(), imported.first(), imported.last()), (1000, Some(&json!("Same")), Some(&json!("Same 1000")))); + // An export writes no file that an import refuses: at most 1,000 presets. + assert!(other.prefs.screen_export_presets.len() > 1000); + assert!(other.execute("document.exportPresets.export", &json!({})).is_err(), "every saved preset"); + let names: Vec = other.prefs.screen_export_presets.iter().take(1001).map(|p| p.name.clone()).collect(); + assert!(other.execute("document.exportPresets.export", &json!({ "names": names })).is_err(), "1,001 names"); + let r = other.execute("document.exportPresets.export", &json!({ "names": names[..1000] })).unwrap(); + assert_eq!(r["count"], 1000); +} + +/// An imported file's unknown keys are dropped, a scale that is not a positive number refuses +/// the file, and a prefix with folder separators names files inside the export folder. +#[test] +fn export_presets_import_drops_unknown_keys_and_checks_values() { + let file = |settings: Value| { + json!({"format": "vcexportpresets", "comment": "extra", "presets": [{"name": "P", "extra": 1, "settings": settings}]}).to_string() + }; + let mut s = session(2); + let r = s.execute("document.exportPresets.import", &json!({"data": file(json!({"formats": [{"format": "svg"}], "unknown": true}))})).unwrap(); + assert_eq!(r["imported"], json!(["P"])); + let saved = &s.prefs.screen_export_presets[0].settings; + assert_eq!(saved.keys().collect::>(), ["formats"], "{saved:?}"); + for scale in [json!("0x"), json!("-2x"), json!("1e9x"), json!("2y"), json!("nanx")] { + let bad = file(json!({"formats": [{"format": "png", "scale": scale}]})); + assert!(s.execute("document.exportPresets.import", &json!({ "data": bad })).is_err(), "{scale}"); + } + assert_eq!(s.prefs.screen_export_presets.len(), 1); + let climb = file(json!({"formats": [{"format": "svg"}], "prefix": "../..\\up/"})); + let r = s.execute("document.exportPresets.import", &json!({ "data": climb })).unwrap(); + assert_eq!(r["imported"], json!(["P 2"])); + assert_eq!(names(&export(&mut s, json!({"exportPreset": "P 2", "range": "2"}))), ["..-..-up-Artboard-2.svg"]); +} + +#[test] +fn export_presets_import_replace_numbers_duplicates_from_one_file() { + let mut source = session(1); + source.execute("document.exportPresets.save", &json!({"name": "A", "settings": {"formats": [{"format": "png"}]}})).unwrap(); + let data = source.execute("document.exportPresets.export", &json!({"names": ["A", "A"]})).unwrap()["data"].clone(); + + let mut empty = session(1); + let reply = empty.execute("document.exportPresets.import", &json!({"data": data, "replace": true})).unwrap(); + assert_eq!(reply["imported"], json!(["A", "A 2"])); + assert_eq!(empty.prefs.screen_export_presets.iter().map(|p| p.name.as_str()).collect::>(), ["A", "A 2"]); + + let mut existing = session(1); + existing.execute("document.exportPresets.save", &json!({"name": "A", "settings": {"formats": [{"format": "jpg"}]}})).unwrap(); + let reply = existing.execute("document.exportPresets.import", &json!({"data": data, "replace": true})).unwrap(); + assert_eq!(reply["imported"], json!(["A", "A"])); + assert_eq!(existing.prefs.screen_export_presets.len(), 1); + assert_eq!(existing.prefs.screen_export_presets[0].settings["formats"][0]["format"], "png"); +} + +#[test] +fn export_presets_import_refuses_oversize_input_from_every_source() { + let mut s = session(1); + let good = s.execute("document.exportPresets.export", &json!({"names": ["Logo Package"]})).unwrap()["data"].as_str().unwrap().to_string(); + let oversized = format!("{good}{}", " ".repeat((4 << 20) + 1)); + let path = std::env::temp_dir().join(format!("vc-oversize-export-presets-{}.vcexportpresets", std::process::id())); + std::fs::write(&path, &oversized).unwrap(); + for params in [ + json!({"path": path.to_string_lossy()}), + json!({"data": oversized}), + json!({"dataBase64": vectorcraft_format::base64_encode(oversized.as_bytes())}), + ] { + let error = s.execute("document.exportPresets.import", ¶ms).unwrap_err().to_string(); + assert!(error.contains("larger than 4194304 bytes"), "{error}"); + assert!(s.prefs.screen_export_presets.is_empty()); + } + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn export_presets_import_accepts_wrapped_base64_near_size_limit() { + const LIMIT: usize = 4 << 20; + let empty = json!({ + "format": "vcexportpresets", + "presets": [{"name": "Wrapped", "settings": {"formats": [{"format": "png"}], "prefix": ""}}], + }); + let prefix = "x".repeat(LIMIT - 1 - empty.to_string().len()); + let file = json!({ + "format": "vcexportpresets", + "presets": [{"name": "Wrapped", "settings": {"formats": [{"format": "png"}], "prefix": prefix}}], + }) + .to_string(); + assert_eq!(file.len(), LIMIT - 1); + let encoded = vectorcraft_format::base64_encode(file.as_bytes()); + let wrapped = encoded.as_bytes().chunks(76).map(|line| std::str::from_utf8(line).unwrap()).collect::>().join("\n"); + assert!(wrapped.len() > LIMIT.div_ceil(3) * 4); + assert_eq!(vectorcraft_format::base64_decode(&wrapped).as_deref(), Some(file.as_bytes())); + + let mut s = session(1); + let reply = s.execute("document.exportPresets.import", &json!({"dataBase64": wrapped})).unwrap(); + assert_eq!(reply["imported"], json!(["Wrapped"])); + assert_eq!(s.prefs.screen_export_presets[0].settings["prefix"], prefix); +} + +#[test] +fn export_presets_export_refuses_oversize_output() { + let mut s = session(1); + let prefix = "x".repeat((4 << 20) + 1); + s.execute("document.exportPresets.save", &json!({"name": "Large", "settings": {"prefix": prefix}})).unwrap(); + + let error = s.execute("document.exportPresets.export", &json!({})).unwrap_err().to_string(); + assert!(error.contains("larger than 4194304 bytes"), "{error}"); + + let path = std::env::temp_dir().join(format!("vc-oversize-preset-output-{}.vcexportpresets", std::process::id())); + assert!(!path.exists()); + let error = s.execute("document.exportPresets.export", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string(); + assert!(error.contains("larger than 4194304 bytes"), "{error}"); + assert!(!path.exists()); +} + +/// An imported preset whose name is taken and ends in a number gets the next free number, not a +/// second one; any other taken name gets the first free number. +#[test] +fn an_imported_numbered_name_counts_on() { + let taken = ["Logo Package", "Logo Package 2", "Logo Package 4", "Web", "Web 2", "2", "Max 18446744073709551615"]; + let name = |base: &str| import_name(base, |n| taken.contains(&n)); + assert_eq!(name("Print"), "Print"); + assert_eq!(name("Logo Package 3"), "Logo Package 3"); + assert_eq!(name("Logo Package"), "Logo Package 3"); + assert_eq!(name("Logo Package 2"), "Logo Package 3"); + assert_eq!(name("Logo Package 4"), "Logo Package 5"); + assert_eq!(name("Web"), "Web 3"); + // A number alone, or one past the largest, is not counted on. + assert_eq!(name("2"), "2 2"); + assert_eq!(name("Max 18446744073709551615"), "Max 18446744073709551615 2"); + // Through the command: a built-in preset imported twice is Logo Package 2, then Logo Package 3. + let mut s = session(1); + let data = s.execute("document.exportPresets.export", &json!({"names": ["Logo Package"]})).unwrap()["data"].clone(); + assert_eq!(s.execute("document.exportPresets.import", &json!({ "data": data })).unwrap()["imported"], json!(["Logo Package 2"])); + let data = s.execute("document.exportPresets.export", &json!({"names": ["Logo Package 2"]})).unwrap()["data"].clone(); + assert_eq!(s.execute("document.exportPresets.import", &json!({ "data": data })).unwrap()["imported"], json!(["Logo Package 3"])); +} + +/// A preset name, imported or saved, keeps at most 255 characters, as an asset name does. +#[test] +fn export_preset_names_are_capped() { + let mut s = session(1); + let long = "é".repeat(300); + let capped = "é".repeat(255); + let file = json!({"format": "vcexportpresets", "presets": [{"name": long, "settings": {"formats": [{"format": "png"}]}}]}).to_string(); + let r = s.execute("document.exportPresets.import", &json!({ "data": file })).unwrap(); + assert_eq!(r["imported"], json!([capped])); + let r = s.execute("document.exportPresets.save", &json!({"name": format!(" {}", "w".repeat(400)), "settings": {}})).unwrap(); + assert_eq!(r["name"], "w".repeat(255)); + let names: Vec = s.prefs.screen_export_presets.iter().map(|p| p.name.chars().count()).collect(); + assert_eq!(names, [255, 255]); + // The same long name imported again gets a number within the limit, and saving under the name + // it got changes that preset alone. + let r = s.execute("document.exportPresets.import", &json!({ "data": file })).unwrap(); + let again = r["imported"][0].as_str().unwrap().to_string(); + assert!(again.chars().count() <= 255 && again != capped && again.ends_with(" 2"), "{again}"); + s.execute("document.exportPresets.save", &json!({"name": again, "settings": {"formats": [{"format": "svg"}]}})).unwrap(); + let formats: Vec> = + s.prefs.screen_export_presets.iter().map(|p| p.settings.get("formats").and_then(|f| f[0]["format"].as_str())).collect(); + assert_eq!(formats, [Some("png"), None, Some("svg")]); +} diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index 6bea6dad72..8497676836 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -63,6 +63,32 @@ fn export_writes_dxf_of_the_chosen_version() { assert_eq!(header(&text(&ser), "$INSUNITS").as_deref(), Some("1")); } +#[test] +fn the_cnc_preset_sets_the_options_that_are_not_given() { + let mut s = two_boards(); + let cnc = text(&s.execute("document.exportDxf", &json!({"dxfPreset": "cnc"})).unwrap()); + assert_eq!(header(&cnc, "$ACADVER").as_deref(), Some("AC1015")); + assert_eq!(header(&cnc, "$INSUNITS").as_deref(), Some("4")); + // document.export takes it too, beside a PDF preset's name. + let r = s.execute("document.export", &json!({"format": "dxf", "dxfPreset": "cnc"})).unwrap(); + assert_eq!(header(&text(&r), "$ACADVER").as_deref(), Some("AC1015")); + let o = dxf::options(&json!({"dxfPreset": "CNC", "unit": "in"})).unwrap(); + assert_eq!( + (o.version, o.unit, o.colors, o.preserve, o.alter_paths, o.outline_text), + ( + vectorcraft_cad::DxfVersion::R2000, + vectorcraft_doc::Unit::Inches, + vectorcraft_cad::ColorDepth::Aci256, + vectorcraft_cad::Preserve::Editability, + false, + true + ) + ); + assert_eq!(dxf::options(&json!({})).unwrap().version, vectorcraft_cad::DxfVersion::R2018, "custom by default"); + let e = s.execute("document.exportDxf", &json!({"dxfPreset": "laser"})).unwrap_err().to_string(); + assert!(e.contains("custom or cnc"), "{e}"); +} + #[test] fn use_artboards_writes_one_drawing_per_artboard() { let mut s = two_boards(); @@ -93,7 +119,7 @@ fn selected_only_exports_the_selection_in_its_layers() { let line = s.execute("shape.line", &json!({"x1": 0, "y1": 90, "x2": 90, "y2": 90})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [line]})).unwrap(); let dxf = text(&s.execute("document.export", &json!({"format": "dxf", "selectedOnly": true})).unwrap()); - assert_eq!(entities(&dxf), ["LWPOLYLINE"]); + assert_eq!(entities(&dxf), ["LINE"]); assert!(dxf.contains("\n 2\nTop\n") && !dxf.contains("\n 2\nLayer 1\n"), "only the selection's layer"); s.execute("select.none", &json!({})).unwrap(); let e = s.execute("document.export", &json!({"format": "dxf", "selectedOnly": true})).unwrap_err().to_string(); @@ -101,7 +127,7 @@ fn selected_only_exports_the_selection_in_its_layers() { // Other formats take it too. s.execute("select.set", &json!({"ids": [line]})).unwrap(); let svg = s.execute("document.serialize", &json!({"format": "svg", "selectedOnly": true})).unwrap()["text"].as_str().unwrap().to_string(); - assert_eq!((svg.matches(" [(u32, u32); 4] { + let (a, b) = (side / 4, side * 3 / 4); + [(a, a), (b, a), (a, b), (b, b)] +} + +#[cfg(feature = "heif")] +fn decoded(bytes: &[u8]) -> image::RgbaImage { + let raster = load::raster_image(bytes).unwrap(); + image::load_from_memory(&raster.blob.bytes).unwrap().to_rgba8() +} + +#[cfg(feature = "heif")] +fn close(got: [u8; 4], want: [u8; 4], tolerance: u8) -> bool { + got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= tolerance) +} + +#[cfg(feature = "heif")] +fn assert_quadrants(img: &image::RgbaImage, side: u32, what: &str) { + assert_eq!(img.dimensions(), (side, side), "{what}"); + for ((x, y), want) in centers(side).into_iter().zip(COLORS) { + let got = img.get_pixel(x, y).0; + assert!(close(got, want, 8), "{what} at ({x}, {y}): {got:?} != {want:?}"); + } +} + +#[cfg(feature = "heif")] +#[test] +fn quadrants_open_and_place_as_their_pixels() { + assert_quadrants(&decoded(QUADRANTS), 32, "quadrants.heic"); + for name in ["photo.heic", "photo.heif", "unknown.bin"] { + let mut s = Session::new(); + let encoded = vectorcraft_format::base64_encode(QUADRANTS); + let opened = s.execute("document.open", &json!({"name": name, "dataBase64": encoded})).unwrap(); + assert_eq!(opened["format"], "heif", "{name}"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(32.0, 32.0)); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + assert_quadrants(&image::load_from_memory(&blob.bytes).unwrap().to_rgba8(), 32, name); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let placed = s.execute("file.place", &json!({"name": name, "dataBase64": encoded})).unwrap(); + assert_eq!(placed["format"], "heif", "{name}"); + } + assert!(load::texture_image(QUADRANTS).is_ok()); + // The general brand alone, without `heic`. + let mut general = QUADRANTS.to_vec(); + assert_eq!(&QUADRANTS[8..28], b"heic\0\0\0\0mif1heicmiaf"); + general[8..12].copy_from_slice(b"mif1"); + general[20..24].copy_from_slice(b"miaf"); + assert_quadrants(&decoded(&general), 32, "mif1 only"); +} + +#[test] +fn signatures_and_every_extension() { + for bytes in EVERY_FIXTURE { + assert!(is_heif(bytes)); + assert_eq!(load::detect("unknown.bin", bytes).map(|f| f.id), Some("heif")); + } + for ext in ["heic", "heif"] { + assert_eq!(load::detect(&format!("a.{ext}"), b"invalid").map(|f| f.id), Some("heif")); + assert!(OPEN_EXTS.contains(&ext) && PLACE_EXTS.contains(&ext) && UNASSOCIATED_EXTS.contains(&ext), "{ext}"); + } + // A brand only among the compatible ones counts, and so do the general brands alone. + assert!(is_heif(b"\0\0\0\x14ftypabcd\0\0\0\0heic")); + assert!(is_heif(b"\0\0\0\x18ftypmif1\0\0\0\0mif1heix")); + assert!(is_heif(b"\0\0\0\x18ftypmsf1\0\0\0\0msf1hevc")); + assert!(is_heif(b"\0\0\0\x18ftypmif1\0\0\0\0mif1miaf")); + // A 64-bit box size (ISO/IEC 14496-12 4.2). + assert!(is_heif(b"\0\0\0\x01ftyp\0\0\0\0\0\0\0\x18heic\0\0\0\0")); + let mut extended = b"\0\0\0\x01ftyp\0\0\0\0\0\0\0\x18heic\0\0\0\0".to_vec(); + extended.extend_from_slice(&QUADRANTS[QUADRANTS.windows(4).position(|w| w == b"meta").unwrap() - 4..]); + assert_eq!(load::detect("unknown.bin", &extended).map(|f| f.id), Some("heif")); + // AVIF, with its brand major or compatible, and brands heic-rs doesn't read. + assert!(!is_heif(b"\0\0\0\x18ftypavif\0\0\0\0mif1miaf")); + assert!(!is_heif(b"\0\0\0\x1cftypmif1\0\0\0\0mif1avifmiaf")); + assert!(!is_heif(b"\0\0\0\x1cftypheic\0\0\0\0mif1heicavis")); + assert!(!is_heif(b"\0\0\0\x18ftyphevx\0\0\0\0hevxiso8")); + assert!(!is_heif(b"\0\0\0\x18ftypisom\0\0\0\0isomavc1")); + // A box shorter than its brands, longer than the file, or of another type. + assert!(!is_heif(b"\0\0\0\x0cftypheic")); + assert!(!is_heif(b"\0\0\0\x40ftypheic\0\0\0\0mif1")); + assert!(!is_heif(b"\0\0\0\x14styphei\0\0\0\0\0heic")); + assert!(!is_heif(b"")); +} + +#[cfg(feature = "heif")] +#[test] +fn alpha_10_bit_and_grid_images_keep_their_pixels() { + let alpha = decoded(ALPHA); + assert_eq!(alpha.dimensions(), (32, 32)); + for ((x, y), want) in centers(32).into_iter().zip(COLORS) { + let got = alpha.get_pixel(x, y).0; + // The left half is opaque; the right half is transparent. + if x < 16 { + assert!(close(got, want, 8), "({x}, {y}): {got:?} != {want:?}"); + } else { + assert!(got[3] <= 8, "({x}, {y}): {got:?}"); + } + } + assert_quadrants(&decoded(TEN_BIT), 32, "10-bit"); + // Four 64 × 64 tiles, one for each quadrant. + assert_quadrants(&decoded(GRID), 128, "2 × 2 grid"); +} + +#[cfg(feature = "heif")] +#[test] +fn a_grid_of_cropped_tiles_is_refused() { + // 32 × 32 quadrants as a 2 × 2 grid of 16 × 16 tiles, each coded 64 × 64 and cropped back + // with its own clap, which heic-rs 0.1.4 leaves out when it composes the grid. + let error = load::raster_image(GRID16).err().unwrap().to_string(); + assert!(error.contains("kind of image that can't be read"), "{error}"); +} + +#[cfg(feature = "heif")] +#[test] +fn a_grid_without_its_own_color_box_uses_its_tiles() { + // The grid item's associations (ipma) list ispe (1), pixi (5) and colr (3); the tiles carry + // the same colr. Pointing the grid's third association at its ispe leaves the grid without one. + let mut tiles_only = GRID.to_vec(); + assert_eq!(&GRID[565..571], &[0, 1, 3, 1, 0x85, 3], "item 1 with three associations, the last colr"); + tiles_only[570] = 1; + assert_quadrants(&decoded(&tiles_only), 128, "colr on the tiles only"); +} + +#[cfg(feature = "heif")] +#[test] +fn the_containers_rotation_is_applied() { + // A 32 × 16 image, red then blue, stored with a quarter turn clockwise. + let img = decoded(ROTATED); + assert_eq!(img.dimensions(), (16, 32)); + assert!(close(img.get_pixel(8, 4).0, [255, 0, 0, 255], 8), "{:?}", img.get_pixel(8, 4)); + assert!(close(img.get_pixel(8, 27).0, [0, 0, 255, 255], 8), "{:?}", img.get_pixel(8, 27)); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "a.heic", "dataBase64": vectorcraft_format::base64_encode(ROTATED)})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(16.0, 32.0)); +} + +#[cfg(feature = "heif")] +#[test] +fn the_containers_mirror_and_crop_are_applied() { + // The rotated image's irot (property 6) turned to no rotation, and to an imir of the same + // size: mirrored left to right (ISO/IEC 23008-12 6.5.12, axis 0). + assert_eq!(&ROTATED[384..393], b"\0\0\0\x09irot\x03"); + let mut stored = ROTATED.to_vec(); + stored[392] = 0; + let mut mirrored = ROTATED.to_vec(); + mirrored[388..393].copy_from_slice(b"imir\0"); + let (stored, mirrored) = (decoded(&stored), decoded(&mirrored)); + assert_eq!((stored.dimensions(), mirrored.dimensions()), ((32, 16), (32, 16))); + let red = [255, 0, 0, 255]; + assert!(close(stored.get_pixel(8, 8).0, red, 8) && !close(stored.get_pixel(24, 8).0, red, 8), "{:?}", stored.get_pixel(8, 8)); + for (x, y) in [(4, 4), (8, 8), (20, 12), (27, 3)] { + assert!(close(mirrored.get_pixel(x, y).0, stored.get_pixel(31 - x, y).0, 8), "({x}, {y})"); + } + // The quadrants' clap (property 4) takes the top-left 32 × 32 of the 64 × 64 coded picture. + // Rewritten to its top-left 16 × 16: a center offset of -24 (ISO/IEC 14496-12 12.1.4) leaves + // the red quadrant alone. Its edge next to green is left out, as lossy chroma blends there. + assert_eq!(&QUADRANTS[329..337], b"\0\0\0\x28clap"); + let mut cropped = QUADRANTS.to_vec(); + let clap: Vec = [16u32, 1, 16, 1, (-48i32).cast_unsigned(), 2, (-48i32).cast_unsigned(), 2].iter().flat_map(|v| v.to_be_bytes()).collect(); + cropped[337..369].copy_from_slice(&clap); + let cropped = decoded(&cropped); + assert_eq!(cropped.dimensions(), (16, 16)); + for (x, y) in [(0, 0), (8, 8), (12, 0), (0, 12), (12, 12)] { + assert!(close(cropped.get_pixel(x, y).0, red, 8), "({x}, {y}): {:?}", cropped.get_pixel(x, y)); + } +} + +#[cfg(feature = "heif")] +#[test] +fn exif_resolution_sizes_the_image_and_72_ppi_without_it() { + let got = ppi::resolution(PPI300).unwrap(); + assert!((got.0 - 300.0).abs() < 0.01 && (got.1 - 300.0).abs() < 0.01, "{got:?}"); + assert_eq!(ppi::resolution(QUADRANTS), None); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "a.heic", "dataBase64": vectorcraft_format::base64_encode(PPI300)})).unwrap(); + let size = s.doc().unwrap().doc.artboards[0].rect.size(); + assert!((size.width - 7.68).abs() < 0.001 && (size.height - 7.68).abs() < 0.001, "{size:?}"); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + let stored = ppi::resolution(&blob.bytes).unwrap(); + assert!((stored.0 - 300.0).abs() < 0.01 && (stored.1 - 300.0).abs() < 0.01); + // 32 × 16 pixels at 300 ppi across and 150 down, turned a quarter: 16 × 32 pixels at 150 ppi + // across and 300 down, the same 7.68 × 7.68 pt either way. + assert_eq!(ppi::resolution(ROTATED_300X150), Some((300.0, 150.0)), "as stored"); + let img = load::raster_image(ROTATED_300X150).unwrap(); + assert_eq!((img.width, img.height, img.ppi), (16, 32, Some((150.0, 300.0)))); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "a.heic", "dataBase64": vectorcraft_format::base64_encode(ROTATED_300X150)})).unwrap(); + let size = s.doc().unwrap().doc.artboards[0].rect.size(); + assert!((size.width - 7.68).abs() < 0.001 && (size.height - 7.68).abs() < 0.001, "{size:?}"); +} + +#[cfg(feature = "heif")] +#[test] +fn display_p3_images_are_converted_to_srgb() { + use vectorcraft_color::cms::{DISPLAY_P3, Intent, icc::builtin_rgb}; + let p3 = builtin_rgb(DISPLAY_P3).unwrap(); + let plain = decoded(TONES); + // The ICC-only file's samples are full-range BT.601, which only its HEVC stream says. + for (what, bytes) in [("nclx", TONES_P3_NCLX), ("ICC", TONES_P3_ICC), ("ICC only", TONES_P3_ICC_ONLY)] { + let converted = decoded(bytes); + for (x, y) in centers(32) { + let [r, g, b, a] = plain.get_pixel(x, y).0; + let rgb = p3.to_srgb_into(&[r, g, b].map(|v| f32::from(v) / 255.0), Intent::RelativeColorimetric).unwrap(); + let [r, g, b] = rgb.map(|v| (v * 255.0).round() as u8); + let got = converted.get_pixel(x, y).0; + assert!(close(got, [r, g, b, a], 2), "{what} at ({x}, {y}): {got:?} != {:?}", [r, g, b, a]); + } + } + // The orange quadrant changes, so the conversion ran. + assert!(!close(decoded(TONES_P3_NCLX).get_pixel(8, 8).0, plain.get_pixel(8, 8).0, 4)); +} + +#[cfg(feature = "heif")] +#[test] +fn display_p3_named_by_the_stream_alone_is_converted_to_srgb() { + // The nclx file's item associates hvcC, colr (property 2), ispe, pixi and clap. Pointing the + // colr association at the ispe leaves the item without a color box, and its HEVC stream's + // video signal type, which names Display P3 with the sRGB curve, describes the samples. + let ipma = TONES_P3_NCLX.windows(4).position(|w| w == b"ipma").unwrap(); + let at = ipma + 4 + 4 + 4 + 2 + 1 + 1; + assert_eq!(&TONES_P3_NCLX[at - 4..at + 4], &[0, 1, 5, 0x81, 2, 3, 5, 0x84], "item 1 with five associations, the second colr"); + let mut stream_only = TONES_P3_NCLX.to_vec(); + stream_only[at] = 3; + let want = decoded(TONES_P3_NCLX); + let got = decoded(&stream_only); + for (x, y) in centers(32) { + assert!(close(got.get_pixel(x, y).0, want.get_pixel(x, y).0, 2), "at ({x}, {y}): {:?} != {:?}", got.get_pixel(x, y), want.get_pixel(x, y)); + } +} + +#[cfg(feature = "heif")] +#[test] +fn two_quarter_turns_keep_the_resolution_axes() { + // The rotated image's ipma lists its irot once; a second association with the same irot turns + // it a half turn, so the EXIF resolution keeps its axes. + let ipma = ROTATED_300X150.windows(4).position(|w| w == b"ipma").unwrap(); + let count = ipma + 4 + 4 + 4 + 2; + let irot = ROTATED_300X150.windows(4).position(|w| w == b"irot").unwrap(); + let ipco = ROTATED_300X150.windows(4).position(|w| w == b"ipco").unwrap(); + // The irot's property index: its place among the boxes of ipco, counted from 1. + let mut index = 1u8; + let mut at = ipco + 4; + while at < irot - 4 { + index += 1; + at += u32::from_be_bytes(ROTATED_300X150[at..at + 4].try_into().unwrap()) as usize; + } + assert_eq!(at, irot - 4, "irot is a box of ipco"); + let n = usize::from(ROTATED_300X150[count]); + assert!(ROTATED_300X150[count + 1..count + 1 + n].contains(&(0x80 | index)), "the item's irot association, essential"); + let mut twice = ROTATED_300X150.to_vec(); + twice[count] += 1; + twice.insert(count + 1 + n, 0x80 | index); + // The ipma, iprp and meta boxes each grow by one byte, and the iloc offsets move with them. + let grow = |bytes: &mut Vec, name: &[u8; 4]| { + let at = bytes.windows(4).position(|w| w == name).unwrap() - 4; + let size = u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap()) + 1; + bytes[at..at + 4].copy_from_slice(&size.to_be_bytes()); + }; + for name in [b"ipma", b"iprp", b"meta"] { + grow(&mut twice, name); + } + let iloc = twice.windows(4).position(|w| w == b"iloc").unwrap(); + assert_eq!(&twice[iloc + 4..iloc + 8], &[0, 0, 0, 0], "iloc version 0"); + let sizes = twice[iloc + 8]; + assert_eq!((sizes >> 4, sizes & 0xf), (4, 4), "4-byte offsets and lengths"); + assert_eq!(twice[iloc + 9] >> 4, 4, "4-byte base offsets"); + let items = u16::from_be_bytes([twice[iloc + 10], twice[iloc + 11]]); + // Each item: its id, data reference index and base offset, which moves, then its extents. + let mut at = iloc + 12; + for _ in 0..items { + at += 2 + 2; + let offset = u32::from_be_bytes(twice[at..at + 4].try_into().unwrap()) + 1; + twice[at..at + 4].copy_from_slice(&offset.to_be_bytes()); + at += 4; + let extents = u16::from_be_bytes([twice[at], twice[at + 1]]); + at += 2 + 8 * usize::from(extents); + } + let img = load::raster_image(&twice).unwrap(); + assert_eq!((img.width, img.height, img.ppi), (32, 16, Some((300.0, 150.0))), "a half turn keeps the stored axes"); +} + +#[cfg(feature = "heif")] +#[test] +fn damaged_unsupported_and_oversized_files_are_refused() { + let error = |bytes: &[u8]| load::raster_image(bytes).err().unwrap().to_string(); + for cut in [16, 40, QUADRANTS.len() / 2, QUADRANTS.len() - 5] { + assert!(load::raster_image(&QUADRANTS[..cut]).is_err(), "{cut}"); + } + // An ftyp and nothing else, as an image sequence starts (its `moov` would follow). + assert!(error(b"\0\0\0\x18ftypmsf1\0\0\0\0msf1hevc").contains("kind of image that can't be read")); + assert!(error(b"\0\0\0\x18ftypheic\0\0\0\0mif1heic\0\0\0\x08free").contains("HEIC or HEIF file")); + // The primary item's type (infe) turned from HEVC to AV1, with its hvcC kept, and with its + // hvcC turned into an av1C. + let mut av1 = QUADRANTS.to_vec(); + assert_eq!((&QUADRANTS[137..141], &QUADRANTS[176..180]), (&b"hvc1"[..], &b"hvcC"[..])); + av1[137..141].copy_from_slice(b"av01"); + assert!(error(&av1).contains("kind of image that can't be read"), "{}", error(&av1)); + av1[176..180].copy_from_slice(b"av1C"); + assert!(error(&av1).contains("kind of image that can't be read"), "{}", error(&av1)); + // The image spatial extents (`ispe`) claim 60,000 × 60,000 pixels. + let mut huge = QUADRANTS.to_vec(); + let at = huge.windows(4).position(|w| w == b"ispe").unwrap() + 8; + huge[at..at + 4].copy_from_slice(&60_000u32.to_be_bytes()); + huge[at + 4..at + 8].copy_from_slice(&60_000u32.to_be_bytes()); + assert!(error(&huge).contains("60000 × 60000 pixels is too large to draw"), "{}", error(&huge)); + // A single 64 × 64 coded picture (cropped to 32 × 32) takes its RGBA output and copy, + // 64 × 64 × 8, and its planes, 64 × 64 × 9: no composed frame is counted. + assert!(super::heifread::decode(QUADRANTS, 64 * 64 * 17).is_ok()); + assert!(super::heifread::decode(QUADRANTS, 64 * 64 * 17 - 1).unwrap_err().contains("too large to draw")); + // The same picture with an ispe of 32 × 32 (its crop's size): its stream still decodes + // 64 × 64, and that size is counted. + let mut small = QUADRANTS.to_vec(); + let at = small.windows(4).position(|w| w == b"ispe").unwrap() + 8; + assert_eq!(&small[at..at + 8], b"\0\0\0\x40\0\0\0\x40"); + small[at..at + 4].copy_from_slice(&32u32.to_be_bytes()); + small[at + 4..at + 8].copy_from_slice(&32u32.to_be_bytes()); + let refused = super::heifread::decode(&small, 64 * 64 * 17 - 1).map(|img| img.dimensions()); + assert!(refused.as_ref().is_err_and(|e| e.contains("too large to draw")), "{refused:?}"); + // A 128 × 128 grid of four 64 × 64 tiles adds its composed frame, 128 × 128 × 6. + let grid = 128 * 128 * (8 + 6) + 4 * 64 * 64 * 9; + assert!(super::heifread::decode(GRID, grid).is_ok()); + assert!(super::heifread::decode(GRID, grid - 1).unwrap_err().contains("too large to draw")); + // The grid's ispe (property 1) claims 16 × 16 pixels; its grid data still composes 128 × 128, + // and that size is counted. + let mut understated = GRID.to_vec(); + assert_eq!(&GRID[358..370], b"ispe\0\0\0\0\0\0\0\x80", "property 1 is the grid's 128 × 128 ispe"); + understated[366..370].copy_from_slice(&16u32.to_be_bytes()); + understated[370..374].copy_from_slice(&16u32.to_be_bytes()); + assert!(super::heifread::decode(&understated, grid - 1).unwrap_err().contains("too large to draw")); +} + +/// Appends `value` as `n` bits, most significant first. +#[cfg(feature = "heif")] +fn put(bits: &mut Vec, value: u64, n: u32) { + bits.extend((0..n).rev().map(|i| i < 64 && value >> i & 1 == 1)); +} + +/// Appends `value` as an unsigned Exp-Golomb code. +#[cfg(feature = "heif")] +fn put_ue(bits: &mut Vec, value: u64) { + let len = 64 - (value + 1).leading_zeros(); + put(bits, 0, len - 1); + put(bits, value + 1, len); +} + +/// The fields of SPS 0 of `width` × `height` 4:2:0 samples with `sub_layers` sub-layers, each +/// with its profile and level, up to its height. +#[cfg(feature = "heif")] +fn sps_head(width: u64, height: u64, sub_layers: u64) -> Vec { + sps_head_with_id(width, height, sub_layers, 0) +} + +/// [`sps_head`] for SPS `id`. +#[cfg(feature = "heif")] +fn sps_head_with_id(width: u64, height: u64, sub_layers: u64, id: u64) -> Vec { + let mut bits = Vec::new(); + put(&mut bits, 0, 4); + put(&mut bits, sub_layers, 3); + put(&mut bits, 1, 1); + put(&mut bits, 0, 96); + for _ in 0..sub_layers { + put(&mut bits, 0b11, 2); + } + if sub_layers > 0 { + put(&mut bits, 0, 2 * (8 - sub_layers as u32)); + } + for _ in 0..sub_layers { + put(&mut bits, 0, 88 + 8); + } + put_ue(&mut bits, id); + put_ue(&mut bits, 1); + put_ue(&mut bits, width); + put_ue(&mut bits, height); + bits +} + +/// An SPS NAL unit of `bits` (see [`nal`]). +#[cfg(feature = "heif")] +fn sps_nal(bits: Vec) -> Vec { + nal(33, bits) +} + +/// A NAL unit of type `kind` holding `bits`, with its stop bit, and emulation prevention bytes +/// inserted as a stream carries them. +#[cfg(feature = "heif")] +fn nal(kind: u8, mut bits: Vec) -> Vec { + put(&mut bits, 1, 1); + while !bits.len().is_multiple_of(8) { + bits.push(false); + } + let rbsp: Vec = bits.chunks(8).map(|b| b.iter().fold(0u8, |v, &bit| v << 1 | u8::from(bit))).collect(); + let mut nal = vec![kind << 1, 1]; + let mut zeros = 0; + for b in rbsp { + if zeros >= 2 && b <= 3 { + nal.push(3); + zeros = 0; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + nal.push(b); + } + nal +} + +#[cfg(feature = "heif")] +fn sps(width: u64, height: u64, sub_layers: u64) -> Vec { + sps_nal(sps_head(width, height, sub_layers)) +} + +/// A 64 × 64 SPS that uses every optional part before the VUI's video signal type: a conformance +/// window, sub-layer ordering for two sub-layers, explicit scaling lists, PCM, a reference picture +/// set predicted from another and a long-term picture, then an Extended_SAR aspect ratio and +/// overscan information. `signal` is the full-range flag and the color description, if any. +#[cfg(feature = "heif")] +fn sps_with_vui(signal: Option<(u64, Option<[u64; 3]>)>) -> Vec { + sps_with_vui_and_id(signal, 0) +} + +/// [`sps_with_vui`] for SPS `id`. +#[cfg(feature = "heif")] +fn sps_with_vui_and_id(signal: Option<(u64, Option<[u64; 3]>)>, id: u64) -> Vec { + let mut bits = sps_head_with_id(64, 64, 1, id); + put(&mut bits, 1, 1); + for offset in [0, 2, 0, 2] { + put_ue(&mut bits, offset); + } + put_ue(&mut bits, 0); + put_ue(&mut bits, 0); + // 8 bits of picture order count. + put_ue(&mut bits, 4); + put(&mut bits, 1, 1); + for _ in 0..2 * 3 { + put_ue(&mut bits, 1); + } + for value in [0, 3, 0, 3, 1, 1] { + put_ue(&mut bits, value); + } + // Scaling lists: matrix 1 of each size given explicitly, the others copied. + put(&mut bits, 0b11, 2); + for size in 0..4 { + for matrix in 0..if size == 3 { 2 } else { 6 } { + if matrix == 1 { + put(&mut bits, 1, 1); + if size > 1 { + put_ue(&mut bits, 5); + } + for _ in 0..if size == 0 { 16 } else { 64 } { + put_ue(&mut bits, 3); + } + } else { + put(&mut bits, 0, 1); + put_ue(&mut bits, 0); + } + } + } + // AMP off, SAO on, PCM with its depths, block sizes and loop filter flag. + put(&mut bits, 0b01, 2); + put(&mut bits, 1, 1); + put(&mut bits, 0x77, 8); + put_ue(&mut bits, 0); + put_ue(&mut bits, 1); + put(&mut bits, 0, 1); + // Two short-term sets: one negative and one positive picture, then a set predicted from it + // with three entries (unused with use_delta_flag, used, unused). + put_ue(&mut bits, 2); + put_ue(&mut bits, 1); + put_ue(&mut bits, 1); + for _ in 0..2 { + put_ue(&mut bits, 0); + put(&mut bits, 1, 1); + } + put(&mut bits, 1, 1); + put(&mut bits, 0, 1); + put_ue(&mut bits, 0); + put(&mut bits, 0b01100, 5); + // One long-term picture: 8 bits of picture order count and its used flag. + put(&mut bits, 1, 1); + put_ue(&mut bits, 1); + put(&mut bits, 0xab, 8); + put(&mut bits, 1, 1); + put(&mut bits, 0b11, 2); + // VUI: Extended_SAR 1:1 and overscan information. + put(&mut bits, 1, 1); + put(&mut bits, 1, 1); + put(&mut bits, 255, 8); + put(&mut bits, 0x0001_0001, 32); + put(&mut bits, 1, 1); + put(&mut bits, 0, 1); + match signal { + Some((full, description)) => { + put(&mut bits, 1, 1); + put(&mut bits, 5, 3); + put(&mut bits, full, 1); + put(&mut bits, u64::from(description.is_some()), 1); + for code in description.into_iter().flatten() { + put(&mut bits, code, 8); + } + } + None => put(&mut bits, 0, 1), + } + // No chroma location, field or display window information, timing or restrictions. + put(&mut bits, 0, 8); + sps_nal(bits) +} + +#[cfg(feature = "heif")] +#[test] +fn picture_sizes_come_from_the_sequence_parameter_sets() { + use super::heifread::{picture_bytes, sps_size}; + for sub_layers in [0, 1, 6] { + for (w, h) in [(32, 32), (4032, 3024), (65535, 65535)] { + let nal = sps(w, h, sub_layers); + assert!(nal.windows(3).any(|w| w == [0, 0, 3]), "the profile's zeros need emulation prevention"); + assert_eq!(sps_size(&nal), Some((w, h, 1)), "{w} × {h}, {sub_layers} sub-layers"); + } + } + let mut vps = sps(32, 32, 0); + vps[0] = 32 << 1; + assert_eq!(sps_size(&vps), None); + assert_eq!(sps_size(&sps(32, 32, 0)[..8]), None); + // 4:2:0 is 3 bytes a sample position in each of three sets of planes, in 64-sample blocks. + assert_eq!(picture_bytes(QUADRANTS), Some(64 * 64 * 9)); + assert_eq!(picture_bytes(GRID), Some(4 * 64 * 64 * 9)); + assert!(picture_bytes(ALPHA).unwrap() > 64 * 64 * 9, "the alpha image is counted"); +} + +#[cfg(feature = "heif")] +#[test] +fn the_color_description_comes_from_the_streams_video_signal_type() { + use super::heifread::{sps_signal, sps_size}; + use heic_rs::{MatrixCoefficients, Range}; + let signal = |nal: &[u8]| sps_signal(nal).map(|n| (n.primaries, n.transfer, n.matrix, n.matrix_code, n.range)); + let described = sps_with_vui(Some((1, Some([12, 13, 6])))); + assert_eq!(sps_size(&described), Some((64, 64, 1))); + assert_eq!(signal(&described), Some((12, 13, MatrixCoefficients::Bt601, 6, Range::Full))); + assert_eq!(signal(&sps_with_vui(Some((0, None)))), Some((2, 2, MatrixCoefficients::Unspecified, 2, Range::Limited))); + assert_eq!(signal(&sps_with_vui(None)), None); + assert_eq!(signal(&sps(64, 64, 0)), None, "cut short before its VUI"); + // The ICC-only fixture's stream: heif-enc writes full-range BT.601. + let ctx = heic_rs::context::Context::open(TONES_P3_ICC_ONLY).unwrap(); + let props = ctx.props(ctx.meta.primary).unwrap(); + assert!(props.nclx.is_none() && props.icc.is_some()); + let sets = props.hvcc.unwrap().parameter_sets(); + let nal = sets.into_iter().find(|nal| nal[0] >> 1 & 0x3f == 33).unwrap(); + assert_eq!(sps_signal(nal).map(|n| (n.matrix, n.range)), Some((MatrixCoefficients::Bt601, Range::Full))); +} + +#[cfg(feature = "heif")] +#[test] +fn the_slices_picture_parameter_set_picks_the_sps() { + use super::heifread::{active_sps, sps_signal}; + use heic_rs::Range; + let full = sps_with_vui_and_id(Some((1, Some([1, 13, 6]))), 0); + let limited = sps_with_vui_and_id(Some((0, Some([1, 13, 1]))), 1); + let pps = |id: u64, sps: u64| { + let mut bits = Vec::new(); + put_ue(&mut bits, id); + put_ue(&mut bits, sps); + nal(34, bits) + }; + // first_slice_segment_in_pic_flag, no_output_of_prior_pics_flag for an IDR picture (type 19), + // slice_pic_parameter_set_id. + let slice = |kind: u8, pps: u64| { + let mut bits = vec![true]; + if kind == 19 { + bits.push(false); + } + put_ue(&mut bits, pps); + nal(kind, bits) + }; + let (pps0, pps3) = (pps(0, 0), pps(3, 1)); + let sets = [full.as_slice(), limited.as_slice(), pps0.as_slice(), pps3.as_slice()]; + let (idr3, trail0, idr5) = (slice(19, 3), slice(1, 0), slice(19, 5)); + assert_eq!(active_sps(&sets, &[&idr3]), Some(limited.as_slice())); + assert_eq!(active_sps(&sets, &[&trail0]), Some(full.as_slice())); + assert_eq!(active_sps(&sets, &[&idr5]), None, "no PPS 5"); + assert_eq!(active_sps(&sets, &[&pps0]), None, "no slice"); + assert_eq!(active_sps(&sets, &[&idr3]).and_then(sps_signal).map(|n| (n.matrix_code, n.range)), Some((1, Range::Limited))); +} + +#[cfg(not(feature = "heif"))] +#[test] +fn a_build_without_the_decoder_refuses_heif_files_with_a_message() { + for bytes in EVERY_FIXTURE { + assert_eq!(load::detect("unknown.bin", bytes).map(|f| f.id), Some("heif")); + let error = load::raster_image(bytes).err().unwrap().to_string(); + assert!(error.contains("can't be opened in this build"), "{error}"); + } + assert_eq!(ppi::resolution(PPI300), None); +} diff --git a/crates/engine/src/cmd/fileio/tests_jp2read.rs b/crates/engine/src/cmd/fileio/tests_jp2read.rs new file mode 100644 index 0000000000..e028350150 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_jp2read.rs @@ -0,0 +1,296 @@ +//! JPEG 2000 Open, Place, pixel and resolution regressions using original synthetic fixtures. + +use serde_json::json; + +use super::jp2read::is_jpeg2000; +use super::*; + +const JP2: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker.jp2"); +const RAW: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker-raw.j2k"); +const PPI300: &[u8] = include_bytes!("../../../tests/fixtures/jpeg2000/checker-300ppi.jp2"); +const COLORS: [[u8; 4]; 4] = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]]; + +fn pixels(bytes: &[u8]) -> Vec<[u8; 4]> { + let raster = load::raster_image(bytes).unwrap(); + image::load_from_memory(&raster.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() +} + +fn boxed(ty: &[u8; 4], data: &[u8]) -> Vec { + let mut out = ((data.len() + 8) as u32).to_be_bytes().to_vec(); + out.extend(ty); + out.extend(data); + out +} + +fn with_resolution(children: &[Vec]) -> Vec { + let mut file = JP2.to_vec(); + let at = file.windows(4).position(|w| w == b"jp2h").unwrap() - 4; + let old_len = u32::from_be_bytes(file[at..at + 4].try_into().unwrap()) as usize; + let mut header = file[at + 8..at + old_len].to_vec(); + if !children.is_empty() { + header.extend(boxed(b"res ", &children.concat())); + } + file.splice(at..at + old_len, boxed(b"jp2h", &header)); + file +} + +fn res(ty: &[u8; 4], vr: u16, hr: u16) -> Vec { + let mut data = Vec::new(); + for n in [vr, hr] { + data.extend(n.to_be_bytes()); + data.extend(254u16.to_be_bytes()); + } + data.extend([2, 2]); + boxed(ty, &data) +} + +#[test] +fn checker_opens_and_places_with_exact_pixels() { + for (name, bytes) in [("checker.jp2", JP2), ("checker-raw.j2k", RAW)] { + assert_eq!(pixels(bytes), COLORS, "{name}"); + let mut s = Session::new(); + let encoded = vectorcraft_format::base64_encode(bytes); + let opened = s.execute("document.open", &json!({"name": name, "dataBase64": encoded})).unwrap(); + assert_eq!(opened["format"], "jpeg2000"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(2.0, 2.0)); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::>(), COLORS); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let placed = s.execute("file.place", &json!({"name": name, "dataBase64": encoded})).unwrap(); + assert_eq!(placed["format"], "jpeg2000"); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect::>(), COLORS); + assert!(load::texture_image(bytes).is_ok()); + } +} + +#[test] +fn signatures_and_every_extension() { + assert!(is_jpeg2000(JP2) && is_jpeg2000(RAW)); + for ext in ["jpf", "jpx", "jp2", "j2k", "j2c", "jpc"] { + assert_eq!(load::detect(&format!("a.{ext}"), b"invalid").map(|f| f.id), Some("jpeg2000")); + assert!(OPEN_EXTS.contains(&ext) && PLACE_EXTS.contains(&ext) && UNASSOCIATED_EXTS.contains(&ext)); + } + assert_eq!(load::detect("unknown.bin", JP2).map(|f| f.id), Some("jpeg2000")); + assert_eq!(load::detect("unknown.bin", RAW).map(|f| f.id), Some("jpeg2000")); +} + +#[test] +fn resolution_boxes_prefer_display_then_last_valid_axis_and_72_fallback() { + let check = |children: &[Vec], want: (f64, f64)| { + let file = with_resolution(children); + let got = ppi::resolution(&file).unwrap(); + assert!((got.0 - want.0).abs() < 0.01 && (got.1 - want.1).abs() < 0.01, "{got:?} != {want:?}"); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "a.jp2", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap(); + let size = s.doc().unwrap().doc.artboards[0].rect.size(); + assert!((size.width - 144.0 / want.0).abs() < 0.01 && (size.height - 144.0 / want.1).abs() < 0.01); + }; + check(&[], (72.0, 72.0)); + check(&[res(b"resc", 30000, 30000)], (300.0, 300.0)); + check(&[res(b"resd", 15000, 15000)], (150.0, 150.0)); + check(&[res(b"resc", 30000, 30000), res(b"resd", 15000, 15000)], (150.0, 150.0)); + check(&[res(b"resd", 15000, 15000), res(b"resc", 30000, 30000)], (150.0, 150.0)); + check(&[res(b"resd", 30000, 15000), res(b"resc", 7500, 7500)], (150.0, 300.0)); + check(&[res(b"resd", 0, 15000), res(b"resc", 30000, 30000)], (150.0, 300.0)); + check(&[res(b"resc", 30000, 30000), res(b"resd", 0, 15000)], (150.0, 300.0)); + check(&[res(b"resc", 30000, 15000)], (150.0, 300.0)); + assert_eq!(ppi::resolution(RAW), Some((72.0, 72.0))); + assert!((ppi::resolution(PPI300).unwrap().0 - 300.0).abs() < 0.01); + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "a.jp2", "dataBase64": vectorcraft_format::base64_encode(PPI300)})).unwrap(); + let size = s.doc().unwrap().doc.artboards[0].rect.size(); + assert!((size.width - 0.48).abs() < 0.001 && (size.height - 0.48).abs() < 0.001); + let blob = s.doc().unwrap().doc.images.values().next().unwrap(); + let stored = ppi::resolution(&blob.bytes).unwrap(); + assert!((stored.0 - 300.0).abs() < 0.01 && (stored.1 - 300.0).abs() < 0.01); +} + +#[test] +fn malformed_resolution_and_image_data_are_bounded() { + let good = res(b"resc", 30000, 15000); + let mut zero = res(b"resd", 15000, 15000); + zero[10..12].copy_from_slice(&0u16.to_be_bytes()); + let got = ppi::resolution(&with_resolution(&[good.clone(), zero])).unwrap(); + assert!((got.0 - 150.0).abs() < 0.01 && (got.1 - 300.0).abs() < 0.01); + let short = boxed(b"resd", &[0; 9]); + assert!(ppi::resolution(&with_resolution(&[good.clone(), short])).unwrap().0 > 149.0); + assert_eq!(ppi::resolution(&with_resolution(&[boxed(b"resc", &[0; 9])])), Some((72.0, 72.0))); + let mut over = good.clone(); + over[..4].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(ppi::resolution(&with_resolution(&[over])), Some((72.0, 72.0))); + let mut outer_over = JP2.to_vec(); + let jp2h = outer_over.windows(4).position(|w| w == b"jp2h").unwrap() - 4; + outer_over[jp2h..jp2h + 4].copy_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(ppi::resolution(&outer_over), Some((72.0, 72.0))); + let mut extended = Vec::from(1u32.to_be_bytes()); + extended.extend(b"resd"); + extended.extend(26u64.to_be_bytes()); + extended.extend(&res(b"resd", 15000, 30000)[8..]); + assert!(ppi::resolution(&with_resolution(&[extended])).unwrap().0 > 299.0); + let mut to_end = res(b"resd", 15000, 30000); + to_end[..4].copy_from_slice(&0u32.to_be_bytes()); + assert!(ppi::resolution(&with_resolution(&[to_end])).unwrap().0 > 299.0); + for bytes in [&JP2[..12], &RAW[..4], &JP2[..JP2.len() - 5]] { + assert!(load::raster_image(bytes).is_err()); + } + assert!(super::jp2read::decode(JP2, 8).is_err()); + // RGBA (16 bytes) and the float component planes (48 bytes) each fit; + // their concurrent allocation with samples and scratch does not. + assert!(super::jp2read::decode(JP2, 80).unwrap_err().contains("too large to draw")); + let mut huge = RAW.to_vec(); + huge[8..12].copy_from_slice(&100_000u32.to_be_bytes()); + huge[12..16].copy_from_slice(&100_000u32.to_be_bytes()); + assert!(load::raster_image(&huge).is_err()); + let mut jpx = JP2.to_vec(); + jpx.extend(boxed(b"jp2c", RAW)); + assert!(load::raster_image(&jpx).err().unwrap().to_string().contains("unsupported color space or JPX content")); + let mut layered = JP2.to_vec(); + layered.extend(boxed(b"jpch", &[])); + assert!(load::raster_image(&layered).err().unwrap().to_string().contains("unsupported color space or JPX content")); + let mut wrapped = JP2.to_vec(); + wrapped.extend(boxed(b"asoc", &boxed(b"jp2c", RAW))); + assert!(load::raster_image(&wrapped).err().unwrap().to_string().contains("unsupported color space or JPX content")); +} + +#[test] +fn compatible_jpx_brand_alone_keeps_checker_pixels() { + let mut branded = JP2.to_vec(); + branded[12..16].copy_from_slice(&24u32.to_be_bytes()); + branded.splice(32..32, b"jpx ".iter().copied()); + assert_eq!(pixels(&branded), COLORS); +} + +#[test] +fn codestream_component_count_bounds_decode_planes() { + assert_eq!(super::jp2read::decode(RAW, 1000).unwrap().pixels().map(|p| p.0).collect::>(), COLORS); + let mut many = RAW.to_vec(); + let component = many[42..45].to_vec(); + many.splice(42..42, component.repeat(17)); + many[4..6].copy_from_slice(&98u16.to_be_bytes()); // 38 + 3 * 20 + many[40..42].copy_from_slice(&20u16.to_be_bytes()); + assert!(super::jp2read::decode(&many, 1000).unwrap_err().contains("too large to draw")); + many[0..4].copy_from_slice(&[0, 0, 0, 0]); + assert!(super::jp2read::decode(&many, 1000).unwrap_err().contains("can't be read")); +} + +fn with_header_boxes(extra: &[Vec]) -> Vec { + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + let mut children = header.to_vec(); + children.extend(extra.concat()); + super::jp2read::boxes(JP2) + .map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>() + .concat() +} + +#[test] +fn channel_definitions_must_cover_every_channel() { + // (channel, type, association): color channels 1 to 3, an opacity channel (type 1). + let cdef = |defs: &[[u16; 3]]| { + let mut data = (defs.len() as u16).to_be_bytes().to_vec(); + data.extend(defs.iter().flatten().flat_map(|v| v.to_be_bytes())); + boxed(b"cdef", &data) + }; + assert_eq!(pixels(&with_header_boxes(&[cdef(&[[0, 0, 1], [1, 0, 2], [2, 0, 3]])])), COLORS); + // Channel 0 as green and channel 1 as red swap the two. + let swapped = [[0, 255, 0, 255], [255, 0, 0, 255], [0, 0, 255, 255], [255; 4]]; + assert_eq!(pixels(&with_header_boxes(&[cdef(&[[0, 0, 2], [1, 0, 1], [2, 0, 3]])])), swapped); + for defs in [ + vec![[0, 0, 1]], + vec![[0, 0, 1], [1, 0, 2], [2, 1, 0]], + vec![[0, 0, 1], [1, 0, 2], [2, 0, 3], [3, 1, 0]], + // Opacity first, a premultiplied opacity, a repeated color, an unassociated color. + vec![[0, 1, 0], [1, 0, 1], [2, 0, 2]], + vec![[0, 0, 1], [1, 0, 2], [2, 2, 0]], + vec![[0, 0, 1], [1, 0, 1], [2, 0, 3]], + vec![[0, 0, 1], [1, 0, 2], [2, 0, 0]], + ] { + assert!(load::raster_image(&with_header_boxes(&[cdef(&defs)])).err().unwrap().to_string().contains("can't be read"), "{defs:?}"); + } + // A second definition box, and a second header, are refused. + let full = cdef(&[[0, 0, 1], [1, 0, 2], [2, 0, 3]]); + assert!(load::raster_image(&with_header_boxes(&[full.clone(), cdef(&[[0, 0, 1]])])).err().unwrap().to_string().contains("can't be read")); + let mut two_headers = JP2.to_vec(); + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + two_headers.extend(boxed(b"jp2h", header)); + assert!(load::raster_image(&two_headers).err().unwrap().to_string().contains("can't be read")); +} + +#[test] +fn palette_needs_one_mapping_per_column() { + // 256 entries of three 8-bit columns, entry i being (i, i, i). + let mut palette = vec![1, 0, 3, 7, 7, 7]; + palette.extend((0..=255u8).flat_map(|i| [i; 3])); + let pclr = boxed(b"pclr", &palette); + let mut deep = vec![1, 0, 3, 7, 7, 31]; + deep.extend((0..=255u8).flat_map(|i| [i, i, 0, 0, 0, i])); + let deep = boxed(b"pclr", &deep); + let cmap = |entries: &[[u8; 4]]| boxed(b"cmap", &entries.concat()); + // Each component through its own column gives the same pixels. + let mapped = with_header_boxes(&[pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 0, 0]])]); + assert_eq!(pixels(&mapped), COLORS); + // 256 rows of three 8-byte values and a 24-byte list each (12,288 bytes) pass a 12,000-byte allowance. + assert!(super::jp2read::decode(&mapped, 12_000).unwrap_err().contains("too large to draw")); + for extra in [ + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 2], [0, 0, 1, 0]])], + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 9, 1, 2]])], + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 3]])], + vec![pclr.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1]])], + // A 32-bit column. + vec![deep.clone(), cmap(&[[0, 0, 1, 0], [0, 1, 1, 1], [0, 2, 1, 2]])], + ] { + assert!(load::raster_image(&with_header_boxes(&extra)).err().unwrap().to_string().contains("can't be read")); + } +} + +#[test] +fn tile_grid_is_bounded_before_decoding() { + let tiled = |size: u32, tile: u32| { + let mut file = RAW.to_vec(); + file[8..12].copy_from_slice(&size.to_be_bytes()); + file[12..16].copy_from_slice(&size.to_be_bytes()); + file[24..28].copy_from_slice(&tile.to_be_bytes()); + file[28..32].copy_from_slice(&tile.to_be_bytes()); + file + }; + // 1,000 × 1,000 one-pixel tiles are more than a codestream can number. + assert!(super::jp2read::decode(&tiled(1000, 1), MAX_RASTER_ALLOC).unwrap_err().contains("can't be read")); + assert!(super::jp2read::decode(&tiled(2, 0), MAX_RASTER_ALLOC).unwrap_err().contains("can't be read")); + // 255 × 255 one-pixel tiles of three components need more than this allowance before decoding. + assert!(super::jp2read::decode(&tiled(255, 1), 1 << 20).unwrap_err().contains("too large to draw")); +} + +#[test] +fn cielab_images_are_refused() { + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + // Enumerated color space 14, CIELab, with its default range and offset. + let children = super::jp2read::boxes(header) + .map(|(ty, data)| if ty == b"colr" { boxed(b"colr", &[1, 0, 0, 0, 0, 0, 14]) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>(); + let file = super::jp2read::boxes(JP2) + .map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children.concat()) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>() + .concat(); + assert!(load::raster_image(&file).err().unwrap().to_string().contains("unsupported color space")); +} + +#[test] +fn embedded_srgb_profile_keeps_checker_pixels() { + let icc = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::SRGB).unwrap(); + let mut colr_data = vec![2, 0, 0]; + colr_data.extend_from_slice(&icc); + let header = super::jp2read::boxes(JP2).find_map(|(ty, data)| (ty == b"jp2h").then_some(data)).unwrap(); + let children = super::jp2read::boxes(header) + .map(|(ty, data)| if ty == b"colr" { boxed(b"colr", &colr_data) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>(); + let file = super::jp2read::boxes(JP2) + .map(|(ty, data)| if ty == b"jp2h" { boxed(b"jp2h", &children.concat()) } else { boxed(ty.try_into().unwrap(), data) }) + .collect::>() + .concat(); + assert_eq!(pixels(&file), COLORS); + // A profile past 4 MiB is refused before the decoder reads the file. + let mut big = vec![2, 0, 0]; + big.resize(3 + 4 * 1024 * 1024 + 1, 0); + assert!(super::jp2read::decode(&with_header_boxes(&[boxed(b"colr", &big)]), MAX_RASTER_ALLOC).unwrap_err().contains("unsupported color space")); +} diff --git a/crates/engine/src/cmd/fileio/tests_pcxread.rs b/crates/engine/src/cmd/fileio/tests_pcxread.rs new file mode 100644 index 0000000000..8cab621bd3 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_pcxread.rs @@ -0,0 +1,221 @@ +//! Reading PCX files: every depth and plane layout decodes to the pixels it stores, the files open, +//! place and paste at the resolution their header gives, and damaged files are refused with a +//! message. + +use serde_json::json; + +use super::pcxread::{decode, is_pcx}; +use super::*; + +/// A PCX file of `version`, `bits` per pixel in `planes` planes, `w` × `h` pixels from (`x0`, 0), +/// `line` bytes per plane line, `dpi` both ways, the header palette `colors` (up to 16 entries), +/// then the encoded image data `data`. +#[allow(clippy::too_many_arguments)] +fn pcx(version: u8, bits: u8, planes: u8, x0: u16, (w, h): (u16, u16), line: u16, dpi: u16, colors: &[[u8; 3]], data: &[u8]) -> Vec { + let mut f = vec![0x0a, version, 1, bits]; + for v in [x0, 0, x0.wrapping_add(w).wrapping_sub(1), h.wrapping_sub(1), dpi, dpi] { + f.extend(v.to_le_bytes()); + } + let mut palette = [0; 48]; + for (i, c) in colors.iter().take(16).enumerate() { + palette[i * 3..i * 3 + 3].copy_from_slice(c); + } + f.extend(palette); + f.extend([0, planes]); + f.extend(line.to_le_bytes()); + f.extend(1u16.to_le_bytes()); + f.resize(128, 0); + f.extend(data); + f +} + +/// `raw` run-length encoded as the manual describes: runs of up to 63 bytes, and single bytes with +/// their top two bits set written as runs of one. +fn rle(raw: &[u8]) -> Vec { + let mut out = vec![]; + let mut i = 0; + while i < raw.len() { + let n = raw[i..].iter().take(63).take_while(|b| **b == raw[i]).count(); + if n > 1 || raw[i] >= 0xc0 { + out.extend([0xc0 | n as u8, raw[i]]); + } else { + out.push(raw[i]); + } + i += n; + } + out +} + +/// The pixels `raster_image` stores for `f`, row by row. +fn pixels(f: &[u8]) -> Vec<[u8; 4]> { + let img = raster_image(f).unwrap(); + image::load_from_memory(&img.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() +} + +/// The 16 colors of a header palette: entry `i` is (16 i, 255 − 16 i, i). +fn header_colors() -> Vec<[u8; 3]> { + (0..16u8).map(|i| [i * 16, 255 - i * 16, i]).collect() +} + +fn opaque([r, g, b]: [u8; 3]) -> [u8; 4] { + [r, g, b, 255] +} + +#[test] +fn every_depth_and_plane_layout_reads() { + let colors = header_colors(); + let (white, black) = ([255; 4], [0, 0, 0, 255]); + + // 1 bit, three pixels in a two-byte line: 101 and 010, in the header palette's first two colors + // (here inverted: white, then black). + let bits = rle(&[0b1010_0000, 0, 0b0100_0000, 0]); + let f = pcx(5, 1, 1, 0, (3, 2), 2, 0, &[[255; 3], [0; 3]], &bits); + assert_eq!(pixels(&f), [black, white, black, white, black, white]); + let f = pcx(5, 1, 1, 0, (3, 2), 2, 0, &colors, &bits); + let (zero, one) = (opaque(colors[0]), opaque(colors[1])); + assert_eq!(pixels(&f), [one, zero, one, zero, one, zero]); + // Black and white when the palette is left unset or the version has none. + for (version, palette) in [(5, &[][..]), (3, &colors[..])] { + let f = pcx(version, 1, 1, 0, (3, 2), 2, 0, palette, &bits); + assert_eq!(pixels(&f), [white, black, white, black, white, black], "version {version}"); + } + + // 1 bit in four planes: plane p gives bit p of the index; indices 5 and 10. + let planes = rle(&[0x80, 0, 0x40, 0, 0x80, 0, 0x40, 0]); + let f = pcx(5, 1, 4, 0, (2, 1), 2, 0, &colors, &planes); + assert_eq!(pixels(&f), [opaque(colors[5]), opaque(colors[10])], "the header palette"); + // Versions 0 and 3 have no palette in their header: the EGA colors. + for version in [0, 3] { + let f = pcx(version, 1, 4, 0, (2, 1), 2, 0, &colors, &planes); + assert_eq!(pixels(&f), [[0xaa, 0, 0xaa, 255], [0x55, 0xff, 0x55, 255]], "version {version}"); + } + // Two planes give four colors, three give eight: index 3 and 6 (planes 1 and 2). + let f = pcx(5, 1, 3, 0, (2, 1), 2, 0, &colors, &rle(&[0x80, 0, 0xc0, 0, 0x40, 0])); + assert_eq!(pixels(&f), [opaque(colors[3]), opaque(colors[6])]); + + // 2 bits: indices 0 to 3 in one byte, the first pixel in the top bits, in the CGA colors that + // header bytes 16 (the background, in its top four bits) and 19 (C, P and I) pick. + let cga = |background: u8, settings: u8| { + let f = pcx(5, 2, 1, 0, (4, 1), 2, 0, &[[background, 0, 0], [settings, 0, 0]], &rle(&[0b0001_1011, 0])); + pixels(&f) + }; + let (blue, cyan, magenta, light_gray) = ([0, 0, 0xaa, 255], [0, 0xaa, 0xaa, 255], [0xaa, 0, 0xaa, 255], [0xaa; 3]); + assert_eq!(cga(0x10, 0b0100_0000), [blue, cyan, magenta, opaque(light_gray)], "P = 1, dim"); + let (light_green, light_red, yellow) = ([0x55, 0xff, 0x55, 255], [0xff, 0x55, 0x55, 255], [0xff, 0xff, 0x55, 255]); + assert_eq!(cga(0x0f, 0b0011_1111), [black, light_green, light_red, yellow], "P = 0, bright; low bits ignored"); + assert_eq!(cga(0xf0, 0b1010_0000), [white, [0x55, 0xff, 0xff, 255], light_red, white], "C = 1, bright"); + assert_eq!(cga(0, 0)[1..], [[0, 0xaa, 0, 255], [0xaa, 0, 0, 255], [0xaa, 0x55, 0, 255]], "P = 0, dim"); + + // 4 bits: indices 15, 1 and 7. + let f = pcx(5, 4, 1, 0, (3, 1), 2, 0, &colors, &rle(&[0xf1, 0x70])); + assert_eq!(pixels(&f), [opaque(colors[15]), opaque(colors[1]), opaque(colors[7])]); + + // 8 bits with the 256-color palette after the image data, from a window that starts at x 10: + // entry i is (i, 255 − i, 7). + let mut f = pcx(5, 8, 1, 10, (2, 2), 2, 0, &[], &rle(&[0, 1, 254, 255])); + f.push(0x0c); + f.extend((0..=255u8).flat_map(|i| [i, 255 - i, 7])); + assert_eq!(pixels(&f), [[0, 255, 7, 255], [1, 254, 7, 255], [254, 1, 7, 255], [255, 0, 7, 255]]); + // Without it, the index is a gray level. + let f = pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &rle(&[0, 1, 254, 255])); + assert_eq!(pixels(&f), [[0, 0, 0, 255], [1, 1, 1, 255], [254, 254, 254, 255], [255; 4]]); + // A gray level 12 769 bytes before the end of image data that runs to the end of the file. + let mut levels = vec![1; 1000]; + levels[231] = 0x0c; + let f = pcx(5, 8, 1, 0, (1000, 1), 1000, 0, &[], &levels); + assert_eq!(f.len() - 769, 128 + 231); + let read = pixels(&f); + assert_eq!((read.len(), read[231], read[232]), (1000, [12, 12, 12, 255], [1, 1, 1, 255])); + // A run may cross the end of a scan line. + let f = pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &[0xc4, 9]); + assert_eq!(pixels(&f), [[9, 9, 9, 255]; 4]); + + // 24 bits: each line holds its red, green and blue planes in turn; the padding byte is skipped. + let f = pcx(5, 8, 3, 0, (1, 2), 2, 0, &[], &rle(&[10, 0, 30, 0, 50, 0, 20, 0, 40, 0, 60, 0])); + assert_eq!(pixels(&f), [[10, 30, 50, 255], [20, 40, 60, 255]]); +} + +#[test] +fn pcx_files_open_place_and_paste_at_their_resolution() { + use crate::cmd::clipboard::{PASTE_ORDER, file_flavour}; + let b64 = vectorcraft_format::base64_encode; + let f = pcx(5, 8, 3, 0, (2, 1), 2, 144, &[], &rle(&[10, 20, 30, 40, 50, 60])); + assert_eq!(ppi::resolution(&f), Some((144.0, 144.0))); + assert_eq!(ppi::resolution(&pcx(5, 8, 3, 0, (2, 1), 2, 0, &[], &[])), None, "no resolution"); + + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"name": "art.pcx", "dataBase64": b64(&f)})).unwrap(); + assert_eq!((&r["format"], &r["warnings"]), (&json!("pcx"), &json!([])), "{r}"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(1.0, 0.5), "2 × 1 px at 144 ppi"); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("file.place", &json!({"name": "ART.PCX", "dataBase64": b64(&f)})).unwrap(); + assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("pcx"), Some(1)), "{r}"); + + // Copied in a file manager, a PCX file pastes as a bitmap. + assert_eq!(file_flavour("art.pcx", &f, &PASTE_ORDER), Some("image/x-pcx")); + let r = s.execute("clipboard.importImage", &json!({"mime": "image/x-pcx", "dataBase64": b64(&f)})).unwrap(); + assert_eq!((&r["count"], &r["pixelWidth"], &r["pixelHeight"]), (&json!(1), &json!(2), &json!(1)), "{r}"); + // Glass's Load Texture… reads it too. + assert!(texture_image(&f).is_ok()); + + // The dialogs list PCX; the desktop packaging doesn't associate it; nothing writes it. + assert!(OPEN_EXTS.contains(&"pcx") && PLACE_EXTS.contains(&"pcx") && UNASSOCIATED_EXTS.contains(&"pcx")); + let filter = ("PCX", &["pcx"][..]); + assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter)); + let r = s.execute("document.formats", &json!({})).unwrap(); + let pcx_format = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pcx").unwrap().clone(); + assert_eq!((pcx_format["read"].as_bool(), pcx_format["write"].as_bool()), (Some(true), Some(false))); + assert_eq!(format_for_name("a.pcx").map(|f| f.id), Some("pcx")); +} + +#[test] +fn damaged_and_unsupported_files_are_refused_with_a_message() { + let message = |f: &[u8]| raster_image(f).err().expect("refused").to_string(); + let gray = pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &[1, 2, 3, 4]); + + // A header or image data cut short. + assert_eq!(message(&gray[..60]), "the PCX file is cut short"); + assert_eq!(message(&gray[..131]), "the PCX file is cut short"); + assert_eq!(message(&pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &[1, 0xc2])), "the PCX file is cut short", "a run without its byte"); + // The palette after the image data isn't read as pixels the image data lacks. + let mut short = pcx(5, 8, 1, 0, (2, 2), 2, 0, &[], &[1, 2, 3]); + short.push(0x0c); + short.extend([7; 768]); + assert_eq!(message(&short), "the PCX file is cut short", "three pixels and a palette"); + // A palette marker after the image data with fewer than 768 colors after it. + let mut cut_palette = gray.clone(); + cut_palette.push(0x0c); + cut_palette.extend([7; 767]); + assert_eq!(message(&cut_palette), "the PCX file is cut short", "a palette cut short"); + assert_eq!(message(&[&gray[..], &[0x0c]].concat()), "the PCX file is cut short", "a marker alone"); + let mut s = Session::new(); + let e = s.execute("document.open", &json!({"name": "a.pcx", "dataBase64": vectorcraft_format::base64_encode(&gray[..131])})); + assert!(e.expect_err("refused").to_string().contains("the PCX file is cut short")); + + // Planes and depths the manual doesn't define. + assert_eq!(message(&pcx(5, 8, 2, 0, (2, 2), 2, 0, &[], &[])), "PCX files with 8-bit pixels in 2 planes can't be read"); + assert_eq!(message(&pcx(5, 4, 3, 0, (2, 2), 2, 0, &[], &[])), "PCX files with 4-bit pixels in 3 planes can't be read"); + assert_eq!(message(&pcx(5, 1, 5, 0, (2, 2), 2, 0, &[], &[])), "PCX files with 1-bit pixels in 5 planes can't be read"); + + // A window that ends before it starts, and lines too short for the width. + let mut backwards = gray.clone(); + backwards[8..10].copy_from_slice(&0u16.to_le_bytes()); + backwards[4..6].copy_from_slice(&5u16.to_le_bytes()); + assert_eq!(message(&backwards), "the PCX file's header is damaged"); + assert_eq!(message(&pcx(5, 8, 1, 0, (3, 1), 2, 0, &[], &[1, 2, 3, 4])), "the PCX file's header is damaged"); + assert_eq!(message(&pcx(5, 1, 1, 0, (17, 1), 2, 0, &[], &[0; 4])), "the PCX file's header is damaged"); + + // Past the allowance, from the header: the pixels as RGBA, and the scan lines of a narrow image + // with long lines. + let huge = pcx(5, 1, 1, 0, (0, 0), 8192, 0, &[], &[]); + assert_eq!(message(&huge), "an image of 65536 × 65536 pixels is too large to draw"); + let long = pcx(5, 8, 3, 0, (1, 0), 65535, 0, &[], &[]); + assert_eq!(message(&long), "an image of 1 × 65536 pixels is too large to draw"); + assert!(decode(&long, 1 << 20).is_err()); + + // Headers with values the manual doesn't define aren't PCX files. + assert!(is_pcx(&gray)); + for bad in [[0x0a, 1, 1, 8], [0x0a, 6, 1, 8], [0x0a, 5, 0, 8], [0x0a, 5, 1, 3], [0x0b, 5, 1, 8]] { + assert!(!is_pcx(&bad), "{bad:?}"); + } +} diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index 35d3945402..4a6f671432 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -403,3 +403,560 @@ fn ai_export_without_artboards_keeps_art_outside_the_original_pages() { assert_eq!(comparable(&s.doc().unwrap().doc), before); assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err()); } + +/// Color Halftone's Max Radius is in pixels of the raster effects resolution since document +/// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from +/// before that opens with the radius converted, drawing the same dots; one saved since opens as +/// it was. +#[test] +fn a_preserve_editing_pdf_opens_with_its_halftone_radius_in_pixels() { + let halftone = |old: bool| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap(); + let r = super::tests_svgedit::rect(&mut s, 10.0, 10.0); + s.execute("effect.apply", &json!({"effect": "pixelate.colorHalftone", "params": {"maxRadius": 8}, "ids": [r]})).unwrap(); + if old { + // As VectorCraft 0.18 wrote it: the document model's version 1, the radius in points. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).version = 1; + } + let pdf = b64(&s.execute("document.exportPdf", &json!({})).unwrap()); + let opened = open(&mut s, "halftone.pdf", &pdf); + assert_eq!(opened["restored"], json!(true), "{opened}"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.version, vectorcraft_doc::FORMAT_VERSION); + let n = d.node(vectorcraft_doc::NodeId(r)).unwrap(); + n.appearance.effects.iter().find(|e| e.id == "pixelate.colorHalftone").and_then(|e| e.params["maxRadius"].as_f64()).unwrap() + }; + // 8 pt at 300 ppi are 33⅓ px. + assert!((halftone(true) - 8.0 * 300.0 / 72.0).abs() < 1e-9, "{}", halftone(true)); + assert_eq!(halftone(false), 8.0); +} + +/// The layers of `doc` as their names and the kinds and bounds of what they hold, rounded. +fn outline(doc: &vectorcraft_doc::Document) -> Vec { + fn walk(nodes: &[std::sync::Arc], depth: usize, out: &mut Vec) { + for n in nodes { + let b = n.visual_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64)); + let kind = match &n.kind { + vectorcraft_doc::NodeKind::Layer { .. } => "layer", + vectorcraft_doc::NodeKind::Group { .. } => "group", + vectorcraft_doc::NodeKind::Path { .. } => "path", + _ => "other", + }; + out.push(format!("{depth} {kind} {:?} {} {b:?}", n.name, n.visible)); + walk(n.children().map(Vec::as_slice).unwrap_or_default(), depth + 1, out); + } + } + let mut out = vec![]; + walk(&doc.layers, 0, &mut out); + out +} + +/// A `.ai` also carries the editing copy of its art that other apps read: opened without the +/// VectorCraft document it carries, it gives back the same layers, groups and paths, its page +/// matching them. `editingData: false` leaves the copy out. +#[test] +fn ai_files_carry_an_editing_copy_for_other_apps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 60, "y": 10, "width": 50, "height": 30})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("layer.new", &json!({"name": "Top"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 120, "y": 50, "width": 60, "height": 40})).unwrap(); + let before = outline(&s.doc().unwrap().doc); + let bytes = b64(&s.execute("document.export", &json!({"format": "ai"})).unwrap()); + let private = vectorcraft_pdf::illustrator_data(&bytes, None).expect("the editing copy for other apps"); + assert!(private.starts_with(b"%AI24_ZStandard_Data")); + let opts = LoadOptions { native: false, ..Default::default() }; + let l = load::load_with("art.ai", &bytes, &opts).unwrap(); + assert!(l.editing_data && !l.restored); + assert!(!l.warnings.iter().any(|w| w.contains("editing data")), "{:?}", l.warnings); + assert_eq!(outline(&l.doc), before); + let r = s.execute("document.export", &json!({"format": "ai", "editingData": false})).unwrap(); + assert_eq!(vectorcraft_pdf::illustrator_data(&b64(&r), None), None); + assert!(s.execute("document.export", &json!({"format": "ai", "editingData": "no"})).is_err()); +} + +/// A `.ai` whose editing copy for other apps differs from the VectorCraft document it carries (the +/// copy leaves the live effect out) opens in VectorCraft from the VectorCraft document. +#[test] +fn an_ai_file_opens_from_its_vectorcraft_document_when_the_editing_copy_differs() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [id]})).unwrap(); + let r = s.execute("document.export", &json!({"format": "ai"})).unwrap(); + assert!(r["warnings"].to_string().contains("live effects"), "{r}"); + let bytes = b64(&r); + let effects = |doc: &vectorcraft_doc::Document| { + let mut out = vec![]; + doc.walk(|n| { + if matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }) { + out.push(n.appearance.effects.len()); + } + }); + out + }; + let copy = load::load_with("art.ai", &bytes, &LoadOptions { native: false, trust_editing_data: true, ..Default::default() }).unwrap(); + assert!(copy.editing_data && !copy.restored); + assert_eq!(effects(©.doc), [0]); + let opened = load::load_with("art.ai", &bytes, &LoadOptions::default()).unwrap(); + assert!(opened.restored); + assert_eq!(effects(&opened.doc), [1]); +} + +/// The layers, groups, compound paths and paths of `doc` with their names, visibility, geometric +/// bounds (rounded), transparency, clipping and opacity masks, one line each; a mask's art after +/// its object. +fn see_through_outline(doc: &vectorcraft_doc::Document) -> Vec { + use vectorcraft_doc::NodeKind; + fn walk(nodes: &[std::sync::Arc], depth: usize, out: &mut Vec) { + for n in nodes { + let kind = match &n.kind { + NodeKind::Layer { clip, .. } => format!("layer clip={clip}"), + NodeKind::Group { clip, .. } => format!("group clip={clip}"), + NodeKind::Compound { .. } => "compound".into(), + NodeKind::Path { clipping, .. } => format!("path clipping={clipping}"), + _ => "other".into(), + }; + let b = n.geometric_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64)); + let mask = n.extras().mask.clone(); + out.push(format!( + "{depth} {kind} {:?} {} {b:?} {} {:?} isolate={} {:?} shape={} mask={:?}", + n.name, + n.visible, + (n.opacity * 100.0).round(), + n.blend, + n.isolate, + n.knockout, + n.knockout_shape, + mask.as_ref().map(|m| (m.clip, m.invert, m.disabled, m.linked)) + )); + if let Some(m) = mask { + walk(std::slice::from_ref(&m.art), depth + 1, out); + } + walk(n.children().map(Vec::as_slice).unwrap_or_default(), depth + 1, out); + } + } + let mut out = vec![]; + walk(&doc.layers, 0, &mut out); + out +} + +/// A document of two artboards (the art on the first) with a compound path at 70% in Screen, a +/// clipping group at 50% in Multiply, a named group (isolated, knockout on, knockout shape) and a +/// square with an opacity mask that doesn't clip on layer `Layer 1`, and layer `Cut` (40%, +/// clipping) holding two squares. +fn see_through_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let rect = |s: &mut Session, x: f64, y: f64, w: f64, h: f64| { + id(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()) + }; + // A compound path at 70% in Screen. + let (a, b) = (rect(&mut s, 10.0, 10.0, 40.0, 40.0), rect(&mut s, 20.0, 20.0, 20.0, 20.0)); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 70, "blend": "Screen"})).unwrap(); + // A clipping group at 50% in Multiply. + let (art, clip) = (rect(&mut s, 60.0, 10.0, 60.0, 40.0), rect(&mut s, 70.0, 20.0, 30.0, 20.0)); + s.execute("select.set", &json!({"ids": [art, clip]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50, "blend": "Multiply"})).unwrap(); + // A named group, isolated, knockout on, whose opacity defines the knockout shape. + let (a, b) = (rect(&mut s, 60.0, 60.0, 30.0, 30.0), rect(&mut s, 75.0, 75.0, 30.0, 30.0)); + let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap()); + s.execute("object.setProps", &json!({"ids": [g], "name": "Knock", "opacity": 80, "isolate": true, "knockout": "on", "knockoutShape": true})) + .unwrap(); + // A square with an opacity mask that doesn't clip. + let masked = rect(&mut s, 130.0, 10.0, 40.0, 40.0); + s.execute("paint.setFill", &json!({"color": "#808080"})).unwrap(); + let mask = rect(&mut s, 140.0, 20.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [masked, mask]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({"clip": false})).unwrap(); + // A clipping layer at 40%. + let cut = id(s.execute("layer.new", &json!({"name": "Cut"})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + rect(&mut s, 10.0, 100.0, 80.0, 60.0); + rect(&mut s, 30.0, 110.0, 40.0, 40.0); + s.execute("layer.clippingMask.toggle", &json!({})).unwrap(); + s.execute("object.setProps", &json!({"ids": [cut], "opacity": 40})).unwrap(); + s +} + +/// The editing copy of `bytes` read alone, checked against its page. +fn editing_copy(bytes: &[u8]) -> vectorcraft_doc::Document { + let l = load::load_with("art.ai", bytes, &LoadOptions { native: false, ..Default::default() }).unwrap(); + assert!(l.editing_data && !l.restored, "{:?}", l.warnings); + assert!(!l.warnings.iter().any(|w| w.contains("editing data")), "{:?}", l.warnings); + l.doc +} + +/// Transparency, a compound path, a clipping group, an opacity mask and a clipping layer come back +/// from the editing copy for other apps alone, its page matching it, with every save option that +/// writes the copy; the version 7 `.ai` keeps the compound path and the clipping group. +#[test] +fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() { + let mut s = see_through_session(); + let before = (*s.doc().unwrap().doc).clone(); + // The mask's art is one path, and it reads back as that path. + let mut arts = vec![]; + before.walk(|n| arts.extend(n.extras().mask.as_ref().map(|m| matches!(m.art.kind, vectorcraft_doc::NodeKind::Path { .. })))); + assert_eq!(arts, [true]); + let want = see_through_outline(&before); + for opts in [json!({"format": "ai"}), json!({"format": "ai", "compress": false}), json!({"format": "ai", "pdfCompatible": true})] { + let bytes = b64(&s.execute("document.export", &opts).unwrap()); + assert_eq!(see_through_outline(&editing_copy(&bytes)), want, "{opts}"); + } + // Each artboard in a file of its own: the first holds all the art. + let path = tmp("see-through.ai"); + let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap(); + let files: Vec = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); + assert_eq!(files.len(), 3, "{r}"); + for f in &files { + let copy = editing_copy(&std::fs::read(f).unwrap()); + if f.ends_with("-2.ai") { + assert!(copy.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "{f} {:#?}", see_through_outline(©)); + } else { + assert_eq!(see_through_outline(©), want, "{f}"); + } + } + // Version 7 has no transparency; it keeps the compound path and the clipping group. + let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": 7})).unwrap(); + let legacy = load::load_with("art.ai", &b64(&r), &LoadOptions::default()).unwrap(); + let kinds = see_through_outline(&legacy.doc); + assert!(kinds.iter().any(|l| l.contains(" compound ")) && kinds.iter().any(|l| l.contains("group clip=true")), "{kinds:#?}"); +} + +/// The paths and compound paths of `doc`'s art and of its patterns' tiles with their geometric +/// bounds (rounded) and fills and strokes, one line each, then its gradient and pattern swatches: a +/// gradient by its kind, its swatch link (`-` when it names no gradient swatch of `doc`), its stops +/// (place, color, opacity, midpoint, swatch link and tint) and the gradient's place at the corners and +/// center of the paint's bounds (rounded to hundredths); a pattern by its name and placement. +fn paint_outline(doc: &vectorcraft_doc::Document) -> Vec { + use std::sync::Arc; + use vectorcraft_color::Paint; + use vectorcraft_doc::{AppearanceItem, Node, NodeKind}; + let link = |name: &Option| match name.as_deref().and_then(|n| doc.swatch(n)) { + Some(sw) if matches!(sw.paint, Paint::Gradient(_)) => sw.name.clone(), + _ => "-".into(), + }; + let drawn = |p: &Paint, b: vectorcraft_geom::Rect| match p { + Paint::Gradient(g) => { + let geom = g.resolve(b); + let at: Vec = [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1), (b.center().x, b.center().y)] + .map(|(x, y)| (geom.param_at(g.gradient.kind, (x, y).into()) * 100.0).round() / 100.0) + .to_vec(); + let stops: Vec = g + .gradient + .stops + .iter() + .map(|s| { + let rgb = s.color.to_rgb().map(|v| (v * 100.0).round()); + format!("{:.3} {rgb:?} {:.2} mid {:.2} {:?} {:.2}", s.offset, s.opacity, s.midpoint, s.swatch, s.tint) + }) + .collect(); + format!("{:?} link {} {stops:?} {at:?}", g.gradient.kind, link(&g.swatch)) + } + Paint::Pattern { pattern, xf } => format!("pattern {pattern} {:?}", xf.as_coeffs().map(|v| (v * 1000.0).round() / 1000.0)), + Paint::Solid { color, .. } => format!("{:?}", color.to_rgb().map(|v| (v * 100.0).round())), + Paint::None => "none".into(), + }; + // A compound path's paint is its own: its members' paint isn't drawn (Release gives them the + // compound path's), so a compound path's line lists only its members' bounds. + fn walk(nodes: &[Arc], f: &mut dyn FnMut(&Node)) { + for n in nodes { + f(n); + if !matches!(n.kind, NodeKind::Compound { .. }) { + walk(n.children().map(Vec::as_slice).unwrap_or_default(), f); + } + } + } + let bounds = |n: &Node| n.geometric_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64)); + let lines = |nodes: &[Arc]| { + let mut lines = vec![]; + walk(nodes, &mut |n| { + if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { + return; + } + let Some(b) = n.geometric_bounds() else { return }; + let kind = match n.children() { + Some(members) => format!("compound of {:?}", members.iter().map(|m| bounds(m)).collect::>()), + None => "path".into(), + }; + let mut line = format!("{kind} {:?}", [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64)); + for it in n.appearance.items.iter().filter(|i| !i.paint().is_none()) { + line += &match it { + AppearanceItem::Fill(f) => format!(" fill {}", drawn(&f.paint, b)), + AppearanceItem::Stroke(st) => format!(" stroke {} {}", st.width, drawn(&st.paint, st.paint_bounds(b))), + }; + } + lines.push(line); + }); + lines + }; + let mut out = lines(&doc.layers); + for p in doc.patterns.iter() { + out.push(format!("pattern {} tile {:?}", p.name, [p.tile.x0, p.tile.y0, p.tile.x1, p.tile.y1])); + out.extend(lines(&p.art)); + } + for sw in doc.swatches_iter() { + match &sw.paint { + // A gradient swatch reads back linked to itself. + Paint::Gradient(g) => { + let own = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g.gradient.clone()))); + out.push(format!("swatch {} {}", sw.name, drawn(&own, vectorcraft_geom::Rect::ZERO))); + } + Paint::Pattern { pattern, .. } => out.push(format!("swatch {} pattern {pattern}", sw.name)), + _ => {} + } + } + out +} + +/// The images of `doc`'s art, one line each: its pixel size, where its corners land (rounded to +/// hundredths), its link's path and relative path, and its pixels (RGBA). +fn image_outline(doc: &vectorcraft_doc::Document) -> Vec { + use vectorcraft_doc::NodeKind; + let mut out = vec![]; + doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + let r = vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)); + let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x0, r.y1)].map(|(x, y)| { + let p = im.xf * vectorcraft_geom::Point::new(x, y); + ((p.x * 100.0).round() / 100.0, (p.y * 100.0).round() / 100.0) + }); + let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone())); + let pixels = doc.image_blob(im).and_then(|b| image::load_from_memory(&b.bytes).ok()).map(|i| i.to_rgba8().into_raw()); + out.push(format!("{}x{} {corners:?} {link:?} {pixels:?}", im.width, im.height)); + } + }); + out +} + +/// An embedded image (RGBA, part of it see-through, turned) and a linked one come back from the +/// editing copy for other apps alone, pixel for pixel, with every save option that writes the copy; +/// the linked image keeps its path and its path relative to the document's folder. +#[test] +fn images_come_back_from_the_editing_copy() { + let dir = tmp("ai-images"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(format!("{dir}/art")).unwrap(); + let png = |w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 4]| { + let mut out = vec![]; + image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + }; + let linked = format!("{dir}/art/linked.png"); + std::fs::write(&linked, png(5, 4, &|x, y| [(x * 50) as u8, (y * 60) as u8, 90, 255])).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + let data = vectorcraft_format::base64_encode(&png(6, 3, &|x, y| [200, (x * 40) as u8, (y * 80) as u8, if x < 2 { 100 } else { 255 }])); + s.execute("file.place", &json!({"name": "embedded.png", "dataBase64": data})).unwrap(); + // The placed image is selected. + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + s.execute("file.place", &json!({"path": linked, "link": true})).unwrap(); + let path = format!("{dir}/images.ai"); + s.execute("document.save", &json!({"path": path})).unwrap(); + let before = image_outline(&s.doc().unwrap().doc); + assert_eq!(before.len(), 2, "{before:#?}"); + assert!(before[1].contains("art/linked.png"), "{before:#?}"); + for opts in [ + json!({"format": "ai"}), + json!({"format": "ai", "compress": false}), + json!({"format": "ai", "embedProfiles": false}), + json!({"format": "ai", "includeLinked": true}), + json!({"format": "ai", "range": "all"}), + json!({"format": "ai", "pdfCompatible": false}), + ] { + let r = s.execute("document.export", &opts).unwrap(); + assert!(!r["warnings"].to_string().contains("image"), "{r}"); + let copy = load::load_with(&path, &b64(&r), &LoadOptions { native: false, ..Default::default() }).unwrap(); + assert!(copy.editing_data && !copy.restored, "{opts} {:?}", copy.warnings); + assert!(!copy.warnings.iter().any(|w| w.contains("editing data")), "{opts} {:?}", copy.warnings); + assert_eq!(image_outline(©.doc), before, "{opts}"); + } +} + +/// The type of `doc`'s art, one line each: its kind, point type's matrix or area type's frame on the +/// document (rounded to hundredths), its characters, and each run's font, size and fill. +fn type_outline(doc: &vectorcraft_doc::Document) -> Vec { + use vectorcraft_doc::{NodeKind, TextKind}; + let mut out = vec![]; + let round = |v: f64| (v * 100.0).round() / 100.0 + 0.0; + doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + let (kind, xf) = match &t.kind { + TextKind::Point => ("point", t.xf.as_coeffs().map(round).to_vec()), + TextKind::Area { frame } => { + let b = frame.transformed(t.xf).bounds().unwrap(); + ("area", vec![round(b.x0), round(b.y0), round(b.x1), round(b.y1)]) + } + TextKind::OnPath { .. } => ("path", vec![]), + }; + let runs: Vec = t + .runs + .iter() + .map(|r| format!("{:?} {} {} {} {:?}", r.text, r.style.font_family, r.style.font_style, round(r.style.size), r.style.fill)) + .collect(); + out.push(format!("{kind} {xf:?} {runs:?}")); + } + }); + out +} + +/// Point type of two paragraphs, turned point type and area type come back from the editing copy +/// for other apps alone as type, with every save option that writes the copy. +#[test] +fn type_comes_back_from_the_editing_copy() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Hello\nWorld", "size": 24})).unwrap(); + s.execute("text.create", &json!({"x": 150, "y": 100, "text": "Turned"})).unwrap(); + // The new type is selected. + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + s.execute("text.create", &json!({"x": 20, "y": 120, "text": "Area type in a frame", "area": {"width": 120, "height": 60}})).unwrap(); + let path = tmp("type.ai"); + s.execute("document.save", &json!({"path": path})).unwrap(); + let before = type_outline(&s.doc().unwrap().doc); + assert_eq!(before.len(), 3, "{before:#?}"); + for opts in [ + json!({"format": "ai"}), + json!({"format": "ai", "compress": false}), + json!({"format": "ai", "embedProfiles": false}), + json!({"format": "ai", "includeLinked": true}), + json!({"format": "ai", "range": "all"}), + json!({"format": "ai", "pdfCompatible": false}), + ] { + let r = s.execute("document.export", &opts).unwrap(); + assert!(!r["warnings"].to_string().contains("type"), "{opts} {}", r["warnings"]); + let copy = load::load_with(&path, &b64(&r), &LoadOptions { native: false, ..Default::default() }).unwrap(); + assert!(copy.editing_data && !copy.restored, "{opts} {:?}", copy.warnings); + assert!(!copy.warnings.iter().any(|w| w.contains("editing data")), "{opts} {:?}", copy.warnings); + assert_eq!(type_outline(©.doc), before, "{opts}"); + } +} + +/// A document of two artboards (the art on the first): a rectangle filled with a linear gradient of +/// three stops placed across part of it, an ellipse filled with an elliptical radial gradient whose +/// focal point is off its center, a rectangle stroked with a gradient, rectangles filled and +/// stroked with the pattern `Dots`, one of them turned, an even-odd compound path filled with a +/// gradient of a gray, a CMYK color and the spot color `Ink` at 70%, and the gradient swatch `Dawn`. +fn gradient_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let rect = |s: &mut Session, x: f64, y: f64, w: f64, h: f64| { + id(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()) + }; + let three = json!({"kind": "linear", "stops": [ + {"offset": 0, "color": "#ff0000", "midpoint": 0.3}, + {"offset": 0.4, "color": "#00ff00", "opacity": 0.5}, + {"offset": 1, "color": "#0000ff"} + ], "start": [20, 40], "end": [60, 17]}); + let a = rect(&mut s, 10.0, 10.0, 80.0, 40.0); + s.execute("paint.setFill", &json!({"ids": [a], "gradient": three})).unwrap(); + let e = id(s.execute("shape.ellipse", &json!({"x": 100, "y": 10, "width": 80, "height": 40})).unwrap()); + let glow = json!({"kind": "radial", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#1a33cc"}], + "start": [140, 30], "end": [180, 30], "aspect": 50, "focal": [150, 25]}); + s.execute("paint.setFill", &json!({"ids": [e], "gradient": glow})).unwrap(); + let c = rect(&mut s, 190.0, 10.0, 90.0, 40.0); + let two = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#000000"}]}); + s.execute("paint.setStroke", &json!({"ids": [c], "gradient": two, "width": 6})).unwrap(); + let tile = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [tile], "color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [tile], "none": true})).unwrap(); + s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap(); + let p = rect(&mut s, 10.0, 70.0, 80.0, 40.0); + s.execute("paint.setFill", &json!({"ids": [p], "swatch": "Dots"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [p], "swatch": "Dots", "width": 4})).unwrap(); + let turned = rect(&mut s, 100.0, 70.0, 80.0, 40.0); + s.execute("paint.setFill", &json!({"ids": [turned], "swatch": "Dots"})).unwrap(); + // Turned 30° and scaled to half about (140, 90). + let (c, k) = (30f64.to_radians().cos() * 0.5, 30f64.to_radians().sin() * 0.5); + let m = [c, k, -k, c, 140.0 - 140.0 * c + 90.0 * k, 90.0 - 140.0 * k - 90.0 * c]; + s.execute("pattern.transform", &json!({"ids": [turned], "matrix": m})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff9900", "spot": true})).unwrap(); + let outer = rect(&mut s, 190.0, 70.0, 90.0, 40.0); + let hole = rect(&mut s, 210.0, 80.0, 40.0, 20.0); + let ring = id(s.execute("object.compoundPath.make", &json!({"ids": [outer, hole]})).unwrap()); + let mixed = json!({"kind": "linear", "stops": [ + {"offset": 0, "color": {"gray": 0.8}}, + {"offset": 0.5, "color": {"c": 1, "m": 0, "y": 0, "k": 0}, "midpoint": 0.7}, + {"offset": 1, "swatch": "Ink", "tint": 70} + ]}); + s.execute("paint.setFill", &json!({"ids": [ring], "gradient": mixed})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [ring], "none": true})).unwrap(); + let dawn = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ffcc00"}, {"offset": 1, "color": "#cc3300"}]}); + s.execute("swatch.new", &json!({"name": "Dawn", "gradient": dawn})).unwrap(); + s +} + +/// Gradients and patterns come back from the editing copy for other apps alone (the native +/// document left out), with every save option that writes the copy; where the file has PDF pages, +/// the reader takes the copy only when it draws as its page does. The version 7 `.ai` keeps each +/// gradient. +#[test] +fn gradients_and_patterns_come_back_from_the_editing_copy() { + let mut s = gradient_session(); + let before = (*s.doc().unwrap().doc).clone(); + let want = paint_outline(&before); + assert!(want.iter().filter(|l| l.starts_with("path") && l.contains("pattern Dots")).count() == 2, "{want:#?}"); + assert!(want.iter().any(|l| l.starts_with("compound") && l.contains("Ink") && l.contains(") 0.70")), "{want:#?}"); + assert!(want.iter().any(|l| l.contains("mid 0.30")) && want.iter().any(|l| l.starts_with("swatch Dawn")), "{want:#?}"); + for opts in [ + json!({"format": "ai"}), + json!({"format": "ai", "compress": false}), + json!({"format": "ai", "embedProfiles": false}), + json!({"format": "ai", "includeLinked": true}), + json!({"format": "ai", "range": "all"}), + json!({"format": "ai", "pdfCompatible": false}), + ] { + let r = s.execute("document.export", &opts).unwrap(); + assert!(!r["warnings"].to_string().contains("gradient") && !r["warnings"].to_string().contains("pattern"), "{r}"); + let copy = editing_copy(&b64(&r)); + assert_eq!(paint_outline(©), want, "{opts}"); + } + let path = tmp("gradients.ai"); + let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap(); + let files: Vec = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); + assert_eq!(files.len(), 3, "{r}"); + for f in files.iter().filter(|f| !f.ends_with("-2.ai")) { + assert_eq!(paint_outline(&editing_copy(&std::fs::read(f).unwrap())), want, "{f}"); + } + let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": 7})).unwrap(); + let legacy = load::load_with("art.ai", &b64(&r), &LoadOptions::default()).unwrap(); + // Each gradient the art paints with, by its kind and its stops' places, and its stops' colors + // within 5% (version 7 writes a gradient stroke as its filled outline, so the objects differ), + // except a spot color's tint, which version 7 writes through its CMYK equivalent: 70% of that + // equivalent displays about 7% off the tint of the spot color. + let gradients = |doc: &vectorcraft_doc::Document| { + let mut all = std::collections::BTreeMap::new(); + doc.walk(|node| { + for it in node.appearance.items.iter() { + if let vectorcraft_color::Paint::Gradient(g) = it.paint() { + let places: Vec = g.gradient.stops.iter().map(|s| format!("{:.3}", s.offset)).collect(); + let colors: Vec<([f32; 3], bool)> = + g.gradient.stops.iter().map(|s| (s.color.to_rgb(), s.swatch.is_some() && s.tint < 1.0)).collect(); + all.insert(format!("{:?} {places:?}", g.gradient.kind), colors); + } + } + }); + all + }; + let (got, want) = (gradients(&legacy.doc), gradients(&before)); + assert_eq!(got.keys().collect::>(), want.keys().collect::>()); + for (key, stops) in &want { + for (i, (rgb, spot)) in stops.iter().enumerate() { + let back = got[key][i].0; + let most = if *spot { 0.1 } else { 0.05 }; + assert!((0..3).all(|c| (back[c] - rgb[c]).abs() < most), "{key} stop {i}: {back:?} for {rgb:?}"); + } + } +} diff --git a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs index 862f3f0bed..86cb84cfcb 100644 --- a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs +++ b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs @@ -141,6 +141,8 @@ fn load_options_read_text_and_layers() { assert!(o.is_partial(), "without its hidden layers, Save doesn't write the file back"); let d = LoadOptions::default(); assert_eq!((d.text_as, d.layers, d.is_partial()), (TextAs::Text, true, false)); + let n = LoadOptions { native: false, ..Default::default() }; + assert!(n.is_partial(), "without the document it carries, Save doesn't write the file back"); } #[test] diff --git a/crates/engine/src/cmd/fileio/tests_pdfimport.rs b/crates/engine/src/cmd/fileio/tests_pdfimport.rs index f270c87b82..5ae8bd6409 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfimport.rs @@ -147,6 +147,76 @@ fn load_options_read_pages_crop_and_password() { assert_eq!(LoadOptions::from_params("x", &Value::Null).unwrap(), LoadOptions::default()); } +/// `cropTo` (and `crop`), `password`, `colorMode` and `textAs` given as anything but a string are an +/// error naming the param: `document.open` opens nothing and `file.place` places nothing and records +/// no undo step. Null is the same as leaving the param out. +#[test] +fn pdf_options_of_the_wrong_type_are_refused() { + let bytes = three_pages(); + let wrong = [ + ("cropTo", json!(5)), + ("crop", json!(true)), + ("password", json!(123)), + ("colorMode", json!(5)), + ("textAs", json!(true)), + ("textAs", json!(["outlines"])), + ]; + let one = |key: &str, v: &Value| { + let mut p = json!({}); + p[key] = v.clone(); + p + }; + let mut s = Session::new(); + for (key, v) in &wrong { + let e = open(&mut s, &bytes, one(key, v)).unwrap_err().to_string(); + assert!(e.contains(&format!("`{key}` must be a string")), "{key}: {e}"); + assert!(s.active().is_none(), "{key}: nothing opened"); + } + // A wrong `cropTo` is refused even when `crop` is a box, and a wrong `crop` when `cropTo` is. + let e = open(&mut s, &bytes, json!({"cropTo": 2, "crop": "art"})).unwrap_err().to_string(); + assert!(e.contains("`cropTo` must be a string"), "{e}"); + let e = open(&mut s, &bytes, json!({"cropTo": "art", "crop": 2})).unwrap_err().to_string(); + assert!(e.contains("`crop` must be a string"), "{e}"); + assert!(s.active().is_none(), "nothing opened"); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + let nodes = s.doc().unwrap().doc.node_count(); + for (key, v) in &wrong { + let mut p = json!({"name": "pages.pdf", "dataBase64": b64(&bytes)}); + p[*key] = v.clone(); + let e = s.execute("file.place", &p).unwrap_err().to_string(); + assert!(e.contains(&format!("`{key}` must be a string")), "{key}: {e}"); + assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.node_count()), (undo, nodes), "{key}: nothing placed"); + } + // Null is left out; valid strings read as before. + let nulls = json!({"cropTo": null, "crop": null, "password": null, "colorMode": null, "textAs": null}); + assert_eq!(LoadOptions::from_params("x", &nulls).unwrap(), LoadOptions::default()); + let o = LoadOptions::from_params("x", &json!({"cropTo": null, "crop": "Bleed", "colorMode": "CMYK", "textAs": "outlines"})).unwrap(); + assert_eq!( + (o.crop, o.color_mode, o.text_as), + (vectorcraft_pdf::CropTo::Bleed, Some(vectorcraft_doc::ColorMode::Cmyk), vectorcraft_pdf::TextAs::Outlines) + ); +} + +/// `document.pdfInfo`'s `thumbnailSize` given as anything but a number is an error, with or without +/// a `thumbnail`; null is 160 px. +#[test] +fn pdf_info_refuses_a_thumbnail_size_that_is_not_a_number() { + let bytes = three_pages(); + let mut s = Session::new(); + for v in [json!("100"), json!(true)] { + for p in [json!({"dataBase64": b64(&bytes), "thumbnail": 1, "thumbnailSize": v}), json!({"dataBase64": b64(&bytes), "thumbnailSize": v})] { + let e = s.execute("document.pdfInfo", &p).unwrap_err().to_string(); + assert!(e.contains("`thumbnailSize` must be a number"), "{v}: {e}"); + } + } + let e = s.execute("document.pdfInfo", &json!({"dataBase64": b64(&bytes), "colorMode": 1})).unwrap_err().to_string(); + assert!(e.contains("`colorMode` must be a string"), "{e}"); + let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(&bytes), "thumbnail": 1, "thumbnailSize": null})).unwrap(); + let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap(); + assert_eq!(image::load_from_memory(&png).unwrap().width(), 160); +} + #[test] fn a_postscript_ai_file_says_it_cannot_be_opened_yet() { // PostScript opens through the EPS reader now (tests_epsimport.rs): a program it can't read, diff --git a/crates/engine/src/cmd/fileio/tests_pdfx.rs b/crates/engine/src/cmd/fileio/tests_pdfx.rs index f8c3e0c59f..abd1bbe4a3 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfx.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfx.rs @@ -90,6 +90,55 @@ fn choosing_a_pdfx_standard_sets_its_version_and_turns_off_what_it_forbids() { } } +/// A PDF/X file without the bleed the document sets exports as asked and warns; the presets and +/// options that take the document's bleed, and files that aren't PDF/X files, don't warn. +#[test] +fn a_pdfx_file_that_leaves_out_the_document_bleed_warns() { + let left_out = |w: &Vec| w.iter().any(|w| w == super::pdf::BLEED_LEFT_OUT); + let mut s = session(); + s.execute("document.setup", &json!({"bleed": 6})).unwrap(); + for standard in ["pdfX1a", "pdfX3", "pdfX4"] { + let (_, warnings) = pdf(&mut s, json!({"standard": standard})); + // First: the status bar shows the first warning, and PDF/X-1a and PDF/X-3 add the flattening note. + assert_eq!(warnings.first().map(String::as_str), Some(super::pdf::BLEED_LEFT_OUT), "{standard}: {warnings:?}"); + // The page has no bleed, as asked. + let v = s.execute("document.exportPdf", &json!({"standard": standard})).unwrap(); + let info = s.execute("document.pdfInfo", &json!({"name": "x.pdf", "dataBase64": v["dataBase64"]})).unwrap(); + let boxes = &info["pageInfo"][0]["boxes"]; + assert!(boxes["media"].is_array() && boxes["media"] == boxes["trim"] && boxes["media"] == boxes["bleed"], "{standard}: {info}"); + } + let v = s.execute("document.export", &json!({"format": "pdf", "standard": "pdfX4"})).unwrap(); + assert!(v["warnings"].as_array().unwrap().iter().any(|w| w == super::pdf::BLEED_LEFT_OUT), "{v}"); + // A side the settings leave out warns, and sides they all keep don't. + let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"top": 6, "bottom": 6, "left": 6}})); + assert!(left_out(&warnings), "{warnings:?}"); + for p in [ + json!({"preset": "PDF/X-1a:2001"}), + json!({"preset": "PDF/X-3:2002"}), + json!({"preset": "PDF/X-4:2010"}), + json!({"standard": "pdfX4", "bleed": {"useDocument": true}}), + json!({"standard": "pdfX4", "bleed": {"top": 1, "bottom": 1, "left": 1, "right": 1}}), + json!({}), + json!({"standard": "pdfA2b"}), + ] { + let (_, warnings) = pdf(&mut s, p.clone()); + assert!(!left_out(&warnings), "{p}: {warnings:?}"); + } + // The dialog's Summary exports in memory, so it lists the warning too. + let v = s.execute("document.pdfSettings", &json!({"standard": "pdfX4", "includeDocument": true})).unwrap(); + assert!(v["warnings"].as_array().unwrap().iter().any(|w| w == super::pdf::BLEED_LEFT_OUT), "{v}"); + // A bleed on the top alone: only that side counts. + s.execute("document.setup", &json!({"bleed": [6, 0, 0, 0]})).unwrap(); + let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"top": 1}})); + assert!(!left_out(&warnings), "{warnings:?}"); + let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"bottom": 1}})); + assert!(left_out(&warnings), "{warnings:?}"); + // A document without a bleed has nothing to leave out. + s.execute("document.setup", &json!({"bleed": 0})).unwrap(); + let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4"})); + assert!(!left_out(&warnings), "{warnings:?}"); +} + /// The ink amounts (0..1) `doc` shows at `p` in its images (the topmost image there). fn image_inks_at(doc: &vectorcraft_doc::Document, p: vectorcraft_geom::Point) -> Option<[f32; 4]> { fn visit(n: &vectorcraft_doc::Node, out: &mut Vec) { diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 76ac9cee41..d411496b02 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -213,6 +213,28 @@ fn psd_exports_open_and_place_again() { assert!(PLACE_EXTS.contains(&"psd") && PLACE_EXTS.contains(&"psb") && OPEN_EXTS.contains(&"psb")); } +/// Photoshop files named `.pdd` open and place as PSD, in any case; the dialogs and a drop on the +/// window take them by their extension, and the desktop packaging doesn't associate them. +#[test] +fn pdd_files_open_and_place() { + let mut s = art(); + let f = exported(&mut s, json!({"format": "psd"})); + for name in ["art.pdd", "ART.PDD"] { + assert_eq!(readable_format_for_name(name).map(|f| f.id), Some("psd"), "{name}"); + let r = s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&f)})).unwrap(); + assert_eq!((&r["format"], &r["warnings"]), (&json!("psd"), &json!([])), "{name}: {r}"); + assert!((s.doc().unwrap().doc.artboards[0].rect.width() - 60.0).abs() < 1e-6, "{name}"); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + let r = s.execute("file.place", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&f)})).unwrap(); + assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("psd"), Some(1)), "{name}: {r}"); + } + assert!(OPEN_EXTS.contains(&"pdd") && PLACE_EXTS.contains(&"pdd") && UNASSOCIATED_EXTS.contains(&"pdd")); + let photoshop = ("PSD", &["psd", "pdd"][..]); + assert!(open_filters().any(|f| f == photoshop) && place_filters().any(|f| f == photoshop)); + assert!(!export_extensions().contains(&"pdd"), "exports still name their files .psd"); + assert!(format_for_name("x.pdd").is_none() && writable_format(None, Some("x.pdd")).is_err(), "an export to .pdd is refused as before"); +} + #[test] fn damaged_and_unsupported_files_are_refused_without_a_panic() { let good = psd(2, 4, (3, 2), 8, 3, &[], &[], &layer_count(-1, true), &raw(&[&[1; 6], &[2; 6], &[3; 6], &[4; 6]])); diff --git a/crates/engine/src/cmd/fileio/tests_pxrread.rs b/crates/engine/src/cmd/fileio/tests_pxrread.rs new file mode 100644 index 0000000000..f9e89e38f1 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_pxrread.rs @@ -0,0 +1,377 @@ +//! Reading Pixar picture files: every channel set, storage mode, packet kind and alpha mode +//! decodes to the pixels it stores, tiled pictures assemble with their border and null tiles, the +//! files open, place and paste, and damaged files are refused with a message. + +use serde_json::json; + +use super::pxrread::{decode, is_pxr}; +use super::*; + +/// The header fields a test sets: the picture's (width, height), the tile's (width, height), the +/// channel bits (R 8, G 4, B 2, A 1), the storage mode, the blocking factor and the alpha mode. +#[derive(Clone, Copy)] +struct Head { + size: (u16, u16), + tile: (u16, u16), + format: u16, + storage: u16, + block: u16, + alpha: u16, +} + +/// A one-tile picture of `w` × `h` pixels. +fn head(w: u16, h: u16, format: u16, storage: u16) -> Head { + Head { size: (w, h), tile: (w, h), format, storage, block: 0, alpha: 1 } +} + +/// A Pixar picture file of `version` with header `h`, whose tiles' data `tiles` (`None` for a +/// null tile) follow one another from byte `start` (at least the end of the tile pointer table). +fn pxr(version: u16, h: Head, start: usize, tiles: &[Option>]) -> Vec { + let mut f = vec![0x80, 0xe8, 0, 0]; + f.extend(version.to_le_bytes()); + f.extend(b"a test picture"); + f.resize(416, 0); + for v in [h.size.1, h.size.0, h.tile.1, h.tile.0, h.format, h.storage, h.block, h.alpha, 7, 9] { + f.extend(v.to_le_bytes()); + } + f.resize(512, 0); + let mut at = start; + let mut data: Vec = vec![]; + for tile in tiles { + match tile { + Some(bytes) => { + f.extend((at as u32).to_le_bytes()); + f.extend((bytes.len() as i32).to_le_bytes()); + data.extend(bytes); + at += bytes.len(); + } + None => f.extend([0; 8]), + } + } + assert!(f.len() <= start, "the tile data starts inside the table"); + f.resize(start, 0); + f.extend(data); + f +} + +/// A one-tile picture whose tile data follows the table. +fn one(h: Head, data: &[u8]) -> Vec { + pxr(0, h, 520, &[Some(data.to_vec())]) +} + +/// A packet header: `kind` in the top four bits, `count` less one in the low twelve. +fn packet(kind: u16, count: u16) -> [u8; 2] { + ((kind << 12) | (count - 1)).to_le_bytes() +} + +/// 12-bit samples, two bytes each. +fn wide(samples: &[u16]) -> Vec { + samples.iter().flat_map(|s| s.to_le_bytes()).collect() +} + +/// The pixels `raster_image` stores for `f`, row by row. +fn pixels(f: &[u8]) -> Vec<[u8; 4]> { + let img = raster_image(f).unwrap(); + image::load_from_memory(&img.blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect() +} + +const RGBA: u16 = 15; +const RGB: u16 = 14; +const R: u16 = 8; + +#[test] +fn every_channel_set_and_dumped_storage_reads() { + // 8 bits dumped, RGBA unassociated: the samples as they are. + let f = one(head(2, 1, RGBA, 2), &[10, 20, 30, 40, 50, 60, 70, 255]); + assert_eq!(pixels(&f), [[10, 20, 30, 40], [50, 60, 70, 255]]); + // RGB is opaque; R alone is gray; G and B alone leave the other colors at 0. + assert_eq!(pixels(&one(head(2, 1, RGB, 2), &[1, 2, 3, 4, 5, 6])), [[1, 2, 3, 255], [4, 5, 6, 255]]); + assert_eq!(pixels(&one(head(3, 1, R, 2), &[0, 128, 255])), [[0, 0, 0, 255], [128, 128, 128, 255], [255; 4]]); + assert_eq!(pixels(&one(head(1, 1, 0b0110, 2), &[9, 8])), [[0, 9, 8, 255]]); + // A alone: black at the stored coverage. + assert_eq!(pixels(&one(head(1, 1, 1, 2), &[77])), [[0, 0, 0, 77]]); + + // 12 bits dumped: 0 is black, 2048 white, 1024 half (127.5, rounded up); values past 1.0 + // (2049 to 3071) are white and values below 0.0 (3072 to 4095) black; the top four bits of + // each pair aren't part of the sample. + let f = one(head(2, 1, RGB, 3), &wide(&[0, 1024, 2048, 3000, 3072, 0xf800])); + assert_eq!(pixels(&f), [[0, 128, 255, 255], [255, 0, 255, 255]]); + let f = one(head(1, 1, R, 3), &wide(&[512])); + assert_eq!(pixels(&f), [[64, 64, 64, 255]], "512 of 2048 is 63.75 of 255"); +} + +#[test] +fn alpha_matted_to_black_becomes_straight_color() { + // Alpha mode 0: color is multiplied by A. 50 and 100 at A 128 are 99.6 and 199.2 straight; + // color past its A is white; A 0 is transparent black. + let mut h = head(3, 1, RGBA, 2); + h.alpha = 0; + let f = one(h, &[50, 100, 0, 128, 200, 0, 0, 100, 30, 30, 30, 0]); + assert_eq!(pixels(&f), [[100, 199, 0, 128], [255, 0, 0, 100], [0, 0, 0, 0]]); + // Alpha mode 1 keeps the color as it is. + h.alpha = 1; + let f = one(h, &[50, 100, 0, 128, 200, 0, 0, 100, 30, 30, 30, 0]); + assert_eq!(pixels(&f), [[50, 100, 0, 128], [200, 0, 0, 100], [30, 30, 30, 0]]); + // Without A, the alpha mode changes nothing. + let mut h = head(1, 1, RGB, 2); + h.alpha = 0; + assert_eq!(pixels(&one(h, &[50, 100, 0])), [[50, 100, 0, 255]]); +} + +#[test] +fn every_packet_kind_decodes() { + // Kind 1 dumps two full pixels; kind 2 holds one run of two pixels (length byte 1). + let mut data = packet(1, 2).to_vec(); + data.extend([1, 2, 3, 4, 5, 6, 7, 8]); + data.extend(packet(2, 1)); + data.extend([1, 9, 10, 11, 12]); + assert_eq!(pixels(&one(head(4, 1, RGBA, 0), &data)), [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [9, 10, 11, 12]]); + + // Kind 3 dumps one pixel's RGB after A 200; kind 4 holds runs of one and two pixels after A 100. + let mut data = packet(3, 1).to_vec(); + data.extend([200, 1, 2, 3]); + data.extend(packet(4, 2)); + data.extend([100, 0, 4, 5, 6, 1, 7, 8, 9]); + assert_eq!(pixels(&one(head(4, 1, RGBA, 0), &data)), [[1, 2, 3, 200], [4, 5, 6, 100], [7, 8, 9, 100], [7, 8, 9, 100]]); + + // Kind 2 in a gray picture: three runs over five pixels. + let mut data = packet(2, 3).to_vec(); + data.extend([0, 10, 2, 20, 0, 30]); + assert_eq!( + pixels(&one(head(5, 1, R, 0), &data)), + [[10, 10, 10, 255], [20, 20, 20, 255], [20, 20, 20, 255], [20, 20, 20, 255], [30, 30, 30, 255]] + ); + + // 12 bits encoded: samples take two bytes; run lengths and the packet header don't change. + let mut data = packet(1, 1).to_vec(); + data.extend(wide(&[2048, 1024, 0])); + data.extend(packet(2, 1)); + data.push(0); + data.extend(wide(&[0, 0, 2048])); + assert_eq!(pixels(&one(head(2, 1, RGB, 1), &data)), [[255, 128, 0, 255], [0, 0, 255, 255]]); + let mut data = packet(3, 1).to_vec(); + data.extend(wide(&[1024, 2048, 0, 0])); + assert_eq!(pixels(&one(head(1, 1, RGBA, 1), &data)), [[255, 0, 0, 128]]); + + // Several rows, one packet each, and a block end: with a blocking factor of 16, kind 0 sends + // reading to byte 32 of the file, where the second row starts. Packets of both rows mix kinds. + let mut h = head(2, 2, RGB, 0); + h.block = 16; + let mut data = packet(1, 2).to_vec(); + data.extend([1, 1, 1, 2, 2, 2]); + data.extend(packet(0, 1)); + data.resize(16, 0); + data.extend(packet(2, 1)); + data.extend([1, 3, 3, 3]); + let f = pxr(0, h, 528, &[Some(data)]); + assert_eq!(528 % 16, 0); + assert_eq!(pixels(&f), [[1, 1, 1, 255], [2, 2, 2, 255], [3, 3, 3, 255], [3, 3, 3, 255]]); +} + +#[test] +fn tiles_assemble_with_border_and_null_tiles() { + // A 3 × 3 picture in 2 × 2 tiles: two across and two down, numbered across. The border tiles' + // pixels past the picture are stored and dropped. Tile 2 (bottom left) is null: black, since + // the picture has no A. + let mut h = head(3, 3, R, 2); + h.tile = (2, 2); + let tiles = [Some(vec![1, 2, 4, 5]), Some(vec![3, 99, 6, 99]), None, Some(vec![9, 99, 99, 99])]; + let f = pxr(0, h, 600, &tiles); + let gray = |v: u8| [v, v, v, 255]; + assert_eq!(pixels(&f), [gray(1), gray(2), gray(3), gray(4), gray(5), gray(6), gray(0), gray(0), gray(9)]); + + // With A, a null tile is transparent. + let mut h = head(2, 1, RGBA, 2); + h.tile = (1, 1); + let f = pxr(0, h, 600, &[None, Some(vec![1, 2, 3, 4])]); + assert_eq!(pixels(&f), [[0, 0, 0, 0], [1, 2, 3, 4]]); + + // A picture smaller than its tile is one border tile: a 1 × 1 picture in a 2 × 2 tile keeps its + // one pixel, dumped and encoded. + let mut h = head(1, 1, RGB, 2); + h.tile = (2, 2); + assert_eq!(pixels(&one(h, &[1, 2, 3, 99, 99, 99, 99, 99, 99, 99, 99, 99])), [[1, 2, 3, 255]]); + h.storage = 0; + let mut data = packet(2, 1).to_vec(); + data.extend([1, 4, 5, 6]); + data.extend(packet(2, 1)); + data.extend([1, 99, 99, 99]); + assert_eq!(pixels(&one(h, &data)), [[4, 5, 6, 255]]); + + // Tile data may lie anywhere after the table, in any order, and a length of 0 is read like any + // other complete tile. + let mut f = pxr(0, head(1, 1, RGB, 2), 1000, &[Some(vec![7, 8, 9])]); + f[516..520].copy_from_slice(&0i32.to_le_bytes()); + assert_eq!(pixels(&f), [[7, 8, 9, 255]]); +} + +#[test] +fn version_2_headers_read_like_version_0() { + let data = [10, 20, 30, 40]; + let (v0, v2) = (pxr(0, head(1, 1, RGBA, 2), 520, &[Some(data.to_vec())]), pxr(2, head(1, 1, RGBA, 2), 520, &[Some(data.to_vec())])); + assert_eq!(v2[4..6], [2, 0]); + assert_eq!(pixels(&v2), pixels(&v0)); +} + +#[test] +fn pxr_files_open_place_and_paste() { + use crate::cmd::clipboard::{PASTE_ORDER, file_flavour}; + let b64 = vectorcraft_format::base64_encode; + let f = one(head(2, 1, RGB, 2), &[10, 20, 30, 40, 50, 60]); + // The header has no resolution: the image takes the default for images without one. + assert_eq!(ppi::resolution(&f), None); + assert_eq!(detect("picture.dat", &f).map(|f| f.id), Some("pxr"), "by its magic number"); + + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"name": "art.pxr", "dataBase64": b64(&f)})).unwrap(); + assert_eq!((&r["format"], &r["warnings"]), (&json!("pxr"), &json!([])), "{r}"); + let size = s.doc().unwrap().doc.artboards[0].rect.size(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("file.place", &json!({"name": "ART.PXR", "dataBase64": b64(&f)})).unwrap(); + assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("pxr"), Some(1)), "{r}"); + // Placed from a path, linked and embedded: both show the file's pixels at its pixel size. + let dir = std::env::temp_dir().join(format!("vectorcraft-pxr-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("art.pxr"); + std::fs::write(&path, &f).unwrap(); + for link in [true, false] { + let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": link})).unwrap(); + assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("pxr"), Some(1)), "link {link}: {r}"); + let doc = &s.doc().unwrap().doc; + let node = doc.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + let vectorcraft_doc::NodeKind::Image(im) = &node.kind else { panic!("link {link}: an image, got {:?}", node.kind) }; + assert_eq!((im.link.is_some(), im.width, im.height), (link, 2, 1), "link {link}"); + let shown = image::load_from_memory(&doc.images[&im.key].bytes).unwrap().to_rgba8(); + assert_eq!(shown.pixels().map(|p| p.0).collect::>(), pixels(&f), "link {link}"); + } + let _ = std::fs::remove_dir_all(&dir); + // Open sizes it as a PNG of 2 × 1 pixels without a resolution. + let mut png = vec![]; + image::RgbaImage::new(2, 1).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut t = Session::new(); + t.execute("document.open", &json!({"name": "same.png", "dataBase64": b64(&png)})).unwrap(); + assert_eq!(t.doc().unwrap().doc.artboards[0].rect.size(), size); + + // Copied in a file manager, a Pixar file pastes as a bitmap. + assert_eq!(file_flavour("art.pxr", &f, &PASTE_ORDER), Some("image/x-pixar")); + let r = s.execute("clipboard.importImage", &json!({"mime": "image/x-pixar", "dataBase64": b64(&f)})).unwrap(); + assert_eq!((&r["count"], &r["pixelWidth"], &r["pixelHeight"]), (&json!(1), &json!(2), &json!(1)), "{r}"); + // Glass's Load Texture… reads it too. + assert!(texture_image(&f).is_ok()); + + // The dialogs list Pixar; the desktop packaging doesn't associate it; nothing writes it. + assert!(OPEN_EXTS.contains(&"pxr") && PLACE_EXTS.contains(&"pxr") && UNASSOCIATED_EXTS.contains(&"pxr")); + let filter = ("Pixar", &["pxr"][..]); + assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter)); + let r = s.execute("document.formats", &json!({})).unwrap(); + let pxr_format = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pxr").unwrap().clone(); + assert_eq!((pxr_format["read"].as_bool(), pxr_format["write"].as_bool()), (Some(true), Some(false))); + assert_eq!(format_for_name("a.pxr").map(|f| f.id), Some("pxr")); +} + +#[test] +fn damaged_files_are_refused_with_a_message() { + let message = |f: &[u8]| raster_image(f).err().expect("refused").to_string(); + let rgb = one(head(2, 1, RGB, 2), &[1, 2, 3, 4, 5, 6]); + let (short, header, data) = ("the Pixar file is cut short", "the Pixar file's header is damaged", "the Pixar file's image data is damaged"); + + // A header, tile table or dumped tile cut short, and a tile whose writing wasn't finished. + assert_eq!(message(&rgb[..300]), short); + assert_eq!(message(&rgb[..516]), short); + assert_eq!(message(&rgb[..rgb.len() - 1]), short); + let mut unfinished = rgb.clone(); + unfinished[516..520].copy_from_slice(&(-1i32).to_le_bytes()); + assert_eq!(message(&unfinished), short); + let mut far = rgb.clone(); + far[512..516].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(message(&far), short, "a pointer past the end of the file"); + // A refused open leaves the active document as it was. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let before = s.doc().unwrap().doc.artboards[0].rect.size(); + let e = s.execute("document.open", &json!({"name": "a.pxr", "dataBase64": vectorcraft_format::base64_encode(&rgb[..516])})); + assert!(e.expect_err("refused").to_string().contains(short)); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), before); + + // Encoded data cut short: in a packet header, a sample and a run length. + let mut cut = packet(1, 2).to_vec(); + cut.extend([1, 2, 3, 4]); + assert_eq!(message(&one(head(2, 1, RGB, 0), &cut)), short); + assert_eq!(message(&one(head(2, 1, RGB, 0), &[0x01])), short); + assert_eq!(message(&one(head(2, 1, RGB, 0), &packet(2, 1))), short); + // A block end that moves past the end of the file. + let mut h = head(1, 1, RGB, 0); + h.block = 4096; + assert_eq!(message(&one(h, &packet(0, 1))), short); + + // Header values the format doesn't define. + let with = |at: usize, v: u16| { + let mut f = rgb.clone(); + f[at..at + 2].copy_from_slice(&v.to_le_bytes()); + message(&f) + }; + for (at, v, what) in [ + (416, 0, "no height"), + (418, 0, "no width"), + (420, 0, "no tile height"), + (422, 0, "no tile width"), + (424, 0, "no channels"), + (424, 16, "a channel bit past A"), + (426, 4, "storage mode 4"), + (430, 2, "alpha mode 2"), + ] { + assert_eq!(with(at, v), header, "{what}"); + } + + // Packets the format doesn't define, packets past the end of the scan line, packets with a + // shared A in a picture without A, and a block end without a blocking factor. + let encoded = |format: u16, data: &[u8]| message(&one(head(2, 1, format, 0), data)); + assert_eq!(encoded(RGB, &[&packet(5, 1)[..], &[0; 8]].concat()), data, "kind 5"); + assert_eq!(encoded(RGB, &[&packet(1, 3)[..], &[0; 9]].concat()), data, "three pixels in a row of two"); + assert_eq!(encoded(RGB, &[&packet(2, 1)[..], &[2, 0, 0, 0]].concat()), data, "a run of three in a row of two"); + assert_eq!(encoded(RGB, &[&packet(3, 1)[..], &[0; 4]].concat()), data, "a shared A without A"); + assert_eq!(encoded(1, &[&packet(4, 1)[..], &[0; 4]].concat()), data, "a shared A without color"); + assert_eq!(encoded(RGB, &packet(0, 1)), data, "a block end without a blocking factor"); + // A block end right after another one: an empty block. + let mut h = head(2, 1, RGB, 0); + h.block = 2; + assert_eq!(message(&one(h, &[&packet(0, 1)[..], &packet(0, 1), &packet(1, 2), &[0; 6]].concat())), data, "two block ends in a row"); + // Tiles that share their encoded data read more than the file holds: a scan line of 2000 + // one-pixel packets, shown one pixel wide, is read once per tile. + let row: Vec = (0..2000).flat_map(|_| [&packet(1, 1)[..], &[5, 6, 7]].concat()).collect(); + let mut h = head(1, 1, RGB, 0); + h.tile = (2000, 1); + assert_eq!(pixels(&pxr(0, h, 520, &[Some(row.clone())])), [[5, 6, 7, 255]], "the one tile alone"); + h.size = (1, 3); + let mut shared = pxr(0, h, 600, &[Some(row.clone()), None, None]); + let first = shared[512..520].to_vec(); + shared[520..528].copy_from_slice(&first); + shared[528..536].copy_from_slice(&first); + assert_eq!(message(&shared), data, "three tiles on the same data"); + + // Past the allowance, from the header, before any tile is read. + let huge = pxr(0, head(65535, 65535, RGBA, 2), 520, &[None]); + assert_eq!(message(&huge), "an image of 65535 × 65535 pixels is too large to draw"); + assert!(decode(&rgb, 7).is_err(), "2 × 1 RGBA is 8 bytes"); + assert!(decode(&rgb, 8).is_ok()); + + // Only the magic number makes a Pixar file. + assert!(is_pxr(&rgb)); + for bad in [[0x80, 0xe8, 0, 1], [0xe8, 0x80, 0, 0], [0, 0, 0xe8, 0x80]] { + assert!(!is_pxr(&bad), "{bad:?}"); + } +} + +#[test] +fn tile_pointers_into_the_header_or_table_are_refused() { + // Tile data follows the tile pointer table, which ends at byte 520 in a one-tile picture. + let rgb = one(head(2, 1, RGB, 2), &[1, 2, 3, 4, 5, 6]); + for pointer in [4u32, 511, 512, 519] { + let mut inside = rgb.clone(); + inside[512..516].copy_from_slice(&pointer.to_le_bytes()); + let e = raster_image(&inside).err().expect("refused").to_string(); + assert_eq!(e, "the Pixar file's image data is damaged", "a pointer to byte {pointer}"); + } + // A pointer at the table's end reads. + assert_eq!(pixels(&rgb), [[1, 2, 3, 255], [4, 5, 6, 255]]); +} diff --git a/crates/engine/src/cmd/fileio/tests_raster.rs b/crates/engine/src/cmd/fileio/tests_raster.rs index 1c9b47abc4..80001476a4 100644 --- a/crates/engine/src/cmd/fileio/tests_raster.rs +++ b/crates/engine/src/cmd/fileio/tests_raster.rs @@ -32,6 +32,44 @@ fn png_chunk<'a>(file: &'a [u8], ty: &[u8; 4]) -> Option<&'a [u8]> { None } +#[test] +fn raster_export_defaults_to_document_resolution() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 72, "height": 36, "rasterEffectsPpi": 300})).unwrap(); + assert_eq!(s.doc().unwrap().doc.raster_effects_ppi, 300.0); + for format in ["png", "psd"] { + for (options, size, ppi) in [ + (json!({}), (300, 150), 300.0), + (json!({"scale": 1}), (72, 36), 72.0), + (json!({"scale": 2}), (144, 72), 144.0), + (json!({"ppi": 150, "scale": 2}), (150, 75), 150.0), + ] { + let mut params = options; + params["format"] = json!(format); + let bytes = b64(&s.execute("document.export", ¶ms).unwrap()); + assert_eq!(super::ppi::resolution(&bytes), Some((ppi, ppi)), "{params}"); + let image = super::load::raster_image(&bytes).unwrap(); + assert_eq!((image.width, image.height), size, "{params}"); + } + } +} + +#[test] +fn raster_export_default_uses_the_sanitised_document_resolution() { + // A stored resolution that isn't finite or is outside 1–2400 ppi exports at the resolution the + // document reports (72 when not finite, else clamped), not at a zero, huge or failed size. + for (stored, (width, height), size) in [(f64::NAN, (72, 36), (72, 36)), (0.0, (144, 72), (2, 1)), (1e9, (36, 18), (1200, 600))] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": width, "height": height})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).raster_effects_ppi = stored; + for format in ["png", "psd"] { + let bytes = b64(&s.execute("document.export", &json!({"format": format})).unwrap()); + let image = super::load::raster_image(&bytes).unwrap(); + assert_eq!((image.width, image.height), size, "{format} with a stored {stored} ppi"); + } + } +} + #[test] fn png_options_resolution_background_interlace_and_anti_aliasing() { let mut s = session(40.0, 30.0, 1); @@ -183,7 +221,7 @@ fn formats_list_the_raster_options() { assert!(opts("png").get(k).is_some(), "png lists {k}"); } assert_eq!(opts("png")["antiAlias"]["default"], "art"); - assert_eq!(opts("png")["ppi"]["default"], 72); + assert_eq!(opts("png")["ppi"]["default"], Value::Null); assert!(opts("jpg").get("quality").is_some() && opts("jpg").get("interlaced").is_none()); assert!(opts("webp").get("antiAlias").is_some() && opts("svg").get("antiAlias").is_none()); } @@ -282,16 +320,10 @@ fn a_raster_export_says_nothing_of_images_another_thread_could_not_decode() { #[test] fn a_raster_export_says_when_an_image_could_not_be_decoded() { - // A PNG whose header reads (so it places at its size) but whose pixel data is cut short: - // the renderer can't decode it and draws nothing, which the export must say. + // A PNG whose header reads but whose pixel data is cut short: the renderer can't decode it + // and draws nothing, which the export must say. let mut s = session(72.0, 36.0, 1); - let mut png = Vec::new(); - image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); - let cut = png_chunk(&png, b"IDAT").map(|d| d.as_ptr() as usize - png.as_ptr() as usize).unwrap() + 4; - png.truncate(cut); - s.execute("file.place", &json!({"name": "cut.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + crate::tests_menucmds::place_undecodable_png(&mut s); let r = s.execute("document.export", &json!({"format": "png", "background": "transparent"})).unwrap(); let warnings = r["warnings"].as_array().cloned().unwrap_or_default(); assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("couldn't be decoded"))), "{r}"); diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index 5da4bdf5e4..b0dcd368ec 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -148,6 +148,19 @@ fn device_names_and_trailing_periods_follow_windows_naming_rules() { assert_eq!(r["name"], "nul-.zip"); } +/// A dot in an artboard's name stays a dot (`example.artboard.png`, #6143); a name of only dots, or +/// ending in one, still can't name another folder or end in a period, a leading dot is a dash (no +/// hidden `.draft.png`), and `/` and `:` are dashes. +#[test] +fn an_artboard_name_keeps_its_dots() { + let mut s = session(7); + for (index, name) in ["example.artboard", "v1.2.final", "..", "a/b:c", "trail.", ".draft", "..x.y"].iter().enumerate() { + s.execute("artboard.setProps", &json!({"index": index, "name": name})).unwrap(); + } + let r = export(&mut s, json!({"formats": [{"format": "png"}]})); + assert_eq!(names(&r), ["example.artboard.png", "v1.2.final.png", "Artboard-3.png", "a-b-c.png", "trail.png", "-draft.png", "--x.y.png"]); +} + /// `first_file` names the file the export writes first, for the same params: the item's file name, /// a prefix and a suffix with characters Windows does not allow, a range, a Windows device name, /// every kind of folder, presets, size suffixes, a name pattern with its counter and date, an @@ -526,6 +539,20 @@ fn include_bleed_grows_each_artboard() { assert_eq!(size(&files(&r)[0].1), (40, 30), "without it, the artboard alone"); } +/// Include Bleed puts the bleed on a PDF/X row's page, so the row doesn't warn that it leaves the bleed out. +#[test] +fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() { + let mut s = session(1); + s.execute("document.setup", &json!({"bleed": 6})).unwrap(); + let warned = |r: &Value| r["warnings"].as_array().unwrap().iter().any(|w| w == super::pdf::BLEED_LEFT_OUT); + let row = json!([{"format": "pdf", "standard": "pdfX4"}]); + assert!(warned(&export(&mut s, json!({"formats": row})))); + assert!(!warned(&export(&mut s, json!({"includeBleed": true, "formats": row})))); + // A selection is written on a page of its own bounds, which Include Bleed doesn't grow. + s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + assert!(warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row})))); +} + #[test] fn png_8_rows_write_indexed_colour() { let mut s = session(1); @@ -533,13 +560,113 @@ fn png_8_rows_write_indexed_colour() { let f = files(&r); // The IHDR colour type: 3 (indexed) for PNG 8, 6 (RGBA) for PNG; both are .png, the PNG 8 row // written first. - assert_eq!(names(&r), ["Artboard-1.png"], "the same file name: the first row wins"); - assert_eq!(f[0].1[25], 3); + assert_eq!(names(&r), ["Artboard-1.png", "Artboard-1-2.png"], "the same file name: the second row's file is numbered"); + assert_eq!((f[0].1[25], f[1].1[25]), (3, 6)); let r = export(&mut s, json!({"formats": [{"format": "png8", "suffix": "-8"}, {"format": "png"}]})); let f = files(&r); assert_eq!((f[0].1[25], f[1].1[25]), (3, 6)); } +/// Without a name pattern, a row that writes a different file under a name another row's file +/// already has gets `-2`, `-3`… as a name pattern's files do, compared without case; the first +/// file keeps its name, and two identical rows still write one file. +#[test] +fn a_second_file_with_a_taken_name_is_numbered() { + let mut s = session(1); + let px = |png: &[u8]| image::load_from_memory(png).unwrap().to_rgba8().get_pixel(1, 1).0; + let rows = json!([{"format": "png", "background": "black"}, {"format": "png", "background": "white"}, {"format": "png", "background": "black"}]); + let r = export(&mut s, json!({ "formats": rows })); + assert_eq!(names(&r), ["Artboard-1.png", "Artboard-1-2.png"]); + let f = files(&r); + assert_eq!((px(&f[0].1), px(&f[1].1)), ([0, 0, 0, 255], [255, 255, 255, 255])); + // Row folders that differ only in case are one folder, spelled as the first row spells it. + let rows = json!([{"format": "png", "folder": "Print"}, {"format": "png", "folder": "print", "scale": 2, "suffix": ""}, {"format": "svg", "folder": "PRINT"}]); + let r = export(&mut s, json!({"subfolders": true, "formats": rows})); + assert_eq!(names(&r), ["Print/Artboard-1.png", "Print/Artboard-1-2.png", "Print/Artboard-1.svg"]); + assert_eq!(size(&files(&r)[1].1), (80, 60)); +} + +/// Names and folders that differ only in case match when a letter's lower case depends on where +/// it stands: Greek `ΟΣ` lower-cases to `ος`, which a case-insensitive file system treats as `οσ`. +#[test] +fn names_that_differ_only_in_greek_sigmas_are_numbered() { + let mut s = session(2); + s.execute("artboard.setProps", &json!({"index": 0, "name": "ΟΣ"})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "name": "οσ"})).unwrap(); + let r = export(&mut s, json!({"name": "", "formats": [{"format": "svg"}]})); + assert_eq!(names(&r), ["ΟΣ.svg", "οσ-2.svg"]); + let rows = json!([{"format": "png", "folder": "ΟΣ"}, {"format": "svg", "folder": "οσ"}]); + let r = export(&mut s, json!({"range": "1", "subfolders": true, "formats": rows})); + assert_eq!(names(&r), ["ΟΣ/ΟΣ.png", "ΟΣ/ΟΣ.svg"]); + // Each item still gets a folder of its own. + let r = export(&mut s, json!({"folders": "item", "formats": [{"format": "svg"}]})); + assert_eq!(names(&r), ["ΟΣ/ΟΣ.svg", "οσ-2/οσ-2.svg"]); + // Letters whose full upper case is two characters still match their other case. + s.execute("artboard.setProps", &json!({"index": 0, "name": "ᾀ"})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "name": "ᾈ"})).unwrap(); + let r = export(&mut s, json!({"name": "", "formats": [{"format": "svg"}]})); + assert_eq!(names(&r), ["ᾀ.svg", "ᾈ-2.svg"]); + // So do names whose lower case is longer than the name: `İ` lower-cases to `i̇`. + s.execute("artboard.setProps", &json!({"index": 0, "name": "İ"})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "name": "i\u{307}"})).unwrap(); + let r = export(&mut s, json!({"name": "", "formats": [{"format": "svg"}]})); + assert_eq!(names(&r), ["İ.svg", "i\u{307}-2.svg"]); +} + +/// Dotless `ı` and dotted `İ` are letters of their own, as on NTFS and in Unicode case folding +/// outside Turkic languages: names and folders spelled with them keep their own files, while `i` +/// and `I` still match. +#[test] +fn dotless_and_dotted_i_are_not_plain_i() { + let mut s = session(4); + for (index, name) in ["i", "ı", "İ", "I"].into_iter().enumerate() { + s.execute("artboard.setProps", &json!({"index": index, "name": name})).unwrap(); + } + let r = export(&mut s, json!({"name": "", "formats": [{"format": "svg"}]})); + assert_eq!(names(&r), ["i.svg", "ı.svg", "İ.svg", "I-2.svg"]); + let rows = json!([{"format": "svg", "folder": "i"}, {"format": "svg", "folder": "ı"}, {"format": "svg", "folder": "İ"}, {"format": "svg", "folder": "I"}]); + let r = export(&mut s, json!({"range": "1", "subfolders": true, "formats": rows})); + assert_eq!(names(&r), ["i/i.svg", "ı/i.svg", "İ/i.svg"]); +} + +/// A fresh folder for one test, emptied first and removed when dropped (also when an assertion +/// fails). +#[cfg(not(target_arch = "wasm32"))] +struct Folder(std::path::PathBuf); + +#[cfg(not(target_arch = "wasm32"))] +impl Folder { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("vc-screens-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + Self(dir) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The numbered file is written beside the first one, and the reply lists both paths. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_numbered_file_is_written_into_the_first_rows_folder() { + let mut s = session(1); + let tmp = Folder::new("taken"); + let dir = &tmp.0; + let folder = dir.to_string_lossy().replace('\\', "/"); + let rows = json!([{"format": "png", "folder": "Print"}, {"format": "png", "folder": "print", "background": "white"}]); + let r = export(&mut s, json!({"folder": folder, "subfolders": true, "formats": rows})); + let written: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); + assert_eq!(written, [format!("{folder}/Print/Artboard-1.png"), format!("{folder}/Print/Artboard-1-2.png")]); + let entries: Vec = std::fs::read_dir(dir.join("Print")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(entries.len(), 2, "{entries:?}"); + assert_eq!(std::fs::read_dir(dir).unwrap().count(), 1, "one sub-folder"); +} + #[test] fn format_settings_apply_to_their_rows_and_rows_win() { let mut s = session(1); @@ -811,3 +938,25 @@ fn the_document_remembers_its_export_settings() { assert!(!plain.contains("export_settings") && !plain.contains("exportSettings"), "not written when empty"); assert!(vectorcraft_format::load(plain.as_bytes()).unwrap().export_settings.is_empty()); } + +/// Export PDFs As › Single file: with several artboards, a PDF row writes them as the pages of one +/// file named after the document (raster rows still write a file per artboard); with one artboard +/// the PDF is that artboard's, as Multiple files writes it. +#[test] +fn single_file_pdfs_hold_every_chosen_artboard() { + let mut s = session(3); + let title = s.doc().unwrap().doc.title.clone(); + let rows = json!([{"format": "png", "scale": "1x"}, {"format": "pdf"}]); + let r = export(&mut s, json!({"range": "1-2", "pdfs": "single", "formats": rows})); + let got = files(&r); + let pdf: Vec<&(String, Vec)> = got.iter().filter(|(n, _)| n.ends_with(".pdf")).collect(); + assert_eq!(pdf.len(), 1, "{:?}", names(&r)); + assert_eq!(pdf[0].0, format!("{title}.pdf")); + assert_eq!(vectorcraft_pdf::import(&pdf[0].1).unwrap().artboards.len(), 2, "one page per artboard"); + assert_eq!(got.iter().filter(|(n, _)| n.ends_with(".png")).count(), 2); + let r = export(&mut s, json!({"range": "2", "pdfs": "single", "formats": [{"format": "pdf"}]})); + assert_eq!(names(&r), ["Artboard-2.pdf"]); + let r = export(&mut s, json!({"range": "1-2", "pdfs": "multiple", "formats": [{"format": "pdf"}]})); + assert_eq!(names(&r), ["Artboard-1.pdf", "Artboard-2.pdf"]); + assert!(s.execute("document.exportForScreens", &json!({"pdfs": "both", "formats": [{"format": "pdf"}]})).is_err()); +} diff --git a/crates/engine/src/cmd/fileio/tests_svg.rs b/crates/engine/src/cmd/fileio/tests_svg.rs index 3b9d793aa7..eb3989597f 100644 --- a/crates/engine/src/cmd/fileio/tests_svg.rs +++ b/crates/engine/src/cmd/fileio/tests_svg.rs @@ -50,7 +50,7 @@ fn every_option_changes_the_output() { changed(&mut s, json!({"svg": {"styling": "css"}}), &|o| o.contains("abc{}", + "abc{}", body.concat() ); survive(&svg, || vectorcraft_svg::import(&svg).ok())?; @@ -872,9 +874,15 @@ proptest! { read = Some(r.as_ref().map(|d| d.layers.iter().any(|l| l.children().is_some_and(|c| !c.is_empty()))).map_err(ToString::to_string)); r.ok() })?; + // A function written in the page's resources goes by the page's object (#4366). + let why = if function == "spaces past the cap" { + "a stream in it (object 3) would decode to more than 256 MB" + } else { + "a stream in it (object 3) has decode parameters that can't be applied" + }; match read.expect("the import ran") { Ok(art) => prop_assert!(!refused && art, "{what}: opened (its art read: {art})"), - Err(e) => prop_assert!(refused && e.contains("would decode to more than 256 MB"), "{what}: {e}"), + Err(e) => prop_assert!(refused && e.contains(why), "{what}: {e}"), } } } @@ -1140,17 +1148,59 @@ fn styles(what: &str, data: &str) -> Result<(), TestCaseError> { }) } +/// A document with type and a character and a paragraph style, saved as pretty native text: what +/// Load All Styles reads. +fn saved_text_styles() -> String { + static TEXT: std::sync::OnceLock = std::sync::OnceLock::new(); + TEXT.get_or_init(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Styled"})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Lead", "attrs": {"size": 30, "tracking": 50, "underline": true, "leading": 36}})).unwrap(); + s.execute("paraStyle.new", &json!({"name": "Centered", "attrs": {"justify": "Center", "space_after": 6, "hyphenate": true}})).unwrap(); + let options = vectorcraft_format::SaveOptions { version: 2, pretty: true, ..vectorcraft_format::SaveOptions::default() }; + let text = String::from_utf8(vectorcraft_format::save_with(&s.doc().unwrap().doc, &options).unwrap()).unwrap(); + // Undamaged, it loads both styles. + let r = rich_session().execute("textStyle.loadAll", &json!({"data": text, "name": "fuzz.vectorcraft"})).unwrap(); + assert_eq!((&r["charStyles"]["added"], &r["paraStyles"]["added"]), (&json!(["Lead"]), &json!(["Centered"]))); + text + }) + .clone() +} + +/// Native file text `data`'s styles loaded into the rich document by Load All Styles, and each +/// style it added applied to all of its type. +fn text_styles(what: &str, data: &str) -> Result<(), TestCaseError> { + survive(what, || { + let mut s = rich_session(); + let r = no_panic(s.execute("textStyle.loadAll", &json!({"data": data, "name": "fuzz.vectorcraft"}))).ok()?; + let _ = no_panic(s.execute("select.all", &json!({}))); + for (list, kind) in [("charStyles", "charStyle"), ("paraStyles", "paraStyle")] { + for name in r[list]["added"].as_array().into_iter().flatten() { + let _ = no_panic(s.execute(&format!("{kind}.apply"), &json!({"name": name}))); + } + } + Some((*s.doc().ok()?.doc).clone()) + }) +} + /// Libraries panel library file `data` imported, then each kind's first item used on the rich -/// document, moved into its first group and next to its kind's last item, the group moved and -/// deleted and the library exported (#926). +/// document, moved into its first group and next to its kind's last item, a colour and the +/// selection added into that group next to the first ones, the group moved and deleted and the +/// library exported (#926). fn libraries(what: &str, data: &str) -> Result<(), TestCaseError> { survive_library(what, "library.import", data, |s, r| { let lib = r["id"].clone(); let Ok(got) = no_panic(s.execute("library.get", &json!({"library": lib}))) else { return }; let _ = no_panic(s.execute("select.all", &json!({}))); - for (list, kind, key) in - [("graphics", "graphic", "id"), ("colors", "fillColor", "name"), ("charStyles", "charStyle", "name"), ("paraStyles", "paraStyle", "name")] - { + for (list, kind, key) in [ + ("graphics", "graphic", "id"), + ("colors", "fillColor", "name"), + ("gradients", "fillGradient", "name"), + ("patterns", "fillPattern", "name"), + ("charStyles", "charStyle", "name"), + ("paraStyles", "paraStyle", "name"), + ] { if let Some(item) = got[list].get(0) { let _ = no_panic(s.execute("library.use", &json!({"library": lib, "kind": kind, "item": item[key]}))); let to = json!({"library": lib, "kind": kind, "item": item[key], "group": got["groups"][0]["name"]}); @@ -1162,6 +1212,11 @@ fn libraries(what: &str, data: &str) -> Result<(), TestCaseError> { } } } + // Added where the panel drops it: into the first group, next to the first colour and graphic. + let group = &got["groups"][0]["name"]; + let to = json!({"library": lib, "kind": "fillColor", "color": "#123456", "group": group, "after": got["colors"][0]["name"]}); + let _ = no_panic(s.execute("library.add", &to)); + let _ = no_panic(s.execute("library.add", &json!({"library": lib, "kind": "graphic", "group": group, "before": got["graphics"][0]["id"]}))); if let Some(g) = got["groups"].get(0) { for to in [0, 1, 1_000_000] { let _ = no_panic(s.execute("library.moveGroup", &json!({"library": lib, "group": g["name"], "to": to}))); @@ -1172,8 +1227,8 @@ fn libraries(what: &str, data: &str) -> Result<(), TestCaseError> { }) } -/// A Libraries panel library of the rich document's first object (a graphic), a colour, its -/// type's character and paragraph styles and a group, exported, made once. +/// A Libraries panel library of the rich document's first object (a graphic) and its gradient, a +/// colour, a pattern, its type's character and paragraph styles and a group, exported, made once. fn saved_library() -> String { static TEXT: std::sync::OnceLock = std::sync::OnceLock::new(); TEXT.get_or_init(|| { @@ -1182,6 +1237,11 @@ fn saved_library() -> String { let first = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0; let g = s.execute("library.add", &json!({"kind": "graphic", "ids": [first]})).unwrap()["id"].clone(); s.execute("library.add", &json!({"kind": "fillColor", "color": "#336699"})).unwrap(); + s.execute("library.add", &json!({"kind": "fillGradient", "ids": [first]})).unwrap(); + s.execute("select.set", &json!({"ids": [first]})).unwrap(); + s.execute("object.pattern.make", &json!({"name": "Tiles", "width": 200, "height": 150})).unwrap(); + s.execute("object.pattern.done", &json!({})).unwrap(); + s.execute("library.add", &json!({"kind": "fillPattern", "swatch": "Tiles"})).unwrap(); s.execute("select.all", &json!({})).unwrap(); for kind in ["charStyle", "paraStyle"] { s.execute("library.add", &json!({"kind": kind})).unwrap(); @@ -1206,6 +1266,16 @@ fn flattener_presets(what: &str, data: &str) -> Result<(), TestCaseError> { }) } +fn export_presets(what: &str, data: &str) -> Result<(), TestCaseError> { + survive_library(what, "document.exportPresets.import", data, |s, r| { + if let Some(name) = r["imported"].get(0) { + let _ = no_panic(s.execute("assets.settings.set", &json!({"exportPreset": name}))); + let _ = no_panic(s.execute("document.exportPresets.export", &json!({"names": [name]}))); + let _ = no_panic(s.execute("document.exportForScreens", &json!({"exportPreset": name, "range": "1"}))); + } + }) +} + /// Swatch exchange (`.ase`) bytes loaded as a swatch library, then added to the rich document. fn swatch_exchange(what: &str, bytes: &[u8]) -> Result<(), TestCaseError> { survive(what, || { @@ -1257,11 +1327,12 @@ proptest! { #![proptest_config(config())] #[test] - fn library_garbage_never_panics(s in ".{0,300}", head in prop::sample::select(vec!["", "GIMP Palette\n","{\"format\": \"vcswatches\", ", "{\"format\": \"vcstyles\", ", "{\"format\": \"vcflattener\", ", "{\"name\": \"L\", "])) { + fn library_garbage_never_panics(s in ".{0,300}", head in prop::sample::select(vec!["", "GIMP Palette\n","{\"format\": \"vcswatches\", ", "{\"format\": \"vcstyles\", ", "{\"format\": \"vcflattener\", ", "{\"format\": \"vcexportpresets\", ", "{\"name\": \"L\", "])) { let data = format!("{head}{s}"); swatches("swatch library garbage", &data)?; styles("style library garbage", &data)?; flattener_presets("flattener preset garbage", &data)?; + export_presets("export preset garbage", &data)?; libraries("library garbage", &data)?; } @@ -1277,12 +1348,23 @@ proptest! { styles("mutated style library", &mutate_text(&text, cut, &edits))?; } + #[test] + fn mutated_text_style_files_never_panic(cut in 0usize..20_000, edits in prop::collection::vec(arb_edit(), 0..10)) { + text_styles("mutated text styles", &mutate_text(&saved_text_styles(), cut, &edits))?; + } + #[test] fn mutated_flattener_presets_never_panic(cut in 0usize..5_000, edits in prop::collection::vec(arb_edit(), 0..10)) { let text = saved("flattener.presets.export", json!({"names": ["high", "medium", "low"]})); flattener_presets("mutated flattener presets", &mutate_text(&text, cut, &edits))?; } + #[test] + fn mutated_export_presets_never_panic(cut in 0usize..5_000, edits in prop::collection::vec(arb_edit(), 0..10)) { + let text = saved("document.exportPresets.export", json!({"names": ["Logo Package", "Print-Ready PDF"]})); + export_presets("mutated export presets", &mutate_text(&text, cut, &edits))?; + } + #[test] fn mutated_libraries_never_panic(keep in 0.0f64..1.2, edits in prop::collection::vec(arb_edit(), 0..10)) { // Cut anywhere in the file (whole most of the time), the edits anywhere in it. @@ -1535,6 +1617,93 @@ fn shortcut_sets_past_the_caps_are_truncated() { } } +// ---------- action sets ---------- + +/// Action set `bytes` read with `actionSet.read`: an error, or a set within the caps. +fn action_set(bytes: &[u8]) -> Result<(), TestCaseError> { + let read = json!({"dataBase64": vectorcraft_format::base64_encode(bytes), "name": "fuzz.aia"}); + if let Ok(r) = no_panic(vectorcraft_engine::Session::new().execute("actionSet.read", &read)) { + let actions = r["actions"].as_array().cloned().unwrap_or_default(); + prop_assert!(actions.len() <= 1000); + prop_assert!(actions.iter().all(|a| a["steps"].as_array().map_or(0, Vec::len) <= 10_000)); + prop_assert!(actions.iter().map(|a| a["steps"].as_array().map_or(0, Vec::len)).sum::() <= 100_000); + prop_assert!(r["unread"].as_array().map_or(0, Vec::len) <= 1000); + } + Ok(()) +} + +/// A token of a text action set: a block or field name, a number of any size and sign, text in +/// parentheses (unclosed, nested or escaped too), bracketed or angled hexadecimal, a brace, a line +/// end, NUL or bytes that aren't UTF-8. +fn arb_aia_token() -> impl Strategy> { + prop_oneof![ + prop::sample::select(vec![ + "/action-1", + "/event-2", + "/parameter-1", + "/name", + "/internalName", + "/localizedName", + "/isOn", + "/value", + "/x", + "/version", + ]) + .prop_map(|t| t.as_bytes().to_vec()), + any::().prop_map(|n| n.to_string().into_bytes()), + Just(b"99999999999999999999999".to_vec()), + "[a-z ()\\\\]{0,12}".prop_map(|t| format!("({t})").into_bytes()), + prop::sample::select(vec!["(", ")", "\\", "[ 2 4142 ]", "[ 3 41 4", "[ 1 zz ]", "[", "]", "< 2 0a0b >", "<", ">", "2.5"]) + .prop_map(|t| t.as_bytes().to_vec()), + prop::sample::select(vec!["{", "}", "\r\n", "\r", "\n"]).prop_map(|t| t.as_bytes().to_vec()), + prop::sample::select(vec![vec![0u8], vec![0xFF, 0xFE], vec![0xC3]]), + ] +} + +proptest! { + #![proptest_config(config())] + + #[test] + fn action_set_garbage_never_panics(bytes in prop::collection::vec(any::(), 0..600), head in any::()) { + let mut data = if head { b"/version 3 ".to_vec() } else { vec![] }; + data.extend(bytes); + action_set(&data)?; + } + + #[test] + fn hostile_action_sets_never_panic(tokens in prop::collection::vec(arb_aia_token(), 0..200), sep in prop::sample::select(vec![" ", "", "\t"])) { + let mut data = b"/version 3".to_vec(); + for t in tokens { + data.extend(sep.as_bytes()); + data.extend(t); + } + action_set(&data)?; + } +} + +/// An action set past any cap (nesting, actions, steps, name length, file size) is read up to it +/// and marked truncated. +#[test] +fn action_sets_past_the_caps_are_truncated() { + let read = |text: String| vectorcraft_engine::Session::new().execute("actionSet.read", &json!({ "data": text })).unwrap(); + let deep = format!("/version 3 /action-1 {{ {} }}", "/x { ".repeat(40)); + let actions = format!("/version 3 {}", "/action-1 { } ".repeat(1001)); + let steps = format!("/version 3 /action-1 {{ {} }}", "/event-1 { } ".repeat(10_001)); + let action = format!("/action-1 {{ {} }} ", "/event-1 { } ".repeat(10_000)); + let all_steps = format!("/version 3 {}", action.repeat(11)); + let long = format!("/version 3 /name [ 2000 {} ]", "6e".repeat(2000)); + let big = format!("/version 3 /action-1 {{ }} {}", " ".repeat(8 << 20)); + let uncapped: Vec<&str> = [("deep", deep), ("actions", actions), ("steps", steps), ("long", long), ("big", big)] + .into_iter() + .filter(|(_, text)| read(text.clone())["truncated"] != true) + .map(|(name, _)| name) + .collect(); + assert!(uncapped.is_empty(), "{uncapped:?}"); + let r = read(all_steps); + assert_eq!(r["truncated"], true); + assert_eq!(r["actions"].as_array().unwrap().iter().map(|a| a["steps"].as_array().unwrap().len()).sum::(), 100_000); +} + /// A small image of each raster format Place reads, with resolution metadata where it has some. fn raster_samples() -> Vec<(&'static str, Vec)> { let img = image::RgbImage::from_pixel(5, 3, image::Rgb([200, 40, 10])); @@ -1703,8 +1872,182 @@ proptest! { } } +/// PCX files of each layout, 3 × 2 pixels at 150 dpi: 1 bit in two colors, 1 bit in four planes, +/// 2 bits with CGA palette settings, 4 bits with the header palette, 8 bits with the 256-color palette after the image data, +/// and 24 bits in three planes, with runs that cross a scan line. +fn pcx_samples() -> Vec<(&'static str, Vec)> { + let pcx = |bits: u8, planes: u8, line: u16, data: &[u8]| { + let mut f = vec![0x0a, 5, 1, bits, 0, 0, 0, 0, 2, 0, 1, 0, 150, 0, 150, 0]; + f.extend((0..48u8).map(|i| i.wrapping_mul(37))); + f.extend([0, planes]); + f.extend(line.to_le_bytes()); + f.extend(1u16.to_le_bytes()); + f.resize(128, 0); + f.extend(data); + f + }; + let mut paletted = pcx(8, 1, 4, &[0xc5, 7, 0xc1, 0xff, 1, 2]); + paletted.push(0x0c); + paletted.extend((0..=255u8).flat_map(|i| [i, 255 - i, i / 2])); + vec![ + ("a.pcx", pcx(1, 1, 2, &[0xa0, 0, 0x40, 0])), + ("b.pcx", pcx(1, 4, 2, &[0xc8, 0xe0, 0x20, 0, 0x60, 0, 0xc4, 0x80])), + ("c.pcx", pcx(2, 1, 2, &[0x1b, 0, 0xc2, 0xe4])), + ("d.pcx", pcx(4, 1, 2, &[0xf1, 0x70, 0x23, 0x40])), + ("e.pcx", paletted), + ("f.pcx", pcx(8, 3, 4, &[0xc9, 200, 0xcf, 40])), + ] +} + +proptest! { + #![proptest_config(config())] + + /// Mutated PCX files (header fields, run-length bytes and the palette after the image data) + /// never crash placing, opening or pasting them. + #[test] + fn mutated_pcx_files_place_without_panics(which in 0usize..6, cut in 0usize..960, edits in prop::collection::vec((0usize..960, any::()), 0..12)) { + let (name, mut bytes) = pcx_samples().swap_remove(which); + for (at, b) in edits { + if let Some(x) = bytes.get_mut(at) { + *x = b; + } + } + bytes.truncate(cut.max(4)); + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "thumbnail": 8}); + let _ = no_panic(s.execute("file.place.info", &p)); + let _ = no_panic(s.execute("file.place", &p)); + let _ = no_panic(s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes)}))); + let _ = no_panic(s.execute("clipboard.importImage", &json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)}))); + }); + prop_assert!(r.is_ok(), "{name}: panicked: {:?}", r.err()); + } +} + +/// Pixar picture files, 3 × 2 pixels: RGBA dumped in 8 bits, RGB dumped in 12 bits, RGBA encoded +/// with every packet kind and a block end, and gray in 2 × 1 tiles with a null tile. +fn pxr_samples() -> Vec<(&'static str, Vec)> { + let pxr = |tile: (u16, u16), format: u16, storage: u16, tiles: &[Option>]| { + let mut f = vec![0x80, 0xe8, 0, 0]; + f.resize(416, 0); + for v in [2, 3, tile.1, tile.0, format, storage, 16, 1, 0, 0] { + f.extend(u16::to_le_bytes(v)); + } + f.resize(512, 0); + let mut at = (512 + tiles.len() * 8).next_multiple_of(16); + let mut data: Vec = vec![]; + for t in tiles { + match t { + Some(bytes) => { + f.extend((at as u32).to_le_bytes()); + f.extend((bytes.len() as u32).to_le_bytes()); + data.extend(bytes); + at += bytes.len(); + } + None => f.extend([0; 8]), + } + } + f.resize((512 + tiles.len() * 8).next_multiple_of(16), 0); + f.extend(data); + f + }; + let rgba: Vec = (0..24u8).map(|i| i.wrapping_mul(41)).collect(); + let wide: Vec = (0..18u16).flat_map(|i| (i * 300).to_le_bytes()).collect(); + let mut packets = vec![0x01, 0x10, 1, 2, 3, 4, 5, 6, 7, 8, 0x00, 0x20, 0, 9, 9, 9, 9]; + packets.extend([0x00, 0x00]); + packets.resize(32, 0); + packets.extend([0x00, 0x30, 200, 1, 2, 3, 0x01, 0x40, 100, 0, 4, 5, 6, 0, 7, 8, 9]); + vec![ + ("a.pxr", pxr((3, 2), 15, 2, &[Some(rgba)])), + ("b.pxr", pxr((3, 2), 14, 3, &[Some(wide)])), + ("c.pxr", pxr((3, 2), 15, 0, &[Some(packets)])), + ("d.pxr", pxr((2, 1), 8, 2, &[Some(vec![1, 2]), Some(vec![3, 4]), None, Some(vec![5, 6])])), + ] +} + +proptest! { + #![proptest_config(config())] + + /// Mutated Pixar picture files (header fields, the tile pointer table, samples and packets) + /// never crash placing, opening or pasting them. + #[test] + fn mutated_pxr_files_place_without_panics(which in 0usize..4, cut in 0usize..640, edits in prop::collection::vec((400usize..640, any::()), 0..12)) { + let (name, mut bytes) = pxr_samples().swap_remove(which); + for (at, b) in edits { + if let Some(x) = bytes.get_mut(at) { + *x = b; + } + } + bytes.truncate(cut.max(4)); + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "thumbnail": 8}); + let _ = no_panic(s.execute("file.place.info", &p)); + let _ = no_panic(s.execute("file.place", &p)); + let _ = no_panic(s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes)}))); + let _ = no_panic(s.execute("clipboard.importImage", &json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)}))); + }); + prop_assert!(r.is_ok(), "{name}: panicked: {:?}", r.err()); + } +} + // ---------- SVG saved with hidden layers and editing data ---------- +proptest! { + #![proptest_config(config())] + + /// Mutated JP2 boxes and raw codestream markers must return errors rather than unwind. + #[test] + fn mutated_jpeg2000_files_do_not_panic(raw in any::(), cut in 0usize..300, edits in prop::collection::vec((0usize..300, any::()), 0..8)) { + let (name, mut bytes) = if raw { + ("a.j2k", include_bytes!("fixtures/jpeg2000/checker-raw.j2k").to_vec()) + } else { + ("a.jp2", include_bytes!("fixtures/jpeg2000/checker.jp2").to_vec()) + }; + for (at, byte) in edits { + if let Some(slot) = bytes.get_mut(at) { *slot = byte; } + } + bytes.truncate(cut); + let result = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + let params = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("document.open", ¶ms)); + let _ = no_panic(s.execute("file.place", ¶ms)); + }); + prop_assert!(result.is_ok(), "{name}: panicked: {:?}", result.err()); + } +} + +proptest! { + #![proptest_config(config())] + + /// Mutated HEIF boxes and HEVC data must return errors rather than unwind. + #[test] + fn mutated_heif_files_do_not_panic(which in 0usize..4, cut in 0usize..1300, edits in prop::collection::vec((0usize..1300, any::()), 0..8)) { + let mut bytes = match which { + 0 => include_bytes!("fixtures/heif/quadrants.heic").to_vec(), + 1 => include_bytes!("fixtures/heif/quadrants-alpha.heic").to_vec(), + 2 => include_bytes!("fixtures/heif/quadrants-grid.heic").to_vec(), + // Its stream's VUI gives the color description. + _ => include_bytes!("fixtures/heif/tones-p3-icc-only.heic").to_vec(), + }; + for (at, byte) in edits { + if let Some(slot) = bytes.get_mut(at) { *slot = byte; } + } + bytes.truncate(cut); + let result = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + let params = json!({"name": "a.heic", "dataBase64": vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("document.open", ¶ms)); + let _ = no_panic(s.execute("file.place", ¶ms)); + }); + prop_assert!(result.is_ok(), "a.heic: panicked: {:?}", result.err()); + } +} + /// The rich document with a hidden layer, saved as SVG with its editing data. fn saved_svg() -> String { let mut d = rich_doc(); @@ -1969,10 +2312,11 @@ proptest! { /// Hostile PostScript programs: operators in any order with any operands, opened and placed; /// as files in the legacy Illustrator format too (the creator line is what turns on its /// documented `u` … `U` groups), the groups unbalanced, deep and among clips; in a layer, which - /// the editing data reader reads from the program too. + /// the editing data reader reads from the program too, or after a setup without a layer, which + /// it reads with the art on one layer. #[test] fn eps_hostile_programs_never_panic(tokens in prop::collection::vec(arb_ps_token(), 0..60), illustrator in any::(), layers in any::()) { - let head = if illustrator { "%%Creator: Adobe Illustrator(R) 8.0\n%%EndComments\n/u {} def /U {} def" } else { "%%EndComments" }; + let head = if illustrator { "%%Creator: Adobe Illustrator(R) 8.0\n%%EndComments\n/u {} def /U {} def\n%%BeginSetup\n%%EndSetup" } else { "%%EndComments" }; let (open, close) = if layers { ("/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def\n%AI5_BeginLayer\n1 1 1 1 0 0 -1 0 0 0 Lb\n(L) Ln\n", "\nLB\n%AI5_EndLayer--") } else { @@ -2037,6 +2381,53 @@ proptest! { ); survive("TIFF-predicted EPS images", || vectorcraft_eps::import(text.as_bytes()).ok().map(|r| r.document))?; } + + /// Damaged or hostile TrueType data in a Type 42 font that a composite font shows (its table + /// directory and its glyphs), any glyph index: drawn, measured and outlined, or left out. + #[test] + fn eps_type42_glyphs_never_panic( + head in prop::collection::vec((0usize..2048, any::()), 0..12), + body in prop::collection::vec((0usize..TYPE42_FONT.len(), any::()), 0..12), + gid in 0u32..70_000, + ) { + let mut font = TYPE42_FONT.to_vec(); + for (at, b) in head.into_iter().chain(body) { + if let Some(x) = font.get_mut(at) { + *x = b; + } + } + let text = type42_composite_eps(&font, gid); + survive("damaged Type 42 glyphs", || vectorcraft_eps::import(text.as_bytes()).ok().map(|r| r.document))?; + } +} + +/// The TrueType font [`type42_composite_eps`] carries. +const TYPE42_FONT: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + +/// An EPS showing glyph `gid` of TrueType font `font` through a Type 42 font and a composite font +/// over it, and measuring and outlining it. +fn type42_composite_eps(font: &[u8], gid: u32) -> String { + let sfnts: String = font.chunks(32_000).map(|c| format!("<{}>\n", c.iter().map(|b| format!("{b:02x}")).collect::())).collect(); + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n\ + 10 dict begin /FontName /T42 def /FontType 42 def /FontMatrix [1 0 0 1 0 0] def /FontBBox [0 0 1 1] def /PaintType 0 def\n\ + /Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for Encoding 1 /c01 put\n\ + /CharStrings 2 dict def CharStrings begin /.notdef 0 def /c01 {gid} def end /sfnts [\n{sfnts}] def FontName currentdict end definefont pop\n\ + 16 dict begin /FontName /Comp def /FontType 0 def /FontMatrix [1 0 0 1 0 0] def /FMapType 2 def /Encoding [0] def\n\ + /FDepVector [/T42 findfont] def FontName currentdict end definefont pop\n\ + /Comp findfont 40 scalefont setfont 10 20 moveto (\\000\\001\\000\\001) show (\\000\\001) stringwidth pop pop\n\ + 10 60 moveto (\\000\\001) true charpath fill\nshowpage\n%%EOF\n" + ) +} + +/// [`type42_composite_eps`] as it is: the glyph draws as filled outlines, not as type. +#[test] +fn the_type42_fixture_draws_its_glyphs() { + let r = vectorcraft_eps::import(type42_composite_eps(TYPE42_FONT, 9).as_bytes()).unwrap(); + assert!(r.warnings.is_empty() && !r.preview, "{:?}", r.warnings); + let mut kinds = vec![]; + r.document.walk(|n| kinds.push(n.kind_label())); + assert!(!kinds.contains(&"Text") && kinds.iter().filter(|k| **k == "Path").count() >= 3, "{kinds:?}"); } /// An EPS with two 8 × 3 CCITT fax images that the PostScript interpreter reads, coded by hand from @@ -2522,11 +2913,12 @@ fn ascii85(data: &[u8]) -> String { const PATTERN: &str = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 6 6\n%_0 A\n%_0 Ae\n%_u\n%_0 0 m\n%_0 6 L\n%_6 6 L\n%_6 0 L\n%_n\n%_0 0 0 1 K\n%_1 J 1 w\n%_3 3 m\n%_3 3 L\n%_S\n%_U\n%_9 () XW\nE\n%AI3_EndPattern\n"; /// The swatches in editing data: process, spot (one the art doesn't use), global, a gradient that -/// isn't defined and a pattern, a colour group, and versioned content read once. -const PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\n%AI17_Begin_Content_if_version_gt:24 15\n1 1 1 1 ([Registration]) 0 Xs\n([Registration])\nPc\n\ +/// isn't defined and a pattern, a colour group, versioned content read once, and the None swatch +/// and a swatch without a name, as version 7 files write them. +const PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\nPn\nPc\n%AI17_Begin_Content_if_version_gt:24 15\n1 1 1 1 ([Registration]) 0 Xs\n([Registration])\nPc\n\ 0 0 0 1 k\n(Black)\nPc\n0.1 0.9 0.8 0 (Unused ink) 0 x\n(Unused ink)\nPc\n0 0 0 1 0 0 0 (Black global) 0 1 Xk\n(Black global)\nPc\n\ Bb\n2 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(G)\nPc\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Dots)\nPc\n\ - %AI17_Alternate_Content\n0 0 0 1 k\n(Black)\nPc\n%AI17_End_Versioned_Content\n1 (Greys) 1 Pg\n0 0 0 0.5 k\n(K50)\nPc\nPB\n%AI5_EndPalette\n"; + %AI17_Alternate_Content\n0 0 0 1 k\n(Black)\nPc\n%AI17_End_Versioned_Content\n1 (Greys) 1 Pg\n0 0 0 0.5 k\n(K50)\nPc\n0.75 g\nPc\nPB\n%AI5_EndPalette\n"; /// The editing data of a file with every sort of object the layers reader knows, and some it doesn't. fn editing_text() -> String { @@ -2543,6 +2935,19 @@ fn editing_text() -> String { square(40), "50 10 m 60 10 L 60 20 L 50 20 L h W f".into(), "Q".into(), + // Transparency: a path's, a group's state block, and an object's opacity mask. + "0 0 1 0 k\n2 0.5 0 0 1 Xy".into(), + square(86), + "0 Ae\nu".into(), + square(90), + "U\n0 0.4 1 1 1 Xy\n0 0 Xd\n6 () XW".into(), + square(94), + "%_/ArtDictionary :\n%_/Mask :\n%_X=\n%_0 g\n%_94 10 m\n%_98 10 L\n%_98 14 L\n%_f\n%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n\ + %_0 /Bool (Inverted) ,\n%_0 /Bool (Disabled) ,\n%_1 /Bool (Linked) ,\n%_; (AI9_Mask) ,\n%_;" + .into(), + // Smooth and corner anchors by the case of each segment's operator, back to the start. + "10 50 m 20 60 30 50 40 50 c 45 50 50 55 v 55 60 60 60 Y 60 50 l 50 40 30 40 10 50 C s".into(), + "70 50 m 80 50 l 80 60 L 70 60 y h S".into(), "1 Xw".into(), "u".into(), "/AI11Text :\n0 /FreeUndo ,\n;".into(), @@ -2560,6 +2965,10 @@ fn editing_text() -> String { "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceCMYK XN\n[ 4 0 0 4 10 30 ] 2 1 0 Xh\n[ 4 0 0 4 10 30 ] 0 0 2 1 2 1 8 4 1 0 0 0 4 4 0 0\n\ %%BeginData: 18\rXI\nff000000000000ff80ff\n%%EndData\nXH\n%AI5_EndRaster\nN" .into(), + // A 9 × 2 1-bit image mask (ImageMask 1) colorized by the global fill before it, in hex. + "0 0 0 1 (Black global) 0.4 0 Xk\n%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceGray XN\n[ 4 0 0 4 10 30 ] 9 2 0 Xh\n\ + [ 4 0 0 4 10 30 ] 0 0 9 2 9 2 1 1 0 0 0 1 4 4 0 0\n%%BeginData: 8\rXI\n6080ff00\n%%EndData\nXH\n%AI5_EndRaster\nN" + .into(), ] .join("\n"); let layer = |name: &str, visible: u8, body: &str| { @@ -2568,7 +2977,8 @@ fn editing_text() -> String { format!( "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n{PATTERN}{PALETTE}{}{}%%Trailer\n", layer("One", 1, &format!("{body}\n{}", layer("Sub", 1, &square(70)))), - layer("Two", 0, &square(80)) + // A layer's own state block after its last compound path. + layer("Two", 0, &format!("{}\n*u\n{}\n{}\n*U\n1 0.6 1 2 1 Xy\n0 0 Xd\n7 () XW", square(80), square(84), square(88))) ) } @@ -2576,6 +2986,39 @@ fn zstd(text: &str) -> Vec { ruzstd::encoding::compress_to_vec(text.as_bytes(), ruzstd::encoding::CompressionLevel::Fastest) } +/// A one-page `.ai` whose page's content stream has decode parameters the import refuses (#4366), +/// carrying `private` in one stream with the entries `filter`, under the key `{key}1` of its +/// `PieceInfo`; with an object stream of entries `object_stream` when they aren't empty. +fn refused_ai(private: &[u8], key: &str, filter: &str, object_stream: &str) -> Vec { + let stream = |dict: &str, data: &[u8]| [format!("<< {dict} /Length {} >>\nstream\n", data.len()).as_bytes(), data, b"\nendstream"].concat(); + let mut objects: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /PieceInfo << /Illustrator << /Private << /{key}1 5 0 R /NumBlock 1 >> >> >> >>") + .into_bytes(), + stream("/DecodeParms << /Predictor 12 /Columns 0 >>", b"0 g 10 10 20 20 re f"), + stream(filter, private), + ]; + if !object_stream.is_empty() { + objects.push(stream(object_stream, b"8 0 << >>")); + } + let mut out = b"%PDF-1.5\n".to_vec(); + let mut offsets = vec![]; + for (i, o) in objects.iter().enumerate() { + offsets.push(out.len()); + out.extend(format!("{} 0 obj\n", i + 1).bytes()); + out.extend_from_slice(o); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).bytes()); + for off in offsets { + out.extend(format!("{off:010} 00000 n \n").bytes()); + } + out.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).bytes()); + out +} + /// An EPS drawing a square whose private data holds `editing`. fn editing_eps(editing: &str) -> Vec { let lines: Vec = ascii85(&zstd(editing)).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); @@ -2596,8 +3039,9 @@ fn the_editing_fixture_reads_its_palette() { let swatches: Vec<&str> = doc.swatches.iter().map(|s| s.name.as_str()).collect(); assert_eq!(swatches, ["[None]", "Black", "Unused ink", "Black global", "Dots"]); assert!(doc.swatch("Unused ink").is_some_and(|s| s.spot && s.global)); - let groups: Vec<(&str, usize)> = doc.swatch_groups.iter().map(|g| (g.name.as_str(), g.swatches.len())).collect(); - assert_eq!(groups, [("Greys", 1)]); + let groups: Vec<(&str, Vec<&str>)> = + doc.swatch_groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|s| s.name.as_str()).collect())).collect(); + assert_eq!(groups, [("Greys", vec!["K50", "Gray K=25"])], "the swatch without a name is named by its values"); } /// The fuzzed editing data, as it is, reads its CMYK image with its ink amounts and its alpha @@ -2611,6 +3055,23 @@ fn the_editing_fixture_reads_its_cmyk_image_with_its_mask() { assert!(layers && found.contains(&(Some(vec![255, 0, 0, 0, 0, 0, 0, 255]), true)), "{found:?} {warnings:?}"); } +/// The fuzzed editing data, as it is, reads its 1-bit image mask as an image colorized with the +/// global color before it. +#[test] +fn the_editing_fixture_reads_its_image_mask_colorized() { + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&editing_text())].concat(); + let (doc, warnings, layers) = vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0); + let mut found = vec![]; + doc.visit_images(|n, im| { + if let Some(vectorcraft_color::Paint::Solid { swatch, .. }) = n.extras().colorize.as_deref() { + found.push((swatch.clone(), im.width, im.height, doc.images[&im.key].coverage().map(|c| c.2))); + } + }); + // Clear bits (black) show the color; set bits (white) are transparent. + let cover = vec![255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255]; + assert!(layers && found == [(Some("Black global".to_string()), 9, 2, Some(cover))], "{found:?} {warnings:?}"); +} + /// The text document of a story of centred type with two styles, as an editing copy keeps it. fn text_document_text() -> String { "/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 3 4 ] >> >> >> ] >> >>\n\ @@ -2651,6 +3112,54 @@ fn frames_document_text() -> String { ) } +/// The text document of vertical type (key 1 of what each frame carries at 2) as an editing copy +/// keeps it: point type in two columns with a Tate-chu-yoko run (key 35 at 3), area type and type +/// on a path. +fn vertical_document_text() -> String { + let area = "<< /0 << /0 [ 0 0 ] /1 << /0 [ 8151.5 8171.5 8151.5 8171.5 8201.5 8171.5 8201.5 8171.5 8201.5 8171.5 8201.5 8171.5 8201.5 8221.5 8201.5 8221.5 8201.5 8221.5 8201.5 8221.5 8151.5 8221.5 8151.5 8221.5 8151.5 8221.5 8151.5 8221.5 8151.5 8171.5 8151.5 8171.5 ] >> /2 << /0 1 /1 2 >> >> >>"; + let path = "<< /0 << /0 [ 0 0 ] /1 << /0 [ 8151.5 8171.5 8151.5 8171.5 8191.5 8161.5 8191.5 8171.5 8191.5 8171.5 8211.5 8181.5 8231.5 8171.5 8231.5 8171.5 ] >> /2 << /0 2 /1 2 /6 [ 0.5 2.0 ] >> >> >>"; + let point = "<< /0 << /0 [ 0 0 ] /2 << /1 2 /2 [ 1 0 0 1 3 4 ] >> >> >>"; + let run = |n: usize, own: &str| format!("<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 12.0 {own}>> >> >> /1 {n} >>"); + let story = |text: &str, frame: usize, runs: &str, layout: &str| { + format!("<< /0 << /0 ({text}) /6 << /0 [ {runs} ] >> >> /1 << /0 [ << /0 {frame} >> ] {layout}>> >>") + }; + let columns = "/2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8200.0 8180.0 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ \ + << /99 /L /6 [ << /99 /S /0 << /0 [ 0.0 0.0 ] >> >> ] >> << /99 /L /0 << /0 [ -6.0 14.4 ] >> /6 [ << /99 /S /0 << /0 [ 0.0 0.0 ] >> >> ] >> \ + ] >> ] >> ] >> ] >> ] "; + format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ {point} {area} {path} ] >> >>\n\ + /1 << /1 [ {} {} {} ] /2 << /1 12.0 /35 1 /47 0 /48 0 >> >>\n", + story("Day 12\\rnext\\r", 0, &format!("{} {} {}", run(4, ""), run(2, "/35 3 /47 -2 /48 3 "), run(6, "/35 2 ")), columns), + story("Vertical area type wraps\\r", 1, &run(25, ""), ""), + story("On a path\\r", 2, &run(10, "/35 3 "), ""), + ) +} + +/// The text objects of [`vertical_document_text`]: one per story. +const VERTICAL_OBJECTS: &str = "/AI11Text :\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n/AI11Text :\n0 /FrameIndex ,\n1 /StoryIndex ,\n;\n/AI11Text :\n0 /FrameIndex ,\n2 /StoryIndex ,\n;\n"; + +/// The fuzzed vertical fixture, as it is, reads as vertical point, area and path type, with the +/// Tate-chu-yoko run marked. +#[test] +fn the_vertical_fixture_reads_as_vertical_type() { + let l = vectorcraft_engine::cmd::fileio::load("x.eps", &text_eps_of(&vertical_document_text(), VERTICAL_OBJECTS)).unwrap(); + let mut found = vec![]; + l.doc.walk(|n| { + if let vectorcraft_doc::NodeKind::Text(t) = &n.kind { + let tcy: Vec<&str> = t.runs.iter().filter(|r| r.style.tate_chu_yoko).map(|r| r.text.as_str()).collect(); + let roman: Vec<&str> = t.runs.iter().filter(|r| r.style.standard_vertical_roman).map(|r| r.text.as_str()).collect(); + found.push((t.plain_text(), t.vertical, tcy.join("|"), roman.join("|"))); + } + }); + // Key 35 at 1 in the defaults: Standard Vertical Roman Alignment, except where a run has 3 or 2. + let want = [ + ("Day 12\nnext", true, "12", "Day "), + ("Vertical area type wraps", true, "", "Vertical area type wraps"), + ("On a path", true, "On a path", ""), + ]; + assert_eq!(found, want.map(|(a, b, c, d)| (a.to_string(), b, c.to_string(), d.to_string())), "{:?}", l.warnings); +} + /// The text objects of [`frames_document_text`]: story 0 in its two frames, story 1 in its one (a /// text object names its frame among its story's). const FRAME_OBJECTS: &str = "/AI11Text :\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n/AI11Text :\n1 /FrameIndex ,\n0 /StoryIndex ,\n;\n/AI11Text :\n0 /FrameIndex ,\n1 /StoryIndex ,\n;\n"; @@ -2698,19 +3207,200 @@ fn text_eps(document: &str) -> Vec { /// An EPS with the text `objects` on a hidden layer, their stories in `document`. fn text_eps_of(document: &str, objects: &str) -> Vec { + editing_eps(&text_editing_of(document, objects)) +} + +/// The editing data of [`text_eps_of`]. +fn text_editing_of(document: &str, objects: &str) -> String { let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); - let editing = format!( + format!( "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\ %AI5_BeginLayer\n0 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(Spare) Ln\n{objects}LB\n%AI5_EndLayer--\n\ %AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n", lines.join("\n") + ) +} + +/// Area Type Options as an area frame's data may keep them: rows, columns, gutters and the first +/// baseline, and keys besides, each with a value of any kind, in or out of range. +fn arb_area_options() -> impl Strategy { + let keys = prop::sample::select(vec!["3", "4", "5", "7", "8", "10", "13", "14"]); + let values = prop::sample::select(vec![ + "0", + "1", + "2", + "3", + "2.5", + "-3", + "1e9", + "1e400", + "NaN", + "inf", + "-inf", + "(x)", + "true", + "/Name", + "[ 1 2 ]", + "<< /0 0 /1 30 >>", + "<< /0 3 /1 NaN >>", + "<< /0 4 /1 -inf >>", + "<< /0 99 /1 1e300 >>", + "<< /0 << /0 1 >> /1 [ ] >>", + "<< /1 30 >>", + ]); + prop::collection::vec((keys, values), 0..8).prop_map(|kv| kv.iter().map(|(k, v)| format!("/{k} {v}")).collect::>().join(" ")) +} + +/// Type on a Path Options as a frame might keep them at key 11: nothing, a value that isn't a +/// dictionary, or a dictionary of codes and flags of any value or type. +fn arb_path_options() -> impl Strategy { + let keys = prop::sample::select(vec!["0", "1", "2", "3", "4", "6", "7", "18", "22"]); + let values = prop::sample::select(vec![ + "0", + "1", + "2", + "3", + "4", + "5", + "-1", + "2.5", + "1e400", + "NaN", + "inf", + "(x)", + "true", + "false", + "/Name", + "[ 1 ]", + "<< /0 1 >>", + ]); + (prop::collection::vec((keys, values), 0..6), 0usize..3).prop_map(|(kv, shape)| match shape { + 0 => format!("/11 << {} >>", kv.iter().map(|(k, v)| format!("/{k} {v}")).collect::>().join(" ")), + 1 => "/11 3".to_string(), + _ => String::new(), + }) +} + +/// A text document of `kinds.len()` stories, story `i` in frame `i` of kind `kinds[i]` (0 point type, +/// 1 area type, 2 type on a path, others a kind the reader doesn't know), with a line break inside +/// its paragraph (`\x03`) at each of `soft` (by character, wrapping, the story's end included) and +/// its paragraph runs `runs` characters long (the whole story when there are none). +fn stories_document_text(kinds: &[u8], soft: &[usize], runs: &[usize]) -> String { + let frames: Vec = kinds + .iter() + .enumerate() + .map(|(i, kind)| { + // Six rows 15 apart on the page (the canvas is y down), then the same rows again a little + // to the right. + let (x, y) = (8150.0 + (i / 6) as f64 * 5.0, 8150.0 + (i % 6) as f64 * 15.0); + match kind { + 0 => format!("<< /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 {x} {y} ] >> >> >>"), + 1 => format!( + "<< /0 << /0 [ 0 0 ] /1 << /0 [ {x} {y} {x} {y} {0} {y} {0} {y} {0} {y} {0} {y} {0} {1} {0} {1} {0} {1} {0} {1} {x} {1} {x} {1} ] >> /2 << /0 1 >> >> >>", + x + 70.0, + y + 12.0 + ), + 2 => format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {x} {y} {x} {y} {0} {y} {0} {y} ] >> /2 << /0 2 /6 [ 0 0.9 ] >> >> >>", x + 70.0), + k => format!("<< /0 << /0 [ 0 0 ] /2 << /0 {k} /2 [ 1 0 0 1 {x} {y} ] >> >> >>"), + } + }) + .collect(); + let stories: Vec = (0..kinds.len()) + .map(|i| { + let mut chars: Vec = format!("Line {i} one two\rand three\r").chars().collect(); + for at in soft { + chars.insert(at % (chars.len() + 1), '\x03'); + } + let n = chars.len(); + let text: String = chars.iter().map(|c| match c { + '\r' => "\\r".to_string(), + '\x03' => "\\003".to_string(), + c => c.to_string(), + }).collect(); + let lengths: Vec = if runs.is_empty() { vec![n] } else { runs.to_vec() }; + let paras: String = lengths + .iter() + .enumerate() + .map(|(j, len)| format!("<< /0 << /0 << /0 () /5 << /0 {} /2 2 /4 {j} >> /6 0 >> >> /1 {len} >> ", j % 3)) + .collect(); + format!( + "<< /0 << /0 ({text}) /5 << /0 [ {paras}] >> /6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /1 8.0 >> >> >> /1 {n} >> ] >> >> /1 << /0 [ << /0 {i} >> ] >> >>" + ) + }) + .collect(); + format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ {} ] >> >>\n/1 << /1 [ {} ] /2 << /1 12.0 >> >>\n", + frames.join(" "), + stories.join(" ") + ) +} + +/// An EPS whose page draws `page` (PostScript), with the text `objects` on a layer that shows and +/// the stories in `document`. +fn shown_text_eps(document: &str, objects: &str, page: &str) -> Vec { + let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + let editing = format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\ + %AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(Words) Ln\n{objects}LB\n%AI5_EndLayer--\n\ + %AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n", + lines.join("\n") ); - editing_eps(&editing) + let stream = ascii85(&zstd(&editing)); + let private: Vec = stream.as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n0 0 0 1 setcmykcolor /Helvetica findfont 8 scalefont setfont {page}\nshowpage\n%%EOF\n%AI9_PrivateDataBegin\n%AI24_DataStream\n{}\n%AI9_PrivateDataEnd\n", + private.join("\n") + ) + .into_bytes() +} + +/// The page of [`stories_document_text`]'s first story's first line, at its place. +const FIRST_LINE: &str = "8.5 91.5 moveto (Line 0 one two) show"; + +/// The text objects of `pairs` (story, frame among the story's). +fn story_objects(pairs: &[(u32, u32)]) -> String { + pairs.iter().map(|(story, frame)| format!("/AI11Text :\n{frame} /FrameIndex ,\n{story} /StoryIndex ,\n;\n")).collect() +} + +/// The fixture, as it is (point type, area type and type on a path, a line break inside each +/// paragraph), opens with its layers and every story's type from its text document. +#[test] +fn the_shown_stories_fixture_opens_with_its_layers() { + let doc = stories_document_text(&[0, 1, 2], &[4], &[]); + // Each story's first line where the page draws it: the area type's below its frame's top, the + // type on a path on its path. + let page = format!("{FIRST_LINE} 8.5 69.5 moveto (Line 1) show 8.5 61.5 moveto (Line 2) show"); + let l = vectorcraft_engine::cmd::fileio::load("x.eps", &shown_text_eps(&doc, &story_objects(&[(0, 0), (1, 0), (2, 0)]), &page)).unwrap(); + let names: Vec<_> = l.doc.layers.iter().map(|l| l.name.clone()).collect(); + assert_eq!(names, [Some("Words".to_string())], "{:?}", l.warnings); + let mut texts = vec![]; + l.doc.walk(|n| { + if let vectorcraft_doc::NodeKind::Text(t) = &n.kind { + texts.push(t.plain_text()); + } + }); + assert_eq!(texts.len(), 3, "{texts:?} {:?}", l.warnings); + assert!(texts.iter().all(|t| t.contains('\u{2028}') && t.contains('\n')), "{texts:?}"); } proptest! { #![proptest_config(config())] + /// An Illustrator EPS with text objects that show, in frames of every kind and some the reader + /// doesn't know, naming stories and frames that may not exist, with line breaks inside their + /// paragraphs and paragraph runs of any length: read as its layers, or as its page. + #[test] + fn eps_shown_stories_never_panic( + kinds in prop::collection::vec(0u8..4, 1..20), + pairs in prop::collection::vec((0u32..24, 0u32..3), 1..24), + soft in prop::collection::vec(0usize..40, 0..5), + runs in prop::collection::vec(0usize..40, 0..5), + ) { + let kinds: Vec = kinds.into_iter().map(|k| if k == 3 { 9 } else { k }).collect(); + let bytes = shown_text_eps(&stories_document_text(&kinds, &soft, &runs), &story_objects(&pairs), FIRST_LINE); + survive("EPS with shown stories", || vectorcraft_engine::cmd::fileio::load("x.eps", &bytes).ok().map(|l| l.doc))?; + } + /// An Illustrator EPS whose text document is damaged or hostile: read as its type, or without it. #[test] fn eps_text_document_never_panics(cut in 0usize..1_500, edits in prop::collection::vec((0usize..1_500, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '[', ']', '<', '>', '\\', 'e', '1'])), 0..12)) { @@ -2728,17 +3418,121 @@ proptest! { survive("mutated EPS text frames", || vectorcraft_engine::cmd::fileio::load("x.eps", &bytes).ok().map(|l| l.doc))?; } + /// The threaded area type of the same text document with hostile Area Type Options in each of its + /// frames, opened as an EPS document and as a `.ai`'s editing data. + #[test] + fn text_frames_with_hostile_area_options_never_panic(first in arb_area_options(), second in arb_area_options()) { + let text = frames_document_text().replacen("/0 1 /7 18", &format!("/0 1 {first}"), 1).replacen("/0 1 /7 18", &format!("/0 1 {second}"), 1); + let editing = text_editing_of(&text, FRAME_OBJECTS); + let bytes = editing_eps(&editing); + survive("EPS text frames with hostile area options", || vectorcraft_engine::cmd::fileio::load("x.eps", &bytes).ok().map(|l| l.doc))?; + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&editing)].concat(); + survive(".ai text frames with hostile area options", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// The type on a path of the same text document with hostile Type on a Path Options, opened as + /// an EPS document and as a `.ai`'s editing data. + #[test] + fn text_frames_with_hostile_path_options_never_panic(options in arb_path_options()) { + let text = frames_document_text().replacen("/6 [ 0.5 2.0 ]", &format!("/6 [ 0.5 2.0 ] {options}"), 1); + let editing = text_editing_of(&text, FRAME_OBJECTS); + let bytes = editing_eps(&editing); + survive("EPS text frames with hostile path options", || vectorcraft_engine::cmd::fileio::load("x.eps", &bytes).ok().map(|l| l.doc))?; + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&editing)].concat(); + survive(".ai text frames with hostile path options", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// The same for vertical type and Tate-chu-yoko runs: orientations and baseline directions of + /// any value, type or size. + #[test] + fn eps_vertical_text_never_panics(cut in 0usize..2_000, edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '[', ']', '<', '>', '\\', 'e', '1', '2', '3'])), 0..12)) { + let text = mutate_text(&vertical_document_text(), cut, &edits); + let bytes = text_eps_of(&text, VERTICAL_OBJECTS); + survive("mutated EPS vertical text", || vectorcraft_engine::cmd::fileio::load("x.eps", &bytes).ok().map(|l| l.doc))?; + } + /// An Illustrator EPS whose editing data is damaged or hostile: read as its layers, or as its page. #[test] - fn eps_editing_data_never_panics(cut in 0usize..3_000, edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', ':', ';', '[', ']', '%', 'q', 'Q', 'W', 'u', 'U', 'L', 'k', 'x'])), 0..12)) { + fn eps_editing_data_never_panics(cut in 0usize..3_000, edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', ':', ';', '[', ']', '%', 'q', 'Q', 'W', 'u', 'U', 'L', 'l', 'c', 'C', 'v', 'V', 'y', 'Y', 'k', 'x'])), 0..12)) { let text = mutate_text(&editing_text(), cut, &edits); let bytes = editing_eps(&text); survive("mutated EPS editing data", || vectorcraft_eps::import(&bytes).ok().map(|r| r.document))?; } + /// A `.ai` whose envelopes are damaged or hostile: any kind, warp style, options word, + /// Fidelity and grid size, corners out of range or repeated, the contents block cut short. + #[test] + fn ai_envelope_never_panics( + kind in prop::sample::select(vec![0i64, 1, 2, 3, 4, -1, 1 << 40]), + style in prop::sample::select(vec![0i64, 1, 8, 15, 16, -3, i64::MAX]), + word in prop::sample::select(vec![0i64, 1, 131073, 65536, 0x2_0007, 1 << 18, -1, i64::MAX]), + fidelity in prop::sample::select(vec!["50", "0", "100", "101", "-1", "1e308", "nan"]), + size in prop::sample::select(vec!["[1 1]", "[3 2]", "[0 0]", "[51 1]", "[100000 100000]", "[-1 2]", "[1e308 1]"]), + corner in prop::sample::select(vec!["10 10", "1e308 -1e308", "nan 0", "10 10 10 10", "0"]), + art_width in prop::sample::select(vec!["81", "80", "0", "-5", "1e308", "nan"]), + art_height in prop::sample::select(vec!["81", "80", "0", "-5", "1e308", "nan"]), + weight in prop::sample::select(vec!["1", "0", "1e308", "-1"]), + edit in 0i64..2, + cut in 0usize..2_000, + edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '9', '-', ' ', '\n', '(', ')', '/', ':', ';', ',', '[', ']', '%', '_', 'X', 'u', 'U'])), 0..8), + ) { + use vectorcraft_testkit::ai; + let n = |x: &str, y: &str| format!("%_[0.5 1 {x} {y} {x} {y} 1 {x} {y} 1] /N X#\n"); + let mesh = format!( + "%_/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n%_{size} /Size X#\n%_/Data X#\n%_[0 0] /P X#\n{}{}{}%_[{corner}] /N X#\n%_/E X#\n%_[0 0] /P X#\n%_/E X#\n%_/End X!\n", + n("10", "10"), + n("10", "90"), + n("90", "90") + ); + let content = format!("%_u\n%_1 0 0 1 0 0 Xa\n%_0 1 1 0 1 0 0 XA\n%_{weight} w\n%_10 10 m\n%_10 90 L\n%_90 90 L\n%_90 10 L\n%_b\n%_U\n"); + let keys = format!( + "%_{word} /Int (AIDeformOptionsKey) ,\n%_{fidelity} /Int (AIDeformFidelityKey) ,\n%_{edit} /Bool (AIDeformEditModeKey) ,\n%_{style} /Int (DeformStyle) ,\n%_0.5 /Real (DeformValue) ,\n%_1 /Bool (Rotate) ,\n%_{art_width} /Real (AIDeformArtWidthKey) ,\n%_{art_height} /Real (AIDeformArtHeightKey) ,\n" + ); + let art = format!( + "%_u\n{mesh}%_U\n%_/ArtDictionary :\n{keys}%_X=\n{content}%_X+\n%_ (AIDeformArtKey) ,\n%_{kind} /Int (AIDeformStyle) ,\n%_;\n%_\nu\n1 0 0 1 0 0 Xa\n12 12 m\n12 88 L\n88 88 L\nf\nU\n(Adobe Deform Plugin) 1 0 0 XP\n0 0 1 1 0 0 Xa\n0 0 m\n5 5 L\nf\n" + ); + let data = mutate_text(&ai::editing_data(100.0, 100.0, &ai::layer("L", &art)), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("hostile .ai envelope", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// A `.ai` whose warped type is damaged or hostile: any warp style and settings, on the object or + /// on a fill, a look that reaches far away or holds type of its own, the text cut short. + #[test] + fn ai_warped_type_never_panics( + style in prop::sample::select(vec![0i64, 1, 8, 15, 16, -3, i64::MAX]), + bend in prop::sample::select(vec!["0.5", "0", "1", "-1", "2", "1e308", "-1e308", "nan"]), + distort in prop::sample::select(vec!["0", "0.4", "-1", "1e308", "nan"]), + reach in prop::sample::select(vec!["90", "16000", "1e7", "1e308", "-1e308", "nan"]), + on_fill in any::(), + look_type in any::(), + objects in 1usize..4, + cut in 0usize..3_000, + edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['0', '9', '-', ' ', '\n', '(', ')', '/', ':', ';', ',', '[', ']', '%', '_', 'X', 'u', 'U'])), 0..8), + ) { + let basic = |name: &str, body: &str| format!("/BasicFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{body}; /Dict ;\n /Part ,\n"); + let chain = |kids: &[String]| format!("/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n{};\n /Part ,\n", kids.concat()); + let fill = basic("Fill Style Filter", "/FillStyle : 0 O\n0 1 1 0 1 0 0 Xa\n0 1 0 0 0 Xy\n0 1 Xd\n/Def ;\n (FillStyle) ,\n"); + let warp = basic("Adobe Deform", &format!("{style} /Int (DeformStyle) ,\n{bend} /Real (DeformValue) ,\n{distort} /Real (DeformHoriz) ,\n{distort} /Real (DeformVert) ,\n0 /Bool (Rotate) ,\n")); + let root = if on_fill { + let stack = format!("/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n{}{};\n /Part ,\n", chain(&[warp, fill]), basic("Conduit Filter", "")); + chain(&[stack]) + } else { + chain(&[fill, warp]) + }; + let styles = format!("%AI9_BeginArtStyles\n/KnownStyle :\n(Warped) /Name ,\n/ActiveStyle :\n{root}%AI9_EndArtStyles\n"); + let slot = if look_type { "/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n" } else { "" }; + let object = format!( + "u\n{slot}0 1 1 0 1 0 0 Xa\n10 10 m\n{reach} 10 L\n{reach} {reach} L\n10 90 L\nf\nU\n9 () XW\n%_/AI11Text :\n%_0 /FreeUndo ,\n%_0 /FrameIndex ,\n%_0 /StoryIndex ,\n%_;\n1 (Warped) XW\n" + ); + let data = mutate_text(&text_editing_of(&vertical_document_text(), &(styles + &object.repeat(objects))), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("hostile .ai warped type", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + /// A `.ai` whose editing data is damaged or hostile. #[test] - fn ai_editing_data_never_panics(cut in 0usize..3_000, edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', ':', ';', '[', ']', '%', 'q', 'Q', 'W', 'u', 'U', 'L', 'k', 'x'])), 0..12), damage in prop::collection::vec((0usize..4_000, any::()), 0..4)) { + fn ai_editing_data_never_panics(cut in 0usize..3_000, edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', ':', ';', '[', ']', '%', 'q', 'Q', 'W', 'u', 'U', 'L', 'l', 'c', 'C', 'v', 'V', 'y', 'Y', 'k', 'x'])), 0..12), damage in prop::collection::vec((0usize..4_000, any::()), 0..4)) { let text = mutate_text(&editing_text(), cut, &edits); let mut private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); for (at, b) in damage { @@ -2750,6 +3544,245 @@ proptest! { survive("mutated .ai editing data", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; } + /// The active artboard that a restored `.ai` opens on, read from damaged or hostile editing data. + #[test] + fn ai_active_artboard_never_panics(cut in 0usize..600, edits in prop::collection::vec((0usize..600, prop::sample::select(vec!['0', '9', '-', ' ', '\n', '/', ':', ';', ',', '%', '_'])), 0..12)) { + let board = |x: u32| format!("%_/Dictionary :\n%_{x} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n", x + 100); + let text = format!( + "%AI9_BeginDocumentData\n%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}%_; (ArtboardArray) ,\n%_1 /Int (CropAreaActive) ,\n%_; /Recorded ,\n%_;\n%AI9_EndDocumentData\n", + board(0), + board(150) + ); + let private = mutate_text(&text, cut, &edits).into_bytes(); + survive("hostile CropAreaActive", || { + let mut doc = Document::new(100.0, 100.0); + doc.opened_artboard = vectorcraft_eps::ai_opened_artboard(&private, &doc); + Some(doc) + })?; + } + + /// A `.ai` whose PDF part can't be read (#4366), its private data damaged or hostile, under + /// any key and filter: it opens from its editing data, or with the error of its PDF part. + #[test] + fn ai_whose_pdf_part_cant_be_read_never_panics( + cut in 0usize..3_000, + edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['0', '9', '-', ' ', '\n', '(', ')', '/', '%', 'u', 'U', 'L'])), 0..8), + junk in prop::collection::vec(any::(), 0..64), + key in prop::sample::select(vec!["AIPrivateData", "AIPDFPrivateData", "AIPrivateData2", "Other"]), + filter in prop::sample::select(vec!["", "/Filter /FlateDecode", "/Filter /Bogus", "/Filter [/FlateDecode /FlateDecode]", "/DP << /Predictor 2 >>", "/Filter 7"]), + ) { + let text = mutate_text(&editing_text(), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text), &junk].concat(); + let bytes = refused_ai(&private, key, filter, ""); + let plain = vectorcraft_engine::cmd::fileio::LoadOptions { editing_data: false, ..Default::default() }; + let page_error = vectorcraft_engine::cmd::fileio::load_with("x.ai", &bytes, &plain).err().map(|e| e.to_string()); + prop_assert!(page_error.is_some()); + let _ = catch_quiet(|| vectorcraft_pdf::illustrator_data_without_pdf_part(&bytes, None)).expect("the private data read panicked"); + let mut opened = None; + survive("a .ai whose PDF part can't be read", || { + let l = vectorcraft_engine::cmd::fileio::load("x.ai", &bytes); + opened = Some(l.as_ref().map(|l| l.editing_data).map_err(|e| e.to_string())); + l.ok().map(|l| l.doc) + })?; + match opened { + Some(Ok(editing)) => prop_assert!(editing), + Some(Err(e)) => prop_assert_eq!(Some(e), page_error), + None => {} + } + } + + /// The same file with a damaged table of objects and an object stream the reader would fail + /// on: refused, as before. + #[test] + fn ai_with_a_hostile_object_stream_is_refused(damage in prop::collection::vec((0usize..200, any::()), 0..6)) { + let private = [&b"%AI12_CompressedData"[..], &deflated(&vectorcraft_testkit::ai::sample_data())].concat(); + let mut bytes = refused_ai(&private, "AIPrivateData", "/Filter /FlateDecode", "/Type /ObjStm /N 1 /First 4 /DecodeParms << /Predictor 12 /Columns 0 >>"); + let table = bytes.windows(5).rposition(|w| w == b"xref\n").unwrap_or(0); + for (at, b) in damage { + let n = bytes.len() - table; + if let Some(x) = bytes.get_mut(table + at % n) { + *x = b; + } + } + let read = catch_quiet(|| vectorcraft_pdf::illustrator_data_without_pdf_part(&bytes, None)).expect("the private data read panicked"); + prop_assert!(read.is_none()); + let opened = catch_quiet(|| vectorcraft_engine::cmd::fileio::load("x.ai", &bytes).is_ok()).expect("the open panicked"); + prop_assert!(!opened); + } + + /// A `.ai` whose strokes have any width (0, which draws a hairline, negative, huge, not a number) on a + /// path, on a gradient-filled path that `1 BB` strokes and on type in any rendering mode, + /// damaged or hostile. + #[test] + fn ai_line_widths_never_panic( + width in prop::sample::select(vec!["0", "0.0", "-0", "-1", "1e308", "1e-308", "nan", "inf", "2"]), + render in prop::sample::select(vec!["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "4.5", "-1", "99"]), + cut in 0usize..2_000, + edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '1', '-', '.', ' ', '\n', '(', ')', 'w', 'B', 'S', 'T'])), 0..8), + ) { + use vectorcraft_testkit::ai; + let gradient = "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n<00FF>\n0\n%_0 0 0 0 1 0 0 2 1 6 50 0 Bs\n%_0 0 0 0 0 0 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let art = format!( + "0 1 1 0 1 0 0 XA\n{width} w\n10 10 m\n90 90 L\nS\n{}Bb\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\nf\n1 BB\n\ + 0 To\n1 0 0 1 10 50 0 Tp\nTP\n{render} Tr\n/_Helvetica 9 Tf\n(hi) Tx\nTO\n", + ai::rect(20.0, 20.0, 80.0, 80.0) + ); + let data = mutate_text(&ai::editing_data(100.0, 100.0, &format!("{gradient}{}", ai::layer("L", &art))), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("hostile .ai line widths", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// A `.ai` whose legacy type is set in a CJK composite font (a predefined CMap the reader + /// carries, one it reads through another, one it decodes byte by byte, a Unicode CMap, or a + /// name that only looks like one), with any bytes in its strings. + #[test] + fn ai_legacy_type_in_cjk_fonts_never_panics( + cmap in prop::sample::select(vec![ + "83pv-RKSJ-H", "90ms-RKSJ-V", "90pv-RKSJ-V", "H", "V", "EUC-H", "GBK2K-H", "CNS-EUC-V", "KSCpc-EUC-H", "KSCms-UHC-HW-V", + "78-RKSJ-H", "GB-H", "KSC-V", "HKdlb-B5-H", "GBT-H", "UniJIS-UCS2-H", "UniGB-UTF8-V", "UniKS-UTF32-H", "UniAKR-UTF16-H", + "Identity-H", "UniFoo-UTF8-H", "-H", "RKSJ", + ]), + strings in prop::collection::vec(prop::collection::vec(any::(), 0..24), 1..4), + ) { + use vectorcraft_testkit::ai; + let tx: String = strings.iter().map(|s| format!("({}) Tx\n", s.iter().map(|b| format!("\\{b:03o}")).collect::())).collect(); + let art = format!("0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n/_Test-W3-{cmap} 9 Tf\n{tx}(\\r) TX\nTO\n"); + let data = ai::editing_data(100.0, 100.0, &ai::layer("L", &art)); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("legacy type in CJK fonts", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// A `.ai` whose pattern definition (a marked tile box, a gradient placed by `Bg`'s matrix) and + /// pattern fill are damaged or hostile. + #[test] + fn ai_pattern_definitions_never_panic( + cut in 0usize..2_000, + edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '1', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', '_', 'n', 'E', 'p', 'B'])), 0..12), + ) { + use vectorcraft_testkit::ai; + let gradient = "%AI5_BeginGradient: (G)\n(G) 1 2 Bd\n[\n%_0 0 0 0 1 0 0 2 1 6 50 0 Bs\n%_0 0 0 0 0 0 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let pattern = "%AI3_BeginPattern: (P)\n(P) 0 -10 10 0\n%_0 A\n%_0 Xw\n%_0 XR\n%_0 0 m\n%_10 0 L\n%_10 -10 L\n%_0 -10 L\n%_0 0 L\n%_n\n\ + %_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_\n%_2 -2 m\n%_8 -2 L\n%_8 -8 L\n%_2 -8 L\n%_Bb\n\ + %_0.1 0.2 45 0.3 Bh\n%_1 (G) 0.1 0.2 0 1.5 3 0 0 3 0 0 1 Bg\n%_3 0 0 3 -8000 8000 Bm\n%_f\n%_0 BB\nE\n%AI3_EndPattern\n"; + let art = format!("(P) 0 0 1 1 0 0 0 0 0 [0.5 0.2 -0.2 0.5 3 -4] p\n{}f\n", ai::rect(20.0, 20.0, 80.0, 80.0)); + let data = mutate_text(&ai::editing_data(100.0, 100.0, &format!("{gradient}{pattern}{}", ai::layer("L", &art))), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("hostile .ai patterns", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// A `.ai` whose gradients and patterns have names with newlines (blank before one, several, + /// repeated, one shown like another's numbered name), used by fills and a palette, damaged or + /// hostile. + #[test] + fn ai_global_names_with_newlines_never_panic( + names in prop::collection::vec(prop::sample::select(vec!["Sky\\n1", "Sky\\n2", "Sky", "Sky 2", "\\n3", "\\n", "Sky\\n\\n1", "\\012x"]), 1..6), + cut in 0usize..3_000, + edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['\\', 'n', '(', ')', ' ', '\n', 'B', 'p', 'E', '%'])), 0..10), + ) { + use vectorcraft_testkit::ai; + let mut setup = String::new(); + let mut art = String::new(); + let mut cells = String::new(); + for name in &names { + setup.push_str(&format!( + "%AI5_BeginGradient: ({name})\n({name}) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n\ + %AI3_BeginPattern: ({name})\n({name}) 0 0 6 6\n%_0 A\n%_0 0 m\n%_0 6 L\n%_6 6 L\n%_6 0 L\n%_0 0 0 1 k\n%_f\nE\n%AI3_EndPattern\n" + )); + art.push_str(&format!("Bb\n1 ({name}) 0 0 0 50 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", ai::rect(10.0, 10.0, 40.0, 40.0))); + art.push_str(&format!("({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", ai::rect(50.0, 50.0, 90.0, 90.0))); + cells.push_str(&format!("Bb\n2 ({name}) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\nPc\n({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\nPc\n")); + } + setup.push_str(&format!("%AI5_BeginPalette\n0 0 Pb\n{cells}PB\n%AI5_EndPalette\n")); + let data = mutate_text(&ai::editing_data(100.0, 100.0, &format!("{setup}{}", ai::layer("L", &art))), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("hostile .ai global names", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// A `.ai` whose images (binary samples with an alpha channel, the operators that end a raster, + /// then a name and an opacity mask) and placed file (an empty relative folder, a preview) are + /// damaged or hostile, bytes of the samples included. + #[test] + fn ai_images_and_placed_files_never_panic( + cut in 0usize..3_000, + edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec![b'0', b'1', b'9', b' ', b'\r', b'\n', b'(', b')', b'[', b']', b'%', b'_', b'N', b'X', b'~', 0u8, 255u8])), 0..12), + ) { + use vectorcraft_testkit::ai; + let raster = "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceRGB XN\n[10 0 0 10 20 -30] 2 1 0 Xh\n[10 0 0 10 20 -30] 0 0 2 1 2 1 8 3 1 17 1 0 4 4 0 0\n%%BeginData: 10\nXI\n@@%%EndData\nXH\n\ + %AI17_Begin_Content_if_version_gt:24 17\n72 72 Xr\n%AI17_End_Versioned_Content\n%AI5_EndRaster\nN\n\ + %_/ArtDictionary :\n%_/Mask :\n%_X=\n%_0 g\n%_0 0 m\n%_5 0 l\n%_5 -5 l\n%_f\n%_X+\n%_ (Art) ,\n%_; (AI9_Mask) ,\n%_/XMLUID : (Photo) ; (AI10_ArtUID) ,\n%_;\n%_\n"; + let place = "%AI5_BeginPlace\n%%FileType: 1\n[1 0 0 -1 -8000 8000] 8000 8000 8002 8001 4 4 0\n(/tmp/p.png)`\n%%IncludeFile:/tmp/p.png\n\ + %AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n()\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n\ + %AI17_Begin_Content_if_version_gt:24 5\n%AI26_BeginPlacedObjectPreview\n2 1 8 32 17 @@\n%AI26_EndPlacedObjectPreview\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n\ + %_/ArtDictionary :\n%_2 /Int (AI11 PlacedPDFPageIndex) ,\n%_4 /Int (AI11 PlacedPDFCropTo) ,\n%_;\n%_\n"; + let text = ai::editing_data(100.0, 100.0, &ai::layer("L", &format!("{raster}{place}"))); + let samples: &[u8] = &[255, 0, 0, 0, 0, 255, 128, 0]; + let preview: &[u8] = &[255, 255, 0, 0, 0, 0, 0, 0]; + let mut data = Vec::new(); + for (i, part) in text.split("@@").enumerate() { + if i > 0 { + data.extend_from_slice(if i == 1 { samples } else { preview }); + } + data.extend_from_slice(part.as_bytes()); + } + for &(i, b) in &edits { + let n = data.len(); + if n > 0 { + data[i % n] = b; + } + } + data.truncate(cut.min(data.len())); + let private = [b"%AI24_ZStandard_Data".as_slice(), &ruzstd::encoding::compress_to_vec(data.as_slice(), ruzstd::encoding::CompressionLevel::Fastest)].concat(); + survive("hostile .ai images and placed files", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// A `.ai` whose type (point type turned, vertical type, area type, threaded area type and type + /// on a path, their stubs with the frames' paths, and the text document they name, as the `.ai` + /// writer writes them) is damaged: read from its editing data alone and beside a page. + #[test] + fn ai_text_documents_never_panic( + cut in 0usize..30_000, + edits in prop::collection::vec((0usize..30_000, prop::sample::select(vec!['0', '1', '9', ' ', '\n', '(', ')', '[', ']', '<', '>', '/', '%', '_', 'n', 'f', 'z', '~'])), 0..16), + ) { + use vectorcraft_doc::{CharStyle, Node, NodeKind, TextKind, TextObject}; + use vectorcraft_geom::{Affine, Point, Rect, shapes}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut point = TextObject::point(Point::new(10.0, 30.0), "Turned\ntype", CharStyle::default()); + point.xf *= Affine::rotate(0.4); + let mut area = TextObject::point(Point::ZERO, "Area type", CharStyle::default()); + area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(20.0, 40.0, 90.0, 90.0)) }; + area.xf = Affine::IDENTITY; + let mut on_path = TextObject::point(Point::ZERO, "On a path", CharStyle::default()); + on_path.kind = TextKind::OnPath { path: shapes::ellipse(Rect::new(100.0, 20.0, 180.0, 80.0)), start: 0.25, end: None }; + on_path.xf = Affine::IDENTITY; + let mut down = TextObject::point(Point::new(190.0, 10.0), "Down", CharStyle::default()); + down.vertical = true; + let mut down_area = area.clone(); + down_area.vertical = true; + down_area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(150.0, 40.0, 180.0, 90.0)) }; + let mut first = area.clone(); + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(20.0, 5.0, 50.0, 35.0)) }; + first.runs = vec![vectorcraft_doc::TextRun::new("A story through two frames", CharStyle::default())]; + let mut second = first.clone(); + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(60.0, 5.0, 90.0, 35.0)) }; + second.runs = vec![vectorcraft_doc::TextRun::new("", CharStyle::default())]; + for t in [point, area, on_path, down, down_area] { + let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let (first, second) = (Node::new(doc.alloc_id(), NodeKind::Text(Box::new(first))), Node::new(doc.alloc_id(), NodeKind::Text(Box::new(second)))); + doc.text_threads.push(vec![first.id, second.id]); + doc.insert(Some(layer), usize::MAX, first).unwrap(); + doc.insert(Some(layer), usize::MAX, second).unwrap(); + let program = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap().program; + let written = String::from_utf8_lossy(&program); + prop_assert_eq!(written.matches("/AI11Text :").count(), 7, "every text object is written as text"); + let text = mutate_text(&written, cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + survive("hostile .ai type", || vectorcraft_eps::ai_alone(&private).ok().map(|r| r.0))?; + survive("hostile .ai type beside a page", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + } + /// A `.ai` whose variable library is damaged or hostile: the library is counted for the warning /// whether the layers are read or not (an inserted `Z` can make an operator the reader doesn't /// handle, and then the layers aren't read). @@ -2762,13 +3795,615 @@ proptest! { let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); survive("mutated .ai variable library", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; } + + /// A `.ai` whose variable library holds values of every kind, values of the wrong type, elements + /// nested deep, and more variables and data sets than are read, then is damaged: its layers are + /// read, or it comes in as its PDF part (an unknown operator), with or without layers. + #[test] + fn ai_variable_library_values_never_panic( + cut in 0usize..40_000, + edits in prop::collection::vec((0usize..40_000, prop::sample::select(vec!['0', '1', '2', '3', '9', ' ', '\n', '(', ')', '\\', '/', ':', ';', ',', '%', '_', 'Z'])), 0..16), + locked in prop::sample::select(vec!["none", "variableAndTypes", "", "other"]), + extra_variables in 0usize..300, + extra_rows in 0usize..1_100, + depth in 0usize..300, + bad in prop::sample::select(vec![0u8, 1, 2, 3, 4]), + layers in prop::sample::select(vec![0u8, 1, 2]), + ) { + use vectorcraft_testkit::ai::{self, XmlValue}; + let mut nested = ai::xml_text(XmlValue::Str("deep")); + for _ in 0..depth { + nested = ai::xml_element("p", &[], &[nested]); + } + // A value of the wrong type, a second value, a value for no variable, wrong-typed children. + let wrong = match bad { + 0 => ai::xml_element("v_visible", &[], &[ai::xml_text(XmlValue::Str("true"))]), + 1 => ai::xml_element("v_text", &[], &[ai::xml_text(XmlValue::Bool(true))]), + 2 => ai::xml_element("v_nope", &[], &[ai::xml_text(XmlValue::Raw("5 /Int"))]), + 3 => ai::xml_element("v_graph", &[], &[ai::xml_text(XmlValue::Str("a,b\n1,2"))]), + _ => ai::xml_element("v_file", &[], &[]).replacen("%_/Array :", "%_/Dictionary :", 1), + }; + let mut library = ai::sample_variable_sets(locked, &[ai::xml_element("v_text", &[], &[nested]), wrong]); + if extra_variables + extra_rows > 0 { + let declared: Vec = (0..extra_variables).map(|i| ai::xml_element("variable", &[("varName", &format!("x{i}")), ("trait", "textcontent")], &[])).collect(); + let rows: Vec = (0..extra_rows).map(|i| ai::xml_element("v:sampleDataSet", &[("dataSetName", &format!("r{}", i % 900))], &[])).collect(); + let set = ai::xml_element("variableSet", &[], &[ai::xml_element("variables", &[], &declared), ai::xml_element("v:sampleDataSets", &[], &rows)]); + library = ai::xml_element("variableSets", &[], &[set]); + } + let art = match layers { + 0 => ai::layer("L", "0 g\n10 10 m\n20 20 L\nS\n"), + 1 => ai::layer("L", "1 Zz\n"), + _ => String::new(), + }; + let data = ai::editing_data(100.0, 100.0, &format!("{}{art}", ai::variable_library_data(&library))); + let text = mutate_text(&data, cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + survive("hostile .ai variable library values", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// A `.ai` whose variable library binds objects by XML ids that repeat, name nothing, are empty + /// or are shared by several objects (a group and its path), with traits of every kind, then is + /// damaged: every object bound is one of the opened document's. + #[test] + fn ai_variable_bindings_never_panic( + cut in 0usize..20_000, + edits in prop::collection::vec((0usize..20_000, prop::sample::select(vec!['0', '1', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', '_', 'Z', 'u', 'U'])), 0..12), + refs in prop::collection::vec((0usize..5, 0usize..5), 0..40), + art in prop::collection::vec(0usize..5, 0..12), + ) { + use vectorcraft_testkit::ai::{self, XmlValue}; + let names = ["a", "b", "a_x5F_1", "", "missing"]; + let traits = ["textcontent", "visibility", "fileref", "graphdata", "other"]; + let declared: Vec = refs + .iter() + .map(|&(t, n)| { + let uid = format!("/XMLUIDREF : ({}) ;", names[n]); + let attributes = [("trait", XmlValue::Str(traits[t])), ("varName", XmlValue::Unicode(traits[t])), ("docRef", XmlValue::Raw(&uid))]; + ai::xml_node(1, "variable", XmlValue::Str(""), &attributes, &[]) + }) + .collect(); + let set = ai::xml_element("variableSet", &[], &[ai::xml_element("variables", &[], &declared)]); + let library = ai::variable_library_data(&ai::xml_element("variableSets", &[], &[set])); + let art: String = art.iter().map(|&n| format!("u\n0 g\n10 10 m\n20 20 L\nS\n{}U\n{}", ai::named(names[n]), ai::named(names[(n + 1) % 5]))).collect(); + let data = ai::editing_data(100.0, 100.0, &format!("{library}{}", ai::layer("L", &art))); + let text = mutate_text(&data, cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + let mut bound = true; + survive("hostile .ai variable bindings", || { + let d = vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0).0; + bound = d.variables.bindings.keys().all(|id| d.node(*id).is_some()); + Some(d) + })?; + prop_assert!(bound, "a binding names an object the document doesn't have"); + } + + /// A `.ai` whose Objects on Path record and group are damaged or hostile. + #[test] + fn ai_objects_on_path_never_panics(cut in 0usize..4_000, edits in prop::collection::vec((0usize..4_000, prop::sample::select(vec!['0', '1', '9', '-', '.', 'e', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', '_', 'u', 'U'])), 0..12)) { + let text = mutate_text(&on_path_data(&ON_PATH_IDS, &ON_PATH_IDS, 4, "4", "0.5", "", ["0", "1", "2"], true, 0), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + // Trusted, so that the layers read are built whatever the empty page shows. + survive("mutated .ai Objects on Path", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; + } + + /// Style lists (`%AI9_BeginArtStyleList`) of any entries, repeated, empty, malformed or not + /// defined, with or without their end, and objects whose `XW` has any code and any style name. + #[test] + fn ai_style_lists_and_style_links_never_panic( + listed in prop::collection::vec(prop_oneof![ + prop::sample::select(vec!["(A)", "(B)", "()", "(Caf\\303\\251)", "(A(B))", "(x\\)", "(", ")", "<41>", "/A", "1"]).prop_map(str::to_string), + "[ -~]{0,12}", + ], 0..12), + ended in any::(), + objects in prop::collection::vec((prop_oneof![arb_num(), prop::sample::select(vec!["1".to_string(), "6".into(), "9".into()])], prop::sample::select(vec!["A", "B", "", "Caf\u{e9}", "Missing"]), any::()), 0..6), + unit in prop::sample::select(vec![1.0, 2.0, 0.0, -1.0, f64::NAN, f64::INFINITY]), + ) { + use vectorcraft_testkit::ai; + let style = |name: &str| { + format!( + "/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 1 0 0 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n; /Part ,\n;\n" + ) + }; + let end = if ended { "%AI9_EndArtStyleList\n" } else { "" }; + let header = format!( + "%AI9_BeginArtStyles\n{}{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n{}\n{end}", + style("A"), + style("B"), + style("Caf\u{e9}"), + listed.join("\n") + ); + let art: String = objects + .iter() + .map(|(code, name, group)| { + let object = if *group { "%_0 Ae\n%_u\n%_0 0 m\n%_0 9 L\n%_9 9 L\n%_f\n%_U\n" } else { "%_0 0 m\n%_0 9 L\n%_9 9 L\n%_f\n" }; + format!("0 Ae\nu\n0 0 m\n0 9 L\n9 9 L\nf\nU\n{object}{code} ({name}) XW\n") + }) + .collect(); + let data = ai::editing_data(200.0, 100.0, &format!("{header}%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n{art}LB\n%AI5_EndLayer--\n")); + survive("style lists and links", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("style lists and links in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + // A graphic style library: the styles and their list, no layers. + let library = ai::editing_data(200.0, 100.0, &header); + survive("style library", || Some(vectorcraft_eps::layered_ai(library.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, unit).0))?; + let eps = ai::eps(library.as_bytes(), ai::page_ps()); + survive("style library in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + } + + /// Objects on Path records of any shape: ids in any order, repeated or missing, any number of + /// objects, pivots and angles out of range or not finite, spacings, order tags that disagree, + /// groups nested or cut short, and versioned content left open. + #[test] + fn ai_objects_on_path_records_never_panic( + listed in prop::collection::vec(prop::sample::select(ON_PATH_IDS.to_vec()), 0..7), + drawn in prop::collection::vec(prop::sample::select(ON_PATH_IDS.to_vec()), 0..7), + members in 0usize..7, + pivot in prop::sample::select(vec!["0", "4", "8", "9", "-1", "2.5", "1e400"]), + rotation in prop::sample::select(vec!["0", "0.5235987755982988", "-3.2", "1e400", "-1e400", "1e300"]), + spacing in prop::sample::select(vec!["", "%_56.5 /Real (Spacing) ,\n", "%_0 /Bool (IsEquiSpaced) ,\n", "%_1 /Bool (Flip) ,\n"]), + tags in prop::array::uniform3(prop::sample::select(vec!["0", "1", "2", "-1", "7", "(x)", "1e400"])), + versioned in any::(), + nest in 0usize..3, + cut in 0usize..2_000, + ) { + let data = on_path_data(&listed, &drawn, members, pivot, rotation, spacing, tags, versioned, nest); + let cut_at = data.len().saturating_sub(cut); + let cut_at = (0..=cut_at).rev().find(|i| data.is_char_boundary(*i)).unwrap_or(0); + for data in [data.as_str(), &data[..cut_at]] { + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(data)].concat(); + survive("hostile Objects on Path", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; + } + } + + /// A `.ai` whose Art brushed path is damaged or hostile: the brush's object and art, the style's + /// entries and the path, cut short or edited, read and drawn. + #[test] + fn ai_art_brushed_paths_never_panic(cut in 0usize..1_600, edits in prop::collection::vec((0usize..1_600, prop::sample::select(vec!['0', '9', '-', '.', 'e', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', 'u', 'U', 'A', 'Z'])), 0..12)) { + let text = mutate_text(&art_brushed_text(), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + survive("mutated .ai Art brushed path", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// [`styled_definitions_text`] (objects with an art style in a pattern's art and in a brush's + /// art), damaged or hostile. + #[test] + fn ai_styled_definitions_never_panic(cut in 0usize..2_400, edits in prop::collection::vec((0usize..2_400, prop::sample::select(vec!['0', '1', '-', '.', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', '_', 'u', 'U', 'X', 'W', 'E'])), 0..12)) { + let text = mutate_text(&styled_definitions_text(), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + survive("mutated .ai styled definitions", || { + let d = vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0; + let _ = vectorcraft_brush::library(&d); + Some(d) + })?; + } + + /// Brush objects of every kind with any parameters, the brush manager's order with any names, + /// and brush art sections nested or cut short, their art alone or in a group after a frame of + /// any corners, painted or not, open or closed, the group ended or not: read with the layers, + /// or as a library without them, the brushes kept within their ranges. + #[test] + fn ai_brushes_never_panic( + kind in 0usize..7, + params in prop::collection::vec(prop_oneof![arb_num(), Just("/".to_string()), Just(" / ".to_string()), Just("nan".to_string()), Just("inf".to_string()), "[A-Za-z ]{0,6}"], 0..40), + order in "[ -~]{0,80}", + nest in 0usize..6, + cut in any::(), + layers in any::(), + frame in prop::option::of((prop::collection::vec(prop_oneof![arb_num(), Just("0".to_string()), Just("4".to_string())], 4), prop::sample::select(vec!["n", "N", "f", "S"]), any::())), + ) { + use vectorcraft_testkit::ai; + let kinds = ["Adobe Calligraphic Brush Tool", "Adobe Scatter Brush Tool", "Adobe ArtOnPath Brush Tool", "Adobe PatternOnPath Brush Tool", "Adobe dBrush Brush Tool", "Adobe Brush Manager Order", "Other"]; + let object = |k: &str, name: &str, p: &str| { + let chars: Vec = p.chars().collect(); + let lines: String = chars.chunks(12).map(|c| format!("({}) -\n", c.iter().collect::())).collect(); + format!("%AI8_BeginPluginObject\n({k})\n({name})\n{lines}() .\n%AI8_EndPluginObject\n") + }; + let p = params.join(" "); + let mut art = String::new(); + for _ in 0..nest { + art.push_str("%AI8_BeginBrushPattern\n(A)\n"); + } + match &frame { + Some((c, op, ended)) => { + let (x0, y0, x1, y1) = (&c[0], &c[1], &c[2], &c[3]); + let end = if *ended { "U\n" } else { "" }; + art.push_str(&format!("u\n{x0} {y0} m\n{x1} {y0} L\n{x1} {y1} L\n{x0} {y1} L\n{x0} {y0} L\n{op}\n0 g\n0 0 m\n4 0 L\n4 4 L\nf\n{end}")); + } + None => art.push_str("0 g\n0 0 m\n4 0 L\n4 4 L\nf\n"), + } + for _ in 0..nest.saturating_sub(usize::from(cut)) { + art.push_str("%AI8_EndBrushPattern\n"); + } + let records = format!("{art}{}{}", object(kinds[kind], "B", &p), object(kinds[5], kinds[5], &order.replace(['(', ')', '\\'], ""))); + let body = if layers { format!("{records}{}", ai::layer("L", "0 g\n10 10 m\n20 20 L\nS\n")) } else { records }; + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&ai::editing_data(100.0, 100.0, &body))].concat(); + survive("hostile .ai brushes", || { + let d = vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0; + let _ = vectorcraft_brush::library(&d); + Some(d) + })?; + } + + /// A `.ai` whose symbols are damaged or hostile: their definitions, the symbol list and the + /// instances (on the page and in a symbol's art), cut short or edited. + #[test] + fn ai_symbols_never_panic(cut in 0usize..2_000, edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '9', '-', '.', 'e', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', 'u', 'U', 'A', 'Z'])), 0..12)) { + let text = mutate_text(&symbols_text(), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + survive("mutated .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + survive("mutated .ai symbols, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; + // A symbol library: the same symbols and list, no layers. + let library = mutate_text(&symbol_library_text(), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&library)].concat(); + survive("mutated .ai symbol library", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let eps = vectorcraft_testkit::ai::eps(library.as_bytes(), vectorcraft_testkit::ai::page_ps()); + survive("mutated symbol library in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + } + + /// A `.ai` whose art styles, as the writer writes them, are damaged: the styles, the style + /// list, a styled object's drawn look, the object on `%_` lines and its `1 (style) XW`, cut + /// short or edited. + #[test] + fn ai_written_styles_never_panic(cut in 0usize..STYLES_FUZZ_CHARS, edits in prop::collection::vec((0usize..STYLES_FUZZ_CHARS, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', '_', 'u', 'U', 'X', 'W'])), 0..12)) { + let text = mutate_text(styles_text(), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + survive("mutated .ai art styles", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + survive("mutated .ai art styles, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; + } +} + +/// The range of [`ai_written_styles_never_panic`]'s cuts and edits: past the end of [`styles_text`]. +const STYLES_FUZZ_CHARS: usize = 64_000; + +/// The editing data VectorCraft writes for a document with a drop shadow on a path, a gradient fill +/// and a width profile on others, a stroked even-odd path with an opacity mask, Pathfinder › Add on +/// a group and a graphic style of its own with effects on one of its fills. +fn styles_text() -> &'static str { + static TEXT: std::sync::OnceLock = std::sync::OnceLock::new(); + TEXT.get_or_init(|| { + use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; + use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, GraphicStyle, Node, NodeKind, OpacityMask, StrokeLayer, WidthProfile}; + use vectorcraft_geom::{FillRule, Rect, shapes}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let fx = |id: &str| vectorcraft_render::effects::new_effect(id, &json!({})).unwrap(); + let mut ap = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::WHITE), 2.0); + ap.effects = vec![fx("stylize.dropShadow")]; + let shaded = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap.clone()); + doc.insert(Some(layer), usize::MAX, shaded).unwrap(); + let ramp = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)]); + let mut graded = Appearance::basic(Paint::Gradient(Box::new(GradientPaint::new(ramp))), Paint::None, 0.0); + graded.effects = vec![fx("stylize.outerGlow")]; + let n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 50.0, 50.0, 90.0)), graded); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let mut tapered = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0); + tapered.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 0.5), (1.0, 0.0, 1.0)] }); + let profiled = Appearance { items: vec![AppearanceItem::Stroke(tapered)], effects: vec![fx("stylize.roundCorners")], contents_index: None }; + let n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 10.0, 150.0, 40.0)), profiled); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let mut stroked = Appearance::basic(Paint::None, Paint::solid(Color::WHITE), 2.0); + stroked.effects = vec![fx("stylize.dropShadow")]; + let mut odd = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 50.0, 150.0, 90.0)), stroked); + if let NodeKind::Path { rule, .. } = &mut odd.kind { + *rule = FillRule::EvenOdd; + } + let mask_art = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(100.0, 50.0, 150.0, 70.0)), + Appearance::basic(Paint::solid(Color::gray(0.0)), Paint::None, 0.0), + ); + odd.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, false))); + doc.insert(Some(layer), usize::MAX, odd).unwrap(); + let square = |doc: &mut Document, x: f64| { + Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(x, 50.0, x + 30.0, 80.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ) + }; + let (a, b) = (square(&mut doc, 60.0), square(&mut doc, 80.0)); + let mut merged = Node::group(doc.alloc_id(), vec![std::sync::Arc::new(a), std::sync::Arc::new(b)]); + merged.appearance = Appearance { effects: vec![fx("pathfinder.add")], ..Appearance::default() }.into(); + doc.insert(Some(layer), usize::MAX, merged).unwrap(); + doc.graphic_styles.push(GraphicStyle::new("Shaded", ap)); + let chained = FillLayer { opacity: 0.5, effects: vec![fx("distort.twist")], ..FillLayer::new(Paint::solid(Color::WHITE)) }; + let chained = Appearance { items: vec![AppearanceItem::Fill(chained)], ..Appearance::default() }; + doc.graphic_styles.push(GraphicStyle::new("Chained", chained)); + let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap(); + String::from_utf8(out.program).unwrap() + }) +} + +/// The data [`ai_written_styles_never_panic`] damages, as it is, opens with its styles live, and the +/// property's cuts and edits reach all of it. +#[test] +fn the_written_styles_fuzz_data_opens_live() { + let text = styles_text(); + assert!(text.chars().count() < STYLES_FUZZ_CHARS, "{}", text.chars().count()); + for mark in [ + "%AI9_BeginArtStyles", + "%AI9_BeginArtStyleList", + "%AI5_BeginLayer", + "\n6 () XW", + "\n1 (Anon", + "(BSLeftWidthsArray)", + "0 /Bool (UseEvenOdd)", + "(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter", + "Bb", + ] { + assert!(text.replace("\r\n", "\n").contains(mark), "{mark}"); + } + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat(); + let (d, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0); + assert!(layered, "{warnings:?}"); + let art = d.layers[0].children().unwrap(); + assert_eq!(art.iter().map(|n| n.appearance.effects.len()).collect::>(), [1, 1, 1, 1, 1]); + assert!(d.graphic_style("Shaded").is_some() && d.graphic_style("Chained").is_some()); +} + +/// [`symbols_text`] without its layer: a symbol library. +fn symbol_library_text() -> String { + let full = symbols_text(); + match (full.find("%AI5_BeginLayer"), full.find("%AI5_EndLayer--\n")) { + (Some(a), Some(b)) if a < b => format!("{}{}", &full[..a], &full[b + "%AI5_EndLayer--\n".len()..]), + _ => full, + } +} + +/// The library [`ai_symbols_never_panic`] damages, as it is, opens with its symbols. +#[test] +fn the_symbol_library_fuzz_data_opens_with_its_symbols() { + let text = symbol_library_text(); + assert!(!text.contains("%AI5_BeginLayer")); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + let (doc, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0); + assert!(!layered, "{warnings:?}"); + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["S2", "S1"], "{warnings:?}"); +} + +/// Editing data with symbols (S2's art holds an instance of S1, F's holds non-native art), the +/// symbol list and a layer of instances, as the format writes them. +fn symbols_text() -> String { + use vectorcraft_testkit::ai; + let def = |name: &str, art: &str, reg: u32| { + format!( + "%AI14_BeginSymbol\n({name})\n0 A\n0 Xw\n0 Ae\nu\n{art}U\n%_/ArtDictionary :\n%_{reg} /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n" + ) + }; + let inst = |name: &str, m: &str| format!("/SymbolInstance :\n({name}) /SymbolRef ,\n{m} /RTransformMatrix\n;\n9 () XW\n"); + // Non-native art keeps ASCII85 data in comment lines, some of them `%_` lines holding a `(`. + let foreign = "/ForeignObject :\n1 /Version ,\n2 0 0 2 10 20 /RTransform ,\n10 20 /Origin ,\n1 2 5 8 /Bounds ,\n/Data ,\n\ + %,u@!!/MSk8%41#ocdN=10d&\n%_O%*mGn(RduU.]4`[u[.f\n%_;(]<[%\n%1H@\n;\n"; + let defs = def("F", &format!("{foreign}-2 -2 m\n2 -2 L\n2 2 L\nf\n"), 5) + + &def("S1", "0 1 1 0 1 0 0 Xa\n-2 -2 m\n2 -2 L\n2 2 L\n-2 2 L\nf\n", 5) + + &def("S2", &inst("S1", "1 0 0 -1 -8081 8237"), 1); + let list = "%AI24_BeginSymbolList\n(S2)\n(S1)\n%AI24_EndSymbolList\n"; + let page = ai::layer( + "L", + &format!( + "1 Xw\n{}0 Xw\n{}1 0.5 0 2 0 Xy\n0 0 Xd\n6 () XW\n0 Ae\nq\n{}10 10 m\n30 10 L\n30 30 L\nh\nW\nn\nQ\n", + inst("S1", "1 0 0 -1 20 50"), + inst("S2", "2 0 0 -2 100 50"), + inst("S1", "1 0 0 -1 20 20") + ), + ); + let data = ai::editing_data( + 200.0, + 100.0, + &format!("%AI5_Begin_NonPrinting\n{defs}%AI5_End_NonPrinting--\n%AI5_Begin_NonPrinting\n{list}%AI5_End_NonPrinting--\n{page}"), + ); + data.replacen("%%EndComments", "%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n%%EndComments", 1) +} + +/// The data [`ai_symbols_never_panic`] damages, as it is, opens with its symbols and instances live. +#[test] +fn the_symbols_fuzz_data_opens_live() { + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&symbols_text())].concat(); + let (doc, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0); + assert!(layered, "{warnings:?}"); + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).filter(|n| *n != "F").collect(); + assert_eq!(names, ["S2", "S1"]); + let mut instances = 0; + doc.walk(|n| instances += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. }))); + assert_eq!(instances, 3); +} + +/// Symbols the reader must stop at: sections that don't end, references and matrices it can't +/// use, definitions nested deeper than it reads, and symbols that hold each other. +#[test] +fn ai_symbol_limits_never_panic() { + use vectorcraft_testkit::ai; + let inst = |name: &str, m: &str| format!("/SymbolInstance :\n{name} /SymbolRef ,\n{m} /RTransformMatrix\n;\n"); + let def = |name: &str, art: &str| format!("%AI14_BeginSymbol\n({name})\n0 A\n0 Xw\n0 Ae\nu\n{art}U\n%AI10_EndSymbol\n"); + let mut nested = String::new(); + for i in 0..400 { + nested.push_str(&format!("%AI14_BeginSymbol\n(N{i})\n0 Ae\nu\n")); + } + for _ in 0..400 { + nested.push_str("U\n%AI10_EndSymbol\n"); + } + let mut chain = String::new(); + for i in 0..300 { + chain.push_str(&def(&format!("C{i}"), &inst(&format!("(C{})", i + 1), "1 0 0 -1 0 0"))); + } + let cases = [ + format!("%AI14_BeginSymbol\n(Open)\n0 Ae\nu\n{}", ai::layer("L", &inst("(Open)", "1 0 0 -1 20 50"))), + format!("%AI24_BeginSymbolList\n(A)\n(B)\n{}", ai::layer("L", "")), + format!( + "{}{}", + def("S", "-2 -2 m\n2 2 L\nS\n"), + ai::layer("L", &(inst("", "1 0 0 -1 20 50") + &inst("/SymbolRef", "1 0 0 -1 20 50") + &inst("(S)", ""))) + ), + format!( + "{}{}", + def("S", "-2 -2 m\n2 2 L\nS\n"), + ai::layer( + "L", + &(inst("(S)", "1 0 0") + &inst("(S)", "1 0 0 -1 20 50 7") + &inst("(S)", "1e400 0 0 -1 20 50") + &inst("(S)", "0 0 0 0 20 50")) + ) + ), + format!("{nested}{}", ai::layer("L", &inst("(N0)", "1 0 0 -1 20 50"))), + format!("{chain}{}", ai::layer("L", &inst("(C0)", "1 0 0 -1 20 50"))), + format!( + "{}{}{}", + def("S1", &inst("(S2)", "1 0 0 -1 0 0")), + def("S2", &inst("(S1)", "1 0 0 -1 0 0")), + ai::layer("L", &inst("(S1)", "1 0 0 -1 20 50")) + ), + format!("{}{}", def("S1", &inst("(S2)", "1 0 0 -1 0 0")), def("S2", &inst("(S1)", "1 0 0 -1 0 0"))), + // Symbol libraries without layers: definitions nested too deep and a long chain. + nested, + chain, + ]; + for body in cases { + let data = ai::editing_data(200.0, 100.0, &body).replacen("%%EndComments", "%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n%%EndComments", 1); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("hostile .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0)) + .unwrap(); + survive("hostile .ai symbols, trusted", || { + Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0) + }) + .unwrap(); + } +} + +/// The data [`ai_objects_on_path_never_panics`] damages, as it is, opens with its Objects on Path group. +#[test] +fn the_objects_on_path_fuzz_data_opens_live() { + let text = on_path_data(&ON_PATH_IDS, &ON_PATH_IDS, 4, "4", "0.5", "", ["0", "1", "2"], true, 0); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + // Trusted: the empty page it is read beside isn't compared with its art. + let (doc, warnings, _) = vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0); + let g = doc.layers.first().and_then(|l| l.children()).and_then(|c| c.first()).unwrap_or_else(|| panic!("{warnings:?}")); + assert!(g.extras().objects_on_path.is_some(), "{g:?}"); +} + +/// Editing data with an Art brush, its art, and a path with its drawn look and the brush in its art +/// style, as the format writes them. +fn art_brushed_text() -> String { + use vectorcraft_testkit::ai; + let tool = "Adobe ArtOnPath Brush Tool"; + let object = format!( + "%AI8_BeginPluginObject\n({tool})\n(R)\n(2 / A/ / / / / 0 0/ 5 0 0 0 / 1) -\n( 1 1 0 1 0 0 0 1 1 0 0 0 0 1) .\n%AI8_EndPluginObject\n" + ); + let art = "%AI8_BeginBrushPattern\n(A)\n0 A\n0 g\n0 0 m\n40 0 L\n40 8 L\nf\n%AI8_EndBrushPattern\n"; + let style = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(S) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n({tool}) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + 0 /Bool (Proportional) ,\n0 /Bool (Segmented) ,\n1 /Real (Scaling) ,\n1 /Real (MinScaling) ,\n1 /Real (MaxScaling) ,\n1 /Int (Adjustment) ,\n1 /Bool (FoldAdjustment) ,\n1 /Int (Colorization) ,\n\ + /StrokeStyle : 0 R\n0 0 0 1 K\n0 1 0 0 0 Xy\n0 J 0 j 2 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n/GObjRef : (R) ({tool}) /PluginObject ; (Brush) ,\n; /Dict ;\n /Part ,\n;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ); + let path = "0 Ae\nu\n0 g\n10 10 m\n90 10 L\n90 30 L\nf\nU\n0 0 Xd\n6 () XW\n%_10 20 m\n%_90 20 L\n%_90 80 L\n%_n\n1 (S) XW\n"; + ai::editing_data(100.0, 100.0, &format!("{object}{art}{style}{}", ai::layer("L", path))) +} + +/// The data [`ai_art_brushed_paths_never_panic`] damages, as it is, opens with its path live and the +/// brush on its stroke. +#[test] +fn the_art_brushed_fuzz_data_opens_live() { + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&art_brushed_text())].concat(); + // Trusted: the empty page it is read beside isn't compared with its art. + let (doc, warnings, _) = vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0); + let n = doc.layers.first().and_then(|l| l.children()).and_then(|c| c.first()).unwrap_or_else(|| panic!("{warnings:?}")); + assert_eq!(n.appearance.stroke().and_then(|s| s.brush.as_deref()), Some("R"), "{warnings:?} {n:?}"); +} + +/// Editing data with an art style (a blue fill and a drop shadow), a pattern, a pattern in the +/// version 7 form (its tile string) and a Scatter brush's art each holding a square with its drawn +/// look and that style, and a path filled with the first pattern. +fn styled_definitions_text() -> String { + use vectorcraft_testkit::ai; + let style = "%AI9_BeginArtStyles\n/KnownStyle :\n(S) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n\ + /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n1 /Int (blnd) ,\n0.75 /Real (opac) ,\n5 /Real (blur) ,\n\ + 0 /Int (csrc) ,\n/FillStyle : 0 O\n0 0 0 1 0 0 0 Xa\n0 1 Xd\n/Def ;\n (sclr) ,\n3 /Real (horz) ,\n4 /Real (vert) ,\n; /Dict ;\n /Part ,\n;\n%AI9_EndArtStyles\n"; + let square = "0 Ae\nu\n1 0 0 0 0 0 0 Xa\n0 0 m\n10 0 L\n10 10 L\n0 10 L\nf\nU\n%_0 0 m\n%_10 0 L\n%_10 10 L\n%_0 10 L\n%_f\n1 (S) XW\n"; + let pattern = format!("%AI3_BeginPattern: (P)\n(P) 0 0 10 10\n0 A\n0 Xw\n{square}E\n%AI3_EndPattern\n"); + let tile = square.replace('\n', "\r"); + let legacy = format!("%AI3_BeginPattern: (Q)\n(Q) 0 0 20 20 [\n%AI3_Tile\n(0 O 0 R 0 0 0 1 k 0 0 0 1 K) @\n(\r{tile}) &\n] E\n%AI3_EndPattern\n"); + let art = format!("%AI8_BeginBrushPattern\n(D)\n0 A\n{square}%AI8_EndBrushPattern\n"); + let object = "%AI8_BeginPluginObject\n(Adobe Scatter Brush Tool)\n(B)\n(2 /D/ 5 1 0 0 / 0 0.5 1.5 1) -\n( 1.2 2 0 -0.25 0.25 2 -45 30 1 1 0) .\n%AI8_EndPluginObject\n"; + let path = format!("(P) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", ai::rect(20.0, 20.0, 80.0, 80.0)); + ai::editing_data(100.0, 100.0, &format!("{style}{pattern}{legacy}{art}{object}{}", ai::layer("L", &path))) +} + +/// The data [`ai_styled_definitions_never_panic`] damages, as it is, opens with the patterns' and +/// the brush's squares live. +#[test] +fn the_styled_definitions_fuzz_data_opens_live() { + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&styled_definitions_text())].concat(); + // Trusted: the empty page it is read beside isn't compared with its art. + let (doc, warnings, _) = vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0); + let live = |n: &vectorcraft_doc::Node| matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }) && n.appearance.effects.len() == 1; + for name in ["P", "Q"] { + let tile = doc.pattern(name).map(|p| p.art.clone()).unwrap_or_else(|| panic!("{name}: {warnings:?}")); + assert!(tile.len() == 1 && live(&tile[0]), "{name}: {warnings:?} {tile:?}"); + } + let lib = vectorcraft_brush::library(&doc); + let brush = lib.iter().find(|b| b.name == "B").unwrap_or_else(|| panic!("{warnings:?}")); + assert!(matches!(brush.art().as_slice(), [n] if live(n)), "{warnings:?} {brush:?}"); +} + +/// The ids of the objects of an Objects on Path group in the fuzz cases. +const ON_PATH_IDS: [&str; 5] = ["f-0001", "f-0002", "f-0003", "f-0004", "f-0005"]; + +/// Editing data with an Objects on Path record naming `listed` for `members` objects (Pivot +/// `pivot`, Rotation `rotation`, then the entries `more`) and a group of a path and squares whose +/// dictionaries give the ids `drawn` (the first the path's, the others with the order tags `tags` +/// in turn), inside `nest` more groups, in versioned content with a copy after it when `versioned` +/// is set. +#[allow(clippy::too_many_arguments)] +fn on_path_data( + listed: &[&str], + drawn: &[&str], + members: usize, + pivot: &str, + rotation: &str, + more: &str, + tags: [&str; 3], + versioned: bool, + nest: usize, +) -> String { + use vectorcraft_testkit::ai; + let options = ai::on_path_options(members, 0, 0.0, more) + .replace("%_0 /Int (PivotPosition)", &format!("%_{pivot} /Int (PivotPosition)")) + .replace("%_0 /Real (Rotation)", &format!("%_{rotation} /Real (Rotation)")); + let record = ai::on_path_record("Adobe Align On Path", listed, &options); // brand-ok: the record's name in the files + let mut group = String::from("0 Ae\nu\n/ConstraintGroup :\n128 /GroupType ,\n;\n0 0 1 0 0 0 1 XA\n20 20 m\n100 80 L\n180 20 L\nS\n"); + for (i, id) in drawn.iter().enumerate() { + if i == 0 { + group += &ai::on_path_member(id, None, 0.0); + } else { + let x = 10.0 + 30.0 * i as f64; + let tag = tags.get(i - 1).map_or_else(|| (i - 1).to_string(), |t| t.to_string()); + group += &format!( + "0 1 1 0 1 0 0 Xa\n{}f\n%_/ArtDictionary :\n%_{tag} /Int (ConstraintArtOrderId) ,\n%_({id}) /String (Persistent ID) ,\n%_({rotation}) /String (BBAccumRotation) ,\n%_;\n%_\n", + ai::rect(x, 40.0, x + 10.0, 46.0) + ); + } + } + group += "U\n"; + for _ in 0..nest { + group = format!("0 Ae\nu\n{group}U\n"); + } + let art = if versioned { + format!("%AI17_Begin_Content_if_version_gt:24 14\n{group}%AI17_Alternate_Content\n{group}%AI17_End_Versioned_Content\n") + } else { + group + }; + ai::editing_data(200.0, 100.0, &format!("{record}{}", ai::layer("L", &art))) } /// A `.ai` in PostScript form as other apps write it: the procsets that define its operators named, /// not included, so its program can't be run and its layers are read from it. const NAMED_PROLOG_AI: &str = "%!PS-Adobe-3.0\n%%BoundingBox: 0 0 200 100\n%%DocumentNeededResources: procset Adobe_packedarray 2.0 0\n%AI3_TemplateBox: 288 384 288 384\n%%EndComments\n\ %%BeginProlog\n%%IncludeResource: procset Adobe_packedarray 2.0 0\nAdobe_packedarray /initialize get exec\n%%EndProlog\n%%BeginSetup\n%AI5_Begin_NonPrinting\nNp\n%AI5_End_NonPrinting--\n%%EndSetup\n\ - %AI5_BeginLayer\n1 1 1 1 0 0 -1 191 63 255 Lb\n(A::B) Ln\n0 A\n0 R\n0 0 0 1 K\n0 i 1 J 1 j 0.8 w 4 M [2 1]0 d\n0 D\n10 10 m\n90 10 L\n90 90 L\n10 90 L\n10 10 L\nS\n\ + %AI5_BeginLayer\n1 1 1 1 0 0 -1 191 63 255 Lb\n(A::B) Ln\n0 A\n0 R\n0 0 0 1 K\n0 i 1 J 1 j 0.8 w 4 M [2 1]0 d\n0 D\n%AI3_Note:a (note)\n%AI5_NoteMore:more\n1 Ap\n10 10 m\n90 10 L\n90 90 L\n10 90 L\n10 10 L\nS\n%%Note:\n0 Ap\n\ u\n0.5 g\n20 20 m\n40 20 L\n40 40 L\nf\nU\n%AI5_BeginLayer\n0 1 1 1 0 0 3 0 0 0 Lb\n(Sub) Ln\n110 10 m\n190 90 L\nS\nLB\n%AI5_EndLayer--\nLB\n%AI5_EndLayer--\n\ %%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n"; @@ -2787,10 +4422,209 @@ proptest! { /// A `.ai` in PostScript form whose prolog is named, not included, damaged: read from its /// layers, or refused. #[test] - fn ps_form_ai_never_panics(cut in 0usize..1_200, edits in prop::collection::vec((0usize..1_200, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '[', ']', '%', 'u', 'U', 'L', 'b', 'B', 'i', 'A', 'K'])), 0..12)) { + fn ps_form_ai_never_panics(cut in 0usize..1_200, edits in prop::collection::vec((0usize..1_200, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '[', ']', '%', 'u', 'U', 'L', 'b', 'B', 'i', 'A', 'K', 'p', ':', '\u{e9}'])), 0..12)) { let text = mutate_text(NAMED_PROLOG_AI, cut, &edits); survive("mutated PostScript-form .ai", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; } + + /// Multi-layer masks (`Mb` `W n` `Md` … `MB`) over any number of layers, with tokens + /// dropped or put anywhere (the mask operators, layer ends, groups, clipping paths) and the + /// data cut short. + #[test] + fn ai_multi_layer_masks_never_panic( + layers in 1usize..5, + aliases in any::(), + edits in prop::collection::vec((0usize..64, prop::sample::select(vec!["", "Mb", "Md", "MB", "Mi", "LB", "u", "U", "q", "Q", "W n", "h W n"])), 0..4), + cut in prop::option::of(0usize..64), + ) { + use vectorcraft_testkit::ai; + let (begin, define) = if aliases { ("Mv", "ME") } else { ("Mb", "Md") }; + let mut tokens: Vec = vec![]; + for i in 0..layers { + if i > 0 { + tokens.push(format!("LB\n%AI5_EndLayer--\n%AI5_BeginLayer\n1 1 1 1 0 1 1 79 128 255 Lb\n(L{i}) Ln\n")); + } else { + tokens.extend([begin.to_string(), "40 40 m 120 40 L 120 120 L 40 120 L h W n".into(), define.to_string()]); + } + let x = 10 * i; + tokens.push(format!("0.5 0 0 0 k {x} {x} m {} {x} L {} {} L f", x + 140, x + 140, x + 140)); + } + tokens.extend(["MB".to_string(), "150 150 m 190 150 L 190 190 L f".into()]); + for (at, with) in &edits { + let at = at % (tokens.len() + 1); + if with.is_empty() { + if at < tokens.len() { + tokens.remove(at); + } + } else { + tokens.insert(at, with.to_string()); + } + } + if let Some(cut) = cut { + tokens.truncate(cut); + } + let data = ai::editing_data(200.0, 100.0, &format!("%AI5_BeginLayer\n1 1 1 1 0 1 1 79 128 255 Lb\n(L0) Ln\n{}\nLB\n", tokens.join("\n"))); + survive("multi-layer masks", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("multi-layer masks in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + } + + /// The same file with placed EPS files in the version 7 form (no `%AI5_BeginPlace`), one + /// linked and one included whole with a nested document and counted data in it, damaged. + #[test] + fn ps_form_ai_with_placed_files_never_panics(cut in 0usize..1_600, edits in prop::collection::vec((0usize..1_600, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', '`', '~', 'E', 'D'])), 0..12)) { + let placed = "[1 0 0 1 10 20] 10 20 50 50 (a.eps) `\n%%IncludeFile: a.eps\n~\n\ + [-1 0 0 1 100 0] 10 20 50 50 4 4 0 (b.eps) `\n%%BeginDocument: b.eps\n%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n\ + %%BeginDocument: c.eps\n~\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n0 0 1 setrgbcolor 10 20 40 30 rectfill\n%%EndDocument\n~\n"; + let fixture = NAMED_PROLOG_AI.replacen("0 Ap\nu\n", &format!("0 Ap\n{placed}u\n"), 1); + prop_assert!(fixture.contains("(b.eps)")); + let text = mutate_text(&fixture, cut, &edits); + survive("mutated PostScript-form .ai with placed files", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; + } + + /// The same file with linked images in the version 7 form (`XG`, then `XF` with no samples), + /// one with an embedded image between its `XG` and `XF`, damaged. + #[test] + fn ps_form_ai_with_linked_images_never_panics(cut in 0usize..1_400, edits in prop::collection::vec((0usize..1_400, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', 'X', 'F', 'G'])), 0..12)) { + let linked = "%AI5_File:\n%AI5_BeginRaster\n(a.tif) 0 XG\n[ 2 0 0 3 10 80 ] 0 0 10 20 10 20 8 3 0 0 0 0 XF\n%AI5_EndRaster\n\ + %AI5_File:\n%AI5_BeginRaster\n(b.tif) 1 XG\n[ 1 0 0 1 0 100 ] 0 0 1 1 1 1 8 3 0 0 0 0 XI\n%FF0000\n%AI5_EndRaster\n\ + [ 0 1 -1 0 50 50 ] 0 0 4 4 4 4 8 3 0 0 0 0 XF\n"; + let fixture = NAMED_PROLOG_AI.replacen("0 Ap\nu\n", &format!("0 Ap\n{linked}u\n"), 1); + prop_assert!(fixture.contains("(a.tif)")); + let text = mutate_text(&fixture, cut, &edits); + survive("mutated PostScript-form .ai with linked images", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; + } +} + +/// A `.ai` in the legacy format without layers (Illustrator 3) whose prolog is included: its +/// program runs, and its art is read on one layer. +const LAYERLESS_AI: &str = "%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: a script\n%%BoundingBox: 0 0 200 100\n%AI3_Cropmarks: 0 0 200 100\n%%EndComments\n\ + %%BeginProlog\n/m {moveto} def /L {lineto} def /f {closepath fill} def /S {stroke} def /A {pop} def /k {setcmykcolor} def /u {} def /U {} def\n\ + %%EndProlog\n%%BeginSetup\n%%EndSetup\n1 A\n0 0 0 1 k\n10 10 m\n90 10 L\n90 90 L\nf\n0 A\nu\n110 10 m\n190 90 L\n150 90 L\nf\nU\n\ + %%PageTrailer\nshowpage\n%%Trailer\n%%EOF\n"; + +/// The fixture, as it is, opens through the reader: its first path keeps its lock. +#[test] +fn the_layerless_fixture_opens_through_the_reader() { + let l = vectorcraft_engine::cmd::fileio::load("x.ai", LAYERLESS_AI.as_bytes()).unwrap(); + assert_eq!(l.doc.layers.len(), 1, "{:?}", l.warnings); + let art = l.doc.layers[0].children().unwrap(); + assert_eq!(art.len(), 2, "{:?}", l.warnings); + assert!(art[0].locked && !art[1].locked); +} + +proptest! { + #![proptest_config(config())] + + /// A `.ai` in the legacy format without layers, damaged: read through the reader, as its page, + /// or refused. + #[test] + fn layerless_ai_never_panics(cut in 0usize..800, edits in prop::collection::vec((0usize..800, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '{', '}', '%', 'u', 'U', 'L', 'f', 'A', 'k'])), 0..12)) { + let text = mutate_text(LAYERLESS_AI, cut, &edits); + survive("mutated layerless .ai", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; + } +} + +/// A pattern's definition in the version 7 form (§3.4): a layer whose `_ &` fills the tile's box, +/// and one whose tile string has CR-separated lines, comments and escapes. +const LEGACY_PATTERN: &str = "%AI3_BeginPattern: (P)\n(P) 0 0 10 10 [\n%AI3_Tile\n(0 O 0 R 0 0 0 0.5 k) @ _ &\n\ + (0 O 1 R 0 0 0 1 \\(Ink\\) 0 X) @ (\r%AI6_BeginPatternLayer\r1 w u\r0 5 m\\r10 5 L\rS\rU\r%AI6_EndPatternLayer\r) &\n] E\n%AI3_EndPattern\n"; + +/// [`NAMED_PROLOG_AI`] with `pattern` in its setup, filling the square. +fn legacy_pattern_ai(pattern: &str) -> String { + NAMED_PROLOG_AI + .replace("%AI5_Begin_NonPrinting", &format!("{pattern}%AI5_Begin_NonPrinting")) + .replace("\n10 10 m\n", "\n(P) 5 5 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n10 10 m\n") + .replace("10 10 L\nS\n", "10 10 L\nB\n") +} + +/// The fixture, as it is, opens with the pattern filling the square. +#[test] +fn the_legacy_pattern_fixture_opens_with_its_pattern() { + let l = vectorcraft_engine::cmd::fileio::load("x.ai", legacy_pattern_ai(LEGACY_PATTERN).as_bytes()).unwrap(); + assert_eq!(l.doc.pattern("P").map(|p| p.art.len()), Some(2), "{:?}", l.warnings); + let square = &l.doc.layers[0].children().unwrap()[0]; + assert!(matches!(square.appearance.fill().map(|f| &f.paint), Some(vectorcraft_color::Paint::Pattern { .. }))); +} + +proptest! { + #![proptest_config(config())] + + /// That `.ai` with its pattern's definition damaged (its strings, `@`, `&`, `_`, the list's + /// brackets and its `E`): read, without the pattern where it can't be read whole, or refused. + #[test] + fn ps_form_ai_legacy_pattern_never_panics(cut in 0usize..500, edits in prop::collection::vec((0usize..500, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '\r', '(', ')', '\\', '[', ']', '%', '@', '&', '_', 'E', 'u', 'U', 'q', 'Q', 'm', 'f', 'S', 'k', 'X'])), 0..12)) { + let text = legacy_pattern_ai(&mutate_text(LEGACY_PATTERN, cut, &edits)); + survive("PostScript-form .ai with a damaged version 7 pattern", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; + } +} + +/// Area type in the version 7 form (§15.5.3) whose story flows through two linked areas: a small +/// one, and one a quarter turn round, each area's characters after its `TP`. +const LINKED_AREAS: &str = "1 To\n1 0 0 1 120 90 0 Tp\n120 60 m\n120 90 L\n180 90 L\n180 60 L\n120 60 L\nn\nTP\n0 Tr\n0 g\n/_Helvetica 9 Tf\n\ + (one two three four five six seven eight nine ten ) Tx\n0 1 -1 0 190 10 0 Tp\n130 10 m\n130 55 L\n190 55 L\n190 10 L\n130 10 L\nn\nTP\n\ + (eleven twelve thirteen fourteen fifteen) Tx\n(\\r) TX\nTO\n"; + +/// [`NAMED_PROLOG_AI`] with `text` on its layer. +fn linked_areas_ai(text: &str) -> String { + NAMED_PROLOG_AI.replace("u\n0.5 g\n", &format!("{text}u\n0.5 g\n")) +} + +/// The fixture, as it is, opens with its area type as two threaded frames, the story flowing from +/// the first into the second. +#[test] +fn the_linked_areas_fixture_opens_as_threaded_frames() { + let l = vectorcraft_engine::cmd::fileio::load("x.ai", linked_areas_ai(LINKED_AREAS).as_bytes()).unwrap(); + let [thread] = &l.doc.text_threads[..] else { panic!("one thread: {:?} {:?}", l.doc.text_threads, l.warnings) }; + let texts: Vec = thread + .iter() + .map(|id| match &l.doc.node(*id).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + k => panic!("type: {k:?}"), + }) + .collect(); + let [first, second] = texts.as_slice() else { panic!("two frames: {texts:?}") }; + assert!(!first.is_empty() && !second.is_empty(), "the story flows on into the second frame: {texts:?}"); + assert_eq!(format!("{first}{second}"), "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen"); +} + +proptest! { + #![proptest_config(config())] + + /// That `.ai` with its linked areas damaged (their text paths, frames and characters): read, or + /// refused. + #[test] + fn ps_form_ai_linked_areas_never_panic(cut in 0usize..400, edits in prop::collection::vec((0usize..400, prop::sample::select(vec!['0', '1', '-', '.', ' ', '\n', '(', ')', '\\', 'T', 'p', 'P', 'O', 'o', 'x', 'X', 'm', 'L', 'n'])), 0..12)) { + let text = linked_areas_ai(&mutate_text(LINKED_AREAS, cut, &edits)); + survive("PostScript-form .ai with damaged linked areas", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; + } +} + +/// An operand of a layer's options (`Lb`): a flag, a colour index or component, a percentage, or +/// anything else. +fn arb_layer_operand() -> impl Strategy { + prop_oneof![Just("0".to_string()), Just("1".to_string()), (-2i32..300).prop_map(|v| v.to_string()), arb_num()] +} + +/// A coordinate of a guide path: the ends of the canvas around the template box's centre (100 50), +/// the edges of the artboards, near them, or anything else. +fn arb_guide_coord() -> impl Strategy { + prop_oneof![ + prop::sample::select(vec!["-8091.5", "8291.5", "-8141.5", "8241.5", "0", "50", "100", "200", "-8091.505", "8291.5001", "1e308"]) + .prop_map(str::to_string), + arb_num(), + ] +} + +/// A value of a `/Document` setting: a number of any type, several numbers, a string or a +/// dictionary. +fn arb_ai_setting() -> impl Strategy { + prop_oneof![ + (arb_num(), prop::sample::select(vec!["/Int", "/Real", "/Bool", "/String", ""])).prop_map(|(n, t)| format!("{n} {t}")), + (arb_num(), arb_num()).prop_map(|(a, b)| format!("{a} {b} /RealPoint\n%_")), + Just("(text) /String".to_string()), + Just("/Dictionary :\n%_1 /Int (x) ,\n%_;\n%_".to_string()), + ] } /// The operators, operands and section comments of hostile editing data. @@ -2819,16 +4653,32 @@ fn arb_ai_token() -> impl Strategy { "b", "W", "(b) *", + "(N) *", + "(S) *", + "-8091.5 50 m 8291.5 50 L (N) *", "u", "U", "*u", "*U", "q", "Q", + // Several clipping paths in one clipping group or layer clip to their intersection (AI7 spec §5.6.2), each + // nesting a clipping group. + "0 0 m 9 0 L 9 9 L h W n 1 1 m 8 1 L 8 8 L h W f", + "q 0 0 m 9 0 L 9 9 L h W n 1 1 m 8 1 L 8 8 L h W n 0 0 m 5 5 L 0 5 L f Q", + "u 0 0 m 9 0 L 9 9 L h W n 1 1 m 8 1 L 8 8 L h W n U", + "q 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n", "LB", "Lb", "Ln", "(name) Ln", + "\n%AI5_BeginLayer\n1 1 1 1 0 1 1 79 128 255 Lb\n", + "Mb", + "Mv", + "Md", + "ME", + "Mi", + "MB", "g", "G", "k", @@ -2843,6 +4693,19 @@ fn arb_ai_token() -> impl Strategy { "O", "R", "XR", + // A path's note and Show Center (version 7 §5.3.1, §12). + "Ap", + "1 Ap", + "\n%AI3_Note: a (note) \n", + "\n%AI3_Note:\n", + "\n%AI5_NoteMore:more\n", + "\n%%Note:old\n", + // Object tags (version 7 §7). + "XT", + "/AdobeURL (https://example.com) XT", + "/tag () XT", + "/ (x) XT", + "(x) (y) XT", "w", "J", "j", @@ -2881,6 +4744,12 @@ fn arb_ai_token() -> impl Strategy { "[ 1 0 0 1 0 0 ] 0 0 2 2 2 2 8 3 1 0 1 0", "[ 1 0 0 1 0 0 ] 0 0 3 2 3 2 1 4 1 0 1 0", "[ 1 0 0 1 0 0 ] 0 0 99999 99999 99999 99999 1 1 0 0 0 0", + // A linked image in the version 7 form (§8.2, §8.3): `(path) modified XG`, then `XF`. + "XG", + "(a.tif) 0 XG", + "XF", + "[ 1 0 0 1 0 0 ] 0 0 2 2 2 2 8 3 0 0 0 0 XF", + "[ 1e308 0 0 1e308 0 0 ] 0 0 1e6 1e6 1e6 1e6 8 3 0 0 0 0 XF", "[", "]", "/Name", @@ -2903,6 +4772,7 @@ fn arb_ai_token() -> impl Strategy { "\n%_/AI11Text :\n%_0 /StoryIndex ,\n%_;\n", "/SymbolInstance :", "/Binary : /ASCII85Decode ,", + "/AI11TextDocument : /ASCII85Decode ,", "~>", "p", "P", @@ -2933,7 +4803,17 @@ fn arb_ai_token() -> impl Strategy { "(\\r) TX", "() Tj", "(x) Tx", + "(\\t) 1 TS", + "() /x TS", + "Te", + "0 0 1e308 -1e308 Te", + "TM", "7 Tr", + "4 Tr", + "9 Tr", + "4.5 Tr", + "*w", + "*W", "-1e308 Ts", "1e308 0 Tz", "1e308 Tt", @@ -2942,10 +4822,40 @@ fn arb_ai_token() -> impl Strategy { "9 Ta", "1e308 -1e308 1e308 Ti", "0 1 Tk", + "-1e308 0 1e308 TC", + "1e308 -1 5 TW", + "/x 100 200 TW", + "1 Tq", + "7 Tq", + "1 TV", + "7 TV", + "1 Tv", + "/x Tv", + "1 Ty", + "1e308 Ty", + "1 TY", + "(x) TY", + "3 Tg", + "1e308 Tg", + "1 1 1e308 -1e308 4e9 Th", + "1 1 (2) 3 4 Th", + "36 2 Xb", + "Xb", + "0 0 4 1e308 Xe", + "0 0 2 -1e308 Xe", + "0 0 3 72 Xe", + "0 0 1e308 72 Xe", + "(x) /y Xe", + "XB", "[39/quotesingle 128/Euro/eacute/nosuch 300/x TE", "[1e308/a -1/b TE", "\n%AI3_BeginEncoding: _Helvetica Helvetica\n[/_Helvetica/Helvetica 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n", "\n%AI3_BeginEncoding:\n", + "[ 39/quotesingle 1e308/a -1/b 200/eacute\n/_Helvetica/Helvetica 0 0 1 [0.5 1e308] TZ", + "/_ 0 TZ", + "[ ] ] [ /a /b (c) TZ", + "\n%AI3_EndEncoding AdobeType\n", + "\n%%BeginEncoding: _x x\n[ 39/grave\n/_x/x 0 1 TZ\n%%EndEncoding\n", "800 Ar", "frobnicate", "\n%AI5_BeginLayer\n", @@ -2954,6 +4864,16 @@ fn arb_ai_token() -> impl Strategy { "\n%AI5_BeginRaster\n", "\n%AI5_EndRaster\n", "\n%%BeginData: 12\rXI\n", + // Image operands past 2^25 pixels, of odd 1-bit rows, and past the hard limits: as + // many pixels as a u32 side allows, more samples than the bytes allowed, sizes that + // overflow when multiplied out, and a matrix that maps the box to nothing. + "[1 0 0 1 0 0] 0 0 6000 6000 6000 6000 1 1 0 0 1 0 4 4 0 0 ", + "[1 0 0 1 0 0] 0 0 17 13 17 13 1 1 0 0 1 0 4 4 0 0 ", + "[1 0 0 1 0 0] 0 0 9 9 65536 32769 1 1 0 0 1 0 4 4 0 0 ", + "[1 0 0 1 0 0] 0 0 9 9 23171 23171 8 4 1 0 1 0 4 4 0 0 ", + "[1 0 0 1 0 0] 0 0 9 9 4294967295 4294967295 8 4 1 0 1 0 4 4 0 0 ", + "[1 0 0 1 0 0] 0 0 9 9 1e308 1e308 8 3 1 0 0 0 4 4 0 0 ", + "[0 0 0 0 0 0] 0 0 9 9 46341 46341 1 1 0 0 1 0 4 4 0 0 ", "\n%%EndData\n", "\n%AI5_BeginGradient: (G)\n", "\n%AI14_BeginSymbol\n", @@ -2971,8 +4891,27 @@ fn arb_ai_token() -> impl Strategy { "\n%AI26_EndPlacedObjectPreview\n", "[1 0 0 -1 0 0] 0 0 2 1 4 4 0 (a.png) `", "[1e308 0 0 1e308 0 0] 0 0 -1e308 1e308 4 4 0 (a.png) `", + "\n%_/ArtDictionary :\n%_2 /Int (AI11 PlacedPDFPageIndex) ,\n%_4 /Int (AI11 PlacedPDFCropTo) ,\n%_;\n%_\n", + "\n%_/ArtDictionary :\n%_-1e308 /Real (AI11 PlacedPDFPageIndex) ,\n%_99 /Int (AI11 PlacedPDFCropTo) ,\n%_;\n%_\n", + "\n%_/ArtDictionary :\n%_(2) /String (AI11 PlacedPDFPageIndex) ,\n%_5 /Int (AI11 PlacedPDFCropTo) ,\n%_;\n%_\n", + "\n%AI28_BeginPlacedRelativePath\n", + "\n%AI28_BeginPlacedRelativePath\n(src/)\n%AI28_EndPlacedRelativePath\n", + "\n%AI28_BeginPlacedRelativePath\n(..\\\\..\\\\art\\\\)\n%AI28_EndPlacedRelativePath\n", + "\n%AI28_BeginPlacedRelativePath\n(C:\\\\x\\001)\n%AI28_EndPlacedRelativePath\n", + "\n%_%AI28_BeginPlacedRelativePath\n%_(src/)\n%_%AI28_EndPlacedRelativePath\n", + "\n%AI28_EndPlacedRelativePath\n", "`", "~", + // The version 7 form (§16): an 11-value `` ` `` with no `%AI5_BeginPlace`, its file + // linked or included whole, a nested document and counted data in that. + "[1 0 0 1 10 20] 10 20 50 50 (a.eps) `", + "[0 0 0 0 0 0] 0 0 0 0 (a.eps) `", + "\n%%IncludeFile: a.eps\n", + "\n%%BeginDocument: a.eps\n", + "\n%%EndDocument\n", + "\n%%BeginData: 14 Binary Bytes\n", + "\n%%BeginBinary: 99999999999\n", + "\n%%BeginData: 3 Hex Lines\n", "\n%AI5_EndPlace\n", "Xm", "50 -50 -100 -100 5000 -2000 Xm", @@ -2996,6 +4935,12 @@ fn arb_ai_token() -> impl Strategy { "[1 1] /P X#", "(Adobe Path Blends) 1 0 92 XP", "(Adobe Path Blends) 1 0 999999 XP", + "(Adobe Deform Plugin) 1 0 0 XP", + "%_/ArtDictionary :\n%_131073 /Int (AIDeformOptionsKey) ,\n%_X=\n", + "%_X+\n%_ (AIDeformArtKey) ,\n%_2 /Int (AIDeformStyle) ,\n%_;\n", + "%_1 /Int (AIDeformStyle) ,\n%_9 /Int (DeformStyle) ,\n%_1e308 /Real (DeformValue) ,\n%_;\n", + "%_1 /Bool (AIDeformEditModeKey) ,", + "[1e308 1e308] /Size X#", "\n%44434241010000000000000000000000\n", "\n%0200000041000000000000000000000000000000\n", "\n%4G\n", @@ -3004,6 +4949,18 @@ fn arb_ai_token() -> impl Strategy { "9 () XW", "\n%AI9_BeginArtStyles\n", "\n%AI9_EndArtStyles\n", + "\n%AI9_BeginArtStyleList\n", + "\n%AI9_EndArtStyleList\n", + "(style)\n", + "(st\\)y(le)\n", + "(\\303\\251", + "(style) XW", + "1 () XW", + "6 (style) XW", + "7 (style) XW", + "-1 (style) XW", + "1e308 (style) XW", + "1 (Caf\\351) XW", "/KnownStyle :", "(style) /Name ,", "/ActiveStyle :", @@ -3013,6 +4970,74 @@ fn arb_ai_token() -> impl Strategy { "(Fill Style Filter) 0 0 /Filter ,", "(Adobe Outer Glow) 1 0 /Filter ,", "(Adobe Drop Shadow) 1 0 /Filter ,", + "(PSAdapter_plugin_BsRl) 1 0 /Filter ,", + "/Binary : /ASCII85Decode ,", + "/Binary : /ASCII85Decode ,\n%!!!!\"z~>\n; (data) ,", + "\n%zzzz~>\n", + "; (data) ,", + "8 /Int (dataSize) ,", + "8 /Real (dataSize) ,", + "(Adobe Pathfinder) 1 0 /Filter ,", + "0 /Int (Command) ,", + "0.5 /Real (Mix) ,", + "(Op) /UnicodeString (DisplayString) ,", + "(Adobe Transform) 1 0 /Filter ,", + "(Adobe Free Distort) 1 0 /Filter ,", + "(Adobe Punk and Bloat) 1 0 /Filter ,", + "(Adobe Roughen) 1 0 /Filter ,", + "(Adobe Scribble and Tweak) 1 0 /Filter ,", + "(Adobe Twirl) 1 0 /Filter ,", + "(Adobe Zigzag) 1 0 /Filter ,", + "1e308 /Real (scaleH_Factor) ,", + "-1e308 /Real (rotate_Radians) ,", + "1000 /Int (numCopies) ,", + "8 /Int (pinPoint) ,", + "0 /Bool (scaleLines) ,", + "0 /Bool (transformPatterns) ,", + "0 /Real (src0h) ,", + "1e-300 /Real (src1h) ,", + "-1 /Real (src2v) ,", + "1e308 /Real (dst3v) ,", + "-200 /Real (d_factor) ,", + "3600 /Real (angle) ,", + "1 /Real (absoluteness) ,", + "100 /Real (ridges) ,", + "1e4 /Real (amount) ,", + "0 /Bool (anch) ,", + "(Adobe Inner Glow) 1 0 /Filter ,", + "(Adobe Fuzzy Mask) 1 0 /Filter ,", + "(Adobe Round Corners) 1 0 /Filter ,", + "(Adobe Scribble Fill) 1 0 /Filter ,", + "(Chain Style Filter) 0 0 /Filter ,", + "/Dictionary : /NotRecorded ,", + "; /Dict ;", + "2.5 /Int (blnd) ,", + "99 /Int (csrc) ,", + "1e308 /Int (gtyp) ,", + "1 /Int (gtyp) ,", + "-13 /Real (vert) ,", + "14 /Real (Radius) ,", + "-1e308 /Real (radius) ,", + "67 /Real (Angle) ,", + "0.17 /Real (Scribbliness) ,", + "1e308 /Real (Spacing) ,", + "(x) /String (note) ,", + "1 /Bool (usePSLBlur) ,", + "16 /Int (Adobe Effect Expand Before Version) ,", + "/FillStyle : 0 O\n0 0 0 0 1 0 0 Xa\n0 1 Xd\n/Def ;\n (sclr) ,", + "/FillStyle : 0 O\nBb\n2 (G) 0 0 0 1 1 0 0 1 0 0 Bg\n0 BB\n/Def ;\n (gclr) ,", + "(sclr) ,", + "(Adobe Offset Path) 1 0 /Filter ,", + "(Adobe Outline Type) 1 0 /Filter ,", + "(Adobe Outline Stroke) 1 0 /Filter ,", + "(Chain Style Filter) 0 0 /Filter ,", + "-1e308 /Real (ofst) ,", + "1e999 /Real (ofst) ,", + "2 /Int (jntp) ,", + "7 /Int (jntp) ,", + "NaN /Real (mlim) ,", + "(x) /UnicodeString (mlim) ,", + "0 /Visible ,", "1 /Visible ,", "2 /FillOrStroke ,", "1 /Bool (BSDashAdj) ,", @@ -3028,6 +5053,18 @@ fn arb_ai_token() -> impl Strategy { "/Def ;", "/Execution ;", "[5 5] 1e308 d", + "(Adobe Shape Effects) 1 0 /Filter ,", + "0 /Visible ,", + "(Rectangle) /UnicodeString (DisplayString) ,", + "2 /Int (Shape) ,", + "1e999 /Int (Shape) ,", + "1 /Real (Absolute) ,", + "-1e308 /Real (RelWidth) ,", + "1e5 /Real (RelHeight) ,", + "NaN /Real (AbsWidth) ,", + "0 /Real (AbsHeight) ,", + "-9 /Real (CornerRadius) ,", + "1 /Bool (Absolute) ,", "-0.5 /Real ,", "1.5 /Real ,", "-2 /Real ,", @@ -3038,11 +5075,51 @@ fn arb_ai_token() -> impl Strategy { "\n%\n", "\n%AI5_EndPlace\n", "\n%%PageTrailer\n", + "\n%AI14_BeginSymbol\n(S1)\n0 A 0 Xw 0 Ae\n", + "\n%AI10_EndSymbol\n", + "\n%AI24_BeginSymbolList\n(S1)\n", + "\n%AI24_EndSymbolList\n", + "/SymbolInstance :", + "(S1) /SymbolRef ,", + "/RTransformMatrix", + "5 /Int (AI13PatternRegistrationType) ,", + "; (AI19SymbolAppearanceMap) ,", ]) .prop_map(str::to_string), ] } +/// Text wrap in editing data: an object's dictionary with the wrap options in any order, missing, +/// repeated or of the wrong type, with numbers that aren't finite, nested dictionaries and the kept +/// outline's art; and wraparound groups (`*w` … `*W`), unmatched or nested. +fn arb_ai_wrap_entry() -> impl Strategy { + let value = prop_oneof![ + arb_num(), + Just("nan".to_string()), + Just("inf".to_string()), + Just("-1e999".to_string()), + Just("1e-999".to_string()), + Just("(far)".to_string()), + Just("/Name".to_string()), + Just("[ 1 2 ]".to_string()), + ]; + let ty = prop::sample::select(vec!["/Real", "/Bool", "/Int", "/String", ""]); + let key = prop::sample::select(vec!["AI11TextWrapOffset", "AI11TextWrapInvert", "AI11TextWrapPath", "AI11TextWrapBeingComputed"]); + let entry = (value, ty, key).prop_map(|(v, t, k)| format!("%_{v} {t} ({k}) ,")); + let art = prop::sample::select(vec![ + "%_X=\n%_0 0 m\n%_0 9 L\n%_9 9 L\n%_f\n%_X+\n%_ (AI11TextWrapPath) ,", + "%_X=\n%_X=\n%_0 0 m\n%_f\n%_X+\n%_ (AI11TextWrapPath) ,", + "%_X+\n%_ (AI11TextWrapPath) ,", + "%_/Dictionary :\n%_6 /Real (AI11TextWrapOffset) ,\n%_; (Nested) ,", + "%_/Dictionary :\n%_1 /Bool (AI11TextWrapInvert) ,", + ]) + .prop_map(str::to_string); + let dictionary = prop::collection::vec(prop_oneof![3 => entry, 1 => art], 0..6) + .prop_map(|entries| format!("\n%_/ArtDictionary :\n{}\n%_;\n%_\n", entries.join("\n"))); + let group = prop::sample::select(vec!["*w", "*W", "*w *w", "*W *W", "*w u", "U *W", "*w 1 To", "TO *W"]).prop_map(str::to_string); + prop_oneof![2 => dictionary, 1 => group] +} + /// The testkit's sample editing data, compressed as older `.ai` files compress it. fn ai_sample_compressed() -> Vec { [&b"%AI12_CompressedData"[..], &deflated(&vectorcraft_testkit::ai::sample_data())].concat() @@ -3059,10 +5136,54 @@ fn deflated(data: &[u8]) -> Vec { proptest! { #![proptest_config(config())] + /// Art styles with Convert to Shape whose dictionary holds any of its entries, and unknown ones, + /// as any kind, with any value (huge, tiny, not a number, a string), repeated or left out, shown + /// or hidden, on a path, a group and type, on the whole object or on its fill. + #[test] + fn ai_convert_to_shape_never_panics( + entries in prop::collection::vec(( + prop::sample::select(vec![ + "Shape", "Absolute", "AbsWidth", "AbsHeight", "RelWidth", "RelHeight", "CornerRadius", "DisplayString", "futureKey", + ]), + prop::sample::select(vec!["Int", "Real", "Bool", "UnicodeString", "String"]), + prop_oneof![ + (-1e4f64..1e4).prop_map(|v| v.to_string()), + prop::sample::select(vec!["0", "1", "2", "3", "-1", "0.5", "1e-300", "1e308", "-1e308", "1e999", "NaN", "(x)", ""]).prop_map(str::to_string), + ], + ), 0..16), + visible in any::(), + on_fill in any::(), + ) { + use vectorcraft_testkit::ai; + let keys: String = entries.iter().map(|(k, kind, v)| format!("{v} /{kind} ({k}) ,\n")).collect(); + let basic = |name: &str, body: &str| format!("/BasicFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{body}; /Dict ;\n /Part ,\n"); + let compound = |name: &str, kids: &[String]| format!("/CompoundFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n{};\n /Part ,\n", kids.concat()); + let fill = basic("Fill Style Filter", "/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n"); + let effect = basic("Adobe Shape Effects", &keys).replacen("1 /Visible", if visible { "1 /Visible" } else { "0 /Visible" }, 1); + let bare = compound("Chain Style Filter", &[effect.clone(), basic("Conduit Filter", "")]); + let root = if on_fill { + compound("Chain Style Filter", &[compound("Stack Style Filter", &[compound("Chain Style Filter", &[fill, effect]), basic("Conduit Filter", "")])]) + } else { + compound("Chain Style Filter", &[effect, compound("Stack Style Filter", &[fill, basic("Conduit Filter", "")])]) + }; + let styles = format!("%AI9_BeginArtStyles\n/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{root}/KnownStyle :\n(Bare) /Name ,\n/ActiveStyle :\n{bare}%AI9_EndArtStyles\n"); + let hidden = ai::rect(20.0, 20.0, 80.0, 60.0).replace('\n', "\n%_"); + let art = format!( + "0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{hidden}f\n1 (Fx) XW\n0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_0 Ae\n%_u\n%_{hidden}f\n%_U\n1 (Bare) XW\nu\n/AI11Text :\n1 /FreeUndo ,\n;\n0 0 1 0 k\n{}f\nU\n1 (Fx) XW\n", + ai::rect(20.0, 20.0, 80.0, 60.0), + ai::rect(20.0, 20.0, 80.0, 60.0), + ai::rect(100.0, 20.0, 180.0, 60.0) + ); + let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("L", &art))); + survive("Convert to Shape art style", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("Convert to Shape art style in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + } + /// Hostile editing data in Illustrator EPS and `.ai` files: operators in any order with any /// operands, sections and dictionaries left open, images of any size. #[test] - fn ai_hostile_editing_data_never_panics(tokens in prop::collection::vec(arb_ai_token(), 0..80)) { + fn ai_hostile_editing_data_never_panics(tokens in prop::collection::vec(prop_oneof![8 => arb_ai_token(), 1 => arb_ai_wrap_entry()], 0..80)) { use vectorcraft_testkit::ai; let data = ai::editing_data(200.0, 100.0, &format!("%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n{}\nLB\n", tokens.join(" "))); survive("hostile editing data", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; @@ -3079,6 +5200,271 @@ proptest! { survive("hostile editing data in an EPS of its art's box", || vectorcraft_engine::cmd::fileio::load("x.eps", &boxed).ok().map(|l| l.doc))?; } + /// A group with an Effect › Pathfinder style whose dictionary is hostile: any `Command`, keys of + /// any type and value (missing, repeated, unknown, not finite), shown or hidden, the style cut + /// short anywhere; in editing data, an EPS and a `.ai`. The dictionary may also start with every + /// option at the value read and any `Mix`. A `Command` other than 0 to 11 never becomes a live + /// effect, and a live Soft Mix's Mixing Rate is a number from 1 to 100. + #[test] + fn ai_pathfinder_styles_never_panic( + command in prop_oneof![(-3i64..16).prop_map(|c| c.to_string()), Just("11".to_string()), arb_num()], + defaults in any::(), + bare in any::(), + mix in prop_oneof![arb_num(), prop::sample::select(vec!["0.5", "0.3", "0.01", "0.0099", "1", "1.0001", "NaN", "1e999"]).prop_map(str::to_string)], + keys in prop::collection::vec( + ( + prop::sample::select(vec!["Mix", "Precision", "RemovePoints", "ExtractUnpainted", "ConvertCustom", "TrapTint", "TrapThickness", "Command", "Extra"]), + prop::sample::select(vec!["Int", "Real", "Bool", "String"]), + arb_num(), + ), + 0..16, + ), + hidden in any::(), + cut in 0usize..4_000, + ) { + use vectorcraft_testkit::ai; + let options = if defaults { + format!( + "1 /Bool (ConvertCustom) ,\n1 /Bool (ExtractUnpainted) ,\n{mix} /Real (Mix) ,\n10 /Real (Precision) ,\n0 /Bool (RemovePoints) ,\n\ + 1 /Real (TrapAspect) ,\n0 /Bool (TrapConvertCustom) ,\n1 /Real (TrapMaxTint) ,\n0 /Bool (TrapReverse) ,\n0.25 /Real (TrapThickness) ,\n\ + 0.4 /Real (TrapTint) ,\n0.05 /Real (TrapTintTolerance) ,\n" + ) + } else { + String::new() + }; + // With every option there, the random keys are left out half the time, so the style can be read. + let keys = if defaults && bare { &keys[..0] } else { &keys[..] }; + let dict: String = keys.iter().map(|(k, kind, v)| format!("{v} /{kind} ({k}) ,\n")).collect(); + let dict = format!("{options}{dict}"); + let styles = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(PF) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Adobe Pathfinder) 1 0 /Filter ,\n{} /Visible ,\n/Dictionary : /NotRecorded ,\n{command} /Int (Command) ,\n{dict}; /Dict ;\n /Part ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n\ + %AI9_EndArtStyles\n", + u8::from(!hidden) + ); + let styles: String = styles.chars().take(cut.max(1)).collect(); + let group = "0 Ae\nu\n1 0 0 1 0 0 Xa\n10 10 m\n10 60 L\n80 60 L\n80 10 L\nf\nU\n\ + %_0 Ae\n%_u\n%_1 0 0 1 0 0 Xa\n%_10 10 m\n%_10 50 L\n%_50 50 L\n%_50 10 L\n%_f\n%_0 0 1 0 0 0 1 Xa\n%_40 20 m\n%_40 60 L\n%_80 60 L\n%_80 20 L\n%_f\n%_U\n1 (PF) XW\n"; + let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("L", group))); + let live = command.parse::().is_ok_and(|c| (0.0..=11.0).contains(&c) && c.fract() == 0.0); + let check = |d: Option| { + if let Some(d) = &d { + d.walk(|n| { + let effects = &n.appearance.effects; + assert!(live || !effects.iter().any(|e| e.id.starts_with("pathfinder.")), "Command {command}: {effects:?}"); + for e in effects.iter().filter(|e| e.id == "pathfinder.softMix") { + let rate = e.params.get("mixingRate").and_then(Value::as_f64); + assert!(rate.is_some_and(|r| (1.0..=100.0).contains(&r)), "Mix {mix}: {effects:?}"); + } + }); + } + d + }; + survive("hostile Pathfinder style", || check(Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0)))?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("hostile Pathfinder style in an EPS", || check(vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc)))?; + let file = ai::ai(data.as_bytes(), ai::page_pdf()); + survive("hostile Pathfinder style in a .ai", || check(vectorcraft_engine::cmd::fileio::load("x.ai", &file).ok().map(|l| l.doc)))?; + } + + /// Art styles with Offset Path, Outline Object and Outline Stroke, in any order, shown or hidden, + /// whose dictionaries hold any of Offset Path's entries and unknown ones, as any kind, with any + /// value (huge, tiny, not a number, a string), repeated or left out, on the whole object, a fill + /// or a stroke, of a path, a group and type. + #[test] + fn ai_path_effects_never_panic( + effects in prop::collection::vec(( + prop::sample::select(vec!["Adobe Offset Path", "Adobe Outline Type", "Adobe Outline Stroke"]), + prop::collection::vec(( + prop::sample::select(vec!["ofst", "jntp", "mlim", "width", "DisplayString"]), + prop::sample::select(vec!["Int", "Real", "Bool", "UnicodeString"]), + prop_oneof![ + (-2e5f64..2e5).prop_map(|v| v.to_string()), + prop::sample::select(vec!["0", "1", "2", "3", "-1", "0.5", "1e-300", "1e308", "-1e308", "1e999", "NaN", "(x)", ""]).prop_map(str::to_string), + ], + ), 0..6), + any::(), + ), 0..5), + target in 0..3usize, + ) { + use vectorcraft_testkit::ai; + let basic = |name: &str, body: &str| format!("/BasicFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{body}; /Dict ;\n /Part ,\n"); + let compound = |name: &str, kids: &[String]| format!("/CompoundFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n{};\n /Part ,\n", kids.concat()); + let filters: Vec = effects + .iter() + .map(|(name, entries, visible)| { + let keys: String = entries.iter().map(|(k, kind, v)| format!("{v} /{kind} ({k}) ,\n")).collect(); + basic(name, &keys).replacen("1 /Visible", if *visible { "1 /Visible" } else { "0 /Visible" }, 1) + }) + .collect(); + let fill = basic("Fill Style Filter", "/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n"); + let stroke = basic("Stroke Style Filter", "/StrokeStyle : 0 R\n0 0 0 0 0 0 1 XA\n0 J 0 j 4 w 10 M []0 d0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n"); + let conduit = basic("Conduit Filter", ""); + let chain = |item: String| compound("Chain Style Filter", &[filters.concat(), item, filters.concat()]); + let root = match target { + 0 => compound("Chain Style Filter", &[filters.concat(), compound("Stack Style Filter", &[stroke, fill, conduit])]), + 1 => compound("Chain Style Filter", &[compound("Stack Style Filter", &[stroke, chain(fill), conduit])]), + _ => compound("Chain Style Filter", &[compound("Stack Style Filter", &[chain(stroke), fill, conduit])]), + }; + let styles = format!("%AI9_BeginArtStyles\n/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{root}%AI9_EndArtStyles\n"); + let hidden = ai::rect(20.0, 20.0, 80.0, 60.0).replace('\n', "\n%_"); + let art = format!( + "0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{hidden}f\n1 (Fx) XW\n0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_0 Ae\n%_u\n%_{hidden}f\n%_U\n1 (Fx) XW\nu\n/AI11Text :\n1 /FreeUndo ,\n;\n0 0 1 0 k\n{}f\nU\n1 (Fx) XW\n", + ai::rect(20.0, 20.0, 80.0, 60.0), + ai::rect(20.0, 20.0, 80.0, 60.0), + ai::rect(100.0, 20.0, 180.0, 60.0) + ); + let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("L", &art))); + survive("Path effect art style", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("Path effect art style in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + } + + /// Art styles with a Distort & Transform effect (Transform, Free Distort, Pucker & Bloat, Roughen, + /// Tweak, Twist, Zig Zag) whose dictionary holds any of its entries, and unknown ones, as any kind, + /// with any value (huge, tiny, not a number, a string), repeated or left out, on a path, on type and + /// on a group nested any number of levels around a curved path, stroked or not, on the whole object + /// or on its fill. + #[test] + fn ai_distort_effects_never_panic( + name in prop::sample::select(vec![ + "Adobe Transform", + "Adobe Free Distort", + "Adobe Punk and Bloat", + "Adobe Roughen", + "Adobe Scribble and Tweak", + "Adobe Twirl", + "Adobe Zigzag", + ]), + entries in prop::collection::vec(( + prop::sample::select(vec![ + "scaleH_Factor", "scaleV_Factor", "scaleH_Percent", "rotate_Radians", "rotate_Degrees", "moveH_Pts", "moveV_Pts", + "numCopies", "pinPoint", "reflectX", "reflectY", "randomize", "transformObjects", "transformPatterns", "scaleLines", + "src0h", "src0v", "src1h", "src1v", "src2h", "src2v", "src3h", "src3v", "dst0h", "dst0v", "dst1h", "dst1v", "dst2h", + "dst2v", "dst3h", "dst3v", "d_factor", "absoluteness", "size", "asiz", "dtal", "roundness", "horz", "vert", "ahor", + "aver", "anch", "in", "out", "angle", "amount", "relAmount", "ridges", "futureKey", + ]), + prop::sample::select(vec!["Int", "Real", "Bool"]), + prop_oneof![ + (-1e4f64..1e4).prop_map(|v| v.to_string()), + prop::sample::select(vec!["0", "1", "-1", "0.5", "1e-300", "1e308", "-1e308", "1e999", "NaN", "(x)", ""]).prop_map(str::to_string), + ], + ), 0..24), + on_fill in any::(), + depth in 0usize..300, + stroked in any::(), + ) { + use vectorcraft_testkit::ai; + let keys: String = entries.iter().map(|(k, kind, v)| format!("{v} /{kind} ({k}) ,\n")).collect(); + let basic = |name: &str, body: &str| format!("/BasicFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{body}; /Dict ;\n /Part ,\n"); + let compound = |name: &str, kids: &[String]| format!("/CompoundFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n{};\n /Part ,\n", kids.concat()); + let fill = basic("Fill Style Filter", "/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n"); + let effect = basic(name, &keys); + let root = if on_fill { + compound("Chain Style Filter", &[compound("Stack Style Filter", &[compound("Chain Style Filter", &[fill, effect]), basic("Conduit Filter", "")])]) + } else { + compound("Chain Style Filter", &[compound("Stack Style Filter", &[fill, basic("Conduit Filter", "")]), effect]) + }; + let styles = format!("%AI9_BeginArtStyles\n/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{root}%AI9_EndArtStyles\n"); + let hidden = ai::rect(20.0, 20.0, 80.0, 60.0).replace('\n', "\n%_"); + let paint = if stroked { "0 0 1 0 K\n2 w\nB\n" } else { "f\n" }; + let curve = format!("0 0 1 0 k\n20 70 m\n20 90 80 90 80 70 c\n80 50 20 50 20 70 c\n{paint}"); + let nested = format!("0 Ae\n{}{curve}{}", "u\n".repeat(depth + 1), "U\n".repeat(depth + 1)).replace('\n', "\n%_"); + let art = format!( + "0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{hidden}f\n1 (Fx) XW\nu\n/AI11Text :\n1 /FreeUndo ,\n;\n0 0 1 0 k\n{}f\nU\n1 (Fx) XW\n\ + 0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{nested}1 (Fx) XW\n", + ai::rect(20.0, 20.0, 80.0, 60.0), + ai::rect(100.0, 20.0, 180.0, 60.0), + ai::rect(20.0, 50.0, 80.0, 90.0) + ); + let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("L", &art))); + survive("distort art style", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("distort art style in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + } + + /// Layer options (`Lb`) of any number of operands with any values, and guide paths (`(N) *`, + /// `(S) *`) of any points, among them ones across the whole canvas or from edge to edge of + /// artboards that overlap or are the same, on layers and sublayers. + #[test] + fn ai_layer_options_and_ruler_guides_never_panic( + options in prop::collection::vec(arb_layer_operand(), 0..17), + guides in prop::collection::vec((prop::collection::vec((arb_guide_coord(), arb_guide_coord()), 0..5), any::(), any::()), 0..12), + boards in prop::collection::vec(prop::sample::select(vec![[0.0, 100.0, 200.0, 0.0], [0.0, 100.0, 100.0, 0.0], [50.0, 100.0, 200.0, 0.0]]), 0..4), + ) { + use vectorcraft_testkit::ai; + let board = |b: &[f64; 4]| { + format!( + "%_/Dictionary :\n%_{} {} /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} {} /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n", + b[0], b[1], b[2], b[3] + ) + }; + let array: String = boards.iter().map(board).collect(); + let document = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{array}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"); + let paths: Vec = guides + .iter() + .map(|(points, ruler, sub)| { + let ops: String = points.iter().enumerate().map(|(i, (x, y))| format!("{x} {y} {}\n", if i == 0 { "m" } else { "L" })).collect(); + let path = format!("{ops}({}) *\n", if *ruler { "N" } else { "S" }); + if *sub { format!("%AI5_BeginLayer\n{} Lb\n(Sub) Ln\n{path}LB\n%AI5_EndLayer--\n", options.join(" ")) } else { path } + }) + .collect(); + let body = format!("{document}%AI5_BeginLayer\n{} Lb\n(L) Ln\n{}\nLB\n%AI5_EndLayer--\n", options.join(" "), paths.concat()); + let data = ai::editing_data(200.0, 100.0, &body).replacen("%%EndComments", "%AI3_TemplateBox: 100 50 100 50\n%%EndComments", 1); + survive("layer options and ruler guides", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + survive("layer options and ruler guides in units of 10 points", || { + Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(2000.0, 1000.0), vec![], false, false, 10.0).0) + })?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("layer options and ruler guides in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + } + + /// Artboard display options and Document Raster Effects Settings of any type and value, and + /// header comments (`%%For`, custom colors and their `%%+` lines, `%%TemplateBox`) with any + /// operands. + #[test] + fn ai_document_settings_never_panic( + boards in prop::collection::vec(prop::collection::vec((prop::sample::select(vec!["DisplayMark", "PAR"]), arb_ai_setting()), 0..4), 0..4), + raster in prop::collection::vec((prop::sample::select(vec!["dpi.", "mask", "alis", "spot", "padd", "colr"]), arb_ai_setting()), 0..8), + header in prop::collection::vec( + ( + prop::sample::select(vec!["%%For:", "%%CMYKCustomColor:", "%%RGBCustomColor:", "%%+", "%%TemplateBox:", "%%DocumentCustomColors:"]), + prop::collection::vec(prop_oneof![arb_num(), "\\(?[ -~]{0,12}\\)?".prop_map(|s| s)], 0..6), + ), + 0..10, + ), + ) { + use vectorcraft_testkit::ai; + let entries = |e: &[(&str, String)]| e.iter().map(|(k, v)| format!("%_{v} ({k}) ,\n")).collect::(); + let array: String = boards + .iter() + .enumerate() + .map(|(i, e)| { + format!( + "%_/Dictionary :\n{}%_{} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n", + entries(e), + i * 100, + i * 100 + 100 + ) + }) + .collect(); + let document = format!( + "%_/Document :\n%_/Dictionary :\n%_/Dictionary :\n{}%_; (AI Auto Rasterize) ,\n%_/Array :\n{array}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n", + entries(&raster) + ); + let comments: String = header.iter().map(|(c, ops)| format!("{c} {}\n", ops.join(" "))).collect(); + let body = format!("{document}{}", ai::layer("L", &format!("{}f\n", ai::rect(0.0, 0.0, 10.0, 10.0)))); + let data = ai::editing_data(200.0, 100.0, &body).replacen("%%EndComments", &format!("{comments}%%EndComments"), 1); + survive("document settings", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("document settings in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + // The same comments in the EPS's own header. + let at = eps.windows(13).position(|w| w == b"%%EndComments").unwrap_or(0); + let outer = [&eps[..at], comments.as_bytes(), &eps[at..]].concat(); + survive("document settings in an EPS's header", || vectorcraft_engine::cmd::fileio::load("x.eps", &outer).ok().map(|l| l.doc))?; + } + /// The testkit's sample damaged, as it is and compressed, in EPS, `.ai` and PDF files. #[test] fn ai_mutated_sample_never_panics(cut in 0usize..4_000, edits in prop::collection::vec((0usize..4_000, any::()), 0..12)) { @@ -3100,6 +5486,53 @@ proptest! { survive(what, || vectorcraft_engine::cmd::fileio::load("x.eps", &file).ok().map(|l| l.doc))?; } } + + /// A filter-gallery effect's settings block in an art style: fields of any key, marker, type and + /// value, objects nested in objects, any version and `dataSize`, and its ASCII85 lines damaged or cut. + #[test] + fn ai_filter_gallery_settings_never_panic( + fields in prop::collection::vec(arb_settings_field(), 0..8), + inner in prop::collection::vec(arb_settings_field(), 0..4), + nesting in 0usize..4, + version in prop_oneof![Just(1u32), any::()], + size in prop_oneof![Just(None), any::().prop_map(Some)], + cut in 0usize..600, + edits in prop::collection::vec((0usize..600, prop::sample::select(vec!['%', '~', '>', 'z', 'v', '!', 'u', '\n', ';', ' '])), 0..6), + ) { + use vectorcraft_testkit::ai; + let object = |body: Vec| [&b"Objc"[..], &0x8000_0000u32.to_be_bytes(), b"Clss", &(body.len() as u32 + 4).to_be_bytes(), &1u32.to_be_bytes(), &body].concat(); + let mut nested = inner.concat(); + for _ in 0..nesting { + nested = object(nested); + } + let data = [version.to_be_bytes().to_vec(), fields.concat(), nested].concat(); + let lines: String = ascii85(&data).as_bytes().chunks(60).map(|c| format!("%{}\n", String::from_utf8_lossy(c))).collect(); + let size = size.unwrap_or(data.len() as i64); + let block = mutate_text(&format!("/Binary : /ASCII85Decode ,\n{lines}; (data) ,\n{size} /Int (dataSize) ,\n"), cut, &edits); + let styles = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(R) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(PSAdapter_plugin_BsRl) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{block}; /Dict ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ); + let hidden = ai::rect(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + let art = format!("0 Ae\nu\n0 1 1 0 1 0 0 Xa\n{}f\nU\n%_{hidden}f\n1 (R) XW\n", ai::rect(0.0, 0.0, 10.0, 10.0)); + let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("L", &art))); + survive("filter-gallery settings", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("filter-gallery settings in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + } +} + +/// A field of a filter-gallery settings descriptor: a key, a marker, a type and a value, each one +/// that is read or anything else. +fn arb_settings_field() -> impl Strategy> { + let key = prop_oneof![prop::sample::select(vec![*b"GEfk", *b"Dtl ", *b"Smth", *b"LghD", *b"Xtra"]), any::<[u8; 4]>()]; + let marker = prop_oneof![Just(0u32), Just(0x2000), Just(0x8000_0000), any::()]; + let kind = prop_oneof![prop::sample::select(vec![*b"long", *b"doub", *b"bool", *b"LghD", *b"GEft"]), any::<[u8; 4]>()]; + let value = prop_oneof![ + prop::sample::select(vec![b"LDBt".to_vec(), b"BsRl".to_vec(), 8i32.to_be_bytes().to_vec(), vec![1], f64::NAN.to_be_bytes().to_vec()]), + prop::collection::vec(any::(), 0..12), + ]; + (key, marker, kind, value).prop_map(|(k, m, t, v)| [&k[..], &m.to_be_bytes(), &t, &v].concat()) } // ---------- font files a folder search reads ---------- @@ -3752,24 +6185,52 @@ fn pdf_streams_the_reader_would_fail_on_are_refused() { }; let spaces = calculator(&spaces_past_the_cap(), ""); let program = deflated(b"{ dup 1 exch sub 0 }"); + // The message names the stream, so a report of a file that can't be shared says which (#4366). + let (parameters, cap) = ("has decode parameters that can't be applied", "would decode to more than 256 MB"); let files = [ - ("a form with Columns 0", form(zero, "0 0 5 5 re f")), - ("a form with a huge Columns", form(huge, "0 0 5 5 re f")), - ("an inline image with Columns 0", deep_pdf(&inline("<< /Predictor 2 /Columns 0 >>"), "<< >>")), - ("an inline image with a huge Columns", deep_pdf(&inline("<< /Predictor 15 /Columns 99999999999 >>"), "<< >>")), - ("an inline image in a compressed form", form("", &inline("<< /Predictor 2 /Columns 0 >>"))), - ("an object stream with Columns 0", pdf_with_object_stream("[0 0 100 100]", zero)), - ("a form of spaces past the cap", pdf_with("/F Do", "<< /XObject << /F 5 0 R >> >>", &[packed_as_is(FORM, &spaces_past_the_cap())])), - ("a function of spaces past the cap in an array", held(format!("[{spaces}]"))), - ("a function of spaces past the cap in a dictionary", held(format!("<< /K {spaces} >>"))), - ("a function of spaces past the cap in a shading", shaded(&spaces)), - ("a function with Columns 0 in an array", held(format!("[{}]", calculator(&program, "/DecodeParms [null << /Predictor 2 /Columns 0 >>]")))), + ("a form with Columns 0", form(zero, "0 0 5 5 re f"), format!("a form in it (object 5) {parameters}")), + ("a form with a huge Columns", form(huge, "0 0 5 5 re f"), format!("a form in it (object 5) {parameters}")), + ( + "an inline image with Columns 0", + deep_pdf(&inline("<< /Predictor 2 /Columns 0 >>"), "<< >>"), + format!("an inline image in the content of object 4 {parameters}"), + ), + ( + "an inline image with a huge Columns", + deep_pdf(&inline("<< /Predictor 15 /Columns 99999999999 >>"), "<< >>"), + format!("an inline image in the content of object 4 {parameters}"), + ), + ( + "an inline image in a compressed form", + form("", &inline("<< /Predictor 2 /Columns 0 >>")), + format!("an inline image in the content of object 5 {parameters}"), + ), + // Read as the file opens, before its objects can be looked at one by one. + ( + "an object stream with Columns 0", + pdf_with_object_stream("[0 0 100 100]", zero), + format!("a stream in it {cap}, or its decode parameters can't be applied"), + ), + ( + "a form of spaces past the cap", + pdf_with("/F Do", "<< /XObject << /F 5 0 R >> >>", &[packed_as_is(FORM, &spaces_past_the_cap())]), + format!("a form in it (object 5) {cap}"), + ), + // A function written inside object 5 goes by it. + ("a function of spaces past the cap in an array", held(format!("[{spaces}]")), format!("a stream in it (object 5) {cap}")), + ("a function of spaces past the cap in a dictionary", held(format!("<< /K {spaces} >>")), format!("a stream in it (object 5) {cap}")), + ("a function of spaces past the cap in a shading", shaded(&spaces), format!("a stream in it (object 5) {cap}")), + ( + "a function with Columns 0 in an array", + held(format!("[{}]", calculator(&program, "/DecodeParms [null << /Predictor 2 /Columns 0 >>]"))), + format!("a stream in it (object 5) {parameters}"), + ), ]; on_a_small_stack(move || { - for (what, bytes) in &files { + for (what, bytes, why) in &files { for name in ["hostile.pdf", "hostile.ai"] { let e = vectorcraft_engine::cmd::fileio::load(name, bytes).err().map(|e| e.to_string()); - assert!(e.as_deref().is_some_and(|e| e.contains("would decode to more than 256 MB")), "{what} as {name}: {e:?}"); + assert!(e.as_deref().is_some_and(|e| e.contains(why.as_str())), "{what} as {name}: {e:?}"); } } }); @@ -3781,6 +6242,112 @@ fn pdf_streams_the_reader_would_fail_on_are_refused() { } } +/// A page drawing a thousand times one form that decodes to 64 MiB (of spaces, then a square): +/// each drawing reads the form again, so the import stops at the page's form content instead of +/// decoding 64 GB (#3569, which hung). +#[test] +fn pdf_a_huge_form_drawn_over_and_over_is_refused_in_bounded_time() { + use std::io::Write as _; + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + for _ in 0..64 { + e.write_all(&[b' '; 1 << 20]).unwrap(); + } + e.write_all(b"0 0 5 5 re f").unwrap(); + let form = packed_as_is(FORM, &e.finish().unwrap()); + let bytes = pdf_with(&"/F Do ".repeat(1000), "<< /XObject << /F 5 0 R >> >>", &[form]); + let start = std::time::Instant::now(); + let e = vectorcraft_engine::cmd::fileio::load("repeated.pdf", &bytes).err().map(|e| e.to_string()); + let took = start.elapsed(); + assert!(e.as_deref().is_some_and(|e| e.contains("no document was imported")), "{e:?}"); + assert!(took < std::time::Duration::from_secs(60), "took {took:?}"); +} + +// A large file the reader would fail on says which stream (#4366): an image with its size in +// pixels, a page's content, or the editing data an `.ai` keeps in its first page's `PieceInfo`. +#[test] +fn a_stream_past_the_cap_is_named() { + let image = "/Type /XObject /Subtype /Image /Width 10 /Height 10 /ColorSpace /DeviceRGB /BitsPerComponent 8"; + let page = |contents: &str, entries: &str| { + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents {contents} /Resources << /XObject << /Im 5 0 R >> >> {entries} >>") + .into_bytes() + }; + let plain = |content: &str| format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len() + 1).into_bytes(); + let pdf = |page: Vec, more: Vec>| { + let head = [b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), page]; + pdf_of(&head.into_iter().chain(more).collect::>()) + }; + let spaces = spaces_past_the_cap(); + let editing = "/PieceInfo << /Illustrator << /Private << /AIPrivateData1 6 0 R /NumBlock 1 >> >> >>"; + let files = [ + ( + "an image", + pdf(page("4 0 R", ""), vec![plain("q 10 0 0 10 0 0 cm /Im Do Q"), packed_as_is(image, &spaces)]), + "an image of 10 × 10 px in it (object 5) would decode to more than 256 MB", + ), + ( + "a page's content", + pdf(page("4 0 R", ""), vec![packed_as_is("", &spaces), packed(image, "\0\0\0")]), + "a page's content in it (object 4) would decode to more than 256 MB", + ), + ( + "a page's content in an array", + pdf(page("[4 0 R]", ""), vec![packed_as_is("", &spaces), packed(image, "\0\0\0")]), + "a page's content in it (object 4) would decode to more than 256 MB", + ), + ( + "a page's content in an array of its own", + pdf(page("6 0 R", ""), vec![packed_as_is("", &spaces), packed(image, "\0\0\0"), b"[4 0 R]".to_vec()]), + "a page's content in it (object 4) would decode to more than 256 MB", + ), + ( + "the editing data", + pdf(page("4 0 R", editing), vec![plain("0 0 5 5 re f"), packed(image, "\0\0\0"), packed_as_is("", &spaces)]), + "its editing data (object 6) would decode to more than 256 MB", + ), + ]; + on_a_small_stack(move || { + for (what, bytes, why) in &files { + for name in ["large.pdf", "large.ai"] { + let e = vectorcraft_engine::cmd::fileio::load(name, bytes).err().map(|e| e.to_string()); + assert!(e.as_deref().is_some_and(|e| e.contains(why)), "{what} as {name}: {e:?}"); + } + } + }); +} + +// Pages that share one `Contents` array, the array an object of its own: its stream is named as +// a page's content, and a refused stream elsewhere is still found past the pages (#4612 review). +#[test] +fn pages_sharing_a_contents_array_name_its_stream() { + let image = "/Type /XObject /Subtype /Image /Width 10 /Height 10 /ColorSpace /DeviceRGB /BitsPerComponent 8"; + let plain = |content: &str| format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len() + 1).into_bytes(); + let spaces = spaces_past_the_cap(); + // 1 catalog, 2 pages, 3 the shared array, 4 its stream, 5 to 7 the pages, 8 an image they draw. + let pdf = |content: Vec, image: Vec| { + let page = b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 3 0 R /Resources << /XObject << /Im 8 0 R >> >> >>"; + let head = [ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [5 0 R 6 0 R 7 0 R] /Count 3 >>".to_vec(), + b"[4 0 R]".to_vec(), + content, + ]; + pdf_of(&head.into_iter().chain([page.to_vec(), page.to_vec(), page.to_vec(), image]).collect::>()) + }; + let files = [ + (pdf(packed_as_is("", &spaces), packed(image, "\0\0\0")), "a page's content in it (object 4) would decode to more than 256 MB"), + ( + pdf(plain("q 10 0 0 10 0 0 cm /Im Do Q"), packed_as_is(image, &spaces)), + "an image of 10 × 10 px in it (object 8) would decode to more than 256 MB", + ), + ]; + on_a_small_stack(move || { + for (bytes, why) in &files { + let e = vectorcraft_engine::cmd::fileio::load("shared.pdf", bytes).err().map(|e| e.to_string()); + assert!(e.as_deref().is_some_and(|e| e.contains(why)), "{why}: {e:?}"); + } + }); +} + #[test] fn pdf_art_that_draws_itself() { let own = "<< /XObject << /F 5 0 R >> /Pattern << /P 5 0 R >> /Font << /F1 5 0 R >> /ExtGState << /G << /SMask << /S /Alpha /G 5 0 R >> >> >> >>"; @@ -3960,7 +6527,7 @@ fn brushed_document(kind: usize, art: usize) -> Document { Node::path(doc.alloc_id(), square(), Appearance::basic(fill, Paint::None, 0.0)) }; let (in_symbol, in_pattern) = (brushed(&mut doc), brushed(&mut doc)); - doc.symbols.push(Symbol { name: "s0".into(), art: std::sync::Arc::new(in_symbol) }); + doc.symbols.push(Symbol { dynamic: false, name: "s0".into(), art: std::sync::Arc::new(in_symbol) }); doc.patterns.push(PatternDef::new("p0", vec![std::sync::Arc::new(in_pattern)])); let art = match art { 0 => instance(&mut doc), @@ -4150,7 +6717,7 @@ fn symbols_document(count: usize, levels: usize, last: &str) -> Document { for _ in 0..levels { art = Node::group(doc.alloc_id(), vec![std::sync::Arc::new(art)]); } - doc.symbols.push(Symbol { name: format!("s{i}"), art: std::sync::Arc::new(art) }); + doc.symbols.push(Symbol { dynamic: false, name: format!("s{i}"), art: std::sync::Arc::new(art) }); } let first = instance(&mut doc, "s0".into()); let layer = doc.layers[0].id; @@ -4268,8 +6835,15 @@ fn a_long_thin_shape_with_a_shadow_renders_and_exports() { /// A blend in `.ai` editing data, written by hand: two keys (10 pt squares, red on the left, blue on /// the right) on a straight spine, `steps` steps drawn between them as the blend lays them out, and -/// the record (`DCBA`, version 1, two keys `A` and `B`, see `vectorcraft_eps`' AI blend reader). +/// the record (`DCBA`, Specified Steps, two keys `A` and `B`, see `vectorcraft_eps`' AI blend +/// reader). fn blend_text(steps: usize) -> String { + blend_text_spaced(steps, [1, 0, 0]) +} + +/// [`blend_text`] with the record's spacing words `spacing`: the spacing (word 1), the bits of the +/// distance (word 2, a 32-bit float) and word 4. +fn blend_text_spaced(steps: usize, spacing: [u32; 3]) -> String { use std::fmt::Write; let square = |x: f64, hidden: bool, t: f64| { let p = if hidden { "%_" } else { "" }; @@ -4293,7 +6867,8 @@ fn blend_text(steps: usize) -> String { s += &square(t * span, false, t); } s += "U\n9 () XW\n0 Ae\n"; - let mut words: Vec = vec![u32::from_le_bytes(*b"DCBA"), 1, 0, 0, 0, 0, 0, 0, 0, 0, 2]; + let [kind, distance, count] = spacing; + let mut words: Vec = vec![u32::from_le_bytes(*b"DCBA"), kind, distance, 0, count, 0, 0, 0, 0, 0, 2]; for id in ['A', 'B'] { words.extend([id as u32, 0, 0, 0, 0, 0]); } @@ -4341,4 +6916,51 @@ proptest! { survive("a .ai blend far out", || Some(vectorcraft_eps::layered_ai(&far, Document::new(100.0, 100.0), vec![], false, true, 1.0).0))?; survive("mutated .ai blend", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0).0))?; } + + /// A `.ai` blend whose record holds any spacing, distance bits (zero, negative, tiny, NaN, + /// infinite) and step count: read live, as its drawn steps, or not at all, never panicking. + #[test] + fn ai_blend_spacing_never_panics(steps in 1usize..6, kind in prop_oneof![0u32..4, any::()], distance in prop_oneof![any::(), prop::sample::select(vec![0u32, 0x8000_0000, 1, 0x7f80_0000, 0xff80_0000, 0x7fc0_0000, 0x7f7f_ffff, 0x41c8_0000])], count in prop_oneof![0u32..1_100, any::()]) { + let private = ai_private(&blend_text_spaced(steps, [kind, distance, count])); + survive("a .ai blend's spacing", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0).0))?; + } +} + +/// A graph in `.ai` editing data, written by hand from the version 7 specification's chapter 17: +/// its data and settings on `%_` lines (cells, strings, an array, a name), then its drawn art, a bar +/// with its `Go` tag and an empty group, in a group. +fn graph_text() -> String { + "%_Gs\n%_10 10 110 90 Gb\n%_3 0 0 12 1 1 0 0 2 30 0 Gy\n%_6 1 1 0 80 70 0 50 60 80 70 Gd\n%_0 1 Gj\n\ + %_1 () Ga 0 12 0 0 0 0 0 () 0 0 GA\n%_40 Gw\n%_2 2 1 1 Gz\n%_() Gc (East) Gc (Q1) Gc 7 Gc GC\n\ + %_Gt\n%_(Bars) GD [1 2 3] 0 Ge\n%_/Name 1 Gi\n%_0.5 G\n%_0 g\n%_GT\n\ + u\n0 0 0 1 k\n10 10 m\n10 50 L\n30 50 L\n30 10 L\nf\n%_2 0 0 0 Go\nu\nU\nU\n%_GS\n" + .to_string() +} + +proptest! { + #![proptest_config(config())] + + /// A `.ai` graph whose records are damaged, cut or hostile never panics. With only the numbers + /// in its records changed, the records keep their shape, and the bar still comes in. + #[test] + fn ai_graph_never_panics(cut in 0usize..700, edits in prop::collection::vec((0usize..700, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '[', ']', '/', '%', '_', 'G', 's', 'S', 't', 'T', 'u', 'U'])), 0..12), digits in prop::collection::vec((0usize..600, 0u8..10), 0..12)) { + let text = mutate_text(&graph_text(), cut, &edits); + let private = ai_private(&text); + survive("mutated .ai graph", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0).0))?; + let src = graph_text(); + let records = src.find("u\n0 0 0 1 k").unwrap_or(0).max(1); + let mut kept: Vec = src.chars().collect(); + for (at, d) in digits { + if let Some(c) = kept.get_mut(at % records).filter(|c| c.is_ascii_digit()) { + *c = char::from(b'0' + d); + } + } + let (doc, notes, read) = vectorcraft_eps::layered_ai(&ai_private(&kept.into_iter().collect::()), Document::new(4000.0, 200.0), vec![], false, true, 1.0); + prop_assert!(read, "{:?}", notes); + let mut paths = 0; + doc.walk(|n| paths += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }))); + prop_assert_eq!(paths, 1, "{:?}", notes); + prop_assert!(notes.iter().any(|n| n.contains("graphs come in as plain art")), "{:?}", notes); + prop_assert!(!notes.iter().any(|n| n.contains("art this can't read")), "the records aren't art: {:?}", notes); + } } diff --git a/crates/engine/tests/it/affinity_features.rs b/crates/engine/tests/it/affinity_features.rs index cfabffc9a7..511fbb25fe 100644 --- a/crates/engine/tests/it/affinity_features.rs +++ b/crates/engine/tests/it/affinity_features.rs @@ -702,3 +702,21 @@ fn objects_beyond_the_document_range_are_left_out() { assert!(names.iter().any(|n| n == "Magenta box") && !names.iter().any(|n| n == "Far box"), "{names:?}"); assert!(loaded.warnings.iter().any(|w| w.contains("beyond the document range")), "{:?}", loaded.warnings); } + +#[test] +fn test_af_g_symbol_fill_is_white() { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test.af"); + let Ok(bytes) = std::fs::read(&path) else { + return; + }; + let loaded = vectorcraft_engine::cmd::fileio::load("test.af", &bytes).unwrap(); + assert!(!loaded.preview_only, "{:?}", loaded.warnings); + let d = &loaded.doc; + // The visible "g41" group holds the "g" symbol (path43). + let g41 = all(d).into_iter().find(|n| n.visible && n.name.as_deref() == Some("g41")).expect("visible g41 group must be present"); + let path43 = g41.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("path43"))).expect("path43 inside g41 must be present"); + let Some(AppearanceItem::Fill(fill)) = path43.appearance.items.first() else { + panic!("path43 has no fill: {:?}", path43.appearance); + }; + assert_eq!(fill.paint, Paint::solid(Color::rgb(1.0, 1.0, 1.0)), "The 'g' symbol must have a white fill in test.af, got {:?}", fill.paint); +} diff --git a/crates/engine/tests/it/clear_commands.rs b/crates/engine/tests/it/clear_commands.rs index 50a6fbd86d..3b7fb79e94 100644 --- a/crates/engine/tests/it/clear_commands.rs +++ b/crates/engine/tests/it/clear_commands.rs @@ -202,3 +202,24 @@ fn cut_direct_selected_anchors_retains_anchor_deletion() { assert_eq!(s.active().unwrap().doc.node(a).unwrap().path_data().unwrap().anchor_count(), 3); assert_eq!(s.active().unwrap().doc.parent_of(b), Some(c)); } + +#[test] +fn clear_explicit_ids_preserves_unrelated_selection() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r1 = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap()); + let r2 = NodeId(s.execute("shape.rectangle", &json!({"x": 50, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [r1.0, r2.0]})).unwrap(); + assert_eq!(s.active().unwrap().selection.objects, vec![r1, r2]); + + // Clearing r1 explicitly should remove r1 from doc and from selection, keeping r2 selected. + s.execute("edit.clear", &json!({"ids": [r1.0]})).unwrap(); + assert!(s.active().unwrap().doc.node(r1).is_none()); + assert!(s.active().unwrap().doc.node(r2).is_some()); + assert_eq!(s.active().unwrap().selection.objects, vec![r2]); + + // Parameterless clear clears the rest of the selection. + s.execute("edit.clear", &json!({})).unwrap(); + assert!(s.active().unwrap().doc.node(r2).is_none()); + assert!(s.active().unwrap().selection.is_empty()); +} diff --git a/crates/engine/tests/it/copy_direct_selection.rs b/crates/engine/tests/it/copy_direct_selection.rs new file mode 100644 index 0000000000..d34b342934 --- /dev/null +++ b/crates/engine/tests/it/copy_direct_selection.rs @@ -0,0 +1,806 @@ +//! Direct-selection Copy and Cut tests (#2122). + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_engine::Session; +use vectorcraft_geom::FillRule; +use vectorcraft_testkit::invariants::check_session; + +fn run(s: &mut Session, command: &str, params: Value) -> Value { + s.execute(command, ¶ms).unwrap() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].as_u64().unwrap()) +} + +#[test] +fn copy_and_paste_direct_selected_segment_of_rect() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Select segment 0 of the rectangle. + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + if let NodeKind::Path { live, .. } = &pasted_node.kind { + assert!(live.is_none(), "extracted partial path must not retain live shape metadata"); + } + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.len(), 2); +} + +#[test] +fn copy_and_paste_direct_selected_adjacent_anchors_of_rect() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Direct-select two adjacent anchors: 0 and 1. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.len(), 2); +} + +#[test] +fn copy_single_anchor_of_rect_copies_three_anchors_with_two_segments() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Direct-select only anchor 1 of the closed 4-anchor rectangle. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + // Copying a single anchor on a closed path copies the anchor and both its incident segments. + assert_eq!(sp.anchors.len(), 3); + assert_eq!(sp.segment_count(), 2); +} + +#[test] +fn copy_disjoint_segments_does_not_copy_unselected_segment_in_between() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Rectangle has 4 segments (0, 1, 2, 3). Select disjoint segments 0 and 2. + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0], [0, 2]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + // Two separate open path pieces should be created, each with 2 anchors. + assert_eq!(ids.len(), 2); + for id in ids { + let node = s.doc().unwrap().doc.node(NodeId(id)).unwrap(); + let path = node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.len(), 2); + } +} + +#[test] +fn cut_direct_selected_segment_cuts_source_and_pastes_segment() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Select segment 0 and cut it. + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0]]})); + run(&mut s, "edit.cut", json!({})); + + // Source rectangle should now have segment 0 removed, turning it into an open path. + let src_node = s.doc().unwrap().doc.node(r).unwrap(); + let src_path = src_node.path_data().unwrap(); + assert_eq!(src_path.subpaths.len(), 1); + assert!(!src_path.subpaths[0].closed); + + // Paste the cut segment: + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let pasted_path = pasted_node.path_data().unwrap(); + assert_eq!(pasted_path.subpaths.len(), 1); + assert!(!pasted_path.subpaths[0].closed); + assert_eq!(pasted_path.subpaths[0].anchors.len(), 2); +} + +#[test] +fn copy_compound_path_direct_selected_segment_inherits_appearance() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + + // Select segment 0 of the inner member. + run(&mut s, "select.segments", json!({"id": inner.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let compound_node = s.doc().unwrap().doc.node(compound).unwrap(); + assert_eq!(pasted_node.appearance, compound_node.appearance); +} + +#[test] +fn direct_selection_copy_preserves_fill_rule_and_attributes() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + run(&mut s, "path.setFillRule", json!({"rule": "evenOdd"})); + + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + assert!(matches!(pasted_node.kind, NodeKind::Path { rule: FillRule::EvenOdd, .. })); +} + +#[test] +fn pen_tool_drawing_copies_whole_path_not_single_anchor() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + // Start drawing with Pen tool + s.select_tool("pen", vectorcraft_engine::ViewInfo::default()).unwrap(); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 50})); + + // Pen tool has the last anchor in sel.anchors, but active tool is pen + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + // The whole 3-point path must be copied, not just the last anchor! + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths[0].anchors.len(), 3); +} + +#[test] +fn cut_adjacent_anchors_clipboard_plus_remaining_equals_original() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Direct-select two adjacent anchors: 1 and 2 of the 4-anchor rectangle. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1], [0, 2]], "mode": "set"})); + run(&mut s, "edit.cut", json!({})); + + // Cut placed 1 segment on the clipboard (anchors 1 to 2). + assert_eq!(s.clipboard.nodes.len(), 1); + let clip_path = s.clipboard.nodes[0].path_data().unwrap(); + assert_eq!(clip_path.subpaths[0].segment_count(), 1); + assert_eq!(clip_path.subpaths[0].anchors.len(), 2); + + // Remaining source path must have the remaining 3 segments (segments 0, 2, 3), not 1. + let src_node = s.doc().unwrap().doc.node(r).unwrap(); + let src_path = src_node.path_data().unwrap(); + assert_eq!(src_path.subpaths[0].segment_count(), 3); + assert_eq!(src_path.subpaths[0].anchors.len(), 4); + assert!(!src_path.subpaths[0].closed); + + // Sum of segments in clipboard + remaining = 1 + 3 = 4 (the original 4 segments). + assert_eq!(clip_path.subpaths[0].segment_count() + src_path.subpaths[0].segment_count(), 4); +} + +#[test] +fn copy_non_adjacent_anchors_on_rect_copies_full_object() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Select non-adjacent anchors 1 and 3 of the 4-anchor rectangle. + // Incident segments for anchor 1 are segments 0 and 1; for anchor 3 are segments 2 and 3. + // Together they cover all 4 segments, so the path is copied whole. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1], [0, 3]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + if let NodeKind::Path { live, .. } = &pasted_node.kind { + assert!(live.is_some(), "copying all segments keeps live shape metadata"); + } + let path = pasted_node.path_data().unwrap(); + assert!(path.subpaths[0].closed); + assert_eq!(path.subpaths[0].segment_count(), 4); +} + +#[test] +fn copy_non_adjacent_anchors_on_five_point_path_extracts_selected_segments() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 60, "y": 50})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 30, "y": 80})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 10, "y": 50})); + run(&mut s, "path.close", json!({"id": id.0})); + + // Path has 5 anchors (0..4) and 5 segments (0..4). + // Select non-adjacent anchors 1 and 3. + // Anchor 1 gives segments 0, 1. Anchor 3 gives segments 2, 3. Segment 4 is unselected. + run(&mut s, "select.anchors", json!({"id": id.0, "anchors": [[0, 1], [0, 3]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert!(!path.subpaths[0].closed); + assert_eq!(path.subpaths[0].segment_count(), 4); + assert_eq!(path.subpaths[0].anchors.len(), 5); +} + +#[test] +fn copy_when_all_segments_selected_preserves_live_shape() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Select all 4 segments explicitly (like Select > Object > Direction Handles). + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0], [0, 1], [0, 2], [0, 3]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + if let NodeKind::Path { live, .. } = &pasted_node.kind { + assert!(live.is_some(), "all segments selected preserves live shape"); + } +} + +#[test] +fn compound_member_selected_whole_with_direct_selection_promotes_member() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + let standalone = rect(&mut s, 120.0, 10.0, 50.0, 50.0); + + // Select outer compound member whole, and direct-select anchor 0 on standalone. + let outer_anchors: Vec> = (0..4).map(|i| vec![0, i]).collect(); + run( + &mut s, + "select.anchorsMany", + json!({ + "items": [ + {"id": outer.0, "anchors": outer_anchors}, + {"id": standalone.0, "anchors": [[0, 0]]} + ] + }), + ); + + // outer is selected whole, standalone is partially selected. + assert!(s.active().unwrap().selection.partial(outer).is_none()); + assert!(s.active().unwrap().selection.partial(standalone).is_some()); + + run(&mut s, "edit.copy", json!({})); + // Clipboard should have: + // 1. The compound path (outer promoted to compound #786) + // 2. The extracted segment piece from standalone + let clip_ids: Vec = s.clipboard.nodes.iter().map(|n| n.id).collect(); + assert_eq!(clip_ids.len(), 2, "promoted compound plus the extracted standalone piece"); + assert!(clip_ids.contains(&compound), "whole compound member must be promoted to compound parent"); +} + +#[test] +fn cut_whole_compound_member_with_direct_selection_cuts_compound_and_extracted_piece() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + let standalone = NodeId(run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50}))["id"].as_u64().unwrap()); + + let outer_anchors = (0..4).map(|i| vec![0, i]).collect::>(); + run( + &mut s, + "select.anchorsMany", + json!({ + "items": [ + {"id": outer.0, "anchors": outer_anchors}, + {"id": standalone.0, "anchors": [[0, 0]]} + ] + }), + ); + + run(&mut s, "edit.cut", json!({})); + let clip_ids: Vec = s.clipboard.nodes.iter().map(|n| n.id).collect(); + assert_eq!(clip_ids.len(), 2, "promoted compound plus the extracted standalone piece"); + assert!(clip_ids.contains(&compound), "whole compound member must be promoted to compound parent"); + + // Compound was removed because member was selected whole + let doc = &s.doc().unwrap().doc; + assert!(doc.node(compound).is_none(), "compound path must be removed on cut"); + // Standalone has cut pieces remaining + assert!(doc.node(standalone).is_some(), "partially cut standalone path remains"); +} + +#[test] +fn cut_direct_selected_only_path_in_layer_preserves_layer() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + // Create a new layer + let layer_id = NodeId(run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap()); + // Create a path inside the layer + let rect = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50}))["id"].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(rect), Some(layer_id)); + + // Direct-select all 4 anchors of rect and cut + let all_anchors = (0..4).map(|i| vec![0, i]).collect::>(); + run(&mut s, "select.anchors", json!({"id": rect.0, "anchors": all_anchors, "mode": "set"})); + run(&mut s, "edit.cut", json!({})); + + // The rect was cut, but the layer must NOT be deleted + let doc = &s.doc().unwrap().doc; + assert!(doc.node(rect).is_none(), "rect was cut"); + assert!(doc.node(layer_id).is_some(), "layer must remain even when empty"); + assert_eq!(doc.node(layer_id).unwrap().children().unwrap().len(), 0); +} + +#[test] +fn copy_and_paste_path_in_compound_path_isolation_adds_member_to_compound() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Enter isolation mode on the compound path. + run(&mut s, "object.isolate", json!({"id": compound.0})); + assert_eq!(s.doc().unwrap().isolation, Some(compound)); + + // In isolation mode, select member `inner` whole. + run(&mut s, "select.set", json!({"ids": [inner.0]})); + run(&mut s, "edit.copy", json!({})); + + // Clipboard copies the selected member path, NOT the entire compound path. + assert_eq!(s.clipboard.nodes.len(), 1); + assert_eq!(s.clipboard.nodes[0].id, inner); + + // Paste in isolation mode: the pasted path must be inserted into the compound path, + // not as a new path beside the compound path. + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + let pasted_id = NodeId(ids[0]); + + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(pasted_id), Some(compound), "pasted path must be added to the compound path"); + let compound_node = doc.node(compound).unwrap(); + assert_eq!(compound_node.children().unwrap().len(), 3, "compound path now has 3 member paths"); +} + +#[test] +fn cut_and_paste_direct_selected_anchors_in_compound_path_isolation() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Enter isolation mode on the compound path. + run(&mut s, "object.isolate", json!({"id": compound.0})); + + // Direct-select anchor 0 of `inner` and cut. + run(&mut s, "select.anchors", json!({"id": inner.0, "anchors": [[0, 0]], "mode": "set"})); + run(&mut s, "edit.cut", json!({})); + + // Clipboard holds the cut segment piece. + assert_eq!(s.clipboard.nodes.len(), 1); + + // Paste inside isolation mode: + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + let pasted_id = NodeId(ids[0]); + + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(pasted_id), Some(compound), "cut and pasted anchors must be inserted into compound path"); + let compound_node = doc.node(compound).unwrap(); + assert_eq!(compound_node.children().unwrap().len(), 3); + check_session(&s).unwrap(); +} + +#[test] +fn paste_non_path_in_compound_path_isolation_inserts_into_layer() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let a = rect(&mut s, 10.0, 10.0, 40.0, 40.0); + let b = rect(&mut s, 60.0, 10.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let _group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + + // Copy the group to the clipboard. + run(&mut s, "edit.copy", json!({})); + + // Create a compound path on the layer. + let c1 = rect(&mut s, 10.0, 100.0, 80.0, 80.0); + let c2 = rect(&mut s, 30.0, 120.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [c1.0, c2.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + let layer_id = s.doc().unwrap().doc.parent_of(compound).unwrap(); + + // Isolate the compound path. + run(&mut s, "object.isolate", json!({"id": compound.0})); + assert_eq!(s.doc().unwrap().isolation, Some(compound)); + + // Generic insertion parent inside compound isolation resolves to the layer, not the compound. + assert_eq!(s.doc().unwrap().insertion_parent(), Some(layer_id)); + + // Paste the group while in compound path isolation. + // The group cannot be inserted into the compound path; it must be pasted into the layer beside the compound. + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + let pasted_group = NodeId(ids[0]); + + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(pasted_group), Some(layer_id), "pasted group must be added to layer, not compound"); + let compound_node = doc.node(compound).unwrap(); + assert_eq!(compound_node.children().unwrap().len(), 2, "compound path must keep only its 2 path children"); + + // All document invariants (including compound children being paths only) must hold. + check_session(&s).unwrap(); +} + +#[test] +fn shape_creation_in_compound_path_isolation_inserts_into_layer() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = rect(&mut s, 10.0, 10.0, 80.0, 80.0); + let inner = rect(&mut s, 30.0, 30.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Isolate the compound path. + run(&mut s, "object.isolate", json!({"id": compound.0})); + + // Draw a new rectangle while isolating the compound path. + let new_rect = rect(&mut s, 40.0, 40.0, 20.0, 20.0); + + let doc = &s.doc().unwrap().doc; + assert_ne!(doc.parent_of(new_rect), Some(compound), "new shape path is placed outside compound path in layer"); + let compound_node = doc.node(compound).unwrap(); + assert_eq!(compound_node.children().unwrap().len(), 2, "compound path maintains original member paths"); + + check_session(&s).unwrap(); +} + +#[test] +fn paste_compound_into_isolated_compound_preserves_child_order() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 300, "height": 300})); + let r1 = rect(&mut s, 10.0, 10.0, 10.0, 10.0); + let r2 = rect(&mut s, 30.0, 10.0, 10.0, 10.0); + let r3 = rect(&mut s, 50.0, 10.0, 10.0, 10.0); + run(&mut s, "select.set", json!({"ids": [r1.0, r2.0, r3.0]})); + let src_compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Copy src_compound (contains [r1, r2, r3] in order) + run(&mut s, "select.set", json!({"ids": [src_compound.0]})); + run(&mut s, "edit.copy", json!({})); + + // Create target compound + let t1 = rect(&mut s, 100.0, 100.0, 80.0, 80.0); + let t2 = rect(&mut s, 120.0, 120.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [t1.0, t2.0]})); + let target_compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Isolate target compound and select member t1 so paste-in-front targets index 1 + run(&mut s, "object.isolate", json!({"id": target_compound.0})); + run(&mut s, "select.set", json!({"ids": [t1.0]})); + + // Paste in front of t1 + let pasted = run(&mut s, "edit.pasteInFront", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 3, "unpacked all 3 children"); + + let doc = &s.doc().unwrap().doc; + let target_node = doc.node(target_compound).unwrap(); + let children = target_node.children().unwrap(); + assert_eq!(children.len(), 5); + + // Verify the 3 pasted children appear in children in exact forward order [r1_copy, r2_copy, r3_copy] + let child_ids: Vec = children.iter().map(|c| c.id.0).collect(); + let pos0 = child_ids.iter().position(|&id| id == ids[0]).unwrap(); + let pos1 = child_ids.iter().position(|&id| id == ids[1]).unwrap(); + let pos2 = child_ids.iter().position(|&id| id == ids[2]).unwrap(); + assert_eq!(pos1, pos0 + 1, "child 1 must immediately follow child 0"); + assert_eq!(pos2, pos1 + 1, "child 2 must immediately follow child 1"); + + check_session(&s).unwrap(); +} + +#[test] +fn copy_and_paste_direct_selected_segment_of_open_path() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 20}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 60, "y": 20})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 100, "y": 80})); + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "paint.setStroke", json!({"color": "#0000ff"})); + run(&mut s, "stroke.set", json!({"weight": 4.0})); + + // Select segment 0 of the open path (from (10, 20) to (60, 20)). + run(&mut s, "select.segments", json!({"id": id.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + + // Paste in place: position and appearance must be preserved. + let pasted = run(&mut s, "edit.pasteInPlace", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let src_node = s.doc().unwrap().doc.node(id).unwrap(); + assert_eq!(pasted_node.appearance, src_node.appearance, "appearance (stroke & fill) must match source"); + + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.segment_count(), 1); + assert_eq!(sp.anchors.len(), 2); + assert_eq!(sp.anchors[0].p.x, 10.0); + assert_eq!(sp.anchors[0].p.y, 20.0); + assert_eq!(sp.anchors[1].p.x, 60.0); + assert_eq!(sp.anchors[1].p.y, 20.0); + + check_session(&s).unwrap(); +} + +#[test] +fn copy_two_non_adjacent_segments_of_open_path_pastes_two_paths() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 300, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 40, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 80, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 120, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 160, "y": 10})); + + // Path has 5 anchors (0..4) and 4 segments (0..3). + // Select disjoint/non-adjacent segments 0 and 2. + run(&mut s, "select.segments", json!({"id": id.0, "segments": [[0, 0], [0, 2]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 2, "two non-adjacent segments paste as two independent paths"); + + for node_id in ids { + let node = s.doc().unwrap().doc.node(NodeId(node_id)).unwrap(); + let path = node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + assert!(!path.subpaths[0].closed); + assert_eq!(path.subpaths[0].segment_count(), 1); + assert_eq!(path.subpaths[0].anchors.len(), 2); + } + + check_session(&s).unwrap(); +} + +#[test] +fn copy_all_anchors_of_open_path_copies_whole_path() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 80, "y": 40})); + + // Select all 3 anchors. + run(&mut s, "select.anchors", json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + assert!(!path.subpaths[0].closed); + assert_eq!(path.subpaths[0].segment_count(), 2); + assert_eq!(path.subpaths[0].anchors.len(), 3); + + check_session(&s).unwrap(); +} + +#[test] +fn copy_single_anchor_on_open_path_and_lone_point_states_what_is_pasted() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + + // 1. Single interior anchor of an open path: + // Path: (10, 10) -> (50, 10) -> (90, 50). + // Selecting interior anchor 1 selects both incident segments (0 and 1). + // Stated behavior: pasting pastes an open path containing the anchor and both its incident segments (3 anchors, 2 segments). + let p1 = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": p1.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": p1.0, "x": 90, "y": 50})); + run(&mut s, "select.anchors", json!({"id": p1.0, "anchors": [[0, 1]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted1 = run(&mut s, "edit.paste", json!({})); + let ids1: Vec = pasted1["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids1.len(), 1); + let path1 = s.doc().unwrap().doc.node(NodeId(ids1[0])).unwrap().path_data().unwrap(); + assert!(!path1.subpaths[0].closed); + assert_eq!(path1.subpaths[0].anchors.len(), 3); + assert_eq!(path1.subpaths[0].segment_count(), 2); + + // 2. Single endpoint anchor of an open path: + // Selecting endpoint anchor 0 selects its single incident segment (segment 0). + // Stated behavior: pasting pastes an open path for that segment (2 anchors, 1 segment). + run(&mut s, "select.anchors", json!({"id": p1.0, "anchors": [[0, 0]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted2 = run(&mut s, "edit.paste", json!({})); + let ids2: Vec = pasted2["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids2.len(), 1); + let path2 = s.doc().unwrap().doc.node(NodeId(ids2[0])).unwrap().path_data().unwrap(); + assert!(!path2.subpaths[0].closed); + assert_eq!(path2.subpaths[0].anchors.len(), 2); + assert_eq!(path2.subpaths[0].segment_count(), 1); + + // 3. A lone point path (a path with only 1 anchor and 0 segments): + // Selecting the lone anchor on a single-point path copies the object whole. + // Stated behavior: pasting pastes a standalone lone-point path (1 anchor, 0 segments). + let p_lone = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 100, "y": 100}]}))["id"].as_u64().unwrap()); + run(&mut s, "select.anchors", json!({"id": p_lone.0, "anchors": [[0, 0]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted_lone = run(&mut s, "edit.paste", json!({})); + let ids_lone: Vec = pasted_lone["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids_lone.len(), 1); + let path_lone = s.doc().unwrap().doc.node(NodeId(ids_lone[0])).unwrap().path_data().unwrap(); + assert_eq!(path_lone.subpaths[0].anchors.len(), 1); + assert_eq!(path_lone.subpaths[0].segment_count(), 0); + + check_session(&s).unwrap(); +} + +#[test] +fn cut_anchor_of_closed_path_opens_it_with_single_undo_step() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Direct-select anchor 1 of the closed 4-anchor rectangle. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1]], "mode": "set"})); + let undo_before = s.doc().unwrap().history.undo.len(); + + // Cut the anchor. + run(&mut s, "edit.cut", json!({})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "cut is recorded as one undo step"); + + // Source rectangle opens: 1 open subpath with 3 anchors remaining. + let src_node = s.doc().unwrap().doc.node(r).unwrap(); + let src_path = src_node.path_data().unwrap(); + assert_eq!(src_path.subpaths.len(), 1); + assert!(!src_path.subpaths[0].closed, "cutting anchor of closed path opens the path"); + assert_eq!(src_path.subpaths[0].anchors.len(), 3); + assert_eq!(src_path.subpaths[0].segment_count(), 2); + + // Clipboard holds the cut portion (the anchor and its two incident segments: 3 anchors). + assert_eq!(s.clipboard.nodes.len(), 1); + let clip_path = s.clipboard.nodes[0].path_data().unwrap(); + assert!(!clip_path.subpaths[0].closed); + assert_eq!(clip_path.subpaths[0].anchors.len(), 3); + assert_eq!(clip_path.subpaths[0].segment_count(), 2); + + // Verify undo restores the closed path in one step. + run(&mut s, "edit.undo", json!({})); + let restored_node = s.doc().unwrap().doc.node(r).unwrap(); + let restored_path = restored_node.path_data().unwrap(); + assert_eq!(restored_path.subpaths.len(), 1); + assert!(restored_path.subpaths[0].closed, "undo restores closed path"); + assert_eq!(restored_path.subpaths[0].anchors.len(), 4); + assert_eq!(restored_path.subpaths[0].segment_count(), 4); + + // Verify redo re-applies the cut. + run(&mut s, "edit.redo", json!({})); + let redone_node = s.doc().unwrap().doc.node(r).unwrap(); + let redone_path = redone_node.path_data().unwrap(); + assert!(!redone_path.subpaths[0].closed); + assert_eq!(redone_path.subpaths[0].anchors.len(), 3); + + check_session(&s).unwrap(); +} + +#[test] +fn cut_middle_segment_of_open_path_splits_into_two_open_paths_with_single_undo_step() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 90, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 130, "y": 10})); + + // Open path has 4 anchors (0, 1, 2, 3) and 3 segments (0, 1, 2). + // Direct-select middle segment 1 (between anchor 1 and 2). + run(&mut s, "select.segments", json!({"id": id.0, "segments": [[0, 1]]})); + let undo_before = s.doc().unwrap().history.undo.len(); + + // Cut the middle segment. + run(&mut s, "edit.cut", json!({})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "cut is recorded as one undo step"); + + // Source path should now be split into two surviving open runs. + let src_node = s.doc().unwrap().doc.node(id).unwrap(); + let src_path = src_node.path_data().unwrap(); + assert_eq!(src_path.subpaths.len(), 2, "two open paths/subpaths remain after cutting middle segment"); + assert!(!src_path.subpaths[0].closed); + assert_eq!(src_path.subpaths[0].anchors.len(), 2); + assert_eq!(src_path.subpaths[0].anchors[0].p.x, 10.0); + assert_eq!(src_path.subpaths[0].anchors[1].p.x, 50.0); + + assert!(!src_path.subpaths[1].closed); + assert_eq!(src_path.subpaths[1].anchors.len(), 2); + assert_eq!(src_path.subpaths[1].anchors[0].p.x, 90.0); + assert_eq!(src_path.subpaths[1].anchors[1].p.x, 130.0); + + // Clipboard holds the cut middle segment: + assert_eq!(s.clipboard.nodes.len(), 1); + let clip_path = s.clipboard.nodes[0].path_data().unwrap(); + assert_eq!(clip_path.subpaths[0].anchors.len(), 2); + assert_eq!(clip_path.subpaths[0].anchors[0].p.x, 50.0); + assert_eq!(clip_path.subpaths[0].anchors[1].p.x, 90.0); + + // Verify undo restores the original intact path in one step: + run(&mut s, "edit.undo", json!({})); + let restored_node = s.doc().unwrap().doc.node(id).unwrap(); + let restored_path = restored_node.path_data().unwrap(); + assert_eq!(restored_path.subpaths.len(), 1, "undo restores single subpath"); + assert_eq!(restored_path.subpaths[0].anchors.len(), 4, "undo restores all 4 anchors"); + + // Redo re-applies the split: + run(&mut s, "edit.redo", json!({})); + let redone_path = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap(); + assert_eq!(redone_path.subpaths.len(), 2); + + check_session(&s).unwrap(); +} diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 65b2f423c1..16deb3d242 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -280,6 +280,348 @@ fn a_moved_linked_dimension_stays_where_it_was_dropped() { assert!((recipe(&s, id).offset - moved).abs() < 1e-6, "moved together"); } +/// How many nodes a dimension's art holds, how many of them are type, and whether it has a recipe. +fn art(s: &Session, id: u64) -> (usize, usize, bool) { + let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap(); + let (mut nodes, mut labels) = (0, 0); + n.walk(&mut |c| { + nodes += 1; + labels += usize::from(matches!(c.kind, NodeKind::Text(_))); + }); + (nodes, labels, n.extras().dimension.is_some()) +} +fn bounds(s: &Session, id: u64) -> [f64; 4] { + let b = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap(); + [b.x0, b.y0, b.x1, b.y1] +} +/// The art of `id`, which holds no type and no recipe, follows a move, a scale, undo and redo as +/// plain art does. +fn stays_plain_art(s: &mut Session, id: u64) { + let plain = art(s, id); + assert_eq!(plain.1, 0, "no type left: {plain:?}"); + let at = bounds(s, id); + run(s, "select.set", json!({"ids":[id]})); + run(s, "object.move", json!({"dx":30,"dy":-20})); + assert_eq!(art(s, id), plain, "after a move"); + let moved = bounds(s, id); + for (k, (a, b)) in at.iter().zip(moved).enumerate() { + let d = if k % 2 == 0 { 30.0 } else { -20.0 }; + assert!((b - a - d).abs() < 1e-6, "{at:?} moved to {moved:?}"); + } + run(s, "object.scale", json!({"sx":200,"sy":100})); + assert_eq!(art(s, id), plain, "after a scale"); + let scaled = bounds(s, id); + assert!(((scaled[2] - scaled[0]) - 2.0 * (at[2] - at[0])).abs() < 1e-6, "{at:?} scaled to {scaled:?}"); + run(s, "edit.undo", json!({})); + assert_eq!(art(s, id), plain, "after undoing the scale"); + run(s, "edit.redo", json!({})); + assert_eq!(art(s, id), plain, "after redoing the scale"); + run(s, "edit.undo", json!({})); + run(s, "edit.undo", json!({})); + assert_eq!(art(s, id), plain); + assert_eq!(bounds(s, id), at); + assert!(!plain.2, "no recipe left"); +} + +/// Object › Expand turns a dimension into plain art for good: it no longer follows the art it +/// measured, and one undo gives the live dimension back. +#[test] +fn an_expanded_dimension_stays_plain_art() { + let mut s = session(); + let line = edge(&mut s); + let id = dim(&mut s, line); + let other = dim(&mut s, line); + let live = art(&s, id); + assert_eq!((live.1, live.2), (1, true)); + run(&mut s, "select.set", json!({"ids":[id]})); + run(&mut s, "object.expand", json!({})); + stays_plain_art(&mut s, id); + let plain = art(&s, id); + let at = bounds(&s, id); + assert_eq!(art(&s, other), live, "the dimension left out of the selection stays live"); + // The art it measured no longer moves it, and deleting that art leaves it. + run(&mut s, "select.set", json!({"ids":[line]})); + run(&mut s, "object.scale", json!({"sx":200,"sy":100})); + assert_eq!(text(&s, other), "20.00 in"); + assert_eq!((art(&s, id), bounds(&s, id)), (plain, at)); + run(&mut s, "edit.clear", json!({})); + assert_eq!((art(&s, id), bounds(&s, id)), (plain, at)); + assert!(s.doc().unwrap().doc.node(NodeId(other)).is_none()); + // Saved and opened again, it is still plain art. + let doc = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let mut reopened = Session::new(); + reopened.add_document(doc, None); + stays_plain_art(&mut reopened, id); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live, "one undo gives the live dimension back"); + assert_eq!(text(&s, id), "10.00 in"); + run(&mut s, "select.set", json!({"ids":[line]})); + run(&mut s, "object.scale", json!({"sx":200,"sy":100})); + assert_eq!(text(&s, id), "20.00 in", "linked again"); +} + +/// Expand's options: any one that changes a dimension's art ends its link, and an Expand that +/// changes nothing leaves it live. +#[test] +fn expand_options_that_change_a_dimension_end_its_link() { + let mut s = session(); + let line = edge(&mut s); + let id = dim(&mut s, line); + let live = art(&s, id); + run(&mut s, "select.set", json!({"ids":[id]})); + assert!(s.execute("object.expand", &json!({"object":false,"stroke":false})).is_err(), "no fills to expand"); + assert_eq!(art(&s, id), live); + assert!(s.doc().unwrap().doc.dimensions); + // Stroke alone leaves type as it is, so a stroked label on its own does not end the link. + let label = { + let children = s.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap(); + children.iter().find(|c| matches!(c.kind, NodeKind::Text(_))).unwrap().id.0 + }; + run(&mut s, "paint.setStroke", json!({"ids":[label],"color":"#ff0000"})); + run(&mut s, "select.set", json!({"ids":[label]})); + assert!(s.execute("object.expand", &json!({"object":false,"fill":false})).is_err(), "no paths to outline"); + assert!(art(&s, id).2, "still live"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live); + run(&mut s, "select.set", json!({"ids":[id]})); + // Stroke alone: the label stays type, in art that no longer redraws. + run(&mut s, "object.expand", json!({"object":false,"fill":false})); + let plain = art(&s, id); + assert_eq!(plain.1, 1, "{plain:?}"); + run(&mut s, "select.set", json!({"ids":[id]})); + run(&mut s, "object.move", json!({"dx":30,"dy":0})); + assert_eq!(art(&s, id), plain); + assert!(!plain.2, "no recipe left"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live); + // Object alone: the lines stay stroked paths, in art that no longer redraws. + run(&mut s, "select.set", json!({"ids":[id]})); + run(&mut s, "object.expand", json!({"stroke":false,"fill":false})); + let plain = art(&s, id); + assert_eq!(plain.1, 0, "{plain:?}"); + run(&mut s, "object.move", json!({"dx":30,"dy":0})); + assert_eq!(art(&s, id), plain); + assert!(!plain.2, "no recipe left"); +} + +/// An Expand that ends up changing no art fails and leaves the dimension live: Outline Stroke skips +/// guides, here the dimension's lines. +#[test] +fn an_expand_that_changes_no_art_leaves_a_dimension_live() { + let mut s = session(); + let line = edge(&mut s); + let id = dim(&mut s, line); + let lines: Vec = { + let children = s.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap(); + children.iter().filter(|c| matches!(c.kind, NodeKind::Path { .. })).map(|c| c.id.0).collect() + }; + run(&mut s, "select.set", json!({"ids":lines})); + run(&mut s, "view.guides.make", json!({})); + let live = art(&s, id); + run(&mut s, "select.set", json!({"ids":[id]})); + assert!(s.execute("object.expand", &json!({"object":false,"fill":false})).is_err()); + assert_eq!(art(&s, id), live); + assert!(live.2); + // A stroked path selected with it expands, and the dimension's art stays live. + let other = run(&mut s, "shape.rectangle", json!({"x":300,"y":300,"width":50,"height":50}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setStroke", json!({"ids":[other],"color":"#000000"})); + let moved_with = s.doc().unwrap().doc.node_count(); + run(&mut s, "select.set", json!({"ids":[id, other]})); + run(&mut s, "object.expand", json!({"object":false,"fill":false})); + assert_ne!(s.doc().unwrap().doc.node_count(), moved_with, "the rectangle's stroke is outlined"); + assert_eq!(art(&s, id), live); +} + +/// A dimension selected with the art it measures, or held by a selected group, expands the same +/// way: outlining that art does not remove it. +#[test] +fn a_dimension_expanded_with_its_art_or_in_a_group_stays_plain_art() { + let mut s = session(); + let line = edge(&mut s); + let id = dim(&mut s, line); + run(&mut s, "select.set", json!({"ids":[line, id]})); + run(&mut s, "object.expand", json!({})); + stays_plain_art(&mut s, id); + let mut s = session(); + let line = edge(&mut s); + let id = dim(&mut s, line); + run(&mut s, "select.set", json!({"ids":[id]})); + run(&mut s, "object.group", json!({})); + run(&mut s, "object.expand", json!({})); + stays_plain_art(&mut s, id); +} + +/// Expand replacing only the art a selected dimension measures leaves the dimension's art as it +/// is, without a link to the art that went. +#[test] +fn a_dimension_keeps_no_link_to_the_art_expand_replaced() { + for circle in [false, true] { + let mut s = session(); + let shape = json!({"x":100,"y":100,"width":72,"height":72}); + let art_id = run(&mut s, if circle { "shape.ellipse" } else { "shape.rectangle" }, shape)["id"].as_u64().unwrap(); + run(&mut s, "paint.setFill", json!({"ids":[art_id],"gradient":{"kind":"linear"}})); + let id = if circle { + run(&mut s, "dimension.create", json!({"mode":"radius","source":{"kind":"circle","node":art_id}}))["id"].as_u64().unwrap() + } else { + dim(&mut s, art_id) + }; + let (nodes, labels, _) = art(&s, id); + run(&mut s, "select.set", json!({"ids":[art_id, id]})); + run(&mut s, "object.expand", json!({"object":false,"stroke":false})); + assert_eq!(art(&s, id), (nodes, labels, false), "circle: {circle}"); + run(&mut s, "select.set", json!({"ids":[id]})); + run(&mut s, "object.move", json!({"dx":30,"dy":0})); + assert_eq!(art(&s, id), (nodes, labels, false), "circle: {circle}"); + } +} + +/// Outline Stroke and Expand Appearance replacing the art a selected dimension measures leave the +/// dimension as a plain group, whether or not they change its own art. +#[test] +fn a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced() { + for command in ["object.path.outlineStroke", "effect.expandAppearance"] { + for whole in [true, false] { + let mut s = session(); + let art_id = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":72,"height":72}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setStroke", json!({"ids":[art_id],"color":"#000000"})); + run(&mut s, "select.set", json!({"ids":[art_id]})); + run(&mut s, "appearance.addStroke", json!({})); + let id = dim(&mut s, art_id); + let lines: Vec = { + let children = s.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap(); + children.iter().filter(|c| matches!(c.kind, NodeKind::Path { .. })).map(|c| c.id.0).collect() + }; + run(&mut s, "select.set", json!({"ids":lines})); + run(&mut s, "view.guides.make", json!({})); + let picked = if whole { id } else { lines[0] }; + run(&mut s, "select.set", json!({"ids":[art_id, picked]})); + run(&mut s, command, json!({})); + assert!(s.doc().unwrap().doc.node(NodeId(id)).is_some(), "{command} removed the dimension, whole: {whole}"); + let plain = art(&s, id); + assert!(!plain.2, "{command}: no recipe left, whole: {whole}"); + run(&mut s, "select.set", json!({"ids":[id]})); + run(&mut s, "object.move", json!({"dx":30,"dy":0})); + assert_eq!(art(&s, id), plain, "{command}, whole: {whole}"); + } + } +} + +/// A part of a dimension expanded on its own ends the link too, so the move does not undo it. +#[test] +fn expanding_a_part_of_a_dimension_ends_its_link() { + let mut s = session(); + let line = edge(&mut s); + let id = dim(&mut s, line); + let part = s.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap()[0].id; + run(&mut s, "select.set", json!({"ids":[part]})); + run(&mut s, "object.expand", json!({})); + let plain = art(&s, id); + assert_eq!(plain.1, 1, "{plain:?}"); + run(&mut s, "select.set", json!({"ids":[id]})); + run(&mut s, "object.move", json!({"dx":30,"dy":0})); + assert_eq!(art(&s, id), plain); + assert!(!plain.2, "no recipe left"); +} + +/// The instance of a symbol whose art is a dimension expands to art that no longer redraws. +#[test] +fn a_dimension_in_an_expanded_symbol_instance_stays_plain_art() { + let mut s = session(); + let id = run(&mut s, "dimension.create", json!({"a":[100,100],"b":[172,100],"options":{"units":"pt","precision":0}}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[id]})); + let instance = run(&mut s, "symbol.new", json!({"name":"Measure"}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[instance]})); + run(&mut s, "object.expand", json!({})); + let root = s.doc().unwrap().selection.objects[0].0; + let mut recipes = 0; + s.doc().unwrap().doc.node(NodeId(root)).unwrap().walk(&mut |c| recipes += usize::from(c.extras().dimension.is_some())); + assert_eq!(recipes, 0); + stays_plain_art(&mut s, root); +} + +/// Create Outlines on a dimension, or on its label alone, ends the link in the same undo step. +#[test] +fn outlining_a_dimension_or_its_label_ends_its_link() { + for label_alone in [false, true] { + let mut s = session(); + let line = edge(&mut s); + let id = dim(&mut s, line); + let live = art(&s, id); + let label = { + let children = s.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap(); + children.iter().find(|c| matches!(c.kind, NodeKind::Text(_))).unwrap().id + }; + let target = if label_alone { label.0 } else { id }; + run(&mut s, "select.set", json!({"ids":[target]})); + run(&mut s, "type.createOutlines", json!({})); + stays_plain_art(&mut s, id); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live, "one undo gives the live dimension back"); + assert_eq!(text(&s, id), "10.00 in"); + } +} + +/// Outline Stroke on a dimension ends its link: the label stays type and the art does not redraw. +#[test] +fn outlining_a_dimensions_strokes_ends_its_link() { + let mut s = session(); + let line = edge(&mut s); + let id = dim(&mut s, line); + let live = art(&s, id); + run(&mut s, "select.set", json!({"ids":[id]})); + run(&mut s, "object.path.outlineStroke", json!({})); + let plain = art(&s, id); + assert_eq!(plain.1, 1, "{plain:?}"); + run(&mut s, "object.move", json!({"dx":30,"dy":0})); + assert_eq!(art(&s, id), plain); + assert!(!plain.2, "no recipe left"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live, "one undo gives the live dimension back"); +} + +/// Expand Appearance, which the menus offer for a dimension in place of Expand, ends its link too. +#[test] +fn expanding_a_dimensions_appearance_ends_its_link() { + let mut s = session(); + let line = edge(&mut s); + let id = dim(&mut s, line); + let live = art(&s, id); + run(&mut s, "select.set", json!({"ids":[id]})); + assert_eq!(run(&mut s, "object.expand.info", json!({}))["appearance"], true); + run(&mut s, "effect.expandAppearance", json!({})); + stays_plain_art(&mut s, id); + run(&mut s, "edit.undo", json!({})); + assert_eq!(art(&s, id), live, "one undo gives the live dimension back"); + assert_eq!(text(&s, id), "10.00 in"); +} + +/// Ungroup takes the group that holds the recipe away, so the parts stay ordinary art. +#[test] +fn an_ungrouped_dimension_stays_ordinary_art() { + let mut s = session(); + let line = edge(&mut s); + let id = dim(&mut s, line); + let (nodes, ..) = art(&s, id); + run(&mut s, "select.set", json!({"ids":[id]})); + run(&mut s, "object.ungroup", json!({})); + assert!(s.doc().unwrap().doc.node(NodeId(id)).is_none()); + let parts = s.doc().unwrap().selection.objects.clone(); + assert_eq!(parts.len(), nodes - 1); + let boxes = |s: &Session| parts.iter().map(|p| s.doc().unwrap().doc.node(*p).unwrap().geometric_bounds().unwrap()).collect::>(); + let at = boxes(&s); + run(&mut s, "object.move", json!({"dx":30,"dy":0})); + for (a, b) in at.iter().zip(boxes(&s)) { + assert!((b.x0 - a.x0 - 30.0).abs() < 1e-6 && (b.y0 - a.y0).abs() < 1e-6, "{a:?} moved to {b:?}"); + } + run(&mut s, "select.set", json!({"ids":[line]})); + run(&mut s, "object.scale", json!({"sx":200,"sy":100})); + assert!(!s.doc().unwrap().doc.dimensions); +} + #[test] fn dimension_options_are_persistent_and_invalid_updates_report_errors() { let mut s = session(); diff --git a/crates/engine/tests/it/js_lexer_vs_scriptcheck.rs b/crates/engine/tests/it/js_lexer_vs_scriptcheck.rs new file mode 100644 index 0000000000..6c84c66b33 --- /dev/null +++ b/crates/engine/tests/it/js_lexer_vs_scriptcheck.rs @@ -0,0 +1,102 @@ +//! The JavaScript parser's lexer (`vectorcraft-js`) and the script checker's (`vectorcraft-scriptcheck`) +//! read the same scripts the same way: both crates stand alone, so each has its own lexer, and these +//! tests run both over one set of scripts and fail on any disagreement about the lines a script has, +//! its preprocessor lines, and where a string, comment or regular expression that is never closed +//! starts. The scripts stay inside ECMAScript 3, the language both read (no XML literals, which +//! only the checker reads). + +use vectorcraft_js::{Options, TokenKind, parse, tokenize}; +use vectorcraft_scriptcheck::{Limits, check}; + +/// The problems the checker reports from its lexer, which the parser reports as a `SyntaxError`. +const LEXICAL: [(&str, &str); 3] = [ + ("unterminatedString", "unterminated string"), + ("unterminatedComment", "unterminated comment"), + ("unterminatedRegExp", "unterminated regular expression"), +]; + +/// Scripts both lexers read without a problem, each with a `/` or a quote in a place where reading +/// it the other way would change the tokens. +const VALID: &[&str] = &[ + "var a = b / c / d;\nvar r = /ab+c/gi;\n", + "if (x) /re/.test(y);\nwhile (z) /q/g.exec(w);\n", + "function f() { return /x/; }\nvar g = function () {} / 2;\n", + "{}\n/re/.test(s);\n", + "x = {a: 1} / 2;\n", + "a = b\n/c/g\n", + "s = 'it\\'s \"q\" // not a comment';\nt = \"/* nor this */\";\n", + "s = 'line\\\ncontinued';\nu = 1;\n", + "x = a++ / 2;\ny = (b) / 2;\nz = c[0] / 2;\n", + "r = /[/]/;\nq = /\\//;\n", + "#target vectorcraft\n#include \"lib.jsxinc\"\n//@includepath \"~/x\"\nvar a = 1;\n#targetengine session\n", + "a = 1;\r\nb = 2;\r\nc = 3;", + "a = 1;\u{2028}b = 2;\u{2029}c = 3;\n", + "typeof /x/ === 'object';\nvoid /y/;\n", + "switch (x) { case /a/.test(y): break; }\n", + "x = y ? /a/ : /b/;\n", + "label: for (;;) { break label; }\n/* multi\nline */ z = 1 / 2;\n", + "var o = { re: /x/, d: 4 / 2 };\n", + "x = [/a/, 1 / 2];\n", + "if (a) {\n} else /x/.test(b);\n", + "a = 'q' + \"r\";\n// a comment with a 'quote\n", + "x = a\n++b\n", + "for (var i = 0; i < n / 2; i++) { s += /\\d/.exec(t[i]) ? 1 : 0; }\n", + "", + "\n\n", +]; + +/// Scripts with a string, comment or regular expression that is never closed: the problem the +/// checker gives and the line it starts on. +const INVALID: &[(&str, &str, usize)] = &[ + ("var a = 1;\nvar s = 'abc;\n", "unterminatedString", 2), + ("a = 1;\n/* never closed\nb = 2;\n", "unterminatedComment", 2), + ("x = 1;\ny = /abc\n", "unterminatedRegExp", 2), + ("if (x)\n /abc\n", "unterminatedRegExp", 2), + ("a = 1;\r\nb = \"x\r\n", "unterminatedString", 2), + ("q = 2 / 3;\nr = /[/]\n", "unterminatedRegExp", 2), +]; + +fn js_options() -> Options { + Options { preprocessor_lines: true, ..Options::default() } +} + +#[test] +fn both_lexers_count_the_same_lines_and_read_the_same_directives() { + for src in VALID { + let program = parse(src, &js_options()).unwrap_or_else(|e| panic!("{src:?}: {e}")); + let report = check("script.jsx", src.as_bytes(), None, &Limits::default()); + assert_eq!(report.lines, program.line_count() as usize, "lines of {src:?}"); + let lexical: Vec<_> = report.problems.iter().filter(|p| LEXICAL.iter().any(|(code, _)| *code == p.code)).collect(); + assert!(lexical.is_empty(), "{src:?}: the checker reports {lexical:?}"); + let theirs: Vec<(String, usize)> = report.directives.iter().map(|d| (d.name.to_string(), d.line)).collect(); + let ours: Vec<(String, usize)> = program.directives.iter().map(|d| (d.name.to_lowercase(), d.line as usize)).collect(); + assert_eq!(ours, theirs, "directives of {src:?}"); + } +} + +#[test] +fn both_lexers_find_the_same_unclosed_token_on_the_same_line() { + for (src, code, line) in INVALID { + let report = check("script.jsx", src.as_bytes(), None, &Limits::default()); + let theirs = report.problems.iter().find(|p| LEXICAL.iter().any(|(c, _)| *c == p.code)); + let theirs = theirs.unwrap_or_else(|| panic!("{src:?}: the checker reports no lexical problem")); + assert_eq!((theirs.code, theirs.line), (*code, Some(*line)), "{src:?}"); + let ours = parse(src, &js_options()).expect_err(src); + let message = LEXICAL.iter().find(|(c, _)| c == code).map(|(_, m)| *m).unwrap(); + assert!(ours.message.contains(message), "{src:?}: {}", ours.message); + assert_eq!(ours.line as usize, *line, "{src:?}"); + } +} + +#[test] +fn the_parser_reads_a_regexp_wherever_the_checker_does() { + // Each `/` that divides has no second `/` after it on its line, so a lexer that read one as a + // regular expression would report it as never closed. The checker reports nothing, and the + // parser reads regular expressions on lines 2 and 3 only. + let src = "a = b / c;\nr = /x/;\nif (a) /y/.test(b);\nz = (1) / 2;\n"; + let tokens = tokenize(src, &js_options()).unwrap(); + let lines: Vec = tokens.iter().filter(|t| matches!(t.kind, TokenKind::RegExp { .. })).map(|t| t.line).collect(); + assert_eq!(lines, [2, 3]); + let report = check("script.jsx", src.as_bytes(), None, &Limits::default()); + assert!(report.problems.iter().all(|p| !LEXICAL.iter().any(|(c, _)| *c == p.code)), "{:?}", report.problems); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 5b9dc39c6c..3689d9caee 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -13,14 +13,17 @@ mod artboard_click; mod beyond_canvas; mod clear_commands; mod compound_attributes; +mod copy_direct_selection; mod dimensions; mod eyedropper_sources; mod find_replace_paras; mod inline_text; +mod js_lexer_vs_scriptcheck; mod known_bugs; mod lossy_overwrite; mod model_based; mod param_keys; +mod paste_many; mod pen_click_after_smooth; mod pen_endpoint_picking; mod ruler_origin; diff --git a/crates/engine/tests/it/param_keys.rs b/crates/engine/tests/it/param_keys.rs index 3da393ca8f..adf75178a1 100644 --- a/crates/engine/tests/it/param_keys.rs +++ b/crates/engine/tests/it/param_keys.rs @@ -1,24 +1,128 @@ -//! A caller's params are checked against the command's description, but a journal replays as it -//! was recorded (#1442). +//! `Session::execute` checks params against the command's description, but a journal replays as +//! it was recorded (#1442). use serde_json::json; use vectorcraft_engine::{Session, check_params}; -/// `Session::execute` takes what it is given: the journal of an older version, an action recorded -/// with a key a command no longer reads, still plays. The check is the caller's. +/// The open document's art and undo history, and the session's journal length. +fn state(s: &Session) -> (Option, usize, usize) { + let st = s.active(); + (st.map(|st| (*st.doc).clone()), st.map_or(0, |st| st.history.undo.len()), s.journal.len()) +} + +/// `Session::execute` answers a key the command's description doesn't name with a parameter +/// error, in a release build too, and the document, its undo history and the journal stay as +/// they were. +#[test] +fn execute_refuses_a_key_its_command_does_not_name() { + let mut s = Session::new(); + let e = s.execute("file.new", &json!({"width": 300, "widht": 1})).unwrap_err().to_string(); + assert!(e.contains("widht"), "{e}"); + assert!(s.active().is_none()); + s.execute("file.new", &json!({})).unwrap(); + let before = state(&s); + let e = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40, "cornerStyle": "round"})).unwrap_err(); + assert!(e.to_string().contains("cornerStyle"), "{e}"); + assert!(state(&s) == before); +} + +/// A step of a `command.batch` with such a key fails the batch before any step runs, and a step +/// whose `effect.setParams` gives an effect a parameter it doesn't take fails it too, though that +/// effect is only there once the steps before it ran. Nothing the batch did stays. +#[test] +fn execute_refuses_a_batch_step_with_a_key_its_command_does_not_name() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let before = state(&s); + let rect = json!({"command": "shape.rectangle", "params": {"x": 10, "y": 10, "width": 50, "height": 40}}); + let bad_step = json!({"commands": [rect, {"command": "object.move", "params": {"dx": 5, "dyy": 5}}]}); + let e = s.execute("command.batch", &bad_step).unwrap_err().to_string(); + assert!(e.contains("dyy"), "{e}"); + assert!(state(&s) == before); + let bad_effect = json!({"commands": [ + rect, + {"command": "effect.apply", "params": {"effect": "blur.gaussian"}}, + {"command": "effect.setParams", "params": {"index": 0, "params": {"blurr": 3}}}, + ]}); + assert!(check_params("command.batch", &bad_effect).is_ok()); + let e = s.execute("command.batch", &bad_effect).unwrap_err().to_string(); + assert!(e.contains("blurr"), "{e}"); + assert!(state(&s) == before); +} + +/// The steps of a `command.batch` step aren't checked, however deep they go: batches can't nest, +/// which running the batch reports. +#[test] +fn the_steps_of_a_nested_batch_are_not_checked() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let mut batch = json!({"commands": [{"command": "object.move", "params": {"dyy": 5}}]}); + assert!(check_params("command.batch", &batch).is_err()); + for _ in 0..3 { + batch = json!({"commands": [{"command": "command.batch", "params": batch}]}); + } + assert!(check_params("command.batch", &batch).is_ok()); + let e = s.execute("command.batch", &batch).unwrap_err().to_string(); + assert!(e.contains("batches cannot nest"), "{e}"); +} + +/// An `action.batch` with a step that has such a key fails before it opens a source file or runs +/// a step. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn execute_refuses_an_action_batch_step_with_a_key_its_command_does_not_name() { + let dir = std::env::temp_dir().join(format!("vc-param-keys-action-batch-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let svg = r#""#; + std::fs::write(dir.join("a.svg"), svg).unwrap(); + let mut s = Session::new(); + let batch = json!({ + "source": "folder", + "folder": dir.to_string_lossy(), + "commands": [{"command": "select.all", "params": {}}, {"command": "object.move", "params": {"dx": 5, "dyy": 5}}], + }); + let e = s.execute("action.batch", &batch).unwrap_err().to_string(); + std::fs::remove_dir_all(&dir).ok(); + assert!(e.contains("dyy"), "{e}"); + assert!(s.documents().is_empty()); + assert!(s.journal.is_empty()); +} + +/// `Session::replay` takes what it is given: the journal of an older version, an action recorded +/// with a key a command no longer reads, still plays, as a step of a `command.batch` too. #[test] fn a_journal_with_a_key_no_longer_read_still_replays() { let old = [ ("file.new", json!({"width": 300, "height": 200, "widht": 1})), ("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40, "cornerStyle": "round"})), + ("command.batch", json!({"commands": [{"command": "object.move", "params": {"dx": 5, "dy": 5, "dyy": 5}}]})), ]; let mut s = Session::new(); for (id, params) in &old { assert!(check_params(id, params).is_err(), "{id}"); - s.execute(id, params).unwrap(); + s.replay(id, params).unwrap(); } + assert!(!s.replaying()); let st = s.active().unwrap(); assert_eq!((st.doc.artboards[0].rect.width(), st.doc.layers[0].children().unwrap().len()), (300.0, 1)); + assert_eq!(s.journal.len(), 3); + assert!(s.execute("object.move", &json!({"dx": 5, "dyy": 5})).is_err()); +} + +/// `Session::replay` still runs an export with an option that is no longer read, and a preset +/// file that holds one still loads and exports. `Session::execute` refuses the same options. +#[test] +fn an_export_step_or_preset_with_a_key_no_longer_read_still_runs() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let old = json!({"format": "pdf", "noSuchOption": true, "marks": {"useDocumentBleed": true}}); + assert!(check_params("document.export", &old).is_err()); + assert!(s.execute("document.export", &old).is_err()); + s.replay("document.export", &old).unwrap(); + let file = json!({"format": "vcpdfpresets", "presets": [{"name": "Old", "settings": {"standard": "none", "noLongerRead": 1, "marks": {"retired": true}}}]}); + s.execute("pdf.preset.import", &json!({"data": file.to_string()})).unwrap(); + check_params("document.export", &json!({"format": "pdf", "preset": "Old"})).unwrap(); + s.execute("document.export", &json!({"format": "pdf", "preset": "Old"})).unwrap(); } /// So do an effect's own parameters (#1592): a journal or a file with a key the effect doesn't @@ -34,7 +138,8 @@ fn effect_params_no_longer_taken_still_replay_and_open() { ]; for (id, params) in &old { assert!(s.check_params(id, params).is_err(), "{id}"); - s.execute(id, params).unwrap(); + assert!(s.execute(id, params).is_err(), "{id}"); + s.replay(id, params).unwrap(); } let doc = &s.active().unwrap().doc; let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap(); diff --git a/crates/engine/tests/it/paste_many.rs b/crates/engine/tests/it/paste_many.rs new file mode 100644 index 0000000000..0482b25c09 --- /dev/null +++ b/crates/engine/tests/it/paste_many.rs @@ -0,0 +1,209 @@ +//! Paste of many objects: what lands in the document (nodes, ids, names, order, selection, one undo +//! step), and the shortcuts the paste takes for objects that have nothing to relink or rename. + +use std::collections::HashSet; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind}; +use vectorcraft_engine::Session; +use vectorcraft_geom::Point; + +fn run(s: &mut Session, command: &str, params: Value) -> Value { + s.execute(command, ¶ms).unwrap() +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn ids_of(v: &Value) -> Vec { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + id_of(&run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 8, "height": 8}))) +} + +/// Three named groups of three named rectangles each, on the document's only layer. +fn named_groups() -> Session { + let mut doc = Document::new(400.0, 400.0); + let layer = doc.layers[0].id; + for g in 0..3 { + let group = doc.alloc_id(); + let mut node = Node::group(group, vec![]); + node.name = Some(format!("group {g}")); + doc.insert(Some(layer), usize::MAX, node).unwrap(); + for r in 0..3 { + let x = f64::from(g * 3 + r) * 10.0; + let shape = vectorcraft_geom::rect_from_points(Point::new(x, 0.0), Point::new(x + 8.0, 8.0)); + let appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0); + let id = doc.alloc_id(); + let mut node = Node::path(id, vectorcraft_geom::shapes::rectangle(shape), appearance); + node.name = Some(format!("rect {g}.{r}")); + doc.insert(Some(group), usize::MAX, node).unwrap(); + } + } + let mut s = Session::new(); + s.add_document(doc, None); + s +} + +/// `n` and its descendants in tree order, as (id, name). +fn tree(n: &Node) -> Vec<(NodeId, Option)> { + let mut out = vec![]; + n.walk(&mut |c| out.push((c.id, c.name.clone()))); + out +} + +#[test] +fn a_paste_of_groups_gives_the_same_nodes_new_ids_in_tree_order_and_one_undo_step() { + let mut s = named_groups(); + run(&mut s, "select.all", json!({})); + run(&mut s, "edit.copy", json!({})); + let st = s.doc().unwrap(); + let (first_id, steps, before) = (st.doc.peek_next_id(), st.history.undo.len(), st.doc.clone()); + let sources: Vec = st.selection.objects.clone(); + + let pasted = run(&mut s, "edit.paste", json!({"dx": 5, "dy": 7})); + let ids = ids_of(&pasted); + let st = s.doc().unwrap(); + + // The copies, on top of the layer in the order of their sources, are selected. + assert_eq!(ids.len(), sources.len()); + assert_eq!(st.selection.objects, ids); + let top: Vec = st.doc.layers[0].children().unwrap().iter().map(|c| c.id).collect(); + assert_eq!(top[sources.len()..], ids[..]); + assert_eq!(top[..sources.len()], sources[..]); + + // Names and geometry match the sources; ids run on from the counter in tree order. + let mut next = first_id; + for (source, copy) in sources.iter().zip(&ids) { + let (source, copy) = (st.doc.node(*source).unwrap(), st.doc.node(*copy).unwrap()); + let (a, b) = (tree(source), tree(copy)); + assert_eq!(a.len(), b.len()); + for ((_, name_a), (id_b, name_b)) in a.iter().zip(&b) { + assert_eq!(name_a, name_b); + assert_eq!(id_b.0, next); + next += 1; + } + let (from, to) = (source.geometric_bounds().unwrap(), copy.geometric_bounds().unwrap()); + assert!((to.x0 - from.x0 - 5.0).abs() < 1e-9 && (to.y0 - from.y0 - 7.0).abs() < 1e-9, "{from:?} {to:?}"); + } + assert_eq!(st.doc.peek_next_id(), next); + + // One undo step, back to the document as it was. + assert_eq!(st.history.undo.len(), steps + 1); + run(&mut s, "edit.undo", json!({})); + let st = s.doc().unwrap(); + assert_eq!(st.history.undo.len(), steps); + assert_eq!(*st.doc, *before); +} + +#[test] +fn pasted_type_in_a_group_gets_its_layout_bounds() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 500, "height": 200})); + let svg = r#"WWWMMM"#; + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + run(&mut s, "edit.paste", json!({})); + let mut checked = 0; + s.doc().unwrap().doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + assert!(t.cached_bounds.is_some(), "{:?} has no layout bounds", n.id); + checked += 1; + } + }); + assert_eq!(checked, 2); +} + +/// A group holding point type and a rectangle: (the group, the type). +fn group_with_type() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 500, "height": 200})); + let text = id_of(&run(&mut s, "text.create", json!({"x": 10, "y": 40, "text": "a", "size": 12}))); + let other = rect(&mut s, 100.0); + run(&mut s, "select.set", json!({"ids": [text.0, other.0]})); + let group = id_of(&run(&mut s, "object.group", json!({}))); + (s, group, text) +} + +#[test] +fn find_and_replace_given_a_group_and_type_in_it_changes_that_type_once() { + let (mut s, group, text) = group_with_type(); + // Replacing "a" with "aa" twice would leave "aaaa". + run(&mut s, "edit.findReplace", json!({"find": "a", "replace": "aa", "ids": [group.0, text.0, group.0]})); + let doc = &s.doc().unwrap().doc; + let NodeKind::Text(t) = &doc.node(text).unwrap().kind else { panic!("the type is gone") }; + assert_eq!(t.runs.iter().map(|r| r.text.as_str()).collect::(), "aa"); +} + +#[test] +fn a_type_command_given_a_group_and_type_in_it_lists_that_type_once() { + let (mut s, group, text) = group_with_type(); + let changed = run(&mut s, "type.orientation.vertical", json!({"ids": [group.0, text.0, group.0]})); + assert_eq!(ids_of(&changed), vec![text]); +} + +#[test] +fn a_pasted_objects_on_path_group_names_its_own_copies() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 500, "height": 200})); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + let path = id_of(&run(&mut s, "shape.line", json!({"x1": 0, "y1": 100, "x2": 300, "y2": 100}))); + let group = id_of(&run(&mut s, "object.objectsOnPath.attach", json!({"path": path.0, "ids": [a.0, b.0]}))); + + // Inside another group too: every level of a copy gets new ids. + let plain = rect(&mut s, 200.0); + run(&mut s, "select.set", json!({"ids": [group.0, plain.0]})); + let outer = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "select.set", json!({"ids": [outer.0]})); + run(&mut s, "edit.copy", json!({})); + let pasted = ids_of(&run(&mut s, "edit.paste", json!({}))); + + let doc = &s.doc().unwrap().doc; + let copy = doc.node(pasted[0]).unwrap().children().unwrap().iter().find(|c| c.extras().objects_on_path.is_some()).unwrap(); + let rec = copy.extras().objects_on_path.as_deref().unwrap(); + let children: HashSet = copy.children().unwrap().iter().map(|c| c.id).collect(); + assert!(children.contains(&rec.path), "the path {:?} is not in the copy", rec.path); + assert_ne!(rec.path, path); + assert_eq!(rec.members.len(), 2); + for m in &rec.members { + assert!(children.contains(&m.id), "the member {:?} is not in the copy", m.id); + } +} + +#[test] +fn a_pasted_object_keeps_its_graphic_style_under_the_id_it_gets_in_the_document() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 500, "height": 200})); + let source = rect(&mut s, 10.0); + run(&mut s, "paint.setFill", json!({"ids": [source.0], "color": "#ff0000"})); + run(&mut s, "graphicStyle.new", json!({"name": "Copied", "id": source.0})); + run(&mut s, "select.set", json!({"ids": [source.0]})); + run(&mut s, "edit.copy", json!({})); + + // A second document whose own style already has the id the copied one has. + run(&mut s, "file.new", json!({"width": 500, "height": 200})); + let own = rect(&mut s, 10.0); + run(&mut s, "paint.setFill", json!({"ids": [own.0], "color": "#0000ff"})); + run(&mut s, "graphicStyle.new", json!({"name": "Own", "id": own.0})); + let pasted = ids_of(&run(&mut s, "edit.paste", json!({}))); + + let doc = &s.doc().unwrap().doc; + let link = doc.node(pasted[0]).unwrap().extras().graphic_style; + let copied = doc.graphic_styles.iter().find(|g| g.name == "Copied").unwrap().id; + assert_ne!(copied, doc.graphic_styles.iter().find(|g| g.name == "Own").unwrap().id); + assert_eq!(link, Some(copied)); + assert_eq!(doc.node(own).unwrap().extras().graphic_style, doc.graphic_styles.iter().find(|g| g.name == "Own").map(|g| g.id)); +} + +#[test] +fn a_pasted_object_without_a_graphic_style_stays_without_one() { + let mut s = named_groups(); + run(&mut s, "select.all", json!({})); + run(&mut s, "edit.copy", json!({})); + for id in ids_of(&run(&mut s, "edit.paste", json!({}))) { + s.doc().unwrap().doc.node(id).unwrap().walk(&mut |n| assert_eq!(n.extras().graphic_style, None)); + } +} diff --git a/crates/engine/tests/it/three_d_light_color.rs b/crates/engine/tests/it/three_d_light_color.rs index cb04c5649e..91ce875796 100644 --- a/crates/engine/tests/it/three_d_light_color.rs +++ b/crates/engine/tests/it/three_d_light_color.rs @@ -48,7 +48,7 @@ fn all_four_light_colors_save_reopen_undo_and_expand_without_editing_source() { assert_eq!(doc(&s), &red); let svg = s.execute("document.serialize", &json!({"format":"svg"})).unwrap(); let text = svg["text"].as_str().unwrap(); - assert!(text.contains(" 0 && !text.contains(" = Mutex::new(()); + +fn process() -> MutexGuard<'static, ()> { + PROCESS.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn style() -> CharStyle { + CharStyle { size: 40.0, ..CharStyle::default() } +} + +fn file_of(objects: Vec) -> Vec { + let mut doc = Document::new(f64::from(WIDTH), f64::from(HEIGHT)); + let layer = doc.layers[0].id; + for (i, mut t) in objects.into_iter().enumerate() { + t.xf = Affine::translate((20.0, 70.0 * (i + 1) as f64)); + let id = doc.alloc_id(); + doc.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); + } + vectorcraft_format::save_file(&doc) +} + +fn latin() -> Vec { + file_of(["Plain Latin type", "AVATAR office", "123 ... 456"].map(|s| TextObject::point(Point::ZERO, s, style())).into()) +} + +fn mixed_fonts() -> Vec { + let font = |family: &str, text: &str| TextRun::new(text, CharStyle { font_family: family.into(), ..style() }); + let mut mixed = TextObject::point(Point::ZERO, "", style()); + mixed.runs = vec![font("Inter", "Inter "), font("JetBrains Mono", "Mono "), font("Source Serif 4", "Serif "), font("No Such Family", "Missing")]; + file_of(vec![mixed, TextObject::point(Point::ZERO, "Source Sans", style())]) +} + +fn complex_scripts() -> Vec { + let scripts = [ + "\u{645}\u{631}\u{62d}\u{628}\u{627}", + "\u{5e9}\u{5dc}\u{5d5}\u{5dd}", + "\u{928}\u{92e}\u{938}\u{94d}\u{924}\u{947}", + "\u{e2a}\u{e27}\u{e31}\u{e2a}\u{e14}\u{e35}", + "\u{65e5}\u{672c}\u{8a9e} abc", + ]; + file_of(scripts.map(|s| TextObject::point(Point::ZERO, s, style())).into()) +} + +/// Area type, and a story through two frames, as a session saves them. +fn threaded_story() -> Vec { + let mut s = Session::new(); + s.add_document(Document::new(f64::from(WIDTH), f64::from(HEIGHT)), None); + let story = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame. ".repeat(4); + let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}})).unwrap()["id"] + .as_u64() + .unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute( + "text.create", + &json!({"x": 10, "y": 300, "text": "Area type on its own. ".repeat(20), "size": 12, "area": {"width": 300, "height": 200}}), + ) + .unwrap(); + vectorcraft_format::save_file(&s.doc().unwrap().doc) +} + +fn documents() -> Vec<(&'static str, Vec)> { + vec![("Latin", latin()), ("mixed fonts", mixed_fonts()), ("complex scripts", complex_scripts()), ("threaded story", threaded_story())] +} + +/// The session `bytes` opened in, as `document.open` reads a file and then opens it. +fn open(bytes: &[u8]) -> Session { + let name = "layouts.vectorcraft"; + let mut s = Session::new(); + let read = fileio::read_for_open(name, bytes, Some(name.into()), &Value::Null, false, false).unwrap(); + fileio::open_read(&mut s, read).unwrap(); + s +} + +fn frame(doc: &Document) -> Vec { + Renderer::new().render(doc, WIDTH, HEIGHT, Affine::IDENTITY, &RenderOptions::default()).pixels +} + +fn type_objects(doc: &Document) -> Vec { + let mut all = vec![]; + doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + all.push((**t).clone()); + } + }); + all +} + +/// Open once to load every font the document uses: a load changes the font database's generation. +fn fonts_loaded(bytes: &[u8]) { + let s = open(bytes); + frame(&s.doc().unwrap().doc); + drop_kept_layouts(); +} + +#[test] +fn the_first_frame_draws_the_pixels_of_laying_every_object_out_again() { + let _process = process(); + for (name, bytes) in documents() { + fonts_loaded(&bytes); + let s = open(&bytes); + let doc = &s.doc().unwrap().doc; + let taken = frame(doc); + drop_kept_layouts(); + let again = frame(doc); + assert!(again != frame(&Document::new(f64::from(WIDTH), f64::from(HEIGHT))), "{name}: the frame shows the type"); + let differing = taken.iter().zip(&again).filter(|(a, b)| a != b).count(); + assert_eq!((taken.len(), differing), (again.len(), 0), "{name}: bytes of the frame that differ"); + } +} + +#[test] +fn the_kept_layouts_are_the_layouts_of_the_opened_objects() { + let _process = process(); + for (name, bytes) in documents() { + fonts_loaded(&bytes); + let s = open(&bytes); + let doc = &s.doc().unwrap().doc; + let mut taken = 0; + let frame_drawn = KeptLayoutsFrame::begin(); + for t in type_objects(doc) { + let fresh = vectorcraft_text::layout(FontDb::global(), &t); + assert_eq!(t.cached_bounds, Some(fresh.bounds), "{name}: {:?}", t.plain_text()); + assert_eq!(t.cached_baselines, fresh.baselines(), "{name}: {:?}", t.plain_text()); + if let Some(kept) = vectorcraft_text::take_kept_layout(&t) { + let outlines = + |l: &vectorcraft_text::TextLayout| l.glyphs.iter().map(|g| (g.font_id, g.gid, g.origin, g.outline.clone())).collect::>(); + assert!(outlines(&kept) == outlines(&fresh), "{name}: {:?}", t.plain_text()); + assert_eq!(kept.bounds, fresh.bounds, "{name}: {:?}", t.plain_text()); + taken += 1; + } + } + assert!(taken > 0, "{name}: the open kept layouts"); + drop(frame_drawn); + drop_kept_layouts(); + let again = open(&bytes); + assert!(*again.doc().unwrap().doc == **doc, "{name}: another open reads the same document"); + drop_kept_layouts(); + } +} + +#[test] +fn the_first_frame_lays_out_no_object_the_open_laid_out() { + let _process = process(); + let bytes = latin(); + fonts_loaded(&bytes); + let s = open(&bytes); + let doc = &s.doc().unwrap().doc; + let before = layouts_on_this_thread(); + frame(doc); + assert_eq!(layouts_on_this_thread() - before, 0, "the frame takes every layout"); + // A second renderer has nothing left to take. + let before = layouts_on_this_thread(); + frame(doc); + assert_eq!(layouts_on_this_thread() - before, 3); +} + +#[test] +fn an_edited_object_is_laid_out_again() { + let _process = process(); + let bytes = latin(); + fonts_loaded(&bytes); + let mut s = open(&bytes); + let id = { + let mut ids = vec![]; + s.doc().unwrap().doc.walk(|n| { + if matches!(n.kind, NodeKind::Text(_)) { + ids.push(n.id.0); + } + }); + ids[0] + }; + s.execute("text.setText", &json!({"id": id, "text": "Edited"})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let before = layouts_on_this_thread(); + let edited = frame(&doc); + assert_eq!(layouts_on_this_thread() - before, 1, "only the edited object is laid out"); + drop_kept_layouts(); + assert!(edited == frame(&doc), "the frame is what laying every object out again draws"); +} + +#[test] +fn changing_the_hyphenation_exceptions_or_the_fonts_lays_every_object_out_again() { + let _process = process(); + let bytes = latin(); + fonts_loaded(&bytes); + let s = open(&bytes); + let doc = &s.doc().unwrap().doc; + vectorcraft_text::set_hyphenation_exceptions(""); + let before = layouts_on_this_thread(); + frame(doc); + assert_eq!(layouts_on_this_thread() - before, 3, "hyphenation exceptions were set"); + let s = open(&bytes); + let doc = &s.doc().unwrap().doc; + FontDb::global().add_font(vectorcraft_text::test_fonts::variable_font().unwrap()); + let generation = FontDb::global().generation(); + let before = layouts_on_this_thread(); + frame(doc); + assert_eq!(layouts_on_this_thread() - before, 3, "fonts were added (generation {generation})"); +} + +/// The layout of an object the first frame culls is dropped when that frame ends. +#[test] +fn a_frame_lets_go_of_what_it_did_not_draw() { + let _process = process(); + let mut objects = vec![TextObject::point(Point::ZERO, "In view", style())]; + objects.extend((0..3).map(|i| TextObject::point(Point::ZERO, &format!("Out of view {i}"), style()))); + let bytes = file_of(objects); + fonts_loaded(&bytes); + let s = open(&bytes); + let doc = &s.doc().unwrap().doc; + let small = Renderer::new().render(doc, 300, 100, Affine::IDENTITY, &RenderOptions::default()); + assert_eq!(small.width, 300); + let out = type_objects(doc).into_iter().find(|t| t.plain_text() == "Out of view 2").unwrap(); + let _frame = KeptLayoutsFrame::begin(); + assert!(vectorcraft_text::take_kept_layout(&out).is_none()); +} + +/// A thumbnail lays its object out, and the first frame still takes that object's layout. +#[test] +fn a_thumbnail_leaves_the_layouts_for_the_first_frame() { + let _process = process(); + let bytes = latin(); + fonts_loaded(&bytes); + let s = open(&bytes); + let doc = &s.doc().unwrap().doc; + let mut ids = vec![]; + doc.walk(|n| { + if matches!(n.kind, NodeKind::Text(_)) { + ids.push(n.id); + } + }); + let before = layouts_on_this_thread(); + assert!(Renderer::new().render_thumbnail(doc, ids[0], 64).is_some()); + assert_eq!(layouts_on_this_thread() - before, 1, "the thumbnail lays its object out"); + let before = layouts_on_this_thread(); + frame(doc); + assert_eq!(layouts_on_this_thread() - before, 0, "the frame takes every layout"); +} + +/// A frame of ink amounts ends like any other. +#[test] +fn an_ink_frame_lets_go_of_what_it_did_not_draw() { + let _process = process(); + let mut objects = vec![TextObject::point(Point::ZERO, "In view", style())]; + objects.extend((0..3).map(|i| TextObject::point(Point::ZERO, &format!("Out of view {i}"), style()))); + let bytes = file_of(objects); + fonts_loaded(&bytes); + let s = open(&bytes); + let doc = &s.doc().unwrap().doc; + let region = vectorcraft_geom::Rect::new(0.0, 0.0, 300.0, 100.0); + assert!(!Renderer::new().render_region_inks(doc, region, 1.0, &RenderOptions::default()).is_empty()); + let out = type_objects(doc).into_iter().find(|t| t.plain_text() == "Out of view 2").unwrap(); + let _frame = KeptLayoutsFrame::begin(); + assert!(vectorcraft_text::take_kept_layout(&out).is_none()); +} diff --git a/crates/engine/tests/open_type_plans.rs b/crates/engine/tests/open_type_plans.rs new file mode 100644 index 0000000000..6ee4c99e6c --- /dev/null +++ b/crates/engine/tests/open_type_plans.rs @@ -0,0 +1,123 @@ +//! A document of type opened with the shaping plans font faces keep, compared with the same file +//! opened while every shaped segment makes a plan of its own: the nodes and the first frame's +//! pixels are the same. Its own test binary: the switch for kept plans applies to the whole process. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::{Mutex, MutexGuard, Once}; + +use serde_json::Value; +use vectorcraft_doc::{CharStyle, Document, Node, NodeKind, TextObject, TextRun}; +use vectorcraft_engine::Session; +use vectorcraft_engine::cmd::fileio; +use vectorcraft_geom::{Affine, Point}; +use vectorcraft_render::{RenderOptions, Renderer}; +use vectorcraft_text::FontDb; +use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, keep_shape_plans, variable_font}; + +const WIDTH: u32 = 900; +const HEIGHT: u32 = 1300; + +/// Taken by each test: the switch for kept plans applies to the whole process. +static SWITCH: Mutex<()> = Mutex::new(()); + +fn switch() -> MutexGuard<'static, ()> { + SWITCH.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn style() -> CharStyle { + CharStyle { size: 60.0, ..CharStyle::default() } +} + +/// A saved document of type objects whose shaping differs in script, direction, language, features +/// and variable font instance, the object in the plain style first. +fn file() -> Vec { + static ADD_FONT: Once = Once::new(); + ADD_FONT.call_once(|| { + FontDb::global().add_font(variable_font().unwrap()); + }); + let manual = CharStyle { kerning: Some(0.0), ..style() }; + let variable = |name: &str| CharStyle { font_family: VARIABLE_FAMILY.into(), font_style: name.into(), ..style() }; + let mut mixed = TextObject::point(Point::ZERO, "AVAV", style()); + mixed.runs = vec![TextRun::new("AV", style()), TextRun::new("AV", manual.clone())]; + let mut vertical = TextObject::point(Point::ZERO, "AB\u{65e5}\u{672c}", style()); + vertical.vertical = true; + let objects = [ + TextObject::point(Point::ZERO, "AVATAR office", style()), + TextObject::point(Point::ZERO, "To Wa fi", style()), + TextObject::point(Point::ZERO, "123 ... 456", style()), + TextObject::point(Point::ZERO, "AVAV", manual), + mixed, + TextObject::point(Point::ZERO, "fi office", CharStyle { language: Some("tr".into()), ..style() }), + TextObject::point(Point::ZERO, "AVAV", CharStyle { optical_kerning: true, ..style() }), + TextObject::point(Point::ZERO, "Small Caps", CharStyle { small_caps: Some(70.0), ..style() }), + TextObject::point(Point::ZERO, "\u{645}\u{631}\u{62d}\u{628}\u{627}", style()), + TextObject::point(Point::ZERO, "\u{5e9}\u{5dc}\u{5d5}\u{5dd}", style()), + TextObject::point(Point::ZERO, "lIn lIn", variable("Regular")), + TextObject::point(Point::ZERO, "lIn lIn", variable("Bold")), + vertical, + ]; + let mut doc = Document::new(WIDTH as f64, HEIGHT as f64); + let layer = doc.layers[0].id; + let count = objects.len(); + for (i, mut t) in objects.into_iter().enumerate() { + // Rows down the page; the vertical object, last, stands in the right margin. + t.xf = Affine::translate(if i + 1 == count { (800.0, 60.0) } else { (20.0, 90.0 * (i + 1) as f64) }); + let id = doc.alloc_id(); + doc.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); + } + vectorcraft_format::save_file(&doc) +} + +/// The session `bytes` opened in, as `document.open` reads a file and then opens it. +fn open(bytes: &[u8]) -> Session { + let name = "plans.vectorcraft"; + let mut s = Session::new(); + let read = fileio::read_for_open(name, bytes, Some(name.into()), &Value::Null, false, false).unwrap(); + fileio::open_read(&mut s, read).unwrap(); + s +} + +fn first_frame(doc: &Document) -> Vec { + Renderer::new().render(doc, WIDTH, HEIGHT, Affine::IDENTITY, &RenderOptions::default()).pixels +} + +#[test] +fn an_opened_document_has_the_nodes_of_one_laid_out_with_plans_of_their_own() { + let _switch = switch(); + let bytes = file(); + keep_shape_plans(false); + let own = open(&bytes); + keep_shape_plans(true); + // The second open shapes every object with plans a face kept. + open(&bytes); + let kept = open(&bytes); + let (own, kept) = (own.doc().unwrap(), kept.doc().unwrap()); + let mut laid_out = 0; + kept.doc.walk(|node| { + if let NodeKind::Text(t) = &node.kind { + assert!(t.cached_bounds.is_some(), "{:?}", t.plain_text()); + laid_out += 1; + } + }); + assert_eq!(laid_out, 13); + assert_eq!(kept.doc.layers, own.doc.layers); + assert!(*kept.doc == *own.doc, "the whole document is the same"); +} + +#[test] +fn an_opened_document_draws_the_first_frame_of_one_shaped_with_plans_of_its_own() { + let _switch = switch(); + let bytes = file(); + let opened = open(&bytes); + let doc = &opened.doc().unwrap().doc; + keep_shape_plans(false); + let own = first_frame(doc); + keep_shape_plans(true); + // Lays out each object with plans a face kept: the first frame lays type out again. + first_frame(doc); + let kept = first_frame(doc); + assert_ne!(kept, first_frame(&Document::new(WIDTH as f64, HEIGHT as f64)), "the frame shows the type"); + let differing = kept.iter().zip(&own).filter(|(a, b)| a != b).count(); + assert_eq!((kept.len(), differing), (own.len(), 0), "bytes of the frame that differ"); +} diff --git a/crates/engine/tests/plugin_clear_cache.rs b/crates/engine/tests/plugin_clear_cache.rs new file mode 100644 index 0000000000..74ba69d644 --- /dev/null +++ b/crates/engine/tests/plugin_clear_cache.rs @@ -0,0 +1,65 @@ +//! `plugin.clearCache` without an id empties the cache of every installed plug-in and leaves their +//! settings. +//! +//! A test binary of its own: installed plug-ins are process-wide, so clearing every plug-in's cache +//! in the engine's other tests would empty the caches those tests check. +// 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 serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_plugins::wat as tpl; + +/// Sets "zoom" to "hello" and writes "hel" to the cache entry "tile". +const WRITES: &str = "(if (call $vc_settings_set (i32.const 0x2000) (i32.const 4) (i32.const 0x2100) (i32.const 5)) (then unreachable)) + (if (call $vc_cache_write (i32.const 0x2004) (i32.const 4) (i32.const 0x2100) (i32.const 3)) (then unreachable))"; + +/// Traps unless "zoom" is "hello". +const READS: &str = + "(if (i32.ne (call $vc_settings_get (i32.const 0x2000) (i32.const 4) (i32.const 0x3000) (i32.const 16)) (i32.const 5)) (then unreachable)) + (if (i32.ne (i32.load (i32.const 0x3000)) (i32.load (i32.const 0x2100))) (then unreachable))"; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// Installs a filter `id` of API level 2 that lists `settings` and `cache` and whose `vc_run` runs +/// `first`, in place of any module installed with its id (`replace: true`). +fn install_storing(s: &mut Session, id: &str, first: &str) { + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["settings","cache"]}}"#); + let data = format!(r#"{} (data (i32.const 0x2000) "zoomtile") (data (i32.const 0x2100) "hello")"#, tpl::STORAGE_IMPORTS); + let wasm = wat::parse_str(tpl::with_imports(&manifest, &data, first, r#"{"objects":[]}"#)).unwrap(); + let data = vectorcraft_format::base64_encode(&wasm); + run(s, "plugin.install", json!({"dataBase64": data, "grant": ["settings", "cache"], "replace": true})); +} + +#[test] +fn clearing_every_cache_empties_each_plugins_cache_and_keeps_its_settings() { + let folder = std::env::temp_dir().join(format!("vc-plugin-clear-cache-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + let ids = ["test.clearcache.a", "test.clearcache.b"]; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + s.attach_plugin_store(folder.clone()); + for id in ids { + install_storing(&mut s, id, WRITES); + run(&mut s, "plugin.run", json!({"id": id, "ids": []})); + assert_eq!(run(&mut s, "plugin.info", json!({"id": id}))["cacheBytes"], json!(3)); + } + + assert_eq!(run(&mut s, "plugin.clearCache", json!({})), json!({"cleared": ids, "bytesFreed": 6})); + for id in ids { + assert_eq!(run(&mut s, "plugin.info", json!({"id": id}))["cacheBytes"], json!(0)); + // The settings stay: a module that reads them runs. + install_storing(&mut s, id, READS); + run(&mut s, "plugin.run", json!({"id": id, "ids": []})); + } + // Nothing is left to clear. + assert_eq!(run(&mut s, "plugin.clearCache", json!({})), json!({"cleared": ids, "bytesFreed": 0})); + + for id in ids { + run(&mut s, "plugin.remove", json!({"id": id})); + } + let _ = std::fs::remove_dir_all(&folder); +} diff --git a/crates/engine/tests/plugin_export.rs b/crates/engine/tests/plugin_export.rs index 1a49f800a9..df06b5ee29 100644 --- a/crates/engine/tests/plugin_export.rs +++ b/crates/engine/tests/plugin_export.rs @@ -69,9 +69,8 @@ fn an_exporter_adds_a_write_only_format_while_it_is_installed() { assert!(e.to_string().contains("unknown format"), "{e}"); } -/// The exporter is given the document as a native file's JSON: what `document.save` writes before -/// the data of large images, which stays behind (compact, where a save of a small document is -/// indented). +/// The exporter receives the native document JSON without optional save renditions or preference +/// metadata. Large image bytes stay in the saved file's tail; plug-in input stays compact. #[test] fn the_exporter_is_given_the_native_file_s_json() { let mut s = session(); @@ -94,8 +93,14 @@ fn the_exporter_is_given_the_native_file_s_json() { let saved = exported(&s.execute("document.save", &json!({})).unwrap()); assert!(saved.len() > given.len() + png.len(), "the image data follows the JSON in the saved file"); let doc: Value = serde_json::from_slice(&given).unwrap(); - let saved_json: Value = serde_json::from_slice(vectorcraft_format::json_part(&saved)).unwrap(); - assert_eq!(doc, saved_json, "the saved file's JSON"); + let mut saved_json: Value = serde_json::from_slice(vectorcraft_format::json_part(&saved)).unwrap(); + assert!(saved_json.get("pdf").is_some(), "a default application save carries a PDF"); + assert_eq!(saved_json["pdfCompatible"], true); + assert!(doc.get("pdf").is_none() && doc.get("pdfCompatible").is_none(), "the plug-in input omits optional save members"); + let saved_members = saved_json.as_object_mut().unwrap(); + saved_members.remove("pdf"); + saved_members.remove("pdfCompatible"); + assert_eq!(doc, saved_json, "the native document JSON without optional save members"); assert!(!given.contains(&b'\n'), "without indentation"); assert_eq!((&doc["format"], &doc["version"]), (&json!("vectorcraft"), &json!(vectorcraft_format::VERSION))); let images = doc["images"].as_object().unwrap(); diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index ac982a20ea..94b702ca8d 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -1,9 +1,11 @@ //! Untrusted plug-ins never crash the app: mutated and garbage modules handed to `plugin.install`, //! and plug-ins returning hostile output (random JSON in the object model's shape: huge or //! malformed coordinates, unknown ids, broken paints and gradients, junk of every type) as object -//! filters (`plugin.run`) or live effects (`effect.apply`). Each run must end as an error that -//! leaves the document as it was, or as a document that then renders and exports, without a -//! panic. +//! filters (`plugin.run`) or live effects (`effect.apply`), and plug-ins running bulk memory +//! instructions (`memory.fill`, `memory.copy`, `memory.init`, `data.drop`) on ranges in, at and past +//! the ends of memory and the data segment, under small and default budgets. Each run must end as +//! an error that leaves the document as it was, or as a document that then renders and exports, +//! without a panic. A bulk memory run traps exactly when a range leaves its region. //! //! `PROPTEST_CASES=2000 cargo test -p vectorcraft-engine --test plugin_fuzz` runs a deeper search. // Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). @@ -13,6 +15,7 @@ use proptest::prelude::*; use serde_json::{Map, Value, json}; use vectorcraft_engine::Session; use vectorcraft_plugins::wat as tpl; +use vectorcraft_plugins::{Error, Limits, Plugin}; use vectorcraft_testkit::catch_quiet; use vectorcraft_testkit::fixtures::rich_session; @@ -27,8 +30,9 @@ fn config() -> ProptestConfig { c } +/// Installs `wasm`, in place of any module installed with its id before (`replace: true`). fn install(s: &mut Session, wasm: &[u8]) -> Result { - s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(wasm)})).map_err(|e| e.to_string()) + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(wasm), "replace": true})).map_err(|e| e.to_string()) } /// The document renders and exports without panicking. @@ -157,6 +161,272 @@ fn arb_paint() -> impl Strategy { ] } +/// Bytes in the passive data segment that bulk memory cases initialize memory from. +const SEGMENT_LEN: u32 = 4096; + +/// Fuel the host hands a run per slice (`FUEL_SLICE` in `vectorcraft_plugins`' runtime). +const FUEL_SLICE: u64 = 20_000_000; + +/// Where a bulk memory plug-in keeps its output (the manifest sits at 16). +const BULK_OUTPUT_AT: u32 = 0x8000; + +/// The output a bulk memory plug-in returns. +const BULK_OUTPUT: &str = r#"{"objects":[]}"#; + +/// The input and parameters a bulk memory plug-in is run on directly: each takes one page, so the +/// memory then ends two pages after the module's initial pages. +const BULK_INPUT: &[u8] = BULK_OUTPUT.as_bytes(); +const BULK_PARAMS: &[u8] = b"{}"; + +/// The end of memory in WAT, read when the instruction runs. +const MEMORY_END: &str = "(i32.shl (memory.size) (i32.const 16))"; + +/// A bulk memory instruction a generated plug-in runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum BulkOp { + /// `memory.fill` over the destination range. + Fill, + /// `memory.copy` from the source range to the destination range, which may overlap. + Copy, + /// `memory.init` from the data segment, then `data.drop`. + Init, + /// `data.drop`, then `memory.init` from the emptied segment. + Drop, +} + +impl BulkOp { + const ALL: [BulkOp; 4] = [BulkOp::Fill, BulkOp::Copy, BulkOp::Init, BulkOp::Drop]; + + /// The instruction a module running this operation contains. + fn opcode(self) -> &'static str { + match self { + BulkOp::Fill => "memory.fill", + BulkOp::Copy => "memory.copy", + BulkOp::Init => "memory.init", + BulkOp::Drop => "data.drop", + } + } +} + +/// What an offset is measured from: the start, the end, or the end less the length (a range that +/// ends exactly at the end). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Base { + Start, + End, + EndLessLen, +} + +/// An offset into memory or the data segment: `base` plus `delta`, in the wrapping 32-bit +/// arithmetic the module computes it in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Offset { + base: Base, + delta: i32, +} + +impl Offset { + const fn start(delta: i32) -> Self { + Offset { base: Base::Start, delta } + } + + /// The offset in a region that ends at `end`, for a range of `len` bytes. + fn value(self, end: u32, len: u32) -> u32 { + let base = match self.base { + Base::Start => 0, + Base::End => end, + Base::EndLessLen => end.wrapping_sub(len), + }; + base.wrapping_add_signed(self.delta) + } + + /// The WAT computing the offset, with `end` the WAT of the region's end. + fn wat(self, end: &str, len: u32) -> String { + let base = match self.base { + Base::Start => "(i32.const 0)".to_string(), + Base::End => end.to_string(), + Base::EndLessLen => format!("(i32.sub {end} (i32.const {len}))"), + }; + format!("(i32.add {base} (i32.const {}))", self.delta) + } +} + +/// A plug-in whose run executes one bulk memory instruction. +#[derive(Clone, Copy, Debug)] +struct BulkCase { + op: BulkOp, + /// The destination in memory. + dst: Offset, + /// The source: in memory for `Copy`, in the data segment for `Init` and `Drop`. + src: Offset, + len: u32, + /// The byte `Fill` writes. + value: u8, + /// How many times `Fill` and `Copy` run; `Init` and `Drop` run once. + repeat: u32, + /// Initial memory pages. + pages: u32, +} + +impl BulkCase { + fn runs(self) -> u32 { + match self.op { + BulkOp::Fill | BulkOp::Copy => self.repeat.max(1), + BulkOp::Init | BulkOp::Drop => 1, + } + } + + /// The memory end when the plug-in is run on [`BULK_INPUT`] and [`BULK_PARAMS`]. + fn end(self) -> u32 { + (self.pages + 2) << 16 + } + + /// Whether every range the instruction touches lies inside memory ending at `end` and inside + /// the data segment (empty once dropped). A range may end exactly at the end; an offset past + /// the end traps even for zero bytes. + fn in_bounds(self, end: u32) -> bool { + let fits = |off: u32, end: u32| u64::from(off) + u64::from(self.len) <= u64::from(end); + let dst = fits(self.dst.value(end, self.len), end); + let segment = self.src.value(SEGMENT_LEN, self.len); + match self.op { + BulkOp::Fill => dst, + BulkOp::Copy => dst && fits(self.src.value(end, self.len), end), + BulkOp::Init => dst && fits(segment, SEGMENT_LEN), + BulkOp::Drop => dst && fits(segment, 0), + } + } + + /// A generous estimate of the fuel the instructions use: a unit per 64 bytes moved, and a few + /// per pass. + fn fuel(self) -> u64 { + u64::from(self.runs()) * (u64::from(self.len) / 64 + 16) + } + + /// The plug-in module in WAT, with `manifest`. + fn wat(self, manifest: &str) -> String { + let (dst, len) = (self.dst.wat(MEMORY_END, self.len), self.len); + let segment = self.src.wat(&format!("(i32.const {SEGMENT_LEN})"), len); + let op = match self.op { + BulkOp::Fill => format!("(memory.fill {dst} (i32.const {}) (i32.const {len}))", self.value), + BulkOp::Copy => format!("(memory.copy {dst} {} (i32.const {len}))", self.src.wat(MEMORY_END, len)), + BulkOp::Init => format!("(memory.init $seg {dst} {segment} (i32.const {len})) (data.drop $seg)"), + BulkOp::Drop => format!("(data.drop $seg) (memory.init $seg {dst} {segment} (i32.const {len}))"), + }; + let run = format!( + "(local $n i32) (local.set $n (i32.const {runs})) + (block $done (loop $again + (br_if $done (i32.eqz (local.get $n))) + (local.set $n (i32.sub (local.get $n) (i32.const 1))) + {op} + (br $again))) + (i64.or (i64.shl (i64.const {out_len}) (i64.const 32)) (i64.const {BULK_OUTPUT_AT}))", + runs = self.runs(), + out_len = BULK_OUTPUT.len(), + ); + let bytes: String = (0..SEGMENT_LEN).map(|i| char::from(b'a' + (i % 26) as u8)).collect(); + let extra = format!(r#"(data $seg "{}") (data (i32.const {BULK_OUTPUT_AT}) "{}")"#, bytes, tpl::string(BULK_OUTPUT)); + tpl::module(manifest, &run, &extra, self.pages) + } +} + +/// Lengths: zero, a byte, around the 64 bytes a unit of fuel pays for, the data segment's length, +/// a page, a mebibyte, or anything up to four pages. +fn arb_bulk_len() -> impl Strategy { + prop_oneof![ + 3 => prop::sample::select(vec![0u32, 1, 63, 64, 65, SEGMENT_LEN - 1, SEGMENT_LEN, SEGMENT_LEN + 1, 0xffff, 0x1_0000, 0x1_0001, 1 << 20]), + 1 => 0u32..0x4_0000, + ] +} + +/// Offsets: near the start, ending at, before or past the end, at the end, or one past it. +fn arb_bulk_offset() -> impl Strategy { + prop_oneof![ + 3 => prop::sample::select(vec![0i32, 1, 100, BULK_OUTPUT_AT as i32]).prop_map(Offset::start), + 3 => (-2i32..=2).prop_map(|delta| Offset { base: Base::EndLessLen, delta }), + 2 => (-1i32..=1).prop_map(|delta| Offset { base: Base::End, delta }), + 1 => any::().prop_map(Offset::start), + ] +} + +/// How many times `Fill` and `Copy` run. +#[derive(Clone, Copy, Debug)] +enum Repeat { + Times(u32), + /// As many passes as a slice of fuel pays for the bytes, plus this (at most 2,000 passes). + AroundSlice(i64), +} + +/// Bulk memory cases in initial memories of 1, 2 or 17 pages. +fn arb_bulk_case() -> impl Strategy { + ( + prop::sample::select(BulkOp::ALL.to_vec()), + arb_bulk_offset(), + arb_bulk_offset(), + arb_bulk_len(), + any::(), + prop_oneof![8 => Just(Repeat::Times(1)), 2 => (2u32..=4).prop_map(Repeat::Times), 1 => (-1i64..=1).prop_map(Repeat::AroundSlice)], + prop::sample::select(vec![1u32, 2, 17]), + ) + .prop_map(|(op, dst, src, len, value, repeat, pages)| { + let repeat = match repeat { + Repeat::Times(n) => n, + Repeat::AroundSlice(k) => { + let slice = (FUEL_SLICE * 64 / u64::from(len.max(1))) as i64; + (slice + k).clamp(1, 2_000) as u32 + } + }; + BulkCase { op, dst, src, len, value, repeat, pages } + }) +} + +/// The fuel a direct run gets: the default budget, or a budget of its own for each call with none +/// added per input byte: a small fixed one, or [`BulkCase::fuel`] plus or minus a little. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Fuel { + Default, + Fixed(u64), + AroundCost(i64), +} + +fn arb_fuel() -> impl Strategy { + prop_oneof![ + 4 => Just(Fuel::Default), + 1 => prop::sample::select(vec![1u64, 100, 1_000, 10_000]).prop_map(Fuel::Fixed), + 2 => (-64i64..64).prop_map(Fuel::AroundCost), + ] +} + +/// Runs `case` directly under `fuel`, without the engine. +fn run_bulk(case: BulkCase, fuel: Fuel) -> Result, Error> { + let wasm = wat::parse_str(case.wat(&tpl::manifest("fuzz.bulk", "filter", "{}"))).unwrap(); + let plugin = Plugin::load(&wasm, Limits::default()).unwrap(); + let fuel_base = match fuel { + Fuel::Default => return plugin.run(BULK_INPUT, BULK_PARAMS), + Fuel::Fixed(f) => f, + Fuel::AroundCost(k) => case.fuel().saturating_add_signed(k).max(1), + }; + plugin.run_limited(BULK_INPUT, BULK_PARAMS, &Limits { fuel_base, fuel_per_byte: 0, ..Limits::default() }) +} + +#[test] +fn bulk_memory_cases_reach_their_instruction() { + for op in BulkOp::ALL { + let base = BulkCase { op, dst: Offset::start(0x1_0000), src: Offset::start(0), len: 1, value: 7, repeat: 1, pages: 2 }; + let (inside, outside) = match op { + BulkOp::Fill | BulkOp::Copy => (base, BulkCase { dst: Offset { base: Base::End, delta: 0 }, ..base }), + BulkOp::Init => (base, BulkCase { src: Offset { base: Base::End, delta: 0 }, ..base }), + BulkOp::Drop => (BulkCase { len: 0, ..base }, base), + }; + let src = inside.wat(&tpl::manifest("fuzz.bulk", "filter", "{}")); + assert!(src.contains(op.opcode()), "{op:?} emits no {}", op.opcode()); + wat::parse_str(&src).unwrap(); + assert!(inside.in_bounds(inside.end()) && !outside.in_bounds(outside.end()), "{op:?}"); + assert!(run_bulk(inside, Fuel::Default).is_ok(), "{op:?} failed in bounds"); + let r = run_bulk(outside, Fuel::Default); + assert!(matches!(r, Err(Error::Trap(_))), "{op:?} out of bounds gave {r:?}"); + } +} + /// An output object: an input object's id (by index into the inputs) or a random one, and any of /// the object keys. fn arb_object() -> impl Strategy, Value)> { @@ -242,6 +512,33 @@ proptest! { renders(&s, &out)?; } + #[test] + fn bulk_memory_plugins_never_crash(case in arb_bulk_case(), fuel in arb_fuel()) { + let r = catch_quiet(|| run_bulk(case, fuel)).map_err(|msg| TestCaseError::fail(format!("panicked on {case:?}: {msg}")))?; + let in_bounds = case.in_bounds(case.end()); + let ample = fuel == Fuel::Default && case.fuel() <= FUEL_SLICE / 4; + match &r { + Ok(_) => prop_assert!(in_bounds, "{:?} ran out of bounds without a trap", case), + Err(Error::Trap(e)) => prop_assert!(!in_bounds && !e.contains("panicked"), "{:?} trapped: {}", case, e), + Err(Error::Limit(e)) => prop_assert!(fuel != Fuel::Default || (in_bounds && !ample), "{:?} hit a limit: {}", case, e), + Err(e) => return Err(TestCaseError::fail(format!("{case:?} failed: {e}"))), + } + if ample { + prop_assert!(r.is_ok() == in_bounds, "{:?} gave {:?}", case, r.err()); + } + + let mut s = rich_session(); + s.execute("select.all", &json!({})).unwrap(); + install(&mut s, &wat::parse_str(case.wat(&tpl::manifest("fuzz.bulk", "filter", "{}"))).unwrap()).unwrap(); + let before = s.doc().unwrap().doc.clone(); + match catch_quiet(|| s.execute("plugin.run", &json!({"id": "fuzz.bulk"})).map(|_| ())) { + Err(msg) => return Err(TestCaseError::fail(format!("panicked on {case:?}: {msg}"))), + Ok(Err(_)) => prop_assert!(s.doc().unwrap().doc == before, "a failed run changed the document: {:?}", case), + Ok(Ok(())) => {} + } + renders(&s, &format!("{case:?}"))?; + } + #[test] fn mutated_and_garbage_modules_never_crash( flips in prop::collection::vec((any::(), any::()), 0..8), @@ -268,4 +565,247 @@ proptest! { } renders(&s, "after mutated modules")?; } + + /// Manifests with hostile `permissions`, `api` and names (unknown, reserved and repeated + /// permissions, junk of every type, control and bidirectional override characters) parse to + /// an error or to a manifest whose permissions fit its kind, and installing one with a junk + /// `grant` ends as an error or an install, never a panic. A prompt never shows a hidden + /// character from the name. + #[test] + fn hostile_manifest_permissions_never_crash( + kind in prop::sample::select(vec!["filter", "effect", "exporter"]), + names in prop::collection::vec( + prop_oneof![ + prop::sample::select(vec!["doc.read", "doc.write", "state", "effect.render", "export.write", "progress", "ui.panel", ""]), + Just("doc.read\u{202E}"), + Just("\u{0007}"), + ], + 0..6, + ), + permissions in prop::option::weighted(0.8, prop_oneof![Just(Value::Null), arb_junk()]), + api in prop_oneof![2 => Just(json!(1)), 1 => Just(json!(2)), 1 => arb_junk()], + name in prop_oneof![3 => "[a-z\u{202E}\u{2066}\u{200F} ]{1,64}", 1 => "[a-z\u{202E}\u{2066}\u{0007}\u{200F} ]{1,80}"], + grant in prop_oneof![Just(Value::Null), arb_junk(), Just(json!(["doc.read", "doc.write", "state", "effect.render", "export.write", "progress"]))], + ) { + let mut m = json!({"id": "fuzz.permissions", "name": name, "kind": kind, "api": api}); + if kind == "exporter" { + m["extensions"] = json!(["fz"]); + } + m["permissions"] = match permissions { + Some(Value::Null) | None => json!(names), + Some(junk) => junk, + }; + let text = m.to_string(); + let parsed = catch_quiet(|| vectorcraft_plugins::Manifest::parse(text.as_bytes())); + let parsed = parsed.map_err(|msg| TestCaseError::fail(format!("panicked on {text}: {msg}")))?; + if let Ok(man) = &parsed { + prop_assert!(man.permissions().iter().all(|p| p.applies(man.kind, !man.commands.is_empty())), "{}", text); + let shown = vectorcraft_plugins::permissions::display_text(&man.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + prop_assert!(!shown.chars().any(|c| c.is_control() || matches!(c, '\u{202E}' | '\u{2066}' | '\u{200F}')), "{}", shown); + prop_assert!(shown.chars().count() <= vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + } + let mut s = rich_session(); + let module = wat::parse_str(tpl::returning(&text, r#"{"objects":[]}"#)).unwrap(); + let data = vectorcraft_format::base64_encode(&module); + let r = catch_quiet(|| { + let _ = s.execute("plugin.inspect", &json!({"dataBase64": data})); + s.execute("plugin.install", &json!({"dataBase64": data, "grant": grant})).is_ok() + }); + let installed = r.map_err(|msg| TestCaseError::fail(format!("panicked installing {text}: {msg}")))?; + prop_assert!(!installed || parsed.is_ok(), "a manifest that doesn't parse installed: {}", text); + vectorcraft_plugins::registry::remove("fuzz.permissions"); + vectorcraft_plugins::registry::revoke("fuzz.permissions"); + } + + /// Manifests with hostile `commands` (junk of every type, bad and repeated ids, labels with + /// control and bidirectional override characters, a `menu` naming another menu, junk + /// parameters) parse to an error or to commands whose menu labels show no hidden character and + /// that sit under Plug-ins alone; installing one and running each of its commands ends as an + /// error or an edit, never a panic, and the document then renders and exports. + #[test] + fn hostile_manifest_commands_never_crash( + kind in prop::sample::select(vec!["filter", "effect", "exporter"]), + entries in prop::collection::vec( + prop_oneof![ + 3 => ( + prop_oneof![Just(json!("grow")), Just(json!("a_1")), Just(json!("Grow")), Just(json!("")), Just(json!("a.b")), arb_junk()], + prop_oneof![ + 3 => "[a-zA-Z\u{202E}\u{2066}\u{200F} ]{0,70}".prop_map(Value::from), + 1 => "[a-z\u{0007}\n]{1,8}".prop_map(Value::from), + 1 => arb_junk(), + ], + prop_oneof![Just(Value::Null), Just(json!("File")), arb_junk()], + prop_oneof![Just(Value::Null), Just(json!({"by": {"type": "number", "min": 0, "max": 10, "default": 2}})), arb_junk()], + ) + .prop_map(|(id, label, menu, params)| { + let mut c = json!({"id": id, "label": label}); + if !menu.is_null() { + c["menu"] = menu; + } + if !params.is_null() { + c["params"] = params; + } + c + }), + 1 => arb_junk(), + ], + 0..5, + ), + junk in prop::option::weighted(0.1, arb_junk()), + given in prop_oneof![Just(json!({})), Just(json!({"by": 3})), arb_junk()], + ) { + let mut m = json!({"id": "fuzz.commands", "name": "Fuzz \u{202E}Commands", "kind": kind}); + if kind == "exporter" { + m["extensions"] = json!(["fz"]); + } + m["commands"] = junk.unwrap_or(json!(entries)); + let text = m.to_string(); + let parsed = catch_quiet(|| vectorcraft_plugins::Manifest::parse(text.as_bytes())); + let parsed = parsed.map_err(|msg| TestCaseError::fail(format!("panicked on {text}: {msg}")))?; + if let Ok(man) = &parsed { + for c in &man.commands { + let shown = c.shown_label(); + prop_assert!(!shown.chars().any(|ch| ch.is_control() || matches!(ch, '\u{202E}' | '\u{2066}' | '\u{200F}')), "{}", shown); + prop_assert!(shown.chars().count() <= vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + } + } + let mut s = rich_session(); + s.execute("select.all", &json!({})).unwrap(); + let module = wat::parse_str(tpl::returning(&text, r#"{"objects":[]}"#)).unwrap(); + let r = catch_quiet(|| { + let mut ran = vec![]; + if install(&mut s, &module).is_ok() { + for c in s.commands().into_iter().filter(|c| c.id.starts_with("plugin.fuzz.commands.")) { + ran.push((c.id, c.menu.clone())); + let _ = s.execute(c.id, &given); + } + } + ran + }); + let ran = r.map_err(|msg| TestCaseError::fail(format!("panicked running {text}: {msg}")))?; + prop_assert!(ran.is_empty() || parsed.is_ok(), "a manifest that doesn't parse installed: {}", text); + for (id, menu) in &ran { + prop_assert!(menu.len() == 3 && menu[1] == "Plug-ins" && matches!(menu[0], "Object" | "Effect"), "{id}: {menu:?}"); + } + renders(&s, "after hostile commands")?; + vectorcraft_plugins::registry::remove("fuzz.commands"); + } + + /// A plug-in of API level 2 that calls the host imports with hostile arguments (any progress + /// counts, any log level, pointers and lengths in and out of its memory, text that isn't + /// UTF-8) runs to an error or an output, never a panic, and its report stays within the caps. + #[test] + fn hostile_host_import_arguments_never_crash( + calls in prop::collection::vec( + prop_oneof![ + (any::(), any::()).prop_map(|(d, t)| format!("(call $vc_progress (i64.const {d}) (i64.const {t}))")), + Just("(drop (call $vc_cancelled))".to_string()), + (prop_oneof![any::(), -1..5i32], prop_oneof![any::(), 0x1ff00..0x20100i32], prop_oneof![any::(), 0..5000i32]) + .prop_map(|(l, p, n)| format!("(drop (call $vc_log (i32.const {l}) (i32.const {p}) (i32.const {n})))")), + ], + 0..24, + ), + bytes in prop::collection::vec(any::(), 0..64), + effect in any::(), + ) { + use vectorcraft_plugins::host::{LOG_TRUNCATED, MAX_LOG_BYTES, MAX_LOG_LINE, MAX_LOG_LINES}; + let manifest = if effect { + r#"{"id":"fuzz.host","name":"F","kind":"effect","api":2,"permissions":["doc.read","effect.render","progress"]}"# + } else { + r#"{"id":"fuzz.host","name":"F","kind":"filter","api":2,"permissions":["doc.read","doc.write","progress"]}"# + }; + let text: String = bytes.iter().map(|b| format!("\\{b:02x}")).collect(); + let imports = format!(r#"{} (data (i32.const 0x2000) "{text}")"#, tpl::HOST_IMPORTS); + let wasm = wat::parse_str(tpl::with_imports(manifest, &imports, &calls.concat(), r#"{"objects":[]}"#)).unwrap(); + let r = catch_quiet(|| { + let p = vectorcraft_plugins::Plugin::load(&wasm, vectorcraft_plugins::Limits::default())?; + let token = vectorcraft_doc::cancel::CancelToken::new(); + let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(|_, _, _| {}); + Ok::<_, vectorcraft_plugins::Error>(vectorcraft_doc::cancel::scope(&token, Some(sink), || p.run_reporting(b"{\"objects\":[]}", b"{}", p.limits()))) + }); + let r = r.map_err(|msg| TestCaseError::fail(format!("panicked on {calls:?}: {msg}")))?; + let (out, report) = r.map_err(|e| TestCaseError::fail(format!("refused at load: {e}")))?; + prop_assert!(out.is_ok(), "{:?}", out); + prop_assert!(report.lines.len() <= MAX_LOG_LINES + 1); + prop_assert!(report.lines.iter().all(|l| l.text.chars().count() <= MAX_LOG_LINE)); + prop_assert!(report.lines.iter().filter(|l| l.text != LOG_TRUNCATED).map(|l| l.text.len()).sum::() <= MAX_LOG_BYTES); + if let Some((done, total)) = report.progress { + prop_assert!(total == 0 || done <= total); + } + } + + /// A plug-in that calls the storage imports with hostile keys (`..`, separators, device names, + /// control characters, too long), values, lengths and pointers in and out of its memory runs to + /// an output, never a panic; every call returns a length or a storage code, and the settings and + /// cache of another plug-in in the same store stay as they were. + #[test] + fn hostile_storage_arguments_never_crash( + calls in prop::collection::vec( + ( + 0..6usize, + prop_oneof![any::(), 0x1ff00..0x20100i32, Just(0x2000)], + prop_oneof![any::(), 0..80i32], + prop_oneof![any::(), 0x1ff00..0x20100i32, Just(0x3000)], + prop_oneof![any::(), 0..5000i32], + ), + 0..16, + ), + key in prop::collection::vec(prop_oneof![Just(b'a'), Just(b'.'), Just(b'/'), Just(b'\\'), Just(b'_'), any::()], 0..80), + ) { + use vectorcraft_plugins::host::STORAGE_BUDGET; + use vectorcraft_plugins::storage::Meter; + const FUNCS: [&str; 6] = ["vc_settings_get", "vc_settings_set", "vc_cache_read", "vc_cache_write", "vc_settings_delete", "vc_cache_clear"]; + // Each case starts with an empty store, and the store is deleted when the case ends, also + // when it fails. + struct Store(std::path::PathBuf); + impl Drop for Store { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let store = Store(std::env::temp_dir().join(format!("vectorcraft-plugin-fuzz-storage-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&store.0); + let folder = store.0.clone(); + let mut s = Session::new(); + s.attach_plugin_store(folder.clone()); + let storing = |id: &str| format!(r#"{{"id":"{id}","name":"F","kind":"filter","api":2,"permissions":["settings","cache"]}}"#); + let grant = json!(["settings", "cache"]); + let other = wat::parse_str(tpl::returning(&storing("fuzz.storage.other"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&other), "grant": grant})).unwrap(); + let theirs = vectorcraft_plugins::registry::storage("fuzz.storage.other").unwrap(); + let m = &mut Meter::unlimited(); + theirs.set_setting("mine", b"kept", m).unwrap(); + theirs.set_cache_entry("mine", b"kept", m).unwrap(); + // Each call's result is checked: a length (0 or more) or one of the storage codes. + let check = |call: String| format!("(local.set $r {call}) (if (i32.lt_s (local.get $r) (i32.const {STORAGE_BUDGET})) (then unreachable))"); + let body: String = calls + .iter() + .map(|&(f, kp, kl, vp, vl)| match f { + 0..4 => check(format!("(call ${} (i32.const {kp}) (i32.const {kl}) (i32.const {vp}) (i32.const {vl}))", FUNCS[f])), + _ => check(format!("(call ${} (i32.const {kp}) (i32.const {kl}))", FUNCS[f])), + }) + .collect(); + let text: String = key.iter().map(|b| format!("\\{b:02x}")).collect(); + let imports = format!(r#"{} (data (i32.const 0x2000) "{text}")"#, tpl::STORAGE_IMPORTS); + let wasm = wat::parse_str(tpl::with_imports(&storing("fuzz.storage"), &imports, &format!("(local $r i32) {body}"), r#"{"objects":[]}"#)).unwrap(); + // A failed case leaves its module installed, and the cases that shrink it install others + // under the same id. + let r = catch_quiet(|| { + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})) + .map_err(|e| e.to_string())?; + let p = vectorcraft_plugins::registry::get("fuzz.storage").ok_or("not installed")?; + p.run(b"{\"objects\":[]}", b"{}").map_err(|e| e.to_string()) + }); + let out = r.map_err(|msg| TestCaseError::fail(format!("panicked on {calls:?}: {msg}")))?; + prop_assert!(out.is_ok(), "{:?}", out); + prop_assert_eq!(theirs.setting("mine", m).unwrap(), Some(b"kept".to_vec())); + prop_assert_eq!(theirs.cache_entry("mine", m).unwrap(), Some(b"kept".to_vec())); + prop_assert_eq!(theirs.cache_bytes(), 4); + // The host names every file: the store holds the two modules, their grants and their folders. + let names = |dir: &std::path::Path| std::fs::read_dir(dir).unwrap().filter_map(Result::ok).map(|e| e.file_name()).collect::>(); + prop_assert!(names(&folder).len() <= 4, "{:?}", names(&folder)); + prop_assert!(names(&folder.join("storage")).len() <= 2, "{:?}", names(&folder.join("storage"))); + let _ = s.execute("plugin.remove", &json!({"id": "fuzz.storage"})); + let _ = s.execute("plugin.remove", &json!({"id": "fuzz.storage.other"})); + } } diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs new file mode 100644 index 0000000000..7fe54fb53e --- /dev/null +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -0,0 +1,432 @@ +//! Safe Mode and disabled plug-ins through the engine: `plugin.safeMode`, `plugin.setEnabled`, the +//! plug-in folder skipping disabled plug-ins at the next launch, and the `plugin.*` commands in Safe +//! Mode. +//! +//! A test binary of its own: Safe Mode and installed plug-ins are process-wide, so these tests run +//! one at a time and no other test sees them. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::PathBuf; +use std::sync::Mutex; + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_plugins::safe_mode; +use vectorcraft_plugins::wat as tpl; + +static LOCK: Mutex<()> = Mutex::new(()); + +/// Safe Mode off, nothing disabled or installed. +fn reset() { + safe_mode::set_active(None); + safe_mode::set_disabled(vec![]); + for p in vectorcraft_plugins::registry::list() { + vectorcraft_plugins::registry::remove(p.id()); + } +} + +/// Holds the lock for one test and resets the process-wide state when the test starts and when it +/// ends, so a test that fails leaves the next one as it would find a new process. +struct Fresh { + _guard: std::sync::MutexGuard<'static, ()>, +} + +fn fresh() -> Fresh { + let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + reset(); + Fresh { _guard: guard } +} + +impl Drop for Fresh { + fn drop(&mut self) { + reset(); + } +} + +fn filter(id: &str) -> Vec { + wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap() +} + +fn tmp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("vc-plugin-safe-mode-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn installed(id: &str) -> bool { + vectorcraft_plugins::registry::get(id).is_some() +} + +/// A new launch: nothing installed, the plug-in folder `dir` attached. +fn launch(dir: &std::path::Path) -> Session { + for p in vectorcraft_plugins::registry::list() { + vectorcraft_plugins::registry::remove(p.id()); + } + let mut s = Session::new(); + s.attach_plugin_store(dir.to_path_buf()); + s +} + +#[test] +fn a_disabled_plug_in_stays_installed_and_loads_again_once_enabled_at_the_next_launch() { + let _f = fresh(); + let dir = tmp_dir("enable"); + let mut s = launch(&dir); + for id in ["test.sm.x", "test.sm.y"] { + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&filter(id))})).unwrap(); + } + let r = s.execute("plugin.setEnabled", &json!({"id": "test.sm.x", "enabled": false})).unwrap(); + assert_eq!(r["changed"], true); + assert_eq!(r["disabled"][0]["id"], "test.sm.x"); + assert!(installed("test.sm.x"), "disabling waits for the next launch"); + let again = s.execute("plugin.setEnabled", &json!({"id": "test.sm.x", "enabled": false})).unwrap(); + assert_eq!(again["changed"], false, "already disabled: nothing changes"); + + let mut s = launch(&dir); + assert!(!installed("test.sm.x") && installed("test.sm.y"), "only the disabled one is skipped"); + assert!(dir.read_dir().unwrap().flatten().filter(|e| e.path().extension().is_some_and(|x| x == "wasm")).count() == 2, "nothing uninstalled"); + let list = s.execute("plugin.list", &json!({})).unwrap(); + assert_eq!((list["safeMode"].clone(), list["disabled"][0]["id"].clone()), (json!(false), json!("test.sm.x"))); + let state = s.execute("plugin.safeMode", &json!({})).unwrap(); + assert_eq!(state, json!({"active": false, "source": null, "pendingItem": null, "disabled": state["disabled"].clone()})); + assert_eq!(state["disabled"].as_array().map(Vec::len), Some(1)); + + s.execute("plugin.setEnabled", &json!({"id": "test.sm.x", "enabled": true})).unwrap(); + assert!(!installed("test.sm.x"), "enabling waits for the next launch"); + launch(&dir); + assert!(installed("test.sm.x") && installed("test.sm.y")); + safe_mode::set_disabled(vec![]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Two windows share a plug-in folder: a plug-in the other one disabled after this one started stays +/// disabled when this one saves its own changes. +#[test] +fn saving_the_disabled_list_keeps_what_another_window_saved_meanwhile() { + let _f = fresh(); + let dir = tmp_dir("two-windows"); + let mut s = launch(&dir); + s.execute("plugin.setEnabled", &json!({"id": "test.sm.a", "enabled": false})).unwrap(); + // The other window disabled b and saved its list. + let other = |ids: &[&str]| { + let items: Vec = ids.iter().map(|id| json!({"id": id})).collect(); + let file = json!({"format": "vectorcraft-disabled-plugins", "version": 1, "items": items}); + std::fs::write(dir.join(vectorcraft_engine::store::DISABLED_FILE), serde_json::to_vec(&file).unwrap()).unwrap(); + }; + other(&["test.sm.a", "test.sm.b"]); + s.execute("plugin.setEnabled", &json!({"id": "test.sm.c", "enabled": false})).unwrap(); + s.execute("plugin.setEnabled", &json!({"id": "test.sm.a", "enabled": true})).unwrap(); + let saved = |s: &mut Session| -> Vec { + let state = s.execute("plugin.safeMode", &json!({})).unwrap(); + state["disabled"].as_array().unwrap().iter().map(|i| i["id"].as_str().unwrap().to_string()).collect() + }; + assert_eq!(saved(&mut s), ["test.sm.b", "test.sm.c"], "b is kept, c added, and a turned on again"); + // The other window turns b back on; this window's next change keeps that too. + other(&["test.sm.c"]); + s.execute("plugin.setEnabled", &json!({"id": "test.sm.d", "enabled": false})).unwrap(); + assert_eq!(saved(&mut s), ["test.sm.c", "test.sm.d"]); + let mut next = launch(&dir); + assert_eq!(saved(&mut next), ["test.sm.c", "test.sm.d"], "the file holds the merged list"); + // While the lock file can't be locked (here a folder stands in its place), nothing is written; + // the next change that is written carries this one too. + let lock = dir.join(vectorcraft_engine::store::DISABLED_LOCK); + std::fs::remove_file(&lock).unwrap(); + std::fs::create_dir_all(&lock).unwrap(); + let in_file = || -> Vec { + let bytes = std::fs::read(dir.join(vectorcraft_engine::store::DISABLED_FILE)).unwrap(); + safe_mode::parse_disabled_file(&bytes).into_iter().filter_map(|i| i.id).collect() + }; + next.execute("plugin.setEnabled", &json!({"id": "test.sm.e", "enabled": false})).unwrap(); + assert_eq!(in_file(), ["test.sm.c", "test.sm.d"]); + std::fs::remove_dir(&lock).unwrap(); + next.execute("plugin.setEnabled", &json!({"id": "test.sm.f", "enabled": false})).unwrap(); + assert_eq!(in_file(), ["test.sm.c", "test.sm.d", "test.sm.e", "test.sm.f"]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_full_list_of_long_disabled_items_is_read_back_at_the_next_launch() { + let _f = fresh(); + let dir = tmp_dir("full-list"); + let field = |i: usize, tag: &str| format!("{tag}{i:04}{}", "\u{1}".repeat(1024)); + let items: Vec = (0..safe_mode::MAX_DISABLED) + .map(|i| safe_mode::Item { id: Some(field(i, "i")), file: Some(field(i, "f")), name: Some(field(i, "n")) }) + .collect(); + safe_mode::set_disabled(items); + let saved = safe_mode::disabled(); + std::fs::write(dir.join(vectorcraft_engine::store::DISABLED_FILE), safe_mode::disabled_file()).unwrap(); + safe_mode::set_disabled(vec![]); + launch(&dir); + assert_eq!(safe_mode::disabled(), saved, "every disabled item stays disabled"); + safe_mode::set_disabled(vec![]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_folder_plug_in_disabled_by_id_is_saved_with_its_file() { + let _f = fresh(); + let dir = tmp_dir("by-id"); + let extra = tmp_dir("by-id-extra"); + let f = extra.join("f.wasm"); + std::fs::write(&f, filter("test.sm.f")).unwrap(); + let mut s = launch(&dir); + s.execute("plugin.setEnabled", &json!({"id": "test.sm.f", "enabled": false})).unwrap(); + let mut s = launch(&dir); + let r = s.execute("plugin.reload", &json!({"path": extra.to_string_lossy()})).unwrap(); + assert_eq!(r["failed"][0]["error"], vectorcraft_plugins::registry::DISABLED); + safe_mode::set_disabled(vec![]); + launch(&dir); + assert_eq!(safe_mode::disabled()[0].file.as_deref(), Some(f.display().to_string().as_str()), "the next launch skips the file before it loads"); + safe_mode::set_disabled(vec![]); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(&extra); +} + +#[test] +fn installing_a_disabled_plug_in_again_turns_it_on() { + let _f = fresh(); + let dir = tmp_dir("reinstall"); + let mut s = launch(&dir); + s.execute("plugin.setEnabled", &json!({"id": "test.sm.r", "enabled": false})).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&filter("test.sm.r"))})).unwrap(); + assert!(safe_mode::disabled().is_empty()); + launch(&dir); + assert!(installed("test.sm.r")); + safe_mode::set_disabled(vec![]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// When the grant of an update can't be stored, the store keeps the old module, and it stays disabled. +#[test] +fn a_disabled_plug_in_whose_new_grant_cant_be_stored_stays_disabled() { + let _f = fresh(); + let dir = tmp_dir("reinstall-no-grant"); + let mut s = launch(&dir); + let manifest = r#"{"id":"test.sm.g","name":"Test","version":"1","kind":"filter","permissions":["doc.read"]}"#; + let module = |out: &str| vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(manifest, out)).unwrap()); + s.execute("plugin.install", &json!({"dataBase64": module(r#"{"objects":[]}"#), "grant": ["doc.read"]})).unwrap(); + s.execute("plugin.setEnabled", &json!({"id": "test.sm.g", "enabled": false})).unwrap(); + let grants = dir.join("grants.json"); + std::fs::remove_file(&grants).unwrap(); + std::fs::create_dir_all(grants.join("block")).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": module(r#"{"objects":[],"error":null}"#), "grant": ["doc.read"], "replace": true})).unwrap(); + assert_eq!(safe_mode::disabled().len(), 1, "the module the update could not replace stays disabled"); + safe_mode::set_disabled(vec![]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A launch where the stored plug-in `id` stopped while loading: it is installed, then disabled by +/// its stored file alone (as Disable and Continue saves it), and the next launch skips it. +fn stored_plug_in_disabled_by_file(dir: &std::path::Path, id: &str) -> Session { + let mut s = launch(dir); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&filter(id))})).unwrap(); + let stored = dir.read_dir().unwrap().flatten().map(|e| e.path()).find(|p| p.extension().is_some_and(|x| x == "wasm")).unwrap(); + s.execute("plugin.setEnabled", &json!({"file": stored.display().to_string(), "enabled": false})).unwrap(); + let s = launch(dir); + assert!(!installed(id), "the next launch skips the file"); + assert_eq!(safe_mode::disabled()[0].id, None); + s +} + +fn nothing_disabled(s: &mut Session, dir: &std::path::Path) { + assert_eq!(s.execute("plugin.safeMode", &json!({})).unwrap()["disabled"], json!([])); + let saved = std::fs::read(dir.join(vectorcraft_engine::store::DISABLED_FILE)).unwrap(); + assert!(safe_mode::parse_disabled_file(&saved).is_empty(), "nothing disabled is saved"); +} + +#[test] +fn installing_a_stored_plug_in_disabled_by_its_file_turns_it_on() { + let _f = fresh(); + let dir = tmp_dir("reinstall-file"); + let mut s = stored_plug_in_disabled_by_file(&dir, "test.sm.p"); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&filter("test.sm.p"))})).unwrap(); + nothing_disabled(&mut s, &dir); + launch(&dir); + assert!(installed("test.sm.p")); + safe_mode::set_disabled(vec![]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_stored_plug_in_disabled_by_its_file_stays_disabled_when_its_update_cannot_be_saved() { + let _f = fresh(); + let dir = tmp_dir("reinstall-unsaved"); + let mut s = stored_plug_in_disabled_by_file(&dir, "test.sm.u"); + let stored = PathBuf::from(safe_mode::disabled()[0].file.clone().unwrap()); + std::fs::remove_file(&stored).unwrap(); + std::fs::create_dir_all(stored.join("block")).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&filter("test.sm.u"))})).unwrap(); + assert_eq!(safe_mode::disabled().len(), 1, "the file the update could not replace stays disabled"); + safe_mode::set_disabled(vec![]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn enabling_a_stored_plug_in_disabled_by_its_file_by_its_id_turns_it_on() { + let _f = fresh(); + let dir = tmp_dir("enable-file"); + let mut s = stored_plug_in_disabled_by_file(&dir, "test.sm.q"); + let r = s.execute("plugin.setEnabled", &json!({"id": "test.sm.q", "enabled": true})).unwrap(); + assert_eq!(r["changed"], true); + nothing_disabled(&mut s, &dir); + launch(&dir); + assert!(installed("test.sm.q")); + safe_mode::set_disabled(vec![]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn set_enabled_rejects_bad_parameters() { + let _f = fresh(); + safe_mode::set_disabled(vec![]); + let mut s = Session::new(); + let err = |s: &mut Session, p: Value| s.execute("plugin.setEnabled", &p).unwrap_err().to_string(); + assert!(err(&mut s, json!({"id": "a"})).contains("`enabled` must be true or false")); + assert!(err(&mut s, json!({"id": "a", "enabled": "yes"})).contains("`enabled` must be true or false")); + assert!(err(&mut s, json!({"id": 3, "enabled": false})).contains("`id` must be a string")); + assert!(err(&mut s, json!({"enabled": false})).contains("give `id` or `file`")); + assert!(err(&mut s, json!({"id": " ", "enabled": false})).contains("give `id` or `file`")); + assert!(err(&mut s, json!({"id": "a", "enabled": true})).contains("isn't disabled")); + assert!(safe_mode::disabled().is_empty(), "nothing changed"); + let r = s.execute("plugin.setEnabled", &json!({"file": "/p/a.wasm", "enabled": false})).unwrap(); + assert_eq!( + (r["changed"].clone(), r["disabled"][0]["file"].clone(), r["disabled"][0]["label"].clone()), + (json!(true), json!("/p/a.wasm"), json!("a.wasm")) + ); + assert_eq!(r["saved"], false, "a session without a plug-in folder can't keep the change for the next launch"); + safe_mode::set_disabled(vec![]); +} + +/// A disabled list too large to read, or one of a later version, stays as it is: the changes wait +/// for a save that can merge them. A file that isn't JSON holds nothing to keep and is replaced. +#[test] +fn a_disabled_list_this_version_cannot_read_is_kept() { + let _f = fresh(); + let dir = tmp_dir("kept"); + let file = dir.join(vectorcraft_engine::store::DISABLED_FILE); + let mut s = launch(&dir); + let later = serde_json::to_vec(&json!({"format": "vectorcraft-disabled-plugins", "version": 2, "items": [{"id": "test.sm.k"}]})).unwrap(); + let large = vec![b' '; safe_mode::MAX_DISABLED_FILE_BYTES as usize + 1]; + for (kept, id) in [(later, "test.sm.a"), (large, "test.sm.b")] { + std::fs::write(&file, &kept).unwrap(); + let r = s.execute("plugin.setEnabled", &json!({"id": id, "enabled": false})).unwrap(); + assert_eq!((r["changed"].clone(), r["saved"].clone()), (json!(true), json!(false)), "{id}"); + assert!(std::fs::read(&file).unwrap() == kept, "{id}: the file is kept"); + } + std::fs::write(&file, b"{\"format\": \"vectorcraft-disab").unwrap(); + let r = s.execute("plugin.setEnabled", &json!({"id": "test.sm.c", "enabled": false})).unwrap(); + assert_eq!(r["saved"], true); + let ids: Vec = safe_mode::parse_disabled_file(&std::fs::read(&file).unwrap()).into_iter().filter_map(|i| i.id).collect(); + assert_eq!(ids, ["test.sm.a", "test.sm.b", "test.sm.c"], "the waiting changes are saved too"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Another window filled the list after this one read it: a plug-in turned off here has no room in +/// the file, and `saved` says so. +#[test] +fn a_disable_that_finds_the_saved_list_full_is_not_saved() { + let _f = fresh(); + let dir = tmp_dir("full-merge"); + let mut s = launch(&dir); + let items: Vec = (0..safe_mode::MAX_DISABLED).map(|i| json!({"id": format!("test.sm.full{i}")})).collect(); + let file = json!({"format": "vectorcraft-disabled-plugins", "version": 1, "items": items}); + std::fs::write(dir.join(vectorcraft_engine::store::DISABLED_FILE), serde_json::to_vec(&file).unwrap()).unwrap(); + let r = s.execute("plugin.setEnabled", &json!({"id": "test.sm.late", "enabled": false})).unwrap(); + assert_eq!((r["changed"].clone(), r["saved"].clone()), (json!(true), json!(false))); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn in_safe_mode_the_plug_in_folder_and_commands_load_and_run_nothing() { + let _f = fresh(); + let dir = tmp_dir("safe"); + let mut s = launch(&dir); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&filter("test.sm.s"))})).unwrap(); + let extra = tmp_dir("safe-extra"); + std::fs::write(extra.join("e.wasm"), filter("test.sm.e")).unwrap(); + + vectorcraft_engine::cmd::plugin::start_in_safe_mode(); + let mut s = launch(&dir); + assert!(!installed("test.sm.s"), "stored plug-ins don't load"); + let safe = "Safe Mode is on: plug-ins don't load or run until VectorCraft starts normally"; + let install = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&filter("test.sm.t"))})); + assert!(install.unwrap_err().to_string().contains(safe)); + let reload = s.execute("plugin.reload", &json!({"path": extra.to_string_lossy()})); + assert!(reload.unwrap_err().to_string().contains(safe)); + assert!(!installed("test.sm.e") && !installed("test.sm.t")); + let state = s.execute("plugin.safeMode", &json!({})).unwrap(); + assert_eq!((state["active"].clone(), state["source"].clone()), (json!(true), json!("flag"))); + assert_eq!(s.execute("plugin.list", &json!({})).unwrap()["safeMode"], true); + + // Leaving the choice after a launch that stopped with Start Normally loads them. + safe_mode::set_active(None); + vectorcraft_engine::cmd::plugin::load_prefs_folder(&mut s); + assert!(installed("test.sm.s")); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(&extra); +} + +#[test] +fn a_live_effect_skipped_in_safe_mode_stays_on_its_object_and_says_so() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.fx", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.fx"})).unwrap(); + let effect = |s: &mut Session| s.execute("effect.list", &json!({})).unwrap()["applied"][0]["effects"][0].clone(); + assert_eq!((effect(&mut s)["id"].clone(), effect(&mut s).get("skipped").cloned()), (json!("plugin.test.sm.fx"), None)); + + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let skipped = effect(&mut s); + assert_eq!((skipped["id"].clone(), skipped["skipped"].clone()), (json!("plugin.test.sm.fx"), json!(true)), "the object keeps it"); + + safe_mode::set_active(None); + assert_eq!(effect(&mut s).get("skipped"), None); +} + +/// In Safe Mode, Expand Appearance refuses an object whose plug-in effect it would drop, its own or +/// in a symbol's art it places, and changes nothing. +#[test] +fn expand_appearance_keeps_a_plug_in_effect_safe_mode_skips() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.xp", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.xp"})).unwrap(); + let doc = |s: &mut Session| s.execute("document.inspect", &json!({})).unwrap(); + let refused = |s: &mut Session| { + let before = doc(s); + let err = s.execute("effect.expandAppearance", &json!({})).unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + assert_eq!(doc(s), before, "nothing changes"); + }; + safe_mode::set_active(Some(safe_mode::Source::Flag)); + refused(&mut s); + // An instance, with an effect of its own, of a symbol whose art holds the plug-in effect. + safe_mode::set_active(None); + s.execute("symbol.new", &json!({"name": "fx"})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.puckerBloat"})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + refused(&mut s); + safe_mode::set_active(None); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + // A plain instance of that symbol doesn't expand: selected with an object that does, they expand. + let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].clone(); + let other = s.execute("shape.rectangle", &json!({"x": 10, "y": 120, "width": 30, "height": 30})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "distort.puckerBloat"})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + s.execute("effect.expandAppearance", &json!({"ids": [plain, other]})).unwrap(); + safe_mode::set_active(None); + // A plug-in effect on a hidden fill: Expand Appearance drops that fill, so it expands. + s.execute("shape.rectangle", &json!({"x": 100, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.xp", "item": 0})).unwrap(); + s.execute("appearance.setItem", &json!({"index": 0, "visible": false})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + s.execute("effect.expandAppearance", &json!({})).unwrap(); +} diff --git a/crates/engine/tests/text_import_fuzz.rs b/crates/engine/tests/text_import_fuzz.rs index 867b016a97..1ea656a158 100644 --- a/crates/engine/tests/text_import_fuzz.rs +++ b/crates/engine/tests/text_import_fuzz.rs @@ -1,6 +1,6 @@ //! Untrusted text files placed with File → Place never crash: any bytes, with any Text Import -//! Options, place as area type or fail with an error, and so do hostile RTF files and Word -//! documents. +//! Options, place as area type or fail with an error, and so do hostile RTF files, Word documents +//! and Word 97-2003 documents, including ones whose compound file container is damaged. //! //! `PROPTEST_CASES=20000 cargo test -p vectorcraft-engine --test text_import_fuzz` runs a deeper search. // Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). @@ -38,8 +38,8 @@ proptest! { "replaceSpaces": spaces, }); let p = json!({"name": "fuzz.txt", "dataBase64": vectorcraft_format::base64_encode(&data), "text": text, "thumbnail": 8}); - let _ = s.execute("file.place.info", &p); - let _ = s.execute("file.place", &p); + let _ = no_panic(s.execute("file.place.info", &p)); + let _ = no_panic(s.execute("file.place", &p)); }); prop_assert!(r.is_ok(), "panicked: {:?}", r.err()); } @@ -55,8 +55,8 @@ proptest! { let mut s = vectorcraft_engine::Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&data), "thumbnail": 8}); - let _ = s.execute("file.place.info", &p); - let _ = s.execute("file.place", &p); + let _ = no_panic(s.execute("file.place.info", &p)); + let _ = no_panic(s.execute("file.place", &p)); }); prop_assert!(r.is_ok(), "panicked: {:?}", r.err()); } @@ -86,11 +86,372 @@ proptest! { let mut s = vectorcraft_engine::Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&data), "thumbnail": 8}); - let _ = s.execute("file.place.info", &p); - let _ = s.execute("file.place", &p); + let _ = no_panic(s.execute("file.place.info", &p)); + let _ = no_panic(s.execute("file.place", &p)); }); prop_assert!(r.is_ok(), "panicked: {:?}", r.err()); } + + #[test] + fn any_doc_places_without_panics( + text in prop::collection::vec(prop::sample::select(DOC_CHARS.chars().collect::>()), 1..60), + compressed in any::(), + chpx in arb_grpprl(), + papx in arb_grpprl(), + istd in 0u16..4, + stsh in prop_oneof![1 => prop::collection::vec(any::(), 0..120), 3 => arb_stsh()], + ffn in prop::collection::vec(any::(), 0..80), + changes in prop_oneof![ + 3 => Just(vec![]), + 1 => prop::collection::vec((any::(), any::(), any::()), 1..4), + ], + name in prop::sample::select(vec!["fuzz.doc", "fuzz.bin"]), + ) { + vectorcraft_text::FontDb::global().set_system_fallback(false); + let text: String = text.into_iter().collect(); + let (mut wd, mut table) = word97(&text, compressed, &chpx, istd, &papx, &stsh, &ffn); + // A changed byte anywhere in either stream: in the FIB, the text, a property page or a + // table. + for (in_table, at, byte) in changes { + let stream = if in_table { &mut table } else { &mut wd }; + let i = at.index(stream.len()); + stream[i] = byte; + } + let data = compound_file(&wd, &table, cfb::Version::V4); + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&data), "thumbnail": 8}); + let _ = no_panic(s.execute("file.place.info", &p)); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "panicked: {:?}", r.err()); + } + + #[test] + fn any_damaged_doc_container_places_without_panics( + text in prop::collection::vec(prop::sample::select(DOC_CHARS.chars().collect::>()), 1..60), + compressed in any::(), + v3 in any::(), + large in any::(), + damage in prop::collection::vec(arb_cfb_damage(), 1..4), + name in prop::sample::select(vec!["fuzz.doc", "fuzz.bin"]), + ) { + vectorcraft_text::FontDb::global().set_system_fallback(false); + // A letter first, so that the undamaged document has text to place. + let text: String = std::iter::once('a').chain(text).collect(); + let (mut wd, table) = word97(&text, compressed, &[], 0, &[], &[], &[]); + // Past the mini stream cutoff (4,096 bytes) the WordDocument stream is kept in sectors the + // FAT chains; below it, both streams are kept in the mini stream the mini FAT chains. + if large { + wd.resize(9000, 0); + } + let mut data = compound_file(&wd, &table, if v3 { cfb::Version::V3 } else { cfb::Version::V4 }); + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let p = json!({"name": "fuzz.doc", "dataBase64": vectorcraft_format::base64_encode(&data)}); + let placed = s.execute("file.place", &p); + prop_assert!(placed.is_ok(), "the undamaged document doesn't place: {:?}", placed.err()); + let layout = CfbLayout::of(&data); + for d in &damage { + d.apply(&mut data, &layout); + } + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&data), "thumbnail": 8}); + let _ = no_panic(s.execute("file.place.info", &p)); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "panicked: {:?}", r.err()); + } +} + +/// `r`, after failing the case if the command panicked. The engine's guard reports a panic as +/// `EngineError::Internal`. +fn no_panic(r: Result) -> Result { + if let Err(vectorcraft_engine::EngineError::Internal { cmd, msg }) = &r { + panic!("{cmd} panicked: {msg}"); + } + r +} + +/// A compound file of `version` holding the WordDocument stream `wd` and the table stream `table`. +fn compound_file(wd: &[u8], table: &[u8], version: cfb::Version) -> Vec { + let mut cf = cfb::CompoundFile::create_with_version(version, std::io::Cursor::new(Vec::new())).unwrap(); + std::io::Write::write_all(&mut cf.create_stream("WordDocument").unwrap(), wd).unwrap(); + std::io::Write::write_all(&mut cf.create_stream("1Table").unwrap(), table).unwrap(); + cf.flush().unwrap(); + cf.into_inner().into_inner() +} + +/// The compound file header's fields (\[MS-CFB\] §2.2) a damage changes: their offset and width. +const CFB_HEADER: [(usize, usize); 17] = [ + (0, 4), // signature + (24, 2), // minor version + (26, 2), // major version + (28, 2), // byte order + (30, 2), // sector shift + (32, 2), // mini sector shift + (40, 4), // directory sectors + (44, 4), // FAT sectors + (48, 4), // first directory sector + (52, 4), // transaction signature + (56, 4), // mini stream cutoff + (60, 4), // first mini FAT sector + (64, 4), // mini FAT sectors + (68, 4), // first DIFAT sector + (72, 4), // DIFAT sectors + (76, 4), // DIFAT[0] + (80, 4), // DIFAT[1] +]; + +/// A directory entry's fields (\[MS-CFB\] §2.6.1) a damage changes: their offset and width. +const CFB_ENTRY: [(usize, usize); 10] = [ + (0, 2), // first character of the name + (64, 2), // name length + (66, 1), // object type + (67, 1), // color + (68, 4), // left sibling + (72, 4), // right sibling + (76, 4), // child + (116, 4), // starting sector + (120, 4), // stream size, low + (124, 4), // stream size, high +]; + +/// Where an undamaged compound file keeps its directory, FAT and mini FAT. +struct CfbLayout { + /// The bytes of one sector. + sector: usize, + /// The offsets of the first directory sector, the first FAT sector and the first mini FAT + /// sector. + directory: usize, + fat: usize, + mini_fat: usize, +} + +impl CfbLayout { + fn of(data: &[u8]) -> Self { + let u32_at = |at: usize| u32::from_le_bytes(data[at..at + 4].try_into().unwrap()) as usize; + let sector = 1 << u16::from_le_bytes(data[30..32].try_into().unwrap()); + let at = |n: usize| (n + 1) * sector; + let layout = Self { sector, directory: at(u32_at(48)), fat: at(u32_at(76)), mini_fat: at(u32_at(60)) }; + // The root entry's name opens the directory, the FAT marks its own sector, and the mini FAT + // has a sector. + assert_eq!(&data[layout.directory..layout.directory + 4], b"R\0o\0"); + assert_eq!(u32_at(layout.fat + 4 * u32_at(76)), 0xFFFF_FFFD); + assert!(u32_at(64) >= 1); + layout + } +} + +/// A change to the container of a compound file rather than to the bytes of its streams. +#[derive(Clone, Debug)] +enum CfbDamage { + /// A header field set to a value. + Header(prop::sample::Index, u32), + /// A field of one of the first directory sector's entries set to a value. + Entry(prop::sample::Index, prop::sample::Index, u32), + /// An entry of the first FAT sector (the next sector of a chain) set to a value. + Fat(prop::sample::Index, u32), + /// An entry of the first mini FAT sector set to a value. + MiniFat(prop::sample::Index, u32), + /// A byte anywhere set to a value. + Byte(prop::sample::Index, u8), + /// The file cut short. + Truncate(prop::sample::Index), +} + +impl CfbDamage { + fn apply(&self, data: &mut Vec, layout: &CfbLayout) { + let mut put = |at: usize, width: usize, value: u32| { + if let Some(b) = data.get_mut(at..at + width) { + b.copy_from_slice(&value.to_le_bytes()[..width]); + } + }; + match self { + Self::Header(field, value) => { + let (at, width) = CFB_HEADER[field.index(CFB_HEADER.len())]; + put(at, width, *value); + } + Self::Entry(entry, field, value) => { + let (at, width) = CFB_ENTRY[field.index(CFB_ENTRY.len())]; + put(layout.directory + 128 * entry.index(layout.sector / 128) + at, width, *value); + } + Self::Fat(entry, value) => put(layout.fat + 4 * entry.index(layout.sector / 4), 4, *value), + Self::MiniFat(entry, value) => put(layout.mini_fat + 4 * entry.index(layout.sector / 4), 4, *value), + // A file cut to nothing has no byte to change and nothing to cut. + Self::Byte(..) | Self::Truncate(_) if data.is_empty() => {} + Self::Byte(at, value) => { + let i = at.index(data.len()); + data[i] = *value; + } + Self::Truncate(at) => data.truncate(at.index(data.len())), + } + } +} + +/// A sector number, size, count or shift: the special sector numbers (\[MS-CFB\] §2.1), small and +/// huge values, or any. +fn arb_cfb_value() -> impl Strategy { + prop_oneof![ + 3 => prop::sample::select(vec![ + 0, + 1, + 2, + 3, + 6, + 7, + 9, + 12, + 13, + 16, + 31, + 64, + 0x1000, + 0x1001, + 0x7FFF_FFFF, + 0xFFFF_FFFA, + 0xFFFF_FFFB, + 0xFFFF_FFFC, + 0xFFFF_FFFD, + 0xFFFF_FFFE, + 0xFFFF_FFFF, + ]), + 1 => any::(), + ] +} + +/// A [`CfbDamage`]. +fn arb_cfb_damage() -> impl Strategy { + let index = any::; + prop_oneof![ + 3 => (index(), arb_cfb_value()).prop_map(|(f, v)| CfbDamage::Header(f, v)), + 3 => (index(), index(), arb_cfb_value()).prop_map(|(e, f, v)| CfbDamage::Entry(e, f, v)), + 2 => (index(), arb_cfb_value()).prop_map(|(e, v)| CfbDamage::Fat(e, v)), + 2 => (index(), arb_cfb_value()).prop_map(|(e, v)| CfbDamage::MiniFat(e, v)), + 1 => (index(), any::()).prop_map(|(at, v)| CfbDamage::Byte(at, v)), + 1 => index().prop_map(CfbDamage::Truncate), + ] +} + +/// Characters of a Word document's text: letters, marks of paragraphs, cells and breaks, fields, +/// pictures, hyphens and surrogate-free Unicode. +const DOC_CHARS: &str = "ab \r\u{7}\u{B}\u{C}\u{13}\u{14}\u{15}\u{1}\u{8}\t\u{1E}\u{1F}(é“✓"; + +/// Character and paragraph properties: Prls the Word 97-2003 reader knows, with operands in and out +/// of range, and raw bytes. +fn arb_grpprl() -> impl Strategy> { + let prl = prop_oneof![ + prop::sample::select(vec![ + &[0x35, 0x08, 0x81][..], + &[0x35, 0x08, 0x80], + &[0x3C, 0x08, 0x01], + &[0x00, 0x08, 0x01], + &[0x01, 0x08, 0x01], + &[0x55, 0x08, 0x01], + &[0x30, 0x4A, 0x0A, 0x00], + &[0x30, 0x4A, 0xFF, 0xFF], + &[0x43, 0x4A, 0xFF, 0xFF], + &[0x4F, 0x4A, 0x07, 0x00], + &[0x42, 0x2A, 0x63], + &[0x70, 0x68, 1, 2, 3, 0xFF], + &[0x45, 0x48, 0x00, 0x80], + &[0x03, 0x24, 0x09], + &[0x61, 0x24, 0x08], + &[0x17, 0x24, 0x01], + &[0x4B, 0x24, 0x01], + &[0x41, 0x24, 0x01], + &[0x0F, 0x84, 0x00, 0x80], + &[0x13, 0xA4, 0xFF, 0xFF], + &[0x08, 0xD6, 0xFF, 0xFF], + &[0x15, 0xC6, 0xFF, 0x7F], + &[0x2A, 0xC6, 0xFF], + ]) + .prop_map(<[u8]>::to_vec), + prop::collection::vec(any::(), 0..4), + ]; + prop::collection::vec(prl, 0..6).prop_map(|p| p.concat()) +} + +/// A style sheet of up to four styles (paragraph or character, based on another or none) with +/// properties of [`arb_grpprl`], or empty slots. +fn arb_stsh() -> impl Strategy> { + let style = prop::option::of((1u16..3, prop_oneof![Just(0x0FFFu16), 0u16..5], arb_grpprl(), arb_grpprl())); + prop::collection::vec(style, 0..5).prop_map(|styles| { + let words = |v: &[u16]| v.iter().flat_map(|w| w.to_le_bytes()).collect::>(); + let mut stsh = words(&[18, styles.len() as u16, 10, 1, 0, 15, 0, 0, 0, 0]); + for s in styles { + let Some((stk, base, papx, chpx)) = s else { + stsh.extend([0, 0]); + continue; + }; + let upx = |b: Vec| [words(&[b.len() as u16]), b.clone(), vec![0; b.len() % 2]].concat(); + let (cupx, grlpupx) = if stk == 1 { (2, [upx([vec![0, 0], papx].concat()), upx(chpx)].concat()) } else { (1, upx(chpx)) }; + let mut std = words(&[0x0FFE, stk | (base << 4), cupx | (0x0FFF << 4), 0, 0, 1, u16::from(b'S'), 0]); + std.extend(grlpupx); + stsh.extend((std.len() as u16).to_le_bytes()); + stsh.extend(std); + } + stsh + }) +} + +/// The WordDocument and table streams of a Word 97-2003 document whose main text is `text` in one +/// piece, with one page of character properties `chpx` and one of paragraph properties `papx` of +/// style `istd` covering it, and the style sheet `stsh` and font table `ffn`. +fn word97(text: &str, compressed: bool, chpx: &[u8], istd: u16, papx: &[u8], stsh: &[u8], ffn: &[u8]) -> (Vec, Vec) { + let mut wd = vec![0u8; 1024]; + let at = wd.len() as u32; + if compressed { + wd.extend(text.chars().map(|c| if c == '“' { 0x93 } else { u32::from(c).min(0xFF) as u8 })); + } else { + wd.extend(text.encode_utf16().flat_map(u16::to_le_bytes)); + } + let ccp = text.encode_utf16().count() as u32; + let end = wd.len() as u32; + // One page each: a run of every character, its properties near the page's end. + let page = |props: Vec, papx: bool| { + let mut p = vec![0u8; 512]; + p[0..4].copy_from_slice(&at.to_le_bytes()); + p[4..8].copy_from_slice(&end.to_le_bytes()); + let blob = if papx { [vec![0, (props.len() / 2) as u8], props].concat() } else { [vec![props.len() as u8], props].concat() }; + let top = (511 - blob.len().min(400)) & !1; + let n = blob.len().min(511 - top); + p[top..top + n].copy_from_slice(&blob[..n]); + p[8] = (top / 2) as u8; + p[511] = 1; + p + }; + let papx_props = [istd.to_le_bytes().to_vec(), papx.to_vec(), vec![0; papx.len() % 2]].concat(); + wd.resize(wd.len().div_ceil(512) * 512, 0); + let chpx_page = (wd.len() / 512) as u32; + wd.extend(page(chpx.iter().copied().take(200).collect(), false)); + wd.extend(page(papx_props.into_iter().take(400).collect(), true)); + let bte = |pn: u32| [at, end, pn].into_iter().flat_map(u32::to_le_bytes).collect::>(); + let fc = if compressed { (at * 2) | 0x4000_0000 } else { at }; + let plc = [&0u32.to_le_bytes()[..], &ccp.to_le_bytes(), &[0, 0], &fc.to_le_bytes(), &[0, 0]].concat(); + let clx = [&[0x02][..], &(plc.len() as u32).to_le_bytes(), &plc].concat(); + let mut table = vec![]; + let mut pairs = vec![(0u32, 0u32); 0x5D]; + for (index, part) in [(1, stsh.to_vec()), (12, bte(chpx_page)), (13, bte(chpx_page + 1)), (15, ffn.to_vec()), (33, clx)] { + pairs[index] = (table.len() as u32, part.len() as u32); + table.extend(part); + } + let words = |v: &[u16]| v.iter().flat_map(|w| w.to_le_bytes()).collect::>(); + let mut put = |at: usize, bytes: &[u8]| wd[at..at + bytes.len()].copy_from_slice(bytes); + put(0, &words(&[0xA5EC, 0x00C1])); + put(10, &words(&[0x0200, 0x00BF])); + put(32, &words(&[14])); + put(62, &words(&[22])); + put(76, &ccp.to_le_bytes()); + put(80, &1u32.to_le_bytes()); + put(152, &words(&[0x5D])); + for (i, (fc, lcb)) in pairs.iter().enumerate() { + put(154 + 8 * i, &[fc.to_le_bytes(), lcb.to_le_bytes()].concat()); + } + (wd, table) } /// A well-formed paragraph, or a table row of two such paragraphs. diff --git a/crates/eps/Cargo.toml b/crates/eps/Cargo.toml index 6743c2a2a4..fb84265b29 100644 --- a/crates/eps/Cargo.toml +++ b/crates/eps/Cargo.toml @@ -13,12 +13,18 @@ vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } vectorcraft-effects = { workspace = true } +# The editing data for other apps writes clipped art cut to its clipping path. +vectorcraft-pathops = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } +# The glyph outlines of Type 42 fonts a composite font shows. +skrifa = { workspace = true } # Windows metafile previews, opened when a file's PostScript can't be read. vectorcraft-metafile = { workspace = true } # Non-native art in Illustrator editing data (a placed PDF's content, kept as a PDF). vectorcraft-pdf = { workspace = true } +# The predefined CMaps that strings of legacy type in CJK fonts are decoded by. +craft-pdf = { workspace = true } # The TIFF writer (previews) and PackBits, shared with raster export. vectorcraft-render = { workspace = true } kurbo = { workspace = true } diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs new file mode 100644 index 0000000000..b8a9bafc04 --- /dev/null +++ b/crates/eps/src/ai_editing.rs @@ -0,0 +1,566 @@ +//! The editing copy of the art that a PDF-compatible `.ai` file carries in its pages' +//! `PieceInfo` ([`vectorcraft_pdf::PrivateData`]): the document's layers, sublayers, groups, paths, +//! colors, swatches and artboards in the form [`crate::import`]'s `.ai` reader reads, so that apps +//! that open `.ai` files from that copy get them as editable objects. +//! +//! The form is the one the published specification documents (Adobe Illustrator File Format +//! Specification, version 7.0, see [`crate::legacy_ai`]) for paths (§5.3), colors (§5.4), +//! groups and compound paths (§5.3.5), guides (§6) and layers (§9), with the newer forms the reader +//! reads from files users sent: +//! +//! - Header comments: `%%Creator` (naming the format's app, see [`CREATOR_TEXT`]), `%%For` (the +//! document's author), `%%Canvassize`, `%%BoundingBox`, +//! `%%HiResBoundingBox`, `%AI5_FileFormat 14.0`, `%AI7_ImageSettings`, the first artboard as +//! `%AI3_Cropmarks` and `%AI3_TileBox`, the canvas's center as `%AI3_TemplateBox`, +//! `%AI5_ArtSize 14400 14400`, `%AI5_RulerUnits`, `%AI24_LargeCanvasScale` (1, or 10 when the +//! artboards together don't fit on the canvas: the art, boxes and artboards are then written at +//! 1/10 of their size), `%AI9_ColorModel` (1 RGB, 2 CMYK), +//! `%AI5_ArtFlags`, `%AI5_TargetResolution`, `%AI5_NumLayers`, `%AI5_OpenViewLayers` (a digit for +//! each layer, 7 shown and 6 hidden), `%AI7_GridSettings` (§2.1.1), and the version comment +//! `%%AI8_CreatorVersion` ([`CREATOR_VERSION`]). +//! - Setup: the gradients the art uses as `n Bn` and a definition of each (§3.5: `%AI5_BeginGradient: +//! (name)`, `(name) type stops Bd`, `[`, each stop on a `%_` line as `color style opacity 6 midpoint +//! rampPoint Bs`, `BD`, `%AI5_EndGradient`), those only the swatches use in a non-printing block +//! (§14: `%AI5_Begin_NonPrinting`, `Np`, `%AI5_End_NonPrinting--`); the patterns the same way +//! (§3.4: `%AI3_BeginPattern: (name)`, `(name) llx lly urx ury`, the tile's art on `%_` lines, `E`, +//! `%AI3_EndPattern`); the swatches (`%AI5_BeginPalette`, `0 0 Pb`, the Registration swatch, each +//! swatch's color operator, gradient instance or pattern operator and `(name) Pc`, a color group as +//! `0 (name) count Pg` before its swatches, `PB`), then the artboards as the `ArtboardArray` of the +//! `/Document` dictionary's `/Recorded` part and the canvas size as its `AIDocumentCanvasSize`, on +//! `%_` lines. +//! - Variables (`writer::variables`): after the canvas size, the variable library as XML nodes +//! (`/XMLNode`: `xmlnode-nodename`, `xmlnode-nodevalue`, `xmlnode-nodetype`, `xmlnode-children`, +//! `xmlnode-attributes`) of an XML document `#document`: a `metadata` element holding +//! `variableSets`, one `variableSet` (`locked`: `none`, or `variableAndTypes` when the variables +//! are locked), its `variables` (a `variable` element with `varName` and `trait`: `textcontent`, +//! `visibility`, `fileref` or `graphdata`, none for a variable of unknown kind; a variable bound to +//! objects declared once for each, its `docRef` the object's XML id, `/XMLUIDREF`) and its +//! `v:sampleDataSets` (`i:activeDataSet`, the data set shown) of `v:sampleDataSet` elements +//! (`dataSetName`), each holding an element named after each variable it gives a value: a `p` +//! element for each line of a text value, a `/Bool` text whether the objects show, a linked file's +//! `file://` URL or path. An object bound to a variable without a name gets an XML id and an empty +//! `AIArtName`. Bindings to layers, to type written as outlines, to graphs and to linked images +//! written as other objects, and graph values, values that don't fit their variable, linked files +//! that aren't absolute paths, paths from the root that the reader reads as other paths (`/` +//! alone, `/C:…`), drive and network paths with white space at either end, values of variables +//! whose names have a colon, and a data set shown that isn't written, are left out, as is what +//! the reader leaves out +//! (variables and data sets whose names are empty, repeated, longer than 255 characters or start +//! or end with white space, variables past 256, data sets past 1,000, bindings past 100,000 or to XML ids longer than +//! 255 characters, names and values past 8,388,608 bytes in all), and values past 200,000 text +//! lines and values in all. +//! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed 0 1 colorIndex r g b 0 +//! dimPercent clipping Lb` (14 operands; a color that isn't one of the preset layer colors has the +//! index -1; `clipping` is 1 for a clipping layer), `(name) Ln`, the layer's name as an XML id in an +//! `/ArtDictionary`, its art and sublayers, `LB`, `%AI5_EndLayer--`. +//! - Colors: `g` gray, `k` CMYK, `c m y k r g b Xa` RGB (Lab is written as RGB); a spot color +//! `c m y k (name) tint x` (CMYK) or `c m y k r g b|L a b (name) tint 1|2 Xx` (RGB or Lab); a +//! global process color `… (name) tint model Xk`; Registration `1 1 1 1 ([Registration]) tint +//! Xs`; a pattern `(name) 0 0 1 1 0 0 0 0 0 [matrix] p` (`P`), the matrix taking the pattern's +//! space (its tile's lower left corner the origin) to art space. Upper case paints the stroke. +//! - Gradients (§3.5.3): around the painting operator of a path (of a compound path's last path), +//! `Bb` (`1 Bb` for the stroke), a radial gradient's focal point `x y angle fraction Bh`, then +//! `flag (name) x y angle length a b c d tx ty 1 Bg`, which places the gradient on the path: a +//! linear one with the identity matrix, `x` the start and `length` the length as fractions of the +//! path's extent along `angle`; a radial one with the matrix taking the unit circle onto its +//! extent ellipse, `x` and `y` its center as fractions of the path's bounds there and `length` its +//! radius as a multiple of the one the bounds give (`writer::paints::placement`). The imaging data +//! follows (a linear gradient's `a b c d tx ty Xm`, its caps `Bc` and a `Bm` for each pair of +//! stops; a radial one's `Bm`), then the operator and `0 BB` (`2 BB` or `1 BB` when the path is +//! stroked too; a fill's instance ends `2 BB` before a stroke's). In a pattern's tile the matrices +//! are in the canvas's space (y down, from art space's origin there). +//! - State before each object: locked `A`, hidden `Xw` (`1` or `0`). An object's name follows it as +//! an `/ArtDictionary` whose `AI10_ArtUID` is the name as an XML id. Guides are the path +//! followed by `(N) *` (`(n) *` when closed), without the `(N) *` that §6 also puts before it. +//! - Transparency: `mode opacity isolate knockout shape Xy` (the blending mode's number, Knockout +//! Group 0 off, 1 on, 2 neutral), written when it changes: in a path's paint after its colors, +//! before a guide, and after a group's end (`U` or `Q`) followed by `0 0 Xd` and `6 () XW`; a +//! group without transparency of its own ends `9 () XW`. A layer's comes after its art: `Xy`, +//! `0 0 Xd`, `7 () XW`, before `LB`. +//! - Compound paths: `*u`, the subpaths, `*U` (§5.3.5). Clipping groups: `q`, the art, the clipping +//! path last with `h` (or `H` when open) and `W` before its painting operator, `Q` (§5.6.2); a +//! clipping layer's clipping path is written the same way, last in the layer. +//! - Opacity masks: an `AI9_Mask` entry in the object's `/ArtDictionary`, a `/Mask` dictionary +//! holding the mask's art between `X=` and `X+` on `%_` lines, `(Art) ,`, and `Clipping`, +//! `Inverted`, `Disabled` and `Linked` as `/Bool` entries. +//! - Embedded images (§8): `%AI5_File:`, `%AI5_BeginRaster`, `() 1 XG`, the color space +//! (`/DeviceGray`, `/DeviceRGB` or `/DeviceCMYK`) with `XN`, `[matrix] w h 0 Xh`, `[matrix] 0 0 +//! w h w h 8 type alpha flags 1 0 4 4 0 0` (type 1 gray, 3 RGB, 4 CMYK; alpha 1 with an alpha +//! channel; flags 0 gray, 1 RGB, 2 CMYK, 16 more with an alpha channel), `%%BeginData:` counting +//! `XI`, its line end and the color samples, `XI`, the samples in binary (8 bits, rows from the +//! top, CMYK images with their ink amounts) followed by the alpha channel, `%%EndData`, `XH`, +//! `%AI5_EndRaster`, `N`. The matrix (to ten decimals) is an art-space matrix applied to the +//! pixels with their rows running downwards. In a part on `%_` lines, `XI` and the samples are +//! not, and `%_%%EndData` ends them. +//! - Linked images (version 7 specification §16, with the newer sections): `%AI5_BeginPlace`, +//! `%%FileType: 1`, `[matrix] llx lly urx ury 4 4 0` and `(path)` with `` ` ``, `%%IncludeFile:`, +//! the folder relative to the document's between `%AI28_BeginPlacedRelativePath` and its end, +//! a preview of at most 256 pixels a side between `%AI26_BeginPlacedObjectPreview` and its end +//! (`w h rowBytes 32 17 `, then rows of premultiplied ARGB), each in versioned content, `~`, +//! `%AI5_EndPlace`. The box is the file's pixels at art space's origin on the canvas; the matrix +//! takes it into art space. In opacity masks, pattern tiles and symbols, linked images are +//! embedded. +//! - Type: a text object `/AI11Text :` naming its story and frame (`/StoryIndex`, `/FrameIndex`), +//! for area type and type on a path with its frame's path (`/Art :` … `; /ConfiningPath ,`), and +//! the text document after the document data (`%AI11_BeginTextDocument`, see +//! `writer::texts`), in the form the reader's `ate.rs` reads: the characters, the fonts, sizes, +//! leading, tracking, baseline shift, scales, solid fills and strokes and capitals of each run, +//! the alignment, indents, spacing, hyphenation and direction of each paragraph, and the frame: +//! point type's point and matrix, area type's frame, rows, columns, gutters and first baseline, +//! type on a path's path and span, vertical type, and the frames a threaded story flows through. +//! - Symbols, as the reader reads them ([`crate::import`]'s `.ai` reader, `read.rs`): every symbol +//! of the document defined in the setup after the patterns, in a non-printing block +//! (`%AI14_BeginSymbol`, `(name)`, `0 A`, `0 Xw`, `0 Ae`, the art in the symbol's space with y +//! down, the registration point as `AI13PatternRegistrationType` 1 to 9 from the top left, row by +//! row (VectorCraft's numbering, in the order the scripting reference lists the points), in the +//! art's dictionary, `%AI10_EndSymbol`), each after those its art uses; the symbol +//! list after the palette (`%AI24_BeginSymbolList`, the names in the Symbols panel's order, +//! `%AI24_EndSymbolList`); each instance as `/SymbolInstance :`, `(name) /SymbolRef ,`, the +//! matrix taking the art to art space as `a b c d tx ty /RTransformMatrix`, `;`, then its name +//! and opacity mask and a state block as a group's with its opacity and blending mode (an +//! instance with isolation, knockout or knockout shape of its own is written as its art). The +//! definitions are at most the reader's 4,096. In a symbol's art, an instance's matrix and +//! a gradient's take the art to the canvas's space turned y up about art space's origin there. +//! - Art styles, as the reader reads them (`style.rs`, `read/ops.rs`): a path, compound path or +//! group with live effects or linked to a graphic style is written as its drawn look (`u`, its +//! vector art as its geometry effects leave it, without shadows, glows or feathers, `U`, its +//! transparency, `0 0 Xd`, `6 () XW`), then the object itself on `%_` lines (its points painted +//! with nothing, or with its gradient fill; a group with its members) with its name and opacity +//! mask, then `1 (style) XW`. The styles are written in a non-printing block after the symbols +//! (`%AI9_BeginArtStyles`, each `/KnownStyle :` with its name and a filter tree: a chain of the +//! stack of fills and strokes with the contents among them, the effects and the blend filter), the +//! Graphic Styles panel's first; the panel's order follows the palette (`%AI9_BeginArtStyleList`). +//! A fill filter fills by the non-zero rule (`0 /Bool (UseEvenOdd)`), so a filled object that +//! fills by the even-odd rule is written as its drawn look. A style is written only when the +//! reader reads it back as the object's appearance (or the graphic style's). +//! +//! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at +//! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the +//! artboards together are centered; each artboard's `RulerOrigin` is its top-left corner there, and +//! `%AI3_TemplateBox` holds the canvas's center in art space. What the form above can't hold is written as plain filled and stroked paths, each such +//! loss a warning: type the text document can't hold (in opacity masks, pattern tiles, symbols and +//! art cut to a clipping object, mirrored, turned or unevenly scaled area type and type on a path, inline graphics, ruby, +//! gradient or pattern paint, an appearance of its own) as its outlines and its inline graphics' +//! art, the character and paragraph attributes the text document doesn't hold, freeform gradients, gradients +//! along or across a stroke and gradients without stops, with more than 256 stops or without extent +//! as their average color +//! (gradients that dither or mix perceptually are written as classic ones, and gradient stops linked +//! to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past +//! the tile or is painted with patterns, and pattern fills in symbols, as their tiles cut +//! to the shape, clipping groups and clipping layers whose clipping object isn't a path, +//! and the clipping groups inside them, as their art cut to that object (its fill cut too, its +//! stroke not; an image in a clipping group of the region it is cut to), images that can't be +//! decoded or have more than 33,554,432 pixels as their outlines filled mid gray, images of 16 bits +//! a channel at 8 bits, linked images in opacity masks, pattern tiles and symbols as embedded images, +//! symbol instances with a fill, appearance changes, isolation, knockout or knockout shape of their +//! own, instances of symbols with 9-slice guides or pattern paint, instances in pattern tiles or in art cut to a +//! clipping object, instances scaled almost flat, instances that turn, mirror or scale symbols holding +//! type, live objects, instances written as their art, shapes with rounded live corners or strokes +//! written as outlines or brush art, +//! instances that scale their symbol more than 100 times, instances on the layers of a large canvas +//! and instances of +//! symbols past 4,096 as their art (symbol art past [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects +//! in all left out), instances of symbols the document doesn't have as empty groups, symbols' 9-slice +//! guides, export types and dynamic type left out, live objects (placed documents included) as their art, +//! strokes a plain line can't draw +//! as their filled outlines, several fills or strokes as a group of a path for each, freeform +//! gradient swatches, gradient swatches of more than 256 stops, swatches of patterns written as +//! tiles and the placement of pattern swatches that move, turn or scale their pattern, the opacity and blending modes of single fills and strokes, opacity masks on +//! layers and opacity masks nested too deep, and, on objects written without an art style, live +//! effects other than geometry effects left out; graphic styles the reader wouldn't read, links to +//! graphic styles on objects not written with them, and every art style on a large canvas, are left +//! out. +//! +//! The data streams hold the program compressed with Zstandard after `%AI24_ZStandard_Data`, with +//! the version numbers of the newest files users sent ([`private_data`]). + +use std::fmt::Write; +use std::sync::Arc; + +use vectorcraft_doc::{Document, Node, Unit}; +use vectorcraft_geom::{Affine, Rect}; +use vectorcraft_pdf::PrivateData; + +use crate::ps; + +mod writer; + +use writer::Writer; + +/// The version comment's value: the creator version of the newest files users sent. +pub const CREATOR_VERSION: &str = "30.7.0"; +/// The `PieceInfo` numbers that go with Zstandard-compressed data: container 12, creator 30, +/// round trip 24, stream type 2. +const CONTAINER_VERSION: u32 = 12; +const CREATOR: u32 = 30; +const ROUNDTRIP_VERSION: u32 = 24; +const ROUNDTRIP_STREAM_TYPE: u32 = 2; +/// What starts the data streams of Zstandard-compressed data. +const ZSTD_MARKER: &[u8] = b"%AI24_ZStandard_Data"; +/// `%%Canvassize`: the side of the canvas in points, as the files users sent have it. +const CANVAS_SIZE: u32 = 16383; +/// The scale of a large canvas: its sides are ten times the canvas's, as the format's large canvas +/// documents have them (2270 inches square). +const LARGE_CANVAS_SCALE: f64 = 10.0; +/// `%AI5_ArtSize`, as the files users sent have it. +const ART_SIZE: u32 = 14400; +/// `%AI5_ArtFlags` (§2.1.1, Table 4), as the files users sent have them: page setup, print tiles, +/// placed images, preview patterns, split long paths, tile full pages, printer's default +/// screens, auto default screens, compatible gradient printing. +const ART_FLAGS: &str = "0 0 0 1 0 0 1 0 0"; +/// `%AI5_TargetResolution` (§2.1.1). +const TARGET_RESOLUTION: u32 = 800; +/// The gridlines' gray: VectorCraft's default grid color (200 of 255). +const GRID_GRAY: f64 = 200.0 / 255.0; + +/// `%%Creator`: the creator line VectorCraft writes in the header of the editing data. It names +/// VectorCraft and the format's app, and holds no version number; the version is written on its +/// own in `%%AI8_CreatorVersion` ([`CREATOR_VERSION`]). +const CREATOR_TEXT: &str = "VectorCraft, editing data for Illustrator"; // brand-ok: the creator line VectorCraft writes + +/// The first line of a PostScript file (the DSC version comment). +const PS_HEADER: &str = "%!PS-Adobe-3.0"; // brand-ok: the PostScript header comment + +/// What to write in the header. +#[derive(Clone, Debug, Default)] +pub struct AiEditingOptions { + /// `%%Title`. + pub title: String, + /// `%%CreationDate`, Unix seconds. + pub created: Option, +} + +/// The editing data and what it couldn't hold. +#[derive(Clone, Debug, Default)] +pub struct AiEditingOutput { + /// The program: header comments, setup, layers, trailer. + pub program: Vec, + /// Its header comments, up to `%%EndComments`. + pub header: Vec, + pub warnings: Vec, +} + +/// Write `doc` as the editing data of a `.ai` file: every artboard and layer. +pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result { + let board = doc.artboards.first().ok_or("the document has no artboard")?.rect; + if !(board.is_finite() && board.width() > 0.0 && board.height() > 0.0) { + return Err("the document has no artboard".into()); + } + // Artboards that don't fit on the canvas are written on a large canvas, at 1/scale. + let scale = canvas_scale(doc); + // The objects that may keep their effects in an art style, as they are before baking (not on + // a large canvas, whose scale the styles' strokes and effects would need). + let styled = writer::styled_objects(doc); + let own_styles = doc.graphic_styles != Document::new(1.0, 1.0).graphic_styles; + let links = writer::style_links(doc); + // Live geometry effects as their result, as the PDF part draws them. + let baked = baked(doc); + let doc = baked.as_ref().unwrap_or(doc); + let reduced = (scale != 1.0).then(|| { + let mut d = doc.clone(); + crate::import::scale_document(&mut d, 1.0 / scale, true); + // Symbol and pattern art is placed without scaling its strokes, so its strokes and effects + // are scaled here. + for s in d.symbols.iter_mut() { + scale_strokes(Arc::make_mut(&mut s.art), 1.0 / scale); + } + for p in d.patterns.iter_mut() { + for a in &mut p.art { + scale_strokes(Arc::make_mut(a), 1.0 / scale); + } + } + d + }); + // Symbols are defined at their own size, whatever the canvas. + let symbol_doc = doc; + let doc = reduced.as_ref().unwrap_or(doc); + let board = doc.artboards.first().map_or(board, |a| a.rect); + // The document is y down; art space is ruler space: y up, its origin the first artboard's + // top-left corner. + let to_art = Affine::new([1.0, 0.0, 0.0, -1.0, -board.x0, board.y0]); + let origin = ruler_origin(doc, to_art); + let mut w = Writer::new(doc, to_art, origin); + // On a large canvas the layers' symbol instances are written as their art. + w.symbols_live = scale == 1.0; + w.symbol_doc = symbol_doc; + w.reserve_swatch_gradients(); + if scale == 1.0 { + w.styled = styled; + w.panel_styles(); + } else if !styled.is_empty() || own_styles || links > 0 { + w.warnings.push(writer::LARGE_CANVAS_STYLES.to_string()); + } + for layer in &doc.layers { + w.layer(layer); + } + if scale == 1.0 { + w.lost_links(links); + } + // The symbols no instance uses too; their art adds definitions. + w.symbols(); + // The palette first: its gradient and pattern swatches add definitions. + let mut palette = String::new(); + w.palette(&mut palette); + let library = w.variable_library(); + let first = to_art.transform_rect_bbox(board); + let art = doc + .layers + .iter() + .filter(|l| l.visible) + .filter_map(|l| l.visual_bounds()) + .map(|b| to_art.transform_rect_bbox(b)) + .filter(|b| b.is_finite()) + .reduce(|a, b| a.union(b)) + .unwrap_or(first); + let header = header(doc, o, &w, art, first, origin, scale); + let mut s = header.clone(); + s.push_str("%%BeginProlog\n%%EndProlog\n%%BeginSetup\n"); + w.definitions(&mut s); + w.symbol_definitions(&mut s); + w.art_styles(&mut s); + s.push_str(&palette); + w.art_style_list(&mut s); + w.symbol_list(&mut s); + artboards(&mut s, doc, to_art, origin, &library); + if !w.texts.is_empty() { + s.push_str(&w.texts.section(doc)); + } + s.push_str("%%EndSetup\n"); + s.push_str(&w.body); + s.push_str("%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n"); + // Lines end in CR LF, as in the files users sent; line breaks inside strings are escaped. + let program = splice(&crlf(&s), &w.payloads); + Ok(AiEditingOutput { program, header: crlf(&header), warnings: w.warnings }) +} + +/// `s` with each line ending in CR LF. +fn crlf(s: &str) -> Vec { + s.replace('\n', "\r\n").into_bytes() +} + +/// `text` with each payload's mark (`\u{1}`, its index in `payloads`, `\u{1}`) replaced by its +/// bytes. Strings are written with that byte escaped, so a mark is never part of one. +fn splice(text: &[u8], payloads: &[Vec]) -> Vec { + let mark = writer::PAYLOAD as u8; + if payloads.is_empty() { + return text.to_vec(); + } + let mut out = Vec::with_capacity(text.len() + payloads.iter().map(Vec::len).sum::()); + let mut parts = text.split(|b| *b == mark); + if let Some(first) = parts.next() { + out.extend_from_slice(first); + } + // The parts alternate: an index, then the text up to the next mark. + while let (Some(index), Some(rest)) = (parts.next(), parts.next()) { + let payload = std::str::from_utf8(index).ok().and_then(|i| i.parse::().ok()).and_then(|i| payloads.get(i)); + if let Some(p) = payload { + out.extend_from_slice(p); + } + out.extend_from_slice(rest); + } + out +} + +/// `doc` with its geometry effects and group paint baked ([`vectorcraft_effects::bake_document`]), +/// in its symbols' art and its patterns' tile art too (which instances and pattern fills are +/// written as); `None` when nothing changes. +fn baked(doc: &Document) -> Option { + let baked = vectorcraft_effects::bake_document(doc); + let d = baked.as_ref().unwrap_or(doc); + let needs = vectorcraft_effects::needs_bake; + if !d.symbols.iter().any(|s| needs(&s.art)) && !d.patterns.iter().any(|p| p.art.iter().any(|a| needs(a))) { + return baked; + } + // The symbols' art, then each pattern's art, baked as the layers of a copy of the document. + let mut art = d.clone(); + let symbols = d.symbols.iter().map(|s| Arc::new(Node::group(s.art.id, vec![s.art.clone()]))); + let patterns = d.patterns.iter().map(|p| Arc::new(Node::group(vectorcraft_doc::NodeId(0), p.art.clone()))); + art.layers = symbols.chain(patterns).collect(); + // The copy keeps what baking adds to the document (the images color adjustments make). + let Some(mut out) = vectorcraft_effects::bake_document(&art) else { return baked }; + let layers = std::mem::replace(&mut out.layers, d.layers.clone()); + let mut members = layers.iter().map(|l| l.children().cloned().unwrap_or_default()); + for s in out.symbols.iter_mut() { + if let Some(a) = members.next().and_then(|m| m.first().cloned()) { + s.art = a; + } + } + for p in out.patterns.iter_mut() { + if let Some(m) = members.next() { + p.art = m; + } + } + Some(out) +} + +/// The editing data of `doc` as a `.ai` file's pages carry it: the program compressed with +/// Zstandard after `%AI24_ZStandard_Data`, its header as the `AIMetaData`, and the version numbers +/// that go with that form; and what it couldn't hold. +pub fn private_data(doc: &Document, o: &AiEditingOptions) -> Result<(PrivateData, Vec), String> { + let out = export_ai_editing(doc, o)?; + let mut data = ZSTD_MARKER.to_vec(); + data.extend(ruzstd::encoding::compress_to_vec(out.program.as_slice(), ruzstd::encoding::CompressionLevel::Fastest)); + let p = PrivateData { + data, + metadata: out.header, + container_version: CONTAINER_VERSION, + creator_version: CREATOR, + roundtrip_version: ROUNDTRIP_VERSION, + roundtrip_stream_type: ROUNDTRIP_STREAM_TYPE, + }; + Ok((p, out.warnings)) +} + +/// Where art space's origin lies on the canvas (y down, [`CANVAS_SIZE`] points square): the +/// artboards together centered on the canvas's center, on whole points, as the files users sent +/// place them. +fn ruler_origin(doc: &Document, to_art: Affine) -> (f64, f64) { + let all = doc.artboards.iter().map(|ab| to_art.transform_rect_bbox(ab.rect)).filter(|r| r.is_finite()).reduce(|a, b| a.union(b)); + let c = all.map_or((0.0, 0.0), |r| (r.center().x, r.center().y)); + let mid = canvas_center(); + ((mid - c.0).floor(), (mid + c.1).floor()) +} + +/// `%AI24_LargeCanvasScale`: 1 when the artboards together fit on the canvas, with a point to +/// spare on each side for the rounding of [`ruler_origin`], else [`LARGE_CANVAS_SCALE`]: then the +/// art, boxes and artboards are written at 1/[`LARGE_CANVAS_SCALE`] of their size. +fn canvas_scale(doc: &Document) -> f64 { + let all = doc.artboards.iter().map(|ab| ab.rect).filter(|r| r.is_finite()).reduce(|a, b| a.union(b)); + let room = f64::from(CANVAS_SIZE) - 2.0; + if all.is_some_and(|r| r.width() > room || r.height() > room) { LARGE_CANVAS_SCALE } else { 1.0 } +} + +/// The strokes and effects of `n` and of what it holds, `k` times as large. +fn scale_strokes(n: &mut Node, k: f64) { + n.appearance.scale_strokes(k); + n.appearance.scale_effects(k, vectorcraft_effects::scale_effect); + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + scale_strokes(Arc::make_mut(&mut mask.art), k); + } + if let Some(children) = n.children_mut() { + for c in children { + scale_strokes(Arc::make_mut(c), k); + } + } +} + +/// The canvas's center, on its own axes and in both directions. +fn canvas_center() -> f64 { + f64::from(CANVAS_SIZE) / 2.0 +} + +/// The header comments, through `%%EndComments`. `art`: the visible art's bounds, `first` the first +/// artboard, in art space; `origin` art space's origin on the canvas ([`ruler_origin`]); `scale` +/// the large canvas scale ([`canvas_scale`]). +fn header(doc: &Document, o: &AiEditingOptions, w: &Writer, art: Rect, first: Rect, origin: (f64, f64), scale: f64) -> String { + let mut s = String::new(); + s.push_str(PS_HEADER); + s.push('\n'); + let _ = writeln!(s, "%%Creator: {CREATOR_TEXT}"); + let _ = writeln!(s, "%%AI8_CreatorVersion: {CREATOR_VERSION}"); + // The user and the organization (§2.1.1). + let _ = writeln!(s, "%%For: {} ()", ps::bytes(doc.metadata.author.as_bytes())); + let _ = writeln!(s, "%%Title: {}", ps::bytes(o.title.as_bytes())); + if let Some(t) = o.created { + let [y, mo, d, h, mi, _] = vectorcraft_doc::metadata::civil(t); + let _ = writeln!(s, "%%CreationDate: ({mo}/{d}/{y:04}) ({h:02}:{mi:02})"); + } + let _ = writeln!(s, "%%Canvassize: {CANVAS_SIZE}"); + let _ = writeln!(s, "%%BoundingBox: {} {} {} {}", art.x0.floor() as i64, art.y0.floor() as i64, art.x1.ceil() as i64, art.y1.ceil() as i64); + s.push_str("%%HiResBoundingBox: "); + ps::push_nums(&mut s, &[art.x0, art.y0, art.x1, art.y1]); + s.pop(); + s.push('\n'); + s.push_str("%%DocumentProcessColors: Cyan Magenta Yellow Black\n"); + s.push_str("%AI5_FileFormat 14.0\n%AI3_ColorUsage: Color\n"); + // Linked files aren't included (their previews are). + s.push_str("%AI7_ImageSettings: 0\n"); + let spots = w.spot_swatches(); + for (i, (name, _)) in spots.iter().enumerate() { + let _ = writeln!(s, "{} {}", if i == 0 { "%%DocumentCustomColors:" } else { "%%+" }, ps::bytes(name.as_bytes())); + } + for (i, (name, cmyk)) in spots.iter().enumerate() { + s.push_str(if i == 0 { "%%CMYKCustomColor: " } else { "%%+ " }); + ps::push_nums(&mut s, &cmyk.map(f64::from)); + let _ = writeln!(s, "{}", ps::bytes(name.as_bytes())); + } + // The first artboard, left, bottom, right, top. + let mut board = String::new(); + ps::push_nums(&mut board, &[first.x0, first.y0, first.x1, first.y1]); + board.pop(); + let _ = writeln!(s, "%AI3_Cropmarks: {board}"); + // The canvas's center in art space. + let (cx, cy) = (ps::num(canvas_center() - origin.0), ps::num(origin.1 - canvas_center())); + let _ = writeln!(s, "%AI3_TemplateBox: {cx} {cy} {cx} {cy}"); + let _ = writeln!(s, "%AI3_TileBox: {board}"); + s.push_str("%AI3_DocumentPreview: None\n"); + let _ = writeln!(s, "%AI5_ArtSize: {ART_SIZE} {ART_SIZE}"); + let _ = writeln!(s, "%AI5_RulerUnits: {}", ruler_units(doc.units)); + let _ = writeln!(s, "%AI24_LargeCanvasScale: {}", ps::num(scale)); + let model = if doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { 2 } else { 1 }; + let _ = writeln!(s, "%AI9_ColorModel: {model}"); + let _ = writeln!(s, "%AI5_ArtFlags: {ART_FLAGS}"); + let _ = writeln!(s, "%AI5_TargetResolution: {TARGET_RESOLUTION}"); + let _ = writeln!(s, "%AI5_NumLayers: {}", doc.layers.len()); + // A digit for each layer: 7 shown, 6 hidden. + let views: String = doc.layers.iter().map(|l| if l.visible { '7' } else { '6' }).collect(); + if !views.is_empty() { + let _ = writeln!(s, "%AI5_OpenViewLayers: {views}"); + } + // Gridlines and subdivisions (§2.1.1, Table 6): in back, lines, in VectorCraft's grid gray. + let (space, subdiv) = (ps::num(doc.grid.spacing), doc.grid.subdivisions); + let gray = ps::num(GRID_GRAY); + let _ = writeln!(s, "%AI7_GridSettings: {space} {subdiv} {space} {subdiv} 1 0 {gray} {gray} {gray} {gray} {gray} {gray}"); + s.push_str("%%EndComments\n"); + s +} + +/// `%AI5_RulerUnits` of `u` (as the reader reads it; units it has no number for are points). +fn ruler_units(u: Unit) -> u8 { + match u { + Unit::Inches => 0, + Unit::Millimeters => 1, + Unit::Picas => 3, + Unit::Centimeters => 4, + Unit::Pixels => 6, + Unit::Points | Unit::FeetInches | Unit::Meters | Unit::Yards | Unit::Feet | Unit::Q | Unit::Ha => 2, + } +} + +/// The artboards as the `ArtboardArray` of the `/Document` dictionary: each one's top-left and +/// bottom-right corners in art space (`PositionPoint1`, `PositionPoint2`), its top-left corner on +/// the canvas (`RulerOrigin`, `origin` being art space's origin there), its pixel aspect ratio +/// (`PAR`), `DisplayMark` 0 (as in the files users sent), whether it is the selected one (the +/// active one) and its name; then the index of the active artboard (`CropAreaActive`: the one +/// [`Document::opened_artboard`] names, else the first) and the canvas's size. Every record holds +/// all of these entries. The artboards, the active artboard and the canvas size are written in the +/// `/Recorded` part of the `/Document` dictionary, followed by an empty `/NotRecorded` part. +fn artboards(s: &mut String, doc: &Document, to_art: Affine, origin: (f64, f64), library: &str) { + let active = doc.opened_artboard.and_then(|id| doc.artboards.iter().position(|a| a.id == id)).unwrap_or(0); + s.push_str("%AI9_BeginDocumentData\n%_/Document :\n%_/Dictionary :\n%_/Array :\n"); + for (i, ab) in doc.artboards.iter().enumerate() { + let r = to_art.transform_rect_bbox(ab.rect); + s.push_str("%_/Dictionary :\n%_"); + ps::push_nums(s, &[r.x0, r.y1]); + s.push_str("/RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_"); + ps::push_nums(s, &[r.x1, r.y0]); + s.push_str("/RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_"); + ps::push_nums(s, &[origin.0 + r.x0, origin.1 - r.y1]); + s.push_str("/RealPoint\n%_ (RulerOrigin) ,\n%_"); + let par = ab.video_ruler_pixel_aspect_ratio; + ps::push_num(s, if par.is_finite() && par > 0.0 { par } else { 1.0 }); + // Display marks: 1 the center mark, 2 cross hairs, 4 video safe areas. + let mark = u8::from(ab.show_center_mark) | u8::from(ab.show_cross_hairs) << 1 | u8::from(ab.show_video_safe_areas) << 2; + let _ = writeln!(s, " /Real (PAR) ,\n%_{mark} /Int (DisplayMark) ,\n%_{} /Bool (IsArtboardSelected) ,", u8::from(i == active)); + let _ = writeln!(s, "%_{} /UnicodeString (Name) ,\n%_; ,", ps::bytes(ab.name.as_bytes())); + } + s.push_str("%_; (ArtboardArray) ,\n"); + let _ = writeln!(s, "%_{active} /Int (CropAreaActive) ,"); + let _ = writeln!(s, "%_{CANVAS_SIZE} /Int (AIDocumentCanvasSize) ,"); + // The variable library, after the canvas size. + s.push_str(library); + s.push_str("%_; /Recorded ,\n%_/Dictionary : /NotRecorded ,\n%_; /NotRecorded ,\n%_;\n%AI9_EndDocumentData\n"); +} + +#[cfg(test)] +mod tests; diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs new file mode 100644 index 0000000000..73c539717a --- /dev/null +++ b/crates/eps/src/ai_editing/tests.rs @@ -0,0 +1,7207 @@ +//! The editing data written, then read back by VectorCraft's own reader ([`crate::ai_alone`]). + +use std::sync::Arc; + +use vectorcraft_color::swatch::{Swatch, SwatchGroup}; +use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, Artboard, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind, + OpacityMask, StrokeLayer, Symbol, +}; +use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; + +use super::*; + +fn opts() -> AiEditingOptions { + AiEditingOptions { title: "Sample".into(), created: Some(0) } +} + +/// The program written from `doc`, as text with its CR LF line ends read as LF. +fn program(doc: &Document) -> String { + String::from_utf8(export_ai_editing(doc, &opts()).unwrap().program).unwrap().replace("\r\n", "\n") +} + +/// `doc` written, then read back from the private data alone. +fn read_back(doc: &Document) -> Document { + let (p, _) = private_data(doc, &opts()).unwrap(); + crate::ai_alone(&p.data).unwrap().0 +} + +fn solid(c: Color) -> Paint { + Paint::solid(c) +} + +/// A swatch's color at `tint`, linked to it. +fn linked(name: &str, full: Color, tint: f32) -> Paint { + Paint::Solid { color: full.tinted(tint), swatch: Some(name.into()), tint } +} + +const BRAND: Color = Color::Cmyk { c: 0.1, m: 0.7, y: 0.2, k: 0.05 }; +const GOLD: Color = Color::Cmyk { c: 0.0, m: 0.25, y: 0.9, k: 0.1 }; +const SKY: Color = Color::Rgb { r: 0.25, g: 0.5, b: 1.0 }; +const MINT: Color = Color::Lab { l: 80.0, a: -40.0, b: 10.0 }; + +/// A 200 × 100 document with a second artboard: swatches (process, global process, CMYK, RGB and +/// Lab spot colors, a color group); a layer `Back` (preset color 2) holding a named group `Pair` +/// of a named rectangle `Red` (stroked 2 pt, round caps, bevel joins, miter limit 4, dashed, over +/// a gray fill that overprints) and a hidden, locked one, an even-odd ellipse in a global color at +/// half tint, an open path stroked in a spot color, a guide, and a hidden locked sublayer `Sub` +/// (a custom color, not printing, dimmed) holding a path filled with an RGB and stroked with a Lab +/// spot color; a second layer `Front`, locked, with a CMYK square named like the rectangle. +fn sample() -> Document { + let mut doc = Document::new(200.0, 100.0); + let mut second = doc.artboards[0].clone(); + second.id = 2; + second.name = "Back side".into(); + second.rect = Rect::new(250.0, 0.0, 450.0, 100.0); + doc.artboards.push(second); + let swatch = |name: &str, c: Color, global: bool, spot: bool| Swatch { name: name.into(), paint: solid(c), global, spot }; + doc.swatches = vec![ + Swatch { name: "[None]".into(), paint: Paint::None, global: false, spot: false }, + swatch("Teal", Color::rgb(0.0, 0.5, 0.5), false, false), + swatch("Brand", BRAND, true, false), + swatch("Gold", GOLD, true, true), + swatch("Sky", SKY, true, true), + swatch("Mint", MINT, true, true), + ] + .into(); + doc.swatch_groups = vec![SwatchGroup { name: "Grays".into(), swatches: vec![swatch("Mid", Color::gray(0.5), false, false)] }].into(); + doc.layers.clear(); + let back = doc.add_layer(Some("Back")); + let front = doc.add_layer(Some("Front")); + + let mut stroke = StrokeLayer::new(solid(Color::rgb(0.0, 0.0, 1.0)), 2.0); + stroke.cap = LineCap::Round; + stroke.join = LineJoin::Bevel; + stroke.miter_limit = 4.0; + stroke.dash = Some(Dash { pattern: vec![3.0, 2.0], offset: 1.0, align_corners: false }); + let fill = FillLayer { overprint: true, ..FillLayer::new(solid(Color::gray(0.25))) }; + let mut red = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(10.0, 10.0, 40.0, 40.0)), + Appearance { items: vec![AppearanceItem::Fill(fill), AppearanceItem::Stroke(stroke)], ..Appearance::default() }, + ); + red.name = Some("Red".into()); + let mut hidden = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(50.0, 10.0, 80.0, 40.0)), + Appearance::basic(solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), Paint::None, 0.0), + ); + hidden.visible = false; + hidden.locked = true; + let mut pair = Node::group(doc.alloc_id(), vec![Arc::new(red), Arc::new(hidden)]); + pair.name = Some("Pair".into()); + doc.insert(Some(back), usize::MAX, pair).unwrap(); + + let ellipse = Node::new( + doc.alloc_id(), + NodeKind::Path { + path: shapes::ellipse(Rect::new(100.0, 10.0, 160.0, 50.0)), + rule: FillRule::EvenOdd, + live: None, + clipping: false, + guide: false, + }, + ); + let ellipse = Node { appearance: Appearance::basic(linked("Brand", BRAND, 0.5), Paint::None, 0.0).into(), ..ellipse }; + doc.insert(Some(back), usize::MAX, ellipse).unwrap(); + let mut open = PathData::from_bezpath(&kurbo::BezPath::from_vec(vec![ + kurbo::PathEl::MoveTo((10.0, 60.0).into()), + kurbo::PathEl::LineTo((60.0, 90.0).into()), + ])); + open.subpaths.iter_mut().for_each(|sp| sp.closed = false); + let line = Node::path(doc.alloc_id(), open, Appearance::basic(Paint::None, linked("Gold", GOLD, 1.0), 3.0)); + doc.insert(Some(back), usize::MAX, line).unwrap(); + let guide = Node::new( + doc.alloc_id(), + NodeKind::Path { + path: shapes::rectangle(Rect::new(0.0, 50.0, 200.0, 50.0)), + rule: FillRule::NonZero, + live: None, + clipping: false, + guide: true, + }, + ); + doc.insert(Some(back), usize::MAX, guide).unwrap(); + + let mut sub = Node::layer(doc.alloc_id(), "Sub", LayerColor::Custom([10, 200, 30])); + if let NodeKind::Layer { printable, dim_images, .. } = &mut sub.kind { + *printable = false; + *dim_images = Some(70); + } + sub.visible = false; + sub.locked = true; + let sub = doc.insert(Some(back), usize::MAX, sub).unwrap(); + let skyfill = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(120.0, 60.0, 190.0, 95.0)), + Appearance::basic(linked("Sky", SKY, 0.8), linked("Mint", MINT, 1.0), 1.0), + ); + doc.insert(Some(sub), usize::MAX, skyfill).unwrap(); + + let mut square = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(300.0, 20.0, 340.0, 60.0)), + Appearance::basic(solid(Color::cmyk(0.5, 0.0, 1.0, 0.0)), Paint::None, 0.0), + ); + square.name = Some("Red".into()); + doc.insert(Some(front), usize::MAX, square).unwrap(); + if let Some(l) = doc.layers.get_mut(1) { + let l = Arc::make_mut(l); + l.locked = true; + if let NodeKind::Layer { color, .. } = &mut l.kind { + *color = LayerColor::Preset(2); + } + } + doc +} + +/// `v` to three decimals. +fn r3(v: f64) -> String { + format!("{:.3}", (v * 1000.0).round() / 1000.0 + 0.0) +} + +fn color(c: &Color) -> String { + let f = |v: f32| r3(f64::from(v)); + match *c { + Color::Gray { k } => format!("gray {}", f(k)), + Color::Cmyk { c, m, y, k } => format!("cmyk {} {} {} {}", f(c), f(m), f(y), f(k)), + Color::Rgb { r, g, b } => format!("rgb {} {} {}", f(r), f(g), f(b)), + Color::Lab { l, a, b } => format!("lab {} {} {}", f(l), f(a), f(b)), + } +} + +fn paint(p: &Paint) -> String { + match p { + Paint::Solid { color: c, swatch, tint } => format!("{} {swatch:?} {}", color(c), r3(f64::from(*tint))), + Paint::None => "none".into(), + other => format!("{other:?}"), + } +} + +/// What the reader's view of the slice's constructs is made of, one line per object. +fn view(nodes: &[Arc], depth: usize, out: &mut Vec) { + for n in nodes { + let head = format!("{depth} {:?} shown={} locked={}", n.name, n.visible, n.locked); + match &n.kind { + NodeKind::Layer { color, printable, preview, dim_images, clip, children, .. } => { + out.push(format!("{head} layer {color:?} printable={printable} preview={preview} dim={dim_images:?} clip={clip}")); + view(children, depth + 1, out); + } + NodeKind::Group { children, clip } => { + out.push(format!("{head} group clip={clip}")); + view(children, depth + 1, out); + } + NodeKind::Path { path, rule, guide, .. } => { + let mut s = format!("{head} path {rule:?} guide={guide}"); + for sp in &path.subpaths { + s += &format!(" [closed={}", sp.closed); + // Points are written to four decimals. + let r2 = |v: f64| format!("{:.2}", v + 0.0); + for a in &sp.anchors { + s += &format!(" {},{} {},{} {},{}", r2(a.h_in.x), r2(a.h_in.y), r2(a.p.x), r2(a.p.y), r2(a.h_out.x), r2(a.h_out.y)); + } + s += "]"; + } + if !guide { + // Items that paint nothing aren't written. + for it in n.appearance.items.iter().filter(|i| !i.paint().is_none()) { + s += &match it { + AppearanceItem::Fill(f) => format!(" fill({} op={})", paint(&f.paint), f.overprint), + AppearanceItem::Stroke(st) => format!( + " stroke({} w={} {:?} {:?} m={} {:?} op={})", + paint(&st.paint), + r3(st.width), + st.cap, + st.join, + r3(st.miter_limit), + st.dash.as_ref().map(|d| (d.pattern.clone(), d.offset)), + st.overprint + ), + }; + } + } + out.push(s); + } + // The compound path's own paint and its members' points (the paint is the compound path's). + NodeKind::Compound { rule, .. } => { + let mut s = format!("{head} compound {rule:?}"); + for c in n.children().map(Vec::as_slice).unwrap_or_default() { + for sp in c.path_data().map(|p| p.subpaths.as_slice()).unwrap_or_default() { + let r2 = |v: f64| format!("{:.2}", v + 0.0); + s += &format!(" [closed={}", sp.closed); + for a in &sp.anchors { + s += &format!(" {},{}", r2(a.p.x), r2(a.p.y)); + } + s += "]"; + } + } + for it in n.appearance.items.iter().filter(|i| !i.paint().is_none()) { + s += &format!(" {}", paint(it.paint())); + } + out.push(s); + } + // The matrix is written to ten decimals. + NodeKind::SymbolInstance { symbol, xf } => { + let xf: Vec = xf.as_coeffs().iter().map(|v| format!("{:.6}", v + 0.0)).collect(); + out.push(format!("{head} instance {symbol:?} [{}] {} {:?}", xf.join(" "), r3(f64::from(n.opacity)), n.blend)); + } + other => out.push(format!("{head} {other:?}")), + } + } +} + +fn lines(doc: &Document) -> Vec { + let mut out = vec![]; + view(&doc.layers, 0, &mut out); + out +} + +fn swatches(doc: &Document) -> Vec { + let one = |s: &Swatch| format!("{} global={} spot={} {}", s.name, s.global, s.spot, paint(&s.paint)); + let mut out: Vec = doc.swatches.iter().filter(|s| !matches!(s.paint, Paint::None)).map(one).collect(); + for g in doc.swatch_groups.iter() { + out.push(format!("group {}", g.name)); + out.extend(g.swatches.iter().map(one)); + } + out +} + +#[test] +fn the_reader_reads_back_every_construct_of_the_slice() { + let doc = sample(); + let back = read_back(&doc); + assert_eq!(lines(&back), lines(&doc)); + assert_eq!(swatches(&back), swatches(&doc)); + let boards: Vec<(String, Rect)> = back.artboards.iter().map(|a| (a.name.clone(), a.rect)).collect(); + assert_eq!( + boards, + vec![("Artboard 1".to_string(), Rect::new(0.0, 0.0, 200.0, 100.0)), ("Back side".to_string(), Rect::new(250.0, 0.0, 450.0, 100.0))] + ); + assert_eq!(back.color_mode, doc.color_mode); + assert_eq!(back.units, doc.units); +} + +#[test] +fn writing_again_gives_the_same_bytes() { + let doc = sample(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + assert_eq!(private_data(&doc, &opts()).unwrap().0, private_data(&doc, &opts()).unwrap().0); + // What the reader reads back is written as the same program. + let read = export_ai_editing(&read_back(&doc), &opts()).unwrap(); + assert_eq!(read.program, first.program); + assert!(first.warnings.is_empty(), "{:?}", first.warnings); +} + +#[test] +fn the_data_is_zstandard_compressed_with_the_header_as_metadata() { + let doc = sample(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let (p, _) = private_data(&doc, &opts()).unwrap(); + assert!(p.data.starts_with(ZSTD_MARKER)); + let mut body = p.data.get(ZSTD_MARKER.len()..).unwrap(); + let mut decoded = vec![]; + std::io::Read::read_to_end(&mut ruzstd::decoding::StreamingDecoder::new(&mut body).unwrap(), &mut decoded).unwrap(); + assert_eq!(decoded, out.program); + assert!(out.program.starts_with(&out.header)); + assert_eq!(p.metadata, out.header); + let header = String::from_utf8(out.header).unwrap(); + assert!(header.ends_with("%%EndComments\r\n")); + let header = header.replace("\r\n", "\n"); + for line in [ + "%%AI8_CreatorVersion: 30.7.0\n%%For: () ()\n%%Title: (Sample)\n", + "%%Canvassize: 16383\n", + "%AI5_FileFormat 14.0\n%AI3_ColorUsage: Color\n%AI7_ImageSettings: 0\n%%DocumentCustomColors: (Gold)\n%%+ (Sky)\n%%+ (Mint)\n", + "%AI3_Cropmarks: 0 -100 200 0\n%AI3_TemplateBox: 225.5 -50.5 225.5 -50.5\n%AI3_TileBox: 0 -100 200 0\n", + "%AI5_ArtSize: 14400 14400\n", + "%AI9_ColorModel: 1\n%AI5_ArtFlags: 0 0 0 1 0 0 1 0 0\n%AI5_TargetResolution: 800\n%AI5_NumLayers: 2\n", + "%AI5_OpenViewLayers: 77\n%AI7_GridSettings: 72 8 72 8 1 0 0.7843 0.7843 0.7843 0.7843 0.7843 0.7843\n%%EndComments\n", + ] { + assert!(header.contains(line), "{line}\n{header}"); + } + assert_eq!((p.container_version, p.creator_version, p.roundtrip_version, p.roundtrip_stream_type), (12, 30, 24, 2)); +} + +/// Art space is ruler space: y up from the first artboard's top-left corner. The artboards +/// together sit centered on the canvas: each one's top-left corner on the canvas (y down) is its +/// `RulerOrigin`, and the template box holds the canvas's center in art space. +#[test] +fn art_lies_on_its_artboard_in_ruler_space() { + let mut doc = Document::new(200.0, 100.0); + let mut second = doc.artboards[0].clone(); + (second.id, second.name, second.rect) = (2, "Back".into(), Rect::new(250.0, 0.0, 450.0, 100.0)); + doc.artboards.push(second); + let rect = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(10.0, 20.0, 30.0, 40.0)), + Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0), + ); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, rect).unwrap(); + let text = program(&doc); + for line in [ + "%%BoundingBox: 10 -40 30 -20\n", + "%AI3_Cropmarks: 0 -100 200 0\n", + "%AI3_TemplateBox: 225.5 -50.5 225.5 -50.5\n", + "\n10 -20 m\n", + "%_0 0 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_200 -100 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_7966 8141 /RealPoint\n%_ (RulerOrigin) ,\n%_1 /Real (PAR) ,\n%_0 /Int (DisplayMark) ,\n%_1 /Bool (IsArtboardSelected) ,\n", + "%_250 0 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_450 -100 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_8216 8141 /RealPoint\n%_ (RulerOrigin) ,\n%_1 /Real (PAR) ,\n%_0 /Int (DisplayMark) ,\n%_0 /Bool (IsArtboardSelected) ,\n", + "%_16383 /Int (AIDocumentCanvasSize) ,\n", + ] { + assert!(text.contains(line), "{line}\n{text}"); + } + // The creator names the format's app, before the canvas size and the template box, and holds + // no version number (the version is written in `%%AI8_CreatorVersion`). + let creator = text.lines().find_map(|l| l.strip_prefix("%%Creator: ")).unwrap(); + assert!(creator.contains("Illustrator"), "{creator}"); + assert!(!creator.contains("88") && !creator.chars().any(|c| c.is_ascii_digit()), "{creator}"); + assert!(text.find("%%Creator: ").unwrap() < text.find("%%Canvassize: 16383").unwrap()); + assert!(text.find("%%Canvassize: 16383").unwrap() < text.find("%AI3_TemplateBox").unwrap()); + // The reader puts the art back where it was, on its artboard. + let read = read_back(&doc); + assert_eq!(read.artboards.iter().map(|a| a.rect).collect::>(), doc.artboards.iter().map(|a| a.rect).collect::>()); + let bounds = read.layers.iter().filter_map(|l| l.visual_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert_eq!(bounds, Rect::new(10.0, 20.0, 30.0, 40.0)); +} + +/// A gray rectangle at `r` (document space) in `doc`'s first layer. +fn add_rect(doc: &mut Document, r: Rect) { + let rect = Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0)); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, rect).unwrap(); +} + +/// The end of the document data: the artboards, the active artboard (the first) and the canvas +/// size in the `/Recorded` part of the `/Document` dictionary, then an empty `/NotRecorded` part. +const RECORDED: &str = "%_; (ArtboardArray) ,\n%_0 /Int (CropAreaActive) ,\n%_16383 /Int (AIDocumentCanvasSize) ,\n%_; /Recorded ,\n%_/Dictionary : /NotRecorded ,\n%_; /NotRecorded ,\n%_;\n%AI9_EndDocumentData\n"; + +/// One letter-size artboard: the art 36 points in from its top-left corner, the artboard's record +/// and the boxes, with the artboards in the `/Recorded` part of the `/Document` dictionary. +#[test] +fn one_artboard_is_recorded_with_its_art_in_place() { + let mut doc = Document::new(612.0, 792.0); + doc.artboards[0].name = "Page".into(); + add_rect(&mut doc, Rect::new(36.0, 36.0, 576.0, 756.0)); + let text = program(&doc); + for line in [ + "%%BoundingBox: 36 -756 576 -36\n", + "%AI3_Cropmarks: 0 -792 612 0\n", + "%AI3_TemplateBox: 306.5 -396.5 306.5 -396.5\n", + "\n36 -36 m\n", + "%_0 0 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_612 -792 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_7885 7795 /RealPoint\n%_ (RulerOrigin) ,\n", + "%_(Page) /UnicodeString (Name) ,\n%_; ,\n", + RECORDED, + ] { + assert!(text.contains(line), "{line}\n{text}"); + } + let read = read_back(&doc); + assert_eq!(read.artboards.iter().map(|a| (a.name.as_str(), a.rect)).collect::>(), [("Page", Rect::new(0.0, 0.0, 612.0, 792.0))]); + let bounds = read.layers.iter().filter_map(|l| l.visual_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert_eq!(bounds, Rect::new(36.0, 36.0, 576.0, 756.0)); +} + +/// Two named artboards of different sizes, tops aligned: each record holds its corners in art +/// space and its top-left corner on the canvas, where the two together are centered. +#[test] +fn artboards_of_different_sizes_keep_their_names_and_places() { + let mut doc = Document::new(400.0, 300.0); + doc.artboards[0].name = "Front".into(); + let mut back = doc.artboards[0].clone(); + (back.id, back.name, back.rect) = (2, "Back".into(), Rect::new(440.0, 0.0, 740.0, 500.0)); + doc.artboards.push(back); + add_rect(&mut doc, Rect::new(50.0, 50.0, 150.0, 100.0)); + add_rect(&mut doc, Rect::new(490.0, 50.0, 590.0, 100.0)); + let text = program(&doc); + for line in [ + "%AI3_Cropmarks: 0 -300 400 0\n", + "%AI3_TemplateBox: 370.5 -250.5 370.5 -250.5\n", + "\n50 -50 m\n", + "\n490 -50 m\n", + "%_0 0 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_400 -300 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_7821 7941 /RealPoint\n%_ (RulerOrigin) ,\n", + "%_1 /Bool (IsArtboardSelected) ,\n%_(Front) /UnicodeString (Name) ,\n", + "%_440 0 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_740 -500 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_8261 7941 /RealPoint\n%_ (RulerOrigin) ,\n", + "%_0 /Bool (IsArtboardSelected) ,\n%_(Back) /UnicodeString (Name) ,\n", + RECORDED, + ] { + assert!(text.contains(line), "{line}\n{text}"); + } + let read = read_back(&doc); + assert_eq!( + read.artboards.iter().map(|a| (a.name.as_str(), a.rect)).collect::>(), + [("Front", Rect::new(0.0, 0.0, 400.0, 300.0)), ("Back", Rect::new(440.0, 0.0, 740.0, 500.0))] + ); + let bounds = read.layers.iter().filter_map(|l| l.visual_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert_eq!(bounds, Rect::new(50.0, 50.0, 590.0, 100.0)); +} + +/// An artboard larger than the canvas (20,000 points square): the data is written on a large +/// canvas, at 1/10 of the size, so the artboard lies on the canvas; read beside a page of the +/// artboard's size in points, it comes back at its size. +#[test] +fn an_artboard_larger_than_the_canvas_is_written_on_a_large_canvas() { + let mut doc = Document::new(20_000.0, 20_000.0); + add_rect(&mut doc, Rect::new(1000.0, 1000.0, 3000.0, 2000.0)); + let text = program(&doc); + for line in [ + "%AI24_LargeCanvasScale: 10\n", + "%AI3_Cropmarks: 0 -2000 2000 0\n", + "\n100 -100 m\n", + "%_0 0 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_2000 -2000 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_7191 7191 /RealPoint\n%_ (RulerOrigin) ,\n", + RECORDED, + ] { + assert!(text.contains(line), "{line}\n{text}"); + } + // A page of the artboard's size in points, as a PDF part in larger units gives it. + let mut page = Document::new(20_000.0, 20_000.0); + add_rect(&mut page, Rect::new(1000.0, 1000.0, 3000.0, 2000.0)); + let (p, _) = private_data(&doc, &opts()).unwrap(); + let (read, notes, layers) = crate::layered_ai(&p.data, page, vec![], false, true, 1.389); + assert!(layers, "{notes:?}"); + assert_eq!(read.artboards.iter().map(|a| a.rect).collect::>(), [Rect::new(0.0, 0.0, 20_000.0, 20_000.0)], "{notes:?}"); + let bounds = read.layers.iter().filter_map(|l| l.visual_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert!((bounds.x0 - 1000.0).abs() < 1e-6 && (bounds.y1 - 2000.0).abs() < 1e-6 && (bounds.width() - 2000.0).abs() < 1e-6, "{bounds:?}"); + // The same without a readable PDF part, on its first page's size. + let (alone, notes) = crate::ai_alone_on_page(&p.data, (20_000.0, 20_000.0), 1.389).unwrap(); + assert_eq!(alone.artboards.iter().map(|a| a.rect).collect::>(), [Rect::new(0.0, 0.0, 20_000.0, 20_000.0)], "{notes:?}"); + // And from the editing data alone, as a file saved without its PDF part opens. + let alone = read_back(&doc); + assert_eq!(alone.artboards.iter().map(|a| a.rect).collect::>(), [Rect::new(0.0, 0.0, 20_000.0, 20_000.0)]); + let bounds = alone.layers.iter().filter_map(|l| l.visual_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert!((bounds.x0 - 1000.0).abs() < 1e-6 && (bounds.width() - 2000.0).abs() < 1e-6, "{bounds:?}"); + + // A symbol's 30-point stroke is written at 1/10 too, as the layers' strokes are. + let mut doc = Document::new(20_000.0, 20_000.0); + let line = shapes::rectangle(Rect::new(0.0, 0.0, 500.0, 500.0)); + let art = Node::path(doc.alloc_id(), line, Appearance::basic(Paint::None, solid(Color::gray(0.5)), 30.0)); + doc.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: Arc::new(art) }); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Box".into(), xf: Affine::translate((1000.0, 1000.0)) }); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let (p, _) = private_data(&doc, &opts()).unwrap(); + let (read, notes, layers) = crate::layered_ai(&p.data, Document::new(20_000.0, 20_000.0), vec![], false, true, 1.389); + assert!(layers, "{notes:?}"); + let mut all = vec![]; + paths(read.layers[0].children().unwrap(), &mut all); + let widths: Vec = all.iter().filter_map(|n| n.appearance.stroke().map(|s| s.width)).collect(); + assert!(!widths.is_empty() && widths.iter().all(|w| (w - 30.0).abs() < 1e-6), "{widths:?}"); + + // Artboards that fit stay on the canvas at their size. + assert!(program(&Document::new(16_000.0, 16_000.0)).contains("%AI24_LargeCanvasScale: 1\n")); +} + +#[test] +fn a_pdf_carries_the_data_on_its_first_page() { + let doc = sample(); + let (p, _) = private_data(&doc, &opts()).unwrap(); + let pdf = + vectorcraft_pdf::export(&doc, &vectorcraft_pdf::PdfOptions { private_data: Some(p.clone()), ..vectorcraft_pdf::PdfOptions::uncompressed() }) + .unwrap(); + assert_eq!(vectorcraft_pdf::illustrator_data(&pdf, None).as_deref(), Some(&p.data[..])); + let (read, _) = crate::ai_alone(&vectorcraft_pdf::illustrator_data(&pdf, None).unwrap()).unwrap(); + assert_eq!(lines(&read), lines(&doc)); +} + +#[test] +fn names_are_xml_ids_numbered_when_taken() { + let text = program(&sample()); + assert!(text.contains("%_/XMLUID : (Red) ; (AI10_ArtUID) ,")); + assert!(text.contains("%_/XMLUID : (Red_00000000000000000001_) ; (AI10_ArtUID) ,")); + assert!(text.contains("%_/XMLUID : (Pair) ; (AI10_ArtUID) ,")); +} + +#[test] +fn many_objects_of_one_name_are_numbered_in_turn() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + for _ in 0..20_000 { + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default()); + n.name = Some("Dot".into()); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let text = program(&doc); + let ids: std::collections::HashSet<&str> = text.lines().filter(|l| l.starts_with("%_/XMLUID : (Dot")).collect(); + assert_eq!(ids.len(), 20_000); + assert!(text.contains("(Dot_00000000000000019999_)")); +} + +#[test] +fn layers_have_fourteen_operands() { + let text = program(&sample()); + assert!(text.contains("%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(Back) Ln\n"), "{text}"); + assert!(text.contains("%AI5_BeginLayer\n0 1 0 0 1 0 1 -1 10 200 30 0 70 0 Lb\n(Sub) Ln\n"), "{text}"); +} + +#[test] +fn layers_are_named_as_xml_ids_after_their_names() { + let mut doc = sample(); + let layer = doc.layers[0].id; + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default()); + n.name = Some("Back".into()); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let text = program(&doc); + assert!(text.contains("(Back) Ln\n%_/ArtDictionary :\n%_/XMLUID : (Back) ; (AI10_ArtUID) ,\n%_;\n%_\n"), "{text}"); + assert!(text.contains("(Sub) Ln\n%_/ArtDictionary :\n%_/XMLUID : (Sub) ; (AI10_ArtUID) ,\n"), "{text}"); + // An object named as a layer is numbered. + assert!(text.contains("%_/XMLUID : (Back_00000000000000000001_) ; (AI10_ArtUID) ,"), "{text}"); + // The reader keeps the names where they were. + let read = read_back(&doc); + assert_eq!(read.layers[0].name.as_deref(), Some("Back")); + let names: Vec> = read.layers[0].children().unwrap().iter().map(|c| c.name.as_deref()).collect(); + assert_eq!(names.last(), Some(&Some("Back"))); +} + +#[test] +fn lines_end_in_cr_lf() { + let mut doc = sample(); + doc.metadata.author = "A\nB".into(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let text = String::from_utf8(out.program).unwrap(); + assert_eq!(text.matches('\n').count(), text.matches("\r\n").count()); + assert_eq!(text.matches('\r').count(), text.matches("\r\n").count()); + // A line break in a string stays in the string, escaped. + assert!(text.contains("%%For: (A\\nB) ()\r\n"), "{text}"); +} + +#[test] +fn the_palette_starts_with_registration() { + let mut doc = sample(); + let rgb = program(&doc); + assert!(rgb.contains("0 0 Pb\n"), "{rgb}"); + let cell = rgb.split("0 0 Pb\n").nth(1).unwrap().lines().take(2).collect::>(); + assert!(cell[0].ends_with(" 0 0 0 ([Registration]) 0 1 Xz") && cell[0].split(' ').count() == 11, "{cell:?}"); + assert_eq!(cell[1], "([Registration]) Pc"); + doc.color_mode = vectorcraft_doc::ColorMode::Cmyk; + assert!(program(&doc).contains("0 0 Pb\n1 1 1 1 ([Registration]) 0 Xs\n([Registration]) Pc\n")); + // It's the built-in swatch: reading back adds no swatch. + assert_eq!(swatches(&read_back(&doc)), swatches(&doc)); +} + +#[test] +fn dotted_strokes_are_written_as_their_dots_with_a_warning() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut stroke = StrokeLayer::new(solid(Color::rgb(0.0, 0.0, 0.0)), 4.0); + stroke.cap = LineCap::Round; + stroke.dash = Some(Dash { pattern: vec![0.0, 10.0], offset: 0.0, align_corners: false }); + let line = PathData::from_bezpath(&kurbo::BezPath::from_vec(vec![ + kurbo::PathEl::MoveTo((10.0, 50.0).into()), + kurbo::PathEl::LineTo((60.0, 50.0).into()), + ])); + let n = Node::path(doc.alloc_id(), line, Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Appearance::default() }); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w.contains("dots")), "{:?}", out.warnings); + let text = program(&doc); + assert!(!text.contains("[0 10] 0 d"), "{text}"); + assert!(text.matches("\nf\n").count() >= 5, "a filled dot for each dash: {text}"); +} + +#[test] +fn hidden_layers_open_hidden() { + let mut doc = sample(); + let mut hidden = Node::layer(doc.alloc_id(), "Off", LayerColor::Preset(1)); + hidden.visible = false; + doc.layers.push(Arc::new(hidden)); + let text = program(&doc); + assert!(text.contains("%AI5_NumLayers: 3\n%AI5_OpenViewLayers: 776\n"), "{text}"); +} + +/// A 200 × 100 document of a gradient fill, a compound path, an image and a symbol instance, and +/// what the data holds as plain paths: type. +fn unsupported() -> Document { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let fill = |p: Paint| Appearance::basic(p, Paint::None, 0.0); + let g = Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.0))], + ); + let shaded = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), fill(Paint::Gradient(Box::new(GradientPaint::new(g))))); + doc.insert(Some(layer), usize::MAX, shaded).unwrap(); + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(70.0, 10.0, 90.0, 30.0)), Appearance::default()); + let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(75.0, 15.0, 85.0, 25.0)), Appearance::default()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + ring.appearance = fill(solid(Color::cmyk(0.0, 1.0, 1.0, 0.0))).into(); + doc.insert(Some(layer), usize::MAX, ring).unwrap(); + let mut png = vec![]; + let img = image::RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]).unwrap(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let blob = ImageBlob::new("image/png", png); + let key = blob.content_key(); + doc.images.insert(key.clone(), blob); + let im = ImageObject { + key, + width: 2, + height: 1, + xf: Affine::new([10.0, 0.0, 0.0, 10.0, 100.0, 10.0]), + link: None, + placement: Default::default(), + pixels: None, + }; + let im = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + // Type the text document can't hold (a gradient fill). + let shade = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]); + let t = vectorcraft_doc::TextObject::point( + vectorcraft_geom::Point::new(10.0, 70.0), + "Type", + vectorcraft_doc::CharStyle { + size: 18.0, + fill: Paint::Gradient(Box::new(GradientPaint::new(shade))), + ..vectorcraft_doc::CharStyle::default() + }, + ); + let t = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(layer), usize::MAX, t).unwrap(); + let art = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), fill(solid(Color::rgb(0.0, 1.0, 0.0)))); + doc.symbols.push(Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(art) }); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((150.0, 10.0)) }); + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + doc +} + +/// Every path in `nodes` and their descendants. +fn paths(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + match n.children() { + Some(c) => paths(c, out), + None => out.push((**n).clone()), + } + } +} + +#[test] +fn art_the_slice_does_not_cover_is_written_as_plain_paths() { + let doc = unsupported(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::TYPE]); + let back = read_back(&doc); + let layer = back.layers[0].children().unwrap(); + let kinds: Vec<&str> = layer + .iter() + .map(|n| match n.kind { + NodeKind::Path { .. } => "path", + NodeKind::Group { .. } => "group", + NodeKind::Compound { .. } => "compound", + NodeKind::Image(_) => "image", + NodeKind::SymbolInstance { .. } => "instance", + _ => "other", + }) + .collect(); + assert_eq!(kinds, ["path", "compound", "image", "group", "instance"]); + let mut all = vec![]; + paths(&layer[3..4], &mut all); + assert!(all.iter().all(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }))); + // The gradient as a gradient, drawing as it did. + let bounds = Rect::new(10.0, 10.0, 30.0, 30.0); + let original = doc.layers[0].children().unwrap()[0].appearance.items[0].paint(); + assert_eq!(drawn(&back, layer[0].appearance.items[0].paint(), bounds), drawn(&doc, original, bounds)); + // The image as an image. + assert_eq!(layer[2].visual_bounds().map(|b| (r3(b.x0), r3(b.y0), r3(b.x1), r3(b.y1))), Some((r3(100.0), r3(10.0), r3(120.0), r3(20.0)))); +} + +#[test] +fn brushed_strokes_are_written_as_their_brush_art() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut line = Node::path( + doc.alloc_id(), + shapes::line((20.0, 50.0).into(), (180.0, 50.0).into()), + Appearance::basic(Paint::None, solid(Color::rgb(1.0, 0.0, 0.0)), 4.0), + ); + line.appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + doc.insert(Some(layer), usize::MAX, line).unwrap(); + let pieces = vectorcraft_brush::stroke_pieces( + &doc, + &vectorcraft_brush::find(&doc, "3 pt. Round").unwrap(), + &shapes::line((20.0, 50.0).into(), (180.0, 50.0).into()).to_bezpath(), + doc.layers[0].children().unwrap()[0].appearance.stroke().unwrap(), + ); + let back = read_back(&doc); + let NodeKind::Group { children, .. } = &back.layers[0].children().unwrap()[0].kind else { panic!("a group of the brush's art") }; + assert_eq!(children.len(), pieces.len()); + let bounds = |n: &Node| n.visual_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| (v * 10.0).round())); + assert_eq!(children.iter().map(|c| bounds(c)).collect::>(), pieces.iter().map(bounds).collect::>()); +} + +#[test] +fn type_is_written_as_create_outlines_makes_it() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + // A pattern fill: type the text document can't hold. + let pattern = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }; + let style = vectorcraft_doc::CharStyle { size: 18.0, fill: pattern, underline: true, ..vectorcraft_doc::CharStyle::default() }; + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "Under", style); + let mut t = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + t.name = Some("Title".into()); + doc.insert(Some(layer), usize::MAX, t.clone()).unwrap(); + let outlined = vectorcraft_effects::outline_text(&t).unwrap(); + let back = read_back(&doc); + let group = &back.layers[0].children().unwrap()[0]; + assert_eq!(group.name.as_deref(), Some("Title")); + let rounded = |n: &Node| n.visual_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| (v * 100.0).round())); + // The underline reaches below the glyphs: the bounds match only with it. + assert_eq!(rounded(group), rounded(&outlined)); +} + +#[test] +fn inline_graphics_in_type_are_written_as_their_art() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mark = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance::basic(solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0), + ); + doc.symbols.push(Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(mark) }); + let style = vectorcraft_doc::CharStyle { size: 18.0, fill: solid(Color::BLACK), ..vectorcraft_doc::CharStyle::default() }; + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "A", style.clone()); + t.runs.push(vectorcraft_doc::TextRun::inline(vectorcraft_doc::InlineArt::new("Mark"), style)); + let mut text = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + // A stroke of the object's own above the Characters row: drawn over the inline graphic. + let red = solid(Color::rgb(1.0, 0.0, 0.0)); + text.appearance = + Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(red.clone(), 3.0))], contents_index: Some(0), ..Appearance::default() } + .into(); + doc.insert(Some(layer), usize::MAX, text).unwrap(); + let back = read_back(&doc); + let mut all = vec![]; + paths(back.layers[0].children().unwrap(), &mut all); + let has = |p: &Node, c: &Paint| p.appearance.items.iter().any(|i| paint(i.paint()) == paint(c)); + let blue = solid(Color::rgb(0.0, 0.0, 1.0)); + let art: Vec<&Node> = all.iter().filter(|p| has(p, &blue)).collect(); + assert_eq!(art.len(), 1, "the inline graphic is written"); + // To the right of the letter, 18 pt high as the run's size makes it. + let b = art[0].visual_bounds().unwrap(); + assert!(b.x0 > 10.0 && (b.height() - 18.0).abs() < 0.01, "{b:?}"); + let at = |c: &Paint| all.iter().position(|p| has(p, c)).unwrap(); + assert!(at(&blue) < at(&red), "the stroke above the characters is over the inline graphic"); +} + +/// A scaled instance of a symbol with 9-slice guides is written as the canvas draws it: the corner +/// keeps its size while the rest stretches. +#[test] +fn a_scaled_nine_slice_symbol_instance_keeps_its_corner_size() { + let mut doc = Document::new(400.0, 400.0); + let layer = doc.layers[0].id; + let square = |doc: &mut Document, r: Rect| { + Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::basic(solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0)) + }; + let frame = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0))); + let corner = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0))); + let art = Node::group(doc.alloc_id(), vec![frame, corner]); + doc.symbols.push(Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); + doc.set_symbol_nine_slice("S", Some(vectorcraft_doc::SymbolNineSlice::default())); + let xf = Affine::scale_non_uniform(2.0, 1.5); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "S".into(), xf }); + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let back = read_back(&doc); + let mut all = vec![]; + paths(back.layers[0].children().unwrap(), &mut all); + let sizes: Vec<(i64, i64)> = + all.iter().filter_map(|p| p.geometric_bounds()).map(|b| (b.width().round() as i64, b.height().round() as i64)).collect(); + assert!(sizes.contains(&(10, 10)), "the corner keeps its size: {sizes:?}"); + assert!(sizes.contains(&(200, 150)), "the frame is scaled: {sizes:?}"); +} + +/// Nested symbols whose instances multiply, written as their art (on a large canvas), stop at +/// [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects of symbol art in all, with a warning. +#[test] +fn nested_symbol_instances_stop_at_the_symbol_art_limit() { + let mut doc = Document::new(20000.0, 100.0); + let layer = doc.layers[0].id; + // Empty paths: counted, but written as nothing, so the test stays small; and one filled square. + let empty = Arc::new(Node::path(doc.alloc_id(), PathData::new(vec![]), Appearance::default())); + let mut members = vec![empty; 4999]; + let square = shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)); + members.push(Arc::new(Node::path(doc.alloc_id(), square, Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0)))); + let leaves = Node::group(doc.alloc_id(), members); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(leaves) }); + let leaf = Arc::new(Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Leaf".into(), xf: Affine::IDENTITY })); + let trees = Node::group(doc.alloc_id(), vec![leaf; 5000]); + doc.symbols.push(Symbol { dynamic: false, name: "Tree".into(), art: Arc::new(trees) }); + let tree = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Tree".into(), xf: Affine::IDENTITY }); + doc.insert(Some(layer), usize::MAX, tree).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_LIMIT), "{:?}", out.warnings); + // 5,001 objects for the tree and each leaf: 3,198 leaves fit in 16,000,000. + let text = String::from_utf8(out.program).unwrap(); + // On the layers; the symbols' definitions come before them, in the setup. + let layers = text.split_once("%%EndSetup").unwrap().1; + assert_eq!(layers.matches("\r\nf\r\n").count(), 3198, "the squares of the leaves written"); +} + +/// On a canvas of the usual size, nested symbols whose instances multiply, written as their art in +/// art cut to a clipping object, stop at [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects of symbol art +/// in all, with a warning. +#[test] +fn clipped_nested_symbol_instances_stop_at_the_symbol_art_limit() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + // Empty paths: counted, but written as nothing, so the test stays small; and one filled square. + let empty = Arc::new(Node::path(doc.alloc_id(), PathData::new(vec![]), Appearance::default())); + let mut members = vec![empty; 4999]; + let square_art = shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)); + members.push(Arc::new(Node::path(doc.alloc_id(), square_art, Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0)))); + let leaves = Node::group(doc.alloc_id(), members); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(leaves) }); + let leaf = Arc::new(Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Leaf".into(), xf: Affine::IDENTITY })); + let trees = Node::group(doc.alloc_id(), vec![leaf; 5000]); + doc.symbols.push(Symbol { dynamic: false, name: "Tree".into(), art: Arc::new(trees) }); + let tree = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Tree".into(), xf: Affine::IDENTITY }); + // A group as the clipping object cuts the art instead of clipping it with a path, so the + // instances in it are written as their art. Its square is unpainted, so the only filled squares + // are the leaves'. + let outline = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default()); + let clip = group(&mut doc, vec![outline], false); + let clipped = group(&mut doc, vec![clip, tree], true); + doc.insert(Some(layer), usize::MAX, clipped).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_LIMIT), "{:?}", out.warnings); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings); + // 5,001 objects for the tree and each leaf: 3,198 leaves fit in 16,000,000. + let text = String::from_utf8(out.program).unwrap(); + let layers = text.split_once("%%EndSetup").unwrap().1; + assert_eq!(layers.matches("\r\nf\r\n").count(), 3198, "the squares of the leaves written"); +} + +#[test] +fn a_stained_symbol_instance_is_written_in_its_stained_colors() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let art = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance::basic(solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0), + ); + doc.symbols.push(Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(art) }); + let mut instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((50.0, 10.0)) }); + instance.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into(); + let stained = vectorcraft_brush::instance_art(&doc.symbols[0].art, &instance); + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let back = read_back(&doc); + let NodeKind::Group { children, .. } = &back.layers[0].children().unwrap()[0].kind else { panic!("the instance's group") }; + assert_eq!(paint(children[0].appearance.items[0].paint()), paint(stained.appearance.items[0].paint())); + assert_ne!(paint(stained.appearance.items[0].paint()), paint(&solid(Color::rgb(0.0, 1.0, 0.0))), "the instance stains its art"); +} + +#[test] +fn a_layer_with_crop_marks_keeps_its_art_and_gets_the_marks() { + for clipping in [false, true] { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let at = Rect::new(50.0, 30.0, 90.0, 60.0); + if clipping { + let clip = Node::new( + doc.alloc_id(), + NodeKind::Path { path: shapes::rectangle(at), rule: FillRule::NonZero, live: None, clipping: true, guide: false }, + ); + doc.insert(Some(layer), usize::MAX, clip).unwrap(); + } + let square = Node::path(doc.alloc_id(), shapes::rectangle(at), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + if let Some(l) = doc.layers.get_mut(0) { + let fx = vectorcraft_doc::Effect { id: vectorcraft_effects::CROP_MARKS.into(), params: serde_json::json!({}), visible: true }; + let l = Arc::make_mut(l); + let mut ap = (*l.appearance).clone(); + ap.effects.push(fx); + l.appearance = ap.into(); + if let NodeKind::Layer { clip, .. } = &mut l.kind { + *clip = clipping; + } + } + let name = doc.layers[0].name.clone(); + let back = read_back(&doc); + assert_eq!(back.layers.len(), 1); + assert_eq!(back.layers[0].name, name); + let members = back.layers[0].children().unwrap(); + assert_eq!(members.len(), 2, "clipping {clipping}: the square and the marks"); + // A clipping layer's art is a clipping group, outside which the marks lie. + let expected = + if clipping { matches!(members[0].kind, NodeKind::Group { clip: true, .. }) } else { matches!(members[0].kind, NodeKind::Path { .. }) }; + assert!(expected && matches!(back.layers[0].kind, NodeKind::Layer { clip: false, .. }), "clipping {clipping}"); + assert!(matches!(members[1].kind, NodeKind::Group { .. })); + // The marks lie around the square, outside a clipping path. + let marks = members[1].visual_bounds().unwrap(); + assert!(marks.x0 < at.x0 - 1.0 && marks.x1 > at.x1 + 1.0, "clipping {clipping}: {marks:?}"); + } +} + +#[test] +fn geometry_effects_in_a_symbol_are_written_as_their_result() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut ap = Appearance::basic(solid(Color::BLACK), Paint::None, 0.0); + ap.effects.push(vectorcraft_doc::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 5}), visible: true }); + let art = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), ap); + doc.symbols.push(Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(art) }); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((50.0, 20.0)) }); + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let back = read_back(&doc); + let b = back.bounds_of_with(&[back.layers[0].children().unwrap()[0].id], true, &back.symbol_boxes()).unwrap(); + // The 10 pt square offset by 5 pt, at (50, 20). + assert!((b.x0 - 45.0).abs() < 0.1 && (b.x1 - 65.0).abs() < 0.1 && (b.y0 - 15.0).abs() < 0.1 && (b.y1 - 35.0).abs() < 0.1, "{b:?}"); +} + +#[test] +fn an_adjusted_image_in_a_symbol_is_written_in_its_adjusted_color() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut png = vec![]; + image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let blob = ImageBlob::new("image/png", png); + let key = blob.content_key(); + doc.images.insert(key.clone(), blob); + let im = ImageObject { key, width: 2, height: 2, xf: Affine::scale(5.0), link: None, placement: Default::default(), pixels: None }; + let mut im = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + let shift = serde_json::json!({"amount": 100, "preserveLightness": false}); + let mut ap = (*im.appearance).clone(); + ap.effects.push(vectorcraft_doc::Effect { id: "adjust.shiftToColor".into(), params: shift, visible: true }); + im.appearance = ap.into(); + doc.symbols.push(Symbol { dynamic: false, name: "Picture".into(), art: Arc::new(im) }); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Picture".into(), xf: Affine::translate((50.0, 20.0)) }); + doc.insert(Some(layer), usize::MAX, instance).unwrap(); + let back = read_back(&doc); + let mut found = vec![]; + let art: Vec> = back.symbols.iter().map(|s| s.art.clone()).collect(); + pictures(&back, &art, "", &mut found); + assert_eq!(found.len(), 1, "the adjusted image is found"); + assert!(!found[0].ends_with("rgba [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255]"), "the image is adjusted: {found:?}"); +} + +#[test] +fn a_group_fill_in_a_pattern_tile_is_written() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let dot = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default()); + let mut group = Node::group(doc.alloc_id(), vec![Arc::new(dot)]); + group.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into(); + doc.patterns.push(vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(group)])); + let filled = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)), + Appearance::basic(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, Paint::None, 0.0), + ); + doc.insert(Some(layer), usize::MAX, filled).unwrap(); + let back = read_back(&doc); + let mut all = vec![]; + paths(&back.pattern("Dots").unwrap().art, &mut all); + let red = paint(&solid(Color::rgb(1.0, 0.0, 0.0))); + assert!(all.iter().any(|p| p.appearance.items.iter().any(|i| paint(i.paint()) == red)), "the tile keeps its group's fill"); +} + +/// A pattern fill written as its tiles (its tiles aren't a grid) that would place more tiles than +/// a fill places is written as the shape filled gray, as a pattern that isn't found is, instead of +/// as nothing. +#[test] +fn a_pattern_fill_of_too_many_tiles_is_written_gray() { + let mut doc = Document::new(1200.0, 1200.0); + let layer = doc.layers[0].id; + let dot = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 0.5, 0.5)), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); + let tiny = vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 1.0, 1.0), + tile_type: vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, + ..vectorcraft_doc::PatternDef::new("Tiny", vec![Arc::new(dot)]) + }; + doc.patterns.push(tiny); + let filled = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(100.0, 100.0, 1100.0, 1100.0)), + Appearance::basic(Paint::Pattern { pattern: "Tiny".into(), xf: Affine::IDENTITY }, Paint::None, 0.0), + ); + doc.insert(Some(layer), usize::MAX, filled).unwrap(); + let back = read_back(&doc); + let mut all = vec![]; + paths(back.layers[0].children().unwrap(), &mut all); + let gray = paint(&solid(Color::gray(0.5))); + assert!(all.iter().any(|p| p.appearance.items.iter().any(|i| paint(i.paint()) == gray)), "{}", all.len()); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PATTERN_TILES), "{:?}", out.warnings); +} + +/// An artboard's center mark, cross hairs and video safe areas are written as the bits of its +/// `DisplayMark` and read back. +#[test] +fn artboard_display_marks_are_written() { + let mut doc = Document::new(200.0, 100.0); + (doc.artboards[0].show_center_mark, doc.artboards[0].show_video_safe_areas) = (true, true); + assert!(program(&doc).contains("%_5 /Int (DisplayMark) ,\n")); + let back = read_back(&doc); + let ab = &back.artboards[0]; + assert!(ab.show_center_mark && !ab.show_cross_hairs && ab.show_video_safe_areas); +} + +/// The active artboard, the one `opened_artboard` names (else the first), is the selected one and +/// its index follows the artboards in the recorded part; the editing data reads back with that +/// artboard active. +#[test] +fn the_active_artboard_follows_the_artboards() { + let mut doc = Document::new(200.0, 100.0); + for (id, x0) in [(2, 250.0), (3, 500.0)] { + doc.artboards.push(Artboard { id, rect: Rect::new(x0, 0.0, x0 + 200.0, 100.0), ..doc.artboards[0].clone() }); + } + let first = doc.artboards[0].id; + // None, the first, the third, and an artboard the document doesn't have (the first). + for (opened, index) in [(None, 0), (Some(first), 0), (Some(3), 2), (Some(9), 0)] { + doc.opened_artboard = opened; + let p = program(&doc); + let entry = format!("%_; (ArtboardArray) ,\n%_{index} /Int (CropAreaActive) ,\n%_16383 /Int (AIDocumentCanvasSize) ,\n%_; /Recorded ,\n"); + assert!(p.contains(&entry), "{opened:?}: {p}"); + assert_eq!(p.matches("%_1 /Bool (IsArtboardSelected) ,\n").count(), 1, "{opened:?}"); + let back = read_back(&doc); + let active = back.opened_artboard.and_then(|id| back.artboards.iter().position(|a| a.id == id)).unwrap_or(0); + assert_eq!((back.artboards.len(), active), (3, index), "{opened:?}"); + } +} + +/// The copy's active artboard read on its own, for a document restored from the file beside the +/// copy: `None` for the first, and when the copy names an artboard that document doesn't have or +/// can't be decoded. +#[test] +fn a_restored_document_opens_on_the_artboard_the_copy_names() { + let mut doc = Document::new(200.0, 100.0); + for (id, x0) in [(2, 250.0), (3, 500.0)] { + doc.artboards.push(Artboard { id, rect: Rect::new(x0, 0.0, x0 + 200.0, 100.0), ..doc.artboards[0].clone() }); + } + let mut one_artboard = doc.clone(); + one_artboard.artboards.truncate(1); + for (opened, read) in [(Some(3), Some(3)), (Some(2), Some(2)), (Some(1), None), (None, None), (Some(9), None)] { + doc.opened_artboard = opened; + let data = private_data(&doc, &opts()).unwrap().0.data; + assert_eq!(crate::ai_opened_artboard(&data, &doc), read, "{opened:?}"); + assert_eq!(crate::ai_opened_artboard(&data, &one_artboard), None, "{opened:?}"); + } + assert_eq!(crate::ai_opened_artboard(b"%AI24_ZStandard_Data not zstd", &doc), None); +} + +/// A guide is its path followed by `(n) *` (closed) or `(N) *` (open), with no `(N) *` before +/// it, and reads back as the same guide. +#[test] +fn guides_are_their_path_then_the_guide_operator() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let line = shapes::line(vectorcraft_geom::Point::new(10.0, 80.0), vectorcraft_geom::Point::new(150.0, 80.0)); + for path in [shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), line] { + let g = Node::new(doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true }); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + } + let p = program(&doc); + let (closed, open) = (p.matches("\n(n) *\n").count(), p.matches("\n(N) *\n").count()); + assert_eq!((closed, open), (1, 1), "{p}"); + assert!(p.contains("0 Xw\n10 -10 m\n") && p.contains("10 -10 L\n(n) *\n10 -80 m\n150 -80 L\n(N) *\nLB\n"), "{p}"); + assert_eq!(lines(&read_back(&doc)), lines(&doc)); +} + +#[test] +fn effects_on_a_fill_are_reported_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut fill = FillLayer::new(solid(Color::BLACK)); + fill.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({}), visible: true }); + let ap = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Appearance::default() }; + let square = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), ap); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); +} + +#[test] +fn images_of_more_pixels_than_the_reader_reads_are_mid_gray() { + let mut png = vec![]; + image::GrayImage::new(6000, 6000).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let im = image_node(&mut doc, ImageBlob::png(png), (10, 10), Affine::IDENTITY, None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::IMAGES]); + assert_eq!(paint(read_back(&doc).layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::gray(0.5)))); +} + +#[test] +fn a_document_without_an_artboard_is_an_error() { + let mut doc = Document::new(200.0, 100.0); + doc.artboards.clear(); + assert!(export_ai_editing(&doc, &opts()).is_err()); + doc.artboards.push(Artboard { rect: Rect::new(0.0, 0.0, 0.0, 10.0), ..Document::new(1.0, 1.0).artboards[0].clone() }); + assert!(export_ai_editing(&doc, &opts()).is_err()); +} + +// ---------- transparency, compound paths, clipping, opacity masks ---------- + +/// A rectangle filled with `c`. +fn square(doc: &mut Document, r: Rect, c: Color) -> Node { + Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::basic(solid(c), Paint::None, 0.0)) +} + +/// A clipping path of `path`, unpainted. +fn clipping(doc: &mut Document, path: PathData) -> Node { + Node::new(doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: true, guide: false }) +} + +fn named(mut n: Node, name: &str) -> Node { + n.name = Some(name.into()); + n +} + +fn see_through(mut n: Node, opacity: f32, blend: BlendMode) -> Node { + (n.opacity, n.blend) = (opacity, blend); + n +} + +fn group(doc: &mut Document, children: Vec, clip: bool) -> Node { + Node::new(doc.alloc_id(), NodeKind::Group { children: children.into_iter().map(Arc::new).collect(), clip }) +} + +/// A 200 × 100 document of what the transparency, compound path and clipping forms hold. Layer +/// `Clear` (60%, Multiply, isolated) holds, bottom first: a path at 50% in Screen whose opacity +/// defines the knockout shape; a group at 40%, isolated, knockout on, whose opacity defines the +/// knockout shape, of a square and a square at 75% in Overlay; a group with knockout off; a group of +/// a square in each blending mode; a clipping group at 50%; a clipping group whose clipping path +/// is an even-odd compound path; a clipping group holding a clipping group; a named path with an +/// inverted opacity mask that doesn't clip; a group with a disabled opacity mask; and a compound +/// path at 70% in Screen whose opacity defines the knockout shape last. The layer's opacity +/// defines the knockout shape too. Layer `Cut` clips by its first path. Layer `Plain` holds an +/// opaque path. +fn transparent() -> Document { + let mut doc = Document::new(200.0, 100.0); + doc.swatches = vec![Swatch { name: "Blue".into(), paint: solid(Color::rgb(0.0, 0.0, 1.0)), global: false, spot: false }].into(); + doc.swatch_groups = vec![].into(); + doc.layers.clear(); + let clear = doc.add_layer(Some("Clear")); + let cut = doc.add_layer(Some("Cut")); + let plain = doc.add_layer(Some("Plain")); + let red = Color::rgb(1.0, 0.0, 0.0); + let blue = Color::rgb(0.0, 0.0, 1.0); + let mut art = vec![]; + + let mut shine = see_through(square(&mut doc, Rect::new(5.0, 5.0, 25.0, 25.0), red), 0.5, BlendMode::Screen); + shine.knockout_shape = true; + art.push(named(shine, "Shine")); + let a = square(&mut doc, Rect::new(30.0, 5.0, 50.0, 25.0), red); + let b = see_through(square(&mut doc, Rect::new(35.0, 10.0, 55.0, 30.0), blue), 0.75, BlendMode::Overlay); + let mut knock = see_through(group(&mut doc, vec![a, b], false), 0.4, BlendMode::Normal); + (knock.isolate, knock.knockout, knock.knockout_shape) = (true, Knockout::On, true); + art.push(named(knock, "Knock")); + let a = square(&mut doc, Rect::new(60.0, 5.0, 70.0, 15.0), red); + let b = square(&mut doc, Rect::new(65.0, 10.0, 75.0, 20.0), blue); + let mut off = group(&mut doc, vec![a, b], false); + off.knockout = Knockout::Off; + art.push(off); + let modes: Vec = BlendMode::ALL + .iter() + .enumerate() + .map(|(i, m)| { + let x = 5.0 + 11.0 * i as f64; + see_through(square(&mut doc, Rect::new(x, 40.0, x + 10.0, 50.0), red), 0.5, *m) + }) + .collect(); + art.push(group(&mut doc, modes, false)); + let clip = clipping(&mut doc, shapes::rectangle(Rect::new(90.0, 5.0, 100.0, 25.0))); + let inside = square(&mut doc, Rect::new(85.0, 10.0, 110.0, 20.0), blue); + art.push(named(see_through(group(&mut doc, vec![named(clip, "Edge"), inside], true), 0.5, BlendMode::Normal), "Window")); + // The subpaths of a compound clipping path are clipping paths, as the reader marks them. + let outer = clipping(&mut doc, shapes::rectangle(Rect::new(115.0, 5.0, 135.0, 25.0))); + let inner = clipping(&mut doc, shapes::rectangle(Rect::new(120.0, 10.0, 130.0, 20.0))); + let compound_clip = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + let green = square(&mut doc, Rect::new(110.0, 0.0, 140.0, 30.0), Color::rgb(0.0, 1.0, 0.0)); + art.push(group(&mut doc, vec![compound_clip, green], true)); + let deep_clip = clipping(&mut doc, shapes::rectangle(Rect::new(145.0, 5.0, 160.0, 25.0))); + let deep = square(&mut doc, Rect::new(140.0, 0.0, 170.0, 30.0), red); + let deep = group(&mut doc, vec![deep_clip, deep], true); + let outer_clip = clipping(&mut doc, shapes::rectangle(Rect::new(150.0, 0.0, 165.0, 20.0))); + art.push(group(&mut doc, vec![outer_clip, deep], true)); + let gray = square(&mut doc, Rect::new(5.0, 60.0, 15.0, 70.0), Color::gray(0.5)); + let white = square(&mut doc, Rect::new(15.0, 60.0, 25.0, 70.0), Color::rgb(1.0, 1.0, 1.0)); + let mask_art = group(&mut doc, vec![gray, white], false); + let mut masked = named(square(&mut doc, Rect::new(0.0, 55.0, 30.0, 75.0), blue), "Masked"); + masked.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(mask_art), clip: false, invert: true, disabled: false, linked: true })); + art.push(masked); + let off_art = square(&mut doc, Rect::new(40.0, 60.0, 50.0, 70.0), Color::gray(0.25)); + let in_faded = square(&mut doc, Rect::new(35.0, 55.0, 60.0, 75.0), red); + let mut faded = group(&mut doc, vec![in_faded], false); + faded.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(off_art), clip: true, invert: false, disabled: true, linked: false })); + art.push(faded); + let o = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(70.0, 55.0, 90.0, 75.0)), Appearance::default()); + let i = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(75.0, 60.0, 85.0, 70.0)), Appearance::default()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(o), Arc::new(i)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance::basic(solid(red), Paint::None, 0.0).into(); + ring.knockout_shape = true; + art.push(named(see_through(ring, 0.7, BlendMode::Screen), "Ring")); + for n in art { + doc.insert(Some(clear), usize::MAX, n).unwrap(); + } + + let edge = clipping(&mut doc, shapes::rectangle(Rect::new(100.0, 40.0, 150.0, 90.0))); + doc.insert(Some(cut), usize::MAX, named(edge, "Edge")).unwrap(); + for (r, c) in [(Rect::new(90.0, 35.0, 130.0, 70.0), red), (Rect::new(120.0, 60.0, 160.0, 95.0), blue)] { + let n = square(&mut doc, r, c); + doc.insert(Some(cut), usize::MAX, n).unwrap(); + } + let opaque = square(&mut doc, Rect::new(170.0, 60.0, 190.0, 80.0), blue); + doc.insert(Some(plain), usize::MAX, opaque).unwrap(); + for (i, l) in doc.layers.iter_mut().enumerate() { + let l = Arc::make_mut(l); + match i { + 0 => { + (l.opacity, l.blend, l.isolate, l.knockout_shape) = (0.6, BlendMode::Multiply, true, true); + } + 1 => { + if let NodeKind::Layer { clip, .. } = &mut l.kind { + *clip = true; + } + } + _ => {} + } + } + doc +} + +/// The transparency, clipping and opacity masks of every object, one line each, the masks' art +/// after their objects. +fn looks(nodes: &[Arc], depth: usize, out: &mut Vec) { + for n in nodes { + let kind = match &n.kind { + NodeKind::Layer { clip, .. } => format!("layer clip={clip}"), + NodeKind::Group { clip, .. } => format!("group clip={clip}"), + NodeKind::Path { clipping, .. } => format!("path clipping={clipping}"), + NodeKind::Compound { .. } => "compound".into(), + NodeKind::SymbolInstance { symbol, .. } => format!("instance {symbol:?}"), + _ => "other".into(), + }; + let mut s = format!( + "{depth} {:?} {kind} {} {:?} isolate={} {:?} shape={}", + n.name, + r3(f64::from(n.opacity)), + n.blend, + n.isolate, + n.knockout, + n.knockout_shape + ); + let mask = n.extras().mask.clone(); + if let Some(m) = &mask { + s += &format!(" mask(clip={} invert={} disabled={} linked={})", m.clip, m.invert, m.disabled, m.linked); + } + out.push(s); + if let Some(m) = mask { + view(std::slice::from_ref(&m.art), depth + 1, out); + } + looks(n.children().map(Vec::as_slice).unwrap_or_default(), depth + 1, out); + } +} + +fn all_looks(doc: &Document) -> Vec { + let mut out = vec![]; + looks(&doc.layers, 0, &mut out); + out +} + +/// Fails with the lines where `got` and `want` differ. +fn same_lines(got: &[String], want: &[String]) { + let differ: Vec = (0..got.len().max(want.len())) + .filter(|&i| got.get(i) != want.get(i)) + .map(|i| format!("line {i}:\n got {:?}\n want {:?}", got.get(i), want.get(i))) + .collect(); + assert!(differ.is_empty(), "{}", differ.join("\n")); +} + +#[test] +fn transparency_clipping_and_masks_are_read_back() { + let doc = transparent(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + same_lines(&lines(&back), &lines(&doc)); + same_lines(&all_looks(&back), &all_looks(&doc)); +} + +/// An opacity mask's art reads back in its own shape: one object, a group of one object, a group +/// of two, a group of one group, a see-through group of two, and a group around a hidden object or +/// a guide. +#[test] +fn opacity_mask_art_keeps_its_shape_when_read_back() { + let mut doc = Document::new(200.0, 100.0); + doc.swatches = vec![Swatch { name: "Blue".into(), paint: solid(Color::rgb(0.0, 0.0, 1.0)), global: false, spot: false }].into(); + doc.swatch_groups = vec![].into(); + let layer = doc.layers[0].id; + let art = |doc: &mut Document| square(doc, Rect::new(5.0, 5.0, 10.0, 10.0), Color::gray(0.5)); + let path = art(&mut doc); + let one = art(&mut doc); + let of_one = group(&mut doc, vec![one], false); + let (a, b) = (art(&mut doc), art(&mut doc)); + let of_two = group(&mut doc, vec![a, b], false); + let (a, b) = (art(&mut doc), art(&mut doc)); + let inner = group(&mut doc, vec![a, b], false); + let of_group = group(&mut doc, vec![inner], false); + let (a, b) = (art(&mut doc), art(&mut doc)); + let faded = see_through(group(&mut doc, vec![a, b], false), 0.5, BlendMode::Normal); + let mut off = art(&mut doc); + off.visible = false; + let of_hidden = group(&mut doc, vec![off], false); + let line = Node::new( + doc.alloc_id(), + NodeKind::Path { + path: shapes::rectangle(Rect::new(5.0, 5.0, 10.0, 10.0)), + rule: FillRule::NonZero, + live: None, + clipping: false, + guide: true, + }, + ); + let of_guide = group(&mut doc, vec![line], false); + for mask_art in [path, of_one, of_two, of_group, faded, of_hidden, of_guide] { + let mut owner = square(&mut doc, Rect::new(0.0, 0.0, 30.0, 30.0), Color::rgb(1.0, 0.0, 0.0)); + owner.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, true))); + doc.insert(Some(layer), usize::MAX, owner).unwrap(); + } + let back = read_back(&doc); + same_lines(&all_looks(&back), &all_looks(&doc)); + let first = String::from_utf8(export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + let again = String::from_utf8(export_ai_editing(&back, &opts()).unwrap().program).unwrap(); + same_lines(&again.lines().map(String::from).collect::>(), &first.lines().map(String::from).collect::>()); +} + +/// Hidden art of a mask is written shown: the canvas draws the art's root either way, and the reader +/// puts a hidden object in a group that doesn't draw it. +#[test] +fn a_hidden_opacity_mask_art_root_reads_back_shown() { + let mut doc = Document::new(200.0, 100.0); + doc.swatches = vec![Swatch { name: "Blue".into(), paint: solid(Color::rgb(0.0, 0.0, 1.0)), global: false, spot: false }].into(); + doc.swatch_groups = vec![].into(); + let layer = doc.layers[0].id; + let art = |doc: &mut Document| square(doc, Rect::new(5.0, 5.0, 10.0, 10.0), Color::gray(0.5)); + let mut path = art(&mut doc); + path.visible = false; + let (a, b) = (art(&mut doc), art(&mut doc)); + let mut of_two = group(&mut doc, vec![a, b], false); + of_two.visible = false; + for mask_art in [path, of_two] { + let mut owner = square(&mut doc, Rect::new(0.0, 0.0, 30.0, 30.0), Color::rgb(1.0, 0.0, 0.0)); + owner.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, true))); + doc.insert(Some(layer), usize::MAX, owner).unwrap(); + } + let back = read_back(&doc); + let roots: Vec<_> = back.layers[0].children().unwrap().iter().map(|o| o.extras().mask.as_ref().unwrap().art.clone()).collect(); + assert!(matches!(roots.as_slice(), [p, g] if p.visible && g.visible + && matches!(p.kind, NodeKind::Path { .. }) + && matches!(&g.kind, NodeKind::Group { children, clip: false } if children.len() == 2 && children.iter().all(|c| c.visible)))); +} + +#[test] +fn transparency_clipping_and_masks_write_the_same_bytes_again() { + let doc = transparent(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + assert_eq!(private_data(&doc, &opts()).unwrap().0, private_data(&doc, &opts()).unwrap().0); + // What the reader reads back is written as the same program. + let again = String::from_utf8(export_ai_editing(&read_back(&doc), &opts()).unwrap().program).unwrap(); + let first = String::from_utf8(first.program).unwrap(); + same_lines(&again.lines().map(String::from).collect::>(), &first.lines().map(String::from).collect::>()); +} + +#[test] +fn transparency_is_written_in_its_forms() { + let p = program(&transparent()); + // A path's in its paint, after its colors; Screen is 2. + assert!(p.contains(" Xa\n0 O\n2 0.5 0 0 1 Xy\n0 XR\n"), "{p}"); + // A compound path's in its paint before `*u`, its knockout shape kept. + let (ring, _) = p.rsplit_once("*u\n").unwrap(); + assert!(ring.ends_with(" O\n2 0.7 0 0 1 Xy\n1 XR\n"), "{ring}"); + // A group's after its end and its name, then `Xd` and the object's own state marker. + let knock = "U\n%_/ArtDictionary :\n%_/XMLUID : (Knock) ; (AI10_ArtUID) ,\n%_;\n%_\n0 0.4 1 1 1 Xy\n0 0 Xd\n6 () XW\n"; + assert!(p.contains(knock), "{p}"); + // A group without transparency of its own. + assert!(p.contains("U\n9 () XW\n"), "{p}"); + // A clipping group: the clipping path last, then `W`. + let window = "h\nW\nn\n%_/ArtDictionary :\n%_/XMLUID : (Edge) ; (AI10_ArtUID) ,\n%_;\n%_\nQ\n\ + %_/ArtDictionary :\n%_/XMLUID : (Window) ; (AI10_ArtUID) ,\n%_;\n%_\n0 0.5 0 2 0 Xy\n0 0 Xd\n6 () XW\n"; + assert!(p.contains(window), "{p}"); + // A layer's after its art, with the layer's state marker; its knockout neutral (2). + assert!(p.contains("1 0.6 1 2 1 Xy\n0 0 Xd\n7 () XW\nLB\n"), "{p}"); + // A clipping layer: its last `Lb` flag, its clipping path last. + assert!(p.contains(" 0 50 1 Lb\n(Cut) Ln\n") && p.contains(" 0 50 0 Lb\n(Plain) Ln\n"), "{p}"); + let (_, cut) = p.split_once("(Cut) Ln").unwrap(); + // The name `Edge` is taken by the clipping group's path: this one is numbered. + let edge = "h\nW\nn\n%_/ArtDictionary :\n%_/XMLUID : (Edge_00000000000000000001_) ; (AI10_ArtUID) ,\n%_;\n%_\n"; + assert!(cut.split_once("LB\n").unwrap().0.ends_with(edge), "{cut}"); + // The next layer's first path sets the state back. + let (_, cut) = p.split_once("(Cut) Ln").unwrap(); + assert!(cut.split_once("\nf\n").unwrap().0.contains(" Xa\n0 O\n0 1 0 0 0 Xy\n0 XR\n"), "{cut}"); + // The mask in the object's dictionary, after its name. + assert!(p.contains("%_/XMLUID : (Masked) ; (AI10_ArtUID) ,\n%_/Mask :\n%_X=\n"), "{p}"); + assert!( + p.contains( + "%_X+\n%_(Art) ,\n%_0 /Bool (Clipping) ,\n%_1 /Bool (Inverted) ,\n%_0 /Bool (Disabled) ,\n%_1 /Bool (Linked) ,\n%_; (AI9_Mask) ,\n" + ), + "{p}" + ); +} + +/// A clipping path filled and stroked is written with its fill and stroke, and reads back with +/// both on the clipping path. +#[test] +fn a_painted_clipping_path_is_written_with_its_paint() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0))); + clip.appearance = Appearance::basic(solid(Color::rgb(1.0, 1.0, 0.0)), solid(Color::BLACK), 2.0).into(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 40.0, 20.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let p = program(&doc); + assert!(p.contains("h\nW\nb\nQ\n"), "{p}"); + let back = read_back(&doc); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + let painted: Vec<(bool, Option, Option)> = children + .iter() + .map(|c| { + let clipping = matches!(c.kind, NodeKind::Path { clipping: true, .. }); + (clipping, c.appearance.fill().map(|f| paint(&f.paint)), c.appearance.stroke().map(|s| paint(&s.paint))) + }) + .collect(); + assert_eq!( + painted, + [ + (true, Some(paint(&solid(Color::rgb(1.0, 1.0, 0.0)))), Some(paint(&solid(Color::BLACK)))), + (false, Some(paint(&solid(Color::rgb(0.0, 0.0, 1.0)))), None) + ] + ); +} + +/// A clipping path without points hides what it clips. +#[test] +fn an_empty_clipping_path_hides_the_art() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let clip = clipping(&mut doc, PathData::new(vec![])); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 40.0, 20.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + // The art is hidden, as it is drawn: the group comes back empty. + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::CLIPPING), "{:?}", out.warnings); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 1, "{art:?}"); + assert!(matches!(&art[0].kind, NodeKind::Group { children, .. } if children.is_empty()), "{art:?}"); +} + +/// A clipping group without members is written as an empty group, and reads back as one. +#[test] +fn an_empty_clipping_group_is_an_empty_group() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let g = see_through(group(&mut doc, vec![], true), 0.5, BlendMode::Normal); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let p = program(&doc); + assert!(p.contains("\nu\nU\n0 0.5 0 2 0 Xy\n0 0 Xd\n6 () XW\n") && !p.contains("\nq\n"), "{p}"); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert_eq!(art.len(), 1, "{art:?}"); + assert!(matches!(&art[0].kind, NodeKind::Group { children, clip: false } if children.is_empty()), "{art:?}"); + assert_eq!(art[0].opacity, 0.5); +} + +/// A clipping path's paint that the path can't carry itself keeps the path's opacity. +#[test] +fn a_clipping_paths_other_paint_keeps_its_opacity() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0))); + // Two fills: a path paints one. + let fills = [Color::rgb(0.5, 0.5, 0.5), Color::rgb(1.0, 0.0, 0.0)].map(|c| AppearanceItem::Fill(FillLayer::new(solid(c)))); + clip.appearance = Appearance { items: fills.to_vec(), ..Appearance::default() }.into(); + clip.opacity = 0.5; + let inside = square(&mut doc, Rect::new(0.0, 0.0, 40.0, 20.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::CLIP_PAINT), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == writer::CLIP_PAINT_MASKS), "{:?}", out.warnings); + // With an opacity mask, which stays on the clipping path: a warning says so. + let mut masked = doc.clone(); + let art = square(&mut masked, Rect::new(10.0, 10.0, 20.0, 20.0), Color::gray(0.5)); + if let Some(c) = Arc::make_mut(&mut masked.layers[0]).children_mut() + && let Some(NodeKind::Group { children, .. }) = c.first_mut().map(|g| &mut Arc::make_mut(g).kind) + { + Arc::make_mut(&mut children[0]).extras_mut().mask = Some(Box::new(OpacityMask::new(art, true))); + } + let out = export_ai_editing(&masked, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::CLIP_PAINT_MASKS), "{:?}", out.warnings); + // Two fills at the clipping path's 50% are a group at 50% of the two at 100%, as the canvas + // draws them together, under the art. + let back = read_back(&doc); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + let fills = &children[1]; + assert!(matches!(fills.kind, NodeKind::Group { clip: false, .. }) && fills.opacity == 0.5, "{fills:?}"); + assert_eq!(fills.children().unwrap().iter().map(|c| c.opacity).collect::>(), [1.0, 1.0]); + let colors: Vec = fills.children().unwrap().iter().map(|c| paint(c.appearance.items[0].paint())).collect(); + assert_eq!(colors, [paint(&solid(Color::rgb(0.5, 0.5, 0.5))), paint(&solid(Color::rgb(1.0, 0.0, 0.0)))]); + assert!(matches!(children[2].kind, NodeKind::Path { .. }) && children.len() == 3, "the art over the fills"); + // One fill a path can't paint (a brick pattern, written as its tiles) is written under the art + // at the clipping path's opacity. + let mut brick = doc.clone(); + let dot = square(&mut brick, Rect::new(0.0, 0.0, 2.0, 2.0), Color::rgb(1.0, 0.0, 0.0)); + brick.patterns.push(vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 4.0, 4.0), + tile_type: vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, + ..vectorcraft_doc::PatternDef::new("Brick", vec![Arc::new(dot)]) + }); + if let Some(c) = Arc::make_mut(&mut brick.layers[0]).children_mut() + && let Some(NodeKind::Group { children, .. }) = c.first_mut().map(|g| &mut Arc::make_mut(g).kind) + { + let fill = Paint::Pattern { pattern: "Brick".into(), xf: Affine::IDENTITY }; + Arc::make_mut(&mut children[0]).appearance = Appearance::basic(fill, Paint::None, 0.0).into(); + } + let out = export_ai_editing(&brick, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PATTERNS) && out.warnings.iter().any(|w| w == writer::CLIP_PAINT), "{:?}", out.warnings); + let back = read_back(&brick); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + assert_eq!(children.len(), 3, "the clipping path, its fill, the art"); + assert_eq!(children[1].opacity, 0.5); + let mut tiles = vec![]; + paths(std::slice::from_ref(&children[1]), &mut tiles); + let painted: Vec<&Node> = tiles.iter().filter(|t| !t.appearance.items.is_empty()).collect(); + let red = paint(&solid(Color::rgb(1.0, 0.0, 0.0))); + assert!(!painted.is_empty() && painted.iter().all(|t| t.opacity == 1.0 && paint(t.appearance.items[0].paint()) == red), "{painted:?}"); + assert_eq!(paint(children[2].appearance.items[0].paint()), paint(&solid(Color::rgb(0.0, 0.0, 1.0))), "the art over the fill"); + // A locked clipping path's fill is locked too, the art it clips not. + let mut locked = doc.clone(); + if let Some(c) = Arc::make_mut(&mut locked.layers[0]).children_mut() + && let Some(NodeKind::Group { children, .. }) = c.first_mut().map(|g| &mut Arc::make_mut(g).kind) + { + Arc::make_mut(&mut children[0]).locked = true; + } + let back = read_back(&locked); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + assert_eq!(children.iter().map(|c| c.locked).collect::>(), [true, true, false]); +} + +/// A clipping path's stroke that a plain line can't draw goes over the clipped art, its fill under it. +#[test] +fn a_clipping_paths_other_stroke_goes_over_the_art() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0))); + let mut stroke = StrokeLayer::new(solid(Color::rgb(1.0, 0.0, 0.0)), 4.0); + stroke.dash = Some(Dash { pattern: vec![2.0, 2.0], offset: 0.0, align_corners: true }); + clip.appearance = Appearance { + items: vec![AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.5, 0.5, 0.5)))), AppearanceItem::Stroke(stroke)], + ..Appearance::default() + } + .into(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 40.0, 20.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let back = read_back(&doc); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + let colors: Vec = children.iter().skip(1).map(|c| paint(c.appearance.items.first().map_or(&Paint::None, |i| i.paint()))).collect(); + // The fill under the blue art, the red stroke's dots over it. + assert_eq!(colors.first(), Some(&paint(&solid(Color::rgb(0.5, 0.5, 0.5)))), "{colors:?}"); + assert_eq!(colors.get(1), Some(&paint(&solid(Color::rgb(0.0, 0.0, 1.0)))), "{colors:?}"); + assert!(colors.len() > 2 && colors.iter().skip(2).all(|c| *c == paint(&solid(Color::rgb(1.0, 0.0, 0.0)))), "{colors:?}"); +} + +/// An unpainted path with transparency of its own after a compound path: the compound path keeps its own. +#[test] +fn an_unpainted_paths_transparency_after_a_compound_path_is_its_own() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let o = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), Appearance::default()); + let i = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(15.0, 15.0, 25.0, 25.0)), Appearance::default()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(o), Arc::new(i)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance::basic(solid(Color::BLACK), Paint::None, 0.0).into(); + doc.insert(Some(layer), usize::MAX, ring).unwrap(); + let bare = see_through( + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(50.0, 10.0, 70.0, 30.0)), Appearance::default()), + 0.5, + BlendMode::Multiply, + ); + doc.insert(Some(layer), usize::MAX, bare).unwrap(); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert_eq!((art[0].opacity, art[0].blend, art[1].opacity, art[1].blend), (1.0, BlendMode::Normal, 0.5, BlendMode::Multiply)); +} + +/// Opacity masks in mask art nested past the limit are left out, not written empty. +#[test] +fn opacity_masks_nested_too_deep_are_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut n = square(&mut doc, Rect::new(10.0, 10.0, 20.0, 20.0), Color::gray(0.5)); + for _ in 0..12 { + let mut owner = square(&mut doc, Rect::new(10.0, 10.0, 20.0, 20.0), Color::gray(0.5)); + owner.extras_mut().mask = Some(Box::new(OpacityMask::new(n, true))); + n = owner; + } + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::DEEP_MASKS), "{:?}", out.warnings); + let p = String::from_utf8(out.program).unwrap().replace("\r\n", "\n"); + assert!(!p.contains("%_X=\n%_X+\n"), "no empty mask"); + // The masks within the limit are read back, one in the art of the other. + let back = read_back(&doc); + let mut n = back.layers[0].children().unwrap()[0].clone(); + let mut depth = 0; + while let Some(m) = n.extras().mask.clone() { + depth += 1; + n = match &m.art.kind { + NodeKind::Group { children, .. } if children.len() == 1 => children[0].clone(), + _ => m.art.clone(), + }; + } + assert_eq!(depth, 8); +} + +#[test] +fn a_clipping_object_other_than_a_path_cuts_the_art() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let t = vectorcraft_doc::TextObject::point( + vectorcraft_geom::Point::new(10.0, 70.0), + "Type", + vectorcraft_doc::CharStyle { size: 18.0, fill: solid(Color::BLACK), ..vectorcraft_doc::CharStyle::default() }, + ); + let t = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![t, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::CLIPPING), "{:?}", out.warnings); + assert!(!String::from_utf8(out.program).unwrap().contains("\nq\n")); + // The type's black fill under the blue square, both cut to the type: within its line, + // narrower than the square. + assert_eq!(cut_to_type(&read_back(&doc).layers[0]), ["black", "blue"]); +} + +/// The colors of the paths `layer` holds, in paint order, each kind once, after checking that they +/// all lie within the line of type `Type` set at (10, 70) in 18 points. +fn cut_to_type(layer: &Node) -> Vec<&'static str> { + let mut all = vec![]; + paths(layer.children().unwrap(), &mut all); + let b = all.iter().filter_map(|n| n.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert!(b.x0 >= 9.0 && b.x1 < 100.0 && b.y0 > 40.0 && b.y1 < 80.0, "{b:?}"); + let mut colors = vec![]; + for n in &all { + let c = match n.appearance.fill().map(|f| paint(&f.paint)) { + Some(p) if p == paint(&solid(Color::BLACK)) => "black", + Some(p) if p == paint(&solid(Color::rgb(0.0, 0.0, 1.0))) => "blue", + _ => "other", + }; + if colors.last() != Some(&c) { + colors.push(c); + } + } + colors +} + +/// A clipping layer whose clipping object isn't a path is written as a layer that doesn't clip, +/// holding its art cut to that object. +#[test] +fn a_clipping_layer_clipped_by_type_is_not_written_as_a_clipping_layer() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let t = vectorcraft_doc::TextObject::point( + vectorcraft_geom::Point::new(10.0, 70.0), + "Type", + vectorcraft_doc::CharStyle { size: 18.0, fill: solid(Color::BLACK), ..vectorcraft_doc::CharStyle::default() }, + ); + let t = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(layer), usize::MAX, t).unwrap(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.0, 0.0, 1.0)); + doc.insert(Some(layer), usize::MAX, inside).unwrap(); + if let NodeKind::Layer { clip, .. } = &mut Arc::make_mut(&mut doc.layers[0]).kind { + *clip = true; + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::CLIPPING), "{:?}", out.warnings); + let p = String::from_utf8(out.program).unwrap().replace("\r\n", "\n"); + assert!(p.contains(" 0 50 0 Lb\n") && !p.contains(" 0 50 1 Lb\n") && !p.contains("\nW\n"), "{p}"); + let back = read_back(&doc); + assert!(matches!(back.layers[0].kind, NodeKind::Layer { clip: false, .. })); + assert_eq!(cut_to_type(&back.layers[0]), ["black", "blue"]); +} + +/// An empty clipping layer is written as an empty layer. +#[test] +fn an_empty_clipping_layer_is_an_empty_layer() { + let mut doc = Document::new(200.0, 100.0); + if let NodeKind::Layer { clip, .. } = &mut Arc::make_mut(&mut doc.layers[0]).kind { + *clip = true; + } + let p = program(&doc); + assert!(p.contains(" 0 50 0 Lb\n(Layer 1) Ln\n") && !p.contains("\nu\n"), "{p}"); + let back = read_back(&doc); + assert!(back.layers[0].children().is_none_or(Vec::is_empty), "{:?}", back.layers[0]); +} + +/// A guide takes its own transparency, not the one of the object before it. +#[test] +fn guides_keep_their_own_transparency() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let bright = see_through(square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb(1.0, 0.0, 0.0)), 0.5, BlendMode::Screen); + doc.insert(Some(layer), usize::MAX, bright).unwrap(); + for (r, opacity, blend) in + [(Rect::new(20.0, 20.0, 40.0, 40.0), 1.0, BlendMode::Normal), (Rect::new(50.0, 20.0, 70.0, 40.0), 0.4, BlendMode::Multiply)] + { + let mut g = clipping(&mut doc, shapes::rectangle(r)); + g.kind = NodeKind::Path { path: shapes::rectangle(r), rule: FillRule::NonZero, live: None, clipping: false, guide: true }; + doc.insert(Some(layer), usize::MAX, see_through(g, opacity, blend)).unwrap(); + } + let back = read_back(&doc); + let got: Vec<(bool, f32, BlendMode)> = + back.layers[0].children().unwrap().iter().map(|n| (matches!(n.kind, NodeKind::Path { guide: true, .. }), n.opacity, n.blend)).collect(); + assert_eq!(got, [(false, 0.5, BlendMode::Screen), (true, 1.0, BlendMode::Normal), (true, 0.4, BlendMode::Multiply)]); +} + +/// The transparency a group's last member or a group's state block sets carries over to the object +/// after the group, which then writes no `Xy` of its own when it has the same. +#[test] +fn objects_after_a_group_keep_their_transparency() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let red = Color::rgb(1.0, 0.0, 0.0); + let screen = |doc: &mut Document, x: f64| see_through(square(doc, Rect::new(x, 0.0, x + 10.0, 10.0), red), 0.5, BlendMode::Screen); + // A plain group whose last member is at 50% in Screen, then a path the same. + let a = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), red); + let b = screen(&mut doc, 10.0); + let plain = group(&mut doc, vec![a, b], false); + let after_plain = screen(&mut doc, 30.0); + // A group at 40% with knockout off, then a path at 40%. + let c = square(&mut doc, Rect::new(50.0, 0.0, 60.0, 10.0), red); + let mut faint = see_through(group(&mut doc, vec![c], false), 0.4, BlendMode::Normal); + faint.knockout = Knockout::Off; + let after_faint = see_through(square(&mut doc, Rect::new(70.0, 0.0, 80.0, 10.0), red), 0.4, BlendMode::Normal); + for n in [plain, after_plain, faint, after_faint] { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let p = program(&doc); + // No `Xy` between the groups' state blocks and the paths after them: the second square's, the + // third's (opaque, after the second) and the second group's. + let after = |block: &str| p.split_once(block).unwrap().1.split_once("\nf\n").unwrap().0.to_string(); + assert!(!after("U\n9 () XW\n").contains("Xy"), "{p}"); + assert!(!after("U\n0 0.4 0 0 0 Xy\n0 0 Xd\n6 () XW\n").contains("Xy"), "{p}"); + assert_eq!(p.matches(" Xy\n").count(), 3, "{p}"); + same_lines(&all_looks(&read_back(&doc)), &all_looks(&doc)); +} + +#[test] +fn transparency_of_single_fills_and_layer_masks_is_reported_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut fill = FillLayer::new(solid(Color::BLACK)); + fill.opacity = 0.5; + let n = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance { items: vec![AppearanceItem::Fill(fill)], ..Appearance::default() }, + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), Color::gray(0.5)); + Arc::make_mut(&mut doc.layers[0]).extras_mut().mask = Some(Box::new(OpacityMask::new(art, true))); + let out = export_ai_editing(&doc, &opts()).unwrap(); + for w in [writer::ITEM_TRANSPARENCY, writer::LAYER_MASKS] { + assert!(out.warnings.iter().any(|x| x == w), "{w}: {:?}", out.warnings); + } + // A disabled one too. + if let Some(m) = Arc::make_mut(&mut doc.layers[0]).extras_mut().mask.as_mut() { + m.disabled = true; + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|x| x == writer::LAYER_MASKS), "{:?}", out.warnings); + // A clipping path's fill of its own opacity. + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0))); + let mut fill = FillLayer::new(solid(Color::BLACK)); + fill.opacity = 0.5; + clip.appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Appearance::default() }.into(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 20.0, 20.0), Color::gray(0.5)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|x| x == writer::ITEM_TRANSPARENCY), "{:?}", out.warnings); +} + +// ---------- gradients and patterns ---------- + +const INK: Color = Color::Cmyk { c: 0.0, m: 0.6, y: 1.0, k: 0.0 }; + +/// A gradient of `kind` through `stops` (offset, color, opacity, midpoint). +fn ramp(kind: GradientKind, stops: &[(f32, Color, f32, f32)]) -> Gradient { + let stops = + stops.iter().map(|&(offset, color, opacity, midpoint)| GradientStop { opacity, midpoint, ..GradientStop::new(offset, color) }).collect(); + Gradient::new(kind, stops) +} + +/// The three-stop linear gradient of the `Sunset` swatch: its middle stop half opaque, its first +/// midpoint at 30%. +fn sunset() -> Gradient { + ramp( + GradientKind::Linear, + &[(0.0, Color::rgb(1.0, 0.0, 0.0), 1.0, 0.3), (0.4, Color::rgb(0.0, 1.0, 0.0), 0.5, 0.5), (1.0, Color::rgb(0.0, 0.0, 1.0), 1.0, 0.5)], + ) +} + +fn gradient_paint(g: Gradient, geom: Option, swatch: Option<&str>) -> Paint { + Paint::Gradient(Box::new(GradientPaint { geom, swatch: swatch.map(Into::into), ..GradientPaint::new(g) })) +} + +fn painted(doc: &mut Document, path: PathData, items: Vec) -> Node { + Node::path(doc.alloc_id(), path, Appearance { items, ..Appearance::default() }) +} + +/// A 300 × 200 document of gradients and patterns. Swatches: the linear gradient `Sunset`, the radial +/// gradient `Glow` that nothing uses, the spot color `Ink`, the pattern `Dots` (a 10-point grid tile of +/// a red square and a circle filled with a gradient) and `Checks`, which nothing uses. Art, bottom +/// first: a rectangle filled with `Sunset` +/// placed at 30° over part of it and stroked black; an ellipse filled with a radial gradient half as +/// high as wide whose focal point is off its center; a rectangle filled yellow and stroked with a +/// gradient; one filled and stroked with gradients; an even-odd compound path filled with a +/// gradient; an open path filled with a gradient; a rectangle filled with a gradient of a gray, a +/// CMYK color and `Ink` at 70%; a rectangle filled with `Dots` turned, scaled and moved; and a +/// rectangle stroked 8 points with `Dots`. +fn gradients_and_patterns() -> Document { + use vectorcraft_color::gradient::GradientGeom; + let mut doc = Document::new(300.0, 200.0); + let glow = ramp(GradientKind::Radial, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.1, 0.2, 0.8), 1.0, 0.5)]); + let two = ramp(GradientKind::Linear, &[(0.0, Color::rgb(1.0, 1.0, 0.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + // The pattern art. + let red = square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), Color::rgb(1.0, 0.0, 0.0)); + let ball = painted( + &mut doc, + shapes::ellipse(Rect::new(5.0, 5.0, 9.0, 9.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(two.clone(), None, None)))], + ); + let mut dots = vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(red), Arc::new(ball)]); + dots.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + let check = square(&mut doc, Rect::new(0.0, 0.0, 5.0, 5.0), Color::BLACK); + let mut checks = vectorcraft_doc::PatternDef::new("Checks", vec![Arc::new(check)]); + checks.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.extend([dots, checks]); + let swatch = |name: &str, paint: Paint, spot: bool| Swatch { name: name.into(), paint, global: spot, spot }; + let mut swatches: Vec = doc.swatches.iter().filter(|s| matches!(s.paint, Paint::None)).cloned().collect(); + swatches.extend([ + swatch("Sunset", gradient_paint(sunset(), None, None), false), + swatch("Glow", gradient_paint(glow.clone(), None, None), false), + swatch("Ink", solid(INK), true), + swatch("Dots", Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, false), + swatch("Checks", Paint::Pattern { pattern: "Checks".into(), xf: Affine::IDENTITY }, false), + ]); + doc.swatches = swatches.into(); + doc.swatch_groups = Default::default(); + let layer = doc.layers[0].id; + let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p)); + let stroke = |p: Paint, w: f64| AppearanceItem::Stroke(StrokeLayer::new(p, w)); + let placed = GradientGeom { start: (20.0, 40.0).into(), end: (60.0, 17.0).into(), aspect: 1.0, focal: None }; + let mut oval = GradientGeom { start: (140.0, 30.0).into(), end: (180.0, 30.0).into(), aspect: 0.5, focal: None }; + oval.set_focal(Some((150.0, 25.0).into())); + let mut nodes = vec![ + painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 50.0)), + vec![fill(gradient_paint(sunset(), Some(placed), Some("Sunset"))), stroke(solid(Color::BLACK), 2.0)], + ), + painted(&mut doc, shapes::ellipse(Rect::new(100.0, 10.0, 180.0, 50.0)), vec![fill(gradient_paint(glow.clone(), Some(oval), None))]), + painted( + &mut doc, + shapes::rectangle(Rect::new(190.0, 10.0, 280.0, 50.0)), + vec![fill(solid(Color::rgb(1.0, 1.0, 0.0))), stroke(gradient_paint(two.clone(), None, None), 6.0)], + ), + painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 70.0, 90.0, 110.0)), + vec![fill(gradient_paint(sunset(), None, Some("Sunset"))), stroke(gradient_paint(two.clone(), None, None), 6.0)], + ), + ]; + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 70.0, 180.0, 110.0)), Appearance::default()); + let hole = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(120.0, 80.0, 160.0, 100.0)), Appearance::default()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance { items: vec![fill(gradient_paint(two.clone(), None, None))], ..Appearance::default() }.into(); + nodes.push(ring); + let mut open = shapes::line((190.0, 110.0).into(), (280.0, 70.0).into()); + if let Some(sp) = open.subpaths.first_mut() { + sp.anchors.push(vectorcraft_geom::Anchor::corner((200.0, 70.0).into())); + sp.closed = false; + } + nodes.push(painted(&mut doc, open, vec![fill(gradient_paint(two, None, None))])); + let mixed = ramp( + GradientKind::Linear, + &[(0.0, Color::gray(0.2), 1.0, 0.5), (0.5, Color::cmyk(1.0, 0.0, 0.0, 0.0), 1.0, 0.5), (1.0, INK.tinted(0.7), 1.0, 0.5)], + ); + let mut mixed_paint = gradient_paint(mixed, None, None); + if let Paint::Gradient(g) = &mut mixed_paint + && let Some(s) = g.gradient.stops.last_mut() + { + s.set_color(INK.tinted(0.7), Some(("Ink".into(), 0.7))); + } + nodes.push(painted(&mut doc, shapes::rectangle(Rect::new(10.0, 130.0, 90.0, 170.0)), vec![fill(mixed_paint)])); + let turned = Affine::translate((103.0, 127.0)) * Affine::rotate(30f64.to_radians()) * Affine::scale(0.5); + nodes.push(painted( + &mut doc, + shapes::rectangle(Rect::new(100.0, 130.0, 180.0, 170.0)), + vec![fill(Paint::Pattern { pattern: "Dots".into(), xf: turned })], + )); + nodes.push(painted( + &mut doc, + shapes::rectangle(Rect::new(195.0, 135.0, 235.0, 165.0)), + vec![stroke(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, 8.0)], + )); + for n in nodes { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + doc +} + +/// A gradient paint's swatch link in `doc`: the gradient swatch it names, `-` for none, and +/// `not a gradient swatch: name` when it names a swatch of other paint. A link that names no swatch +/// of `doc` at all is `-` too: the reader links every gradient instance to its definition's name, +/// and a definition of a gradient that isn't a swatch has a name no swatch has. +fn link(doc: &Document, swatch: &Option) -> String { + match swatch.as_deref().map(|s| (s, doc.swatch(s))) { + Some((s, Some(w))) if matches!(w.paint, Paint::Gradient(_)) => s.to_string(), + Some((s, Some(_))) => format!("not a gradient swatch: {s}"), + Some((_, None)) | None => "-".into(), + } +} + +/// Paint `p` as it draws on `bounds`: a gradient by its kind, stops (place, color, opacity, +/// midpoint, link) and its parameter at the corners, edge midpoints and center of `bounds`; a +/// pattern by its name and matrix. +fn drawn(doc: &Document, p: &Paint, bounds: Rect) -> String { + match p { + Paint::Gradient(g) => { + let geom = g.resolve(bounds); + let stops: Vec = g + .gradient + .stops + .iter() + .map(|s| { + format!( + "{} {} {} {} {:?}", + r3(f64::from(s.offset)), + color(&s.color), + r3(f64::from(s.opacity)), + r3(f64::from(s.midpoint)), + s.swatch + ) + }) + .collect(); + let (x, y) = ([bounds.x0, bounds.center().x, bounds.x1], [bounds.y0, bounds.center().y, bounds.y1]); + let at: Vec = + x.iter().flat_map(|x| y.iter().map(move |y| (*x, *y))).map(|(x, y)| r3(geom.param_at(g.gradient.kind, (x, y).into()))).collect(); + format!("{:?} [{}] link={} at {}", g.gradient.kind, stops.join(", "), link(doc, &g.swatch), at.join(" ")) + } + Paint::Pattern { pattern, xf } => format!("pattern {pattern} {:?}", xf.as_coeffs().map(r3)), + other => paint(other), + } +} + +/// What each object of `nodes` draws: its kind, bounds and paint. +fn paints_of(doc: &Document, nodes: &[Arc], depth: usize, out: &mut Vec) { + for n in nodes { + let bounds = n.geometric_bounds().unwrap_or(Rect::ZERO); + let mut s = format!("{depth} {} {:?}", n.kind_label(), [bounds.x0, bounds.y0, bounds.x1, bounds.y1].map(r3)); + // Items that paint nothing aren't written. + for it in n.appearance.items.iter().filter(|i| !i.paint().is_none()) { + s += &match it { + AppearanceItem::Fill(f) => format!(" fill({})", drawn(doc, &f.paint, bounds)), + AppearanceItem::Stroke(st) => format!(" stroke({} w={})", drawn(doc, &st.paint, st.paint_bounds(bounds)), r3(st.width)), + }; + } + out.push(s); + // A compound path's paint is its own, not its members'. + if !matches!(n.kind, NodeKind::Compound { .. }) { + paints_of(doc, n.children().map(Vec::as_slice).unwrap_or_default(), depth + 1, out); + } + } +} + +/// What `doc`'s art, patterns and gradient and pattern swatches draw. +fn gradient_looks(doc: &Document) -> Vec { + let mut out = vec![]; + paints_of(doc, &doc.layers, 0, &mut out); + for p in doc.patterns.iter() { + out.push(format!("pattern {} tile {:?}", p.name, [p.tile.x0, p.tile.y0, p.tile.x1, p.tile.y1].map(r3))); + paints_of(doc, &p.art, 1, &mut out); + } + for s in doc.swatches_iter() { + match &s.paint { + Paint::Gradient(g) => { + out.push(format!("swatch {} {}", s.name, drawn(doc, &Paint::Gradient(Box::new(GradientPaint::new(g.gradient.clone()))), Rect::ZERO))) + } + Paint::Pattern { pattern, .. } => out.push(format!("swatch {} pattern {pattern}", s.name)), + _ => {} + } + } + out +} + +#[test] +fn gradients_and_patterns_are_read_back() { + let doc = gradients_and_patterns(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + same_lines(&gradient_looks(&read_back(&doc)), &gradient_looks(&doc)); +} + +/// A new document's gradient swatches read back with the paint they were written with, not linked +/// to a swatch, and art filled with one of them reads back linked to it. +#[test] +fn gradient_swatches_read_back_unlinked() { + let mut doc = Document::new(200.0, 100.0); + let Some(Paint::Gradient(sunset)) = doc.swatch("Sunset").map(|s| s.paint.clone()) else { panic!("no Sunset swatch") }; + let layer = doc.layers[0].id; + let linked = gradient_paint(sunset.gradient.clone(), None, Some("Sunset")); + let rect = painted(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 50.0)), vec![AppearanceItem::Fill(FillLayer::new(linked))]); + doc.insert(Some(layer), usize::MAX, rect).unwrap(); + let back = read_back(&doc); + let gradients = |d: &Document| -> Vec { + d.swatches_iter() + .filter_map(|s| match &s.paint { + Paint::Gradient(g) => { + Some(format!("{} {:?} stops={} geom={:?} swatch={:?}", s.name, g.gradient.kind, g.gradient.stops.len(), g.geom, g.swatch)) + } + _ => None, + }) + .collect() + }; + let want = gradients(&doc); + assert_eq!(want.len(), 4, "{want:?}"); + assert_eq!(gradients(&back), want); + let link = back.layers[0].children().and_then(|c| c.first()).map(|n| match n.appearance.items.first().map(AppearanceItem::paint) { + Some(Paint::Gradient(g)) => g.swatch.clone(), + other => panic!("{other:?}"), + }); + assert_eq!(link, Some(Some("Sunset".to_string()))); +} + +#[test] +fn gradients_and_patterns_write_the_same_bytes_again() { + let doc = gradients_and_patterns(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + let again = export_ai_editing(&read_back(&doc), &opts()).unwrap(); + same_lines( + &String::from_utf8(again.program).unwrap().lines().map(str::to_string).collect::>(), + &String::from_utf8(first.program).unwrap().lines().map(str::to_string).collect::>(), + ); +} + +#[test] +fn gradients_and_patterns_are_written_in_their_forms() { + let text = program(&gradients_and_patterns()); + // The gradients the art uses, then the one only the palette uses; then the patterns. + let setup = text.split("%%BeginSetup\n").nth(1).and_then(|s| s.split("%AI5_BeginPalette").next()).unwrap(); + let markers: Vec<&str> = setup.lines().filter(|l| l.starts_with("%AI") || l.ends_with(" Bn")).collect(); + assert_eq!( + markers, + [ + "4 Bn", + "%AI5_BeginGradient: (Sunset)", + "%AI5_EndGradient", + "%AI5_BeginGradient: (Gradient)", + "%AI5_EndGradient", + "%AI5_BeginGradient: (Gradient 2)", + "%AI5_EndGradient", + "%AI5_BeginGradient: (Gradient 3)", + "%AI5_EndGradient", + "%AI5_Begin_NonPrinting", + "1 Bn", + "%AI5_BeginGradient: (Glow)", + "%AI5_EndGradient", + "%AI5_End_NonPrinting--", + "%AI3_BeginPattern: (Dots)", + "%AI3_EndPattern", + "%AI5_Begin_NonPrinting", + "%AI3_BeginPattern: (Checks)", + "%AI3_EndPattern", + "%AI5_End_NonPrinting--", + ] + ); + // A linear gradient's stops from the last; RGB with its CMYK equivalent, style 2, opacity, 6, + // midpoint, place on the ramp. + assert!(text.contains("(Sunset) 0 3 Bd\n[\n%_"), "{setup}"); + assert!( + setup.contains(" 0 0 1 2 1 6 50 100 Bs\n") && setup.contains(" 0 1 0 2 0.5 6 50 40 Bs\n") && setup.contains(" 1 0 0 2 1 6 30 0 Bs\n"), + "{setup}" + ); + // Gray, CMYK, and a spot color at 70%. + assert!( + setup.contains("%_0.8 0 1 6 50 0 Bs\n%_1 0 0 0 1 1 6 50 50 Bs\n") + || setup.contains("(Ink) 0.3 3 1 6 50 100 Bs\n%_1 0 0 0 1 1 6 50 50 Bs\n%_0.8 0 1 6 50 0 Bs\n"), + "{setup}" + ); + // The tile in the pattern's space, y up, the art on `%_` lines. + assert!(setup.contains("%AI3_BeginPattern: (Dots)\n(Dots) 0 -10 10 0\n%_"), "{setup}"); + assert!(!setup.contains("%_E\n") && setup.contains("\nE\n%AI3_EndPattern\n"), "{setup}"); + // The swatches. + assert!(text.contains("Bb\n2 (Sunset) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sunset) Pc\n"), "{text}"); + assert!(text.contains("Bb\n0 0 0 0 Bh\n2 (Glow) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Glow) Pc\n"), "{text}"); + assert!(text.contains("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Dots) Pc\n"), "{text}"); + // The instances: the stroked rectangle's fill placed at 29.9° from 0.15 of the rectangle's extent + // that way, 0.52 of it long, with `Xm`, caps and a `Bm` for each pair of stops, `b` and `2 BB`; the + // stroke's `1 Bb`; the radial's focal point and `Bm`. + let art = text.split("%AI5_BeginLayer").nth(1).unwrap(); + assert!(art.contains("Bb\n1 (Sunset) 0.1529 0 29.8989 0.5167 1 0 0 1 0 0 1 Bg\n") && art.contains(" Xm\n"), "{art}"); + let sunset_instance = art.split("Bb\n1 (Sunset)").nth(1).unwrap(); + let ops: Vec<&str> = sunset_instance.lines().take(7).map(|l| l.rsplit(' ').next().unwrap_or(l)).collect(); + assert_eq!(ops, ["Bg", "Xm", "Bc", "Bm", "Bm", "Bc", "b"], "{sunset_instance}"); + assert!(sunset_instance.contains("\nb\n2 BB\n"), "{sunset_instance}"); + assert!(art.contains("1 Bb\n1 (Gradient 2) "), "{art}"); + assert!(art.contains("2 BB\n1 Bb\n"), "fill and stroke: {art}"); + // The radial (40 wide, 20 high) as the unit circle through its matrix: the focal point 10 right of + // the center and 5 up, at 45° and 0.35 of the radius on that circle. + assert!(art.contains("Bb\n10 5 45 0.3536 Bh\n1 (Gradient) 0 0 0 1 40 0 0 20 0 0 1 Bg\n40 0 0 -20 140 -30 Bm\nf\n0 BB\n"), "{art}"); + // The tile's box first in a pattern's definition. + assert!(setup.contains("(Dots) 0 -10 10 0\n%_0 A\n%_0 Xw\n%_0 XR\n%_0 0 m\n"), "{setup}"); + assert!(setup.contains("%_n\n%_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_\n"), "{setup}"); + assert!(art.contains("F\n0 BB\n"), "the open path: {art}"); + assert!(art.contains(" p\n") && art.contains(" P\n"), "{art}"); +} + +/// A clipping path filled with a gradient keeps it, and reads back with it. +#[test] +fn a_clipping_path_keeps_its_gradient() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::ellipse(Rect::new(10.0, 10.0, 90.0, 60.0))); + clip.appearance = Appearance::basic(gradient_paint(sunset(), None, None), Paint::None, 0.0).into(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 50.0, 40.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::CLIP_PAINT), "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("h\nW\nBb\n0 (Gradient) "), "{text}"); + let back = read_back(&doc); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + assert_eq!(children.len(), 2, "the clipping path and the art"); + let fill = &children[0]; + assert!(matches!(fill.kind, NodeKind::Path { clipping: true, .. }), "{:?}", fill.kind); + let bounds = Rect::new(10.0, 10.0, 90.0, 60.0); + let want = drawn(&doc, &gradient_paint(sunset(), None, None), bounds); + assert_eq!(drawn(&back, fill.appearance.items[0].paint(), bounds), want); +} + +#[test] +fn freeform_gradients_are_written_as_their_average_color() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let g = ramp(GradientKind::Freeform, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::GRADIENTS), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(paint(back.layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.5, 0.5)))); +} + +/// A gradient that dithers or mixes perceptually is written as a classic one; a stop linked to a +/// global process color is written as its color; each with a warning. +#[test] +fn gradient_options_and_links_the_data_cant_hold_are_reported() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut g = sunset(); + g.dither = true; + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::GRADIENT_MIX]); + // A swatch of such a gradient that nothing uses. + let mut swatch_only = Document::new(200.0, 100.0); + let mut dithered = sunset(); + dithered.dither = true; + let mut swatches: Vec = swatch_only.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Dithered".into(), paint: gradient_paint(dithered, None, None), global: false, spot: false }); + swatch_only.swatches = swatches.into(); + let out = export_ai_editing(&swatch_only, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::GRADIENT_MIX), "{:?}", out.warnings); + // A gradient along a stroke: the stroke's outline in its average color. + let mut along = Document::new(200.0, 100.0); + let layer = along.layers[0].id; + let mut st = StrokeLayer::new(gradient_paint(sunset(), None, None), 4.0); + st.gradient_mode = vectorcraft_doc::StrokeGradientMode::Along; + let n = painted(&mut along, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), vec![AppearanceItem::Stroke(st)]); + along.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&along, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::GRADIENTS), "{:?}", out.warnings); + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Brand".into(), paint: solid(BRAND), global: true, spot: false }); + doc.swatches = swatches.into(); + let mut g = sunset(); + g.method = vectorcraft_color::gradient::GradientMethod::Perceptual; + if let Some(s) = g.stops.first_mut() { + s.set_color(BRAND, Some(("Brand".into(), 1.0))); + } + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::GRADIENT_MIX, writer::STOP_LINKS]); + let back = read_back(&doc); + let Paint::Gradient(g) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") }; + assert_eq!((color(&g.gradient.stops[0].color), g.gradient.stops[0].swatch.as_deref()), (color(&BRAND), None)); +} + +/// A pattern whose art reaches past its tile is written as its tiles cut to the shape: a definition +/// would cut its art off at the tile's edge. +#[test] +fn a_pattern_whose_art_reaches_past_its_tile_is_written_as_its_tiles() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let big = square(&mut doc, Rect::new(-2.0, -2.0, 6.0, 6.0), Color::rgb(1.0, 0.0, 0.0)); + let mut over = vectorcraft_doc::PatternDef::new("Over", vec![Arc::new(big)]); + over.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.push(over); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), + vec![AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: "Over".into(), xf: Affine::IDENTITY }))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings); + assert!(!program(&doc).contains("%AI3_BeginPattern")); +} + +/// A pattern fill in another pattern's tile is written there as its tiles cut to the shape; the +/// outer pattern is defined and fills the shape. +#[test] +fn a_pattern_fill_in_a_pattern_tile_is_written_as_its_tiles() { + let mut doc = gradients_and_patterns(); + let layer = doc.layers[0].id; + let inner = painted( + &mut doc, + shapes::rectangle(Rect::new(2.0, 2.0, 18.0, 18.0)), + vec![AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }))], + ); + let mut nest = vectorcraft_doc::PatternDef::new("Nest", vec![Arc::new(inner)]); + nest.tile = Rect::new(0.0, 0.0, 20.0, 20.0); + doc.patterns.push(nest); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(250.0, 130.0, 290.0, 170.0)), + vec![AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: "Nest".into(), xf: Affine::IDENTITY }))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("%AI3_BeginPattern: (Nest)") && text.contains("%AI3_BeginPattern: (Dots)")); + let back = read_back(&doc); + let filled = back.layers[0].children().unwrap().last().unwrap(); + assert!(matches!(filled.appearance.items[0].paint(), Paint::Pattern { pattern, .. } if pattern == "Nest")); + // Nest's tile: the dots' tiles (a red square, a gradient circle) cut to its square. + let mut all = vec![]; + paths(&back.pattern("Nest").unwrap().art, &mut all); + assert!(all.len() > 2, "{}", all.len()); + assert!(all.iter().all(|p| !matches!(p.appearance.items[0].paint(), Paint::Pattern { .. }))); + assert!(all.iter().any(|p| paint(p.appearance.items[0].paint()) == paint(&solid(Color::rgb(1.0, 0.0, 0.0))))); +} + +/// A 200 × 100 document with one object of `items` on `path`, and only the None swatch. +fn one_object(path: PathData, items: Vec) -> Document { + let mut doc = Document::new(200.0, 100.0); + doc.swatches = doc.swatches.iter().filter(|s| matches!(s.paint, Paint::None)).cloned().collect::>().into(); + doc.swatch_groups = Default::default(); + let layer = doc.layers[0].id; + let n = painted(&mut doc, path, items); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + doc +} + +/// What `doc`'s art draws (a palette of only the None swatch reads back as the default swatches). +fn art_looks(doc: &Document) -> Vec { + let mut out = vec![]; + paints_of(doc, &doc.layers, 0, &mut out); + out +} + +fn swatches_plus(doc: &mut Document, more: Vec) { + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.extend(more); + doc.swatches = swatches.into(); +} + +/// `Bg` places each gradient on its path: a radial one 30 right of and 10 above the middle of a +/// 120 × 60 rectangle, 20 in radius, by its unit circle's matrix, its center's place as fractions of +/// the bounds and its radius as a multiple of √((1.5² + 2²) / 2) (the center's distances to the +/// right side and to the bottom in that circle's units); and a linear one at −45° on a triangle, +/// from a quarter of the triangle's extent that way, half of it long. In a pattern's tile the same +/// two are placed mirrored top to bottom: the radial's center 10 below the middle, its radius a +/// multiple of √((1.5² + 1²) / 2), and the linear one at 45°. +#[test] +fn bg_places_gradients_on_their_paths() { + use vectorcraft_color::gradient::GradientGeom; + let radial = ramp(GradientKind::Radial, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 1.0), 1.0, 0.5)]); + let off_center = GradientGeom { start: (90.0, 20.0).into(), end: (110.0, 20.0).into(), aspect: 1.0, focal: None }; + let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p)); + let mut doc = one_object(shapes::rectangle(Rect::new(0.0, 0.0, 120.0, 60.0)), vec![fill(gradient_paint(radial.clone(), Some(off_center), None))]); + let layer = doc.layers[0].id; + let mut triangle = shapes::line((130.0, 10.0).into(), (190.0, 10.0).into()); + if let Some(sp) = triangle.subpaths.first_mut() { + sp.anchors.push(vectorcraft_geom::Anchor::corner((130.0, 40.0).into())); + sp.closed = true; + } + let turned = GradientGeom { start: (145.0, 10.0).into(), end: (160.0, 25.0).into(), aspect: 1.0, focal: None }; + let n = painted(&mut doc, triangle.clone(), vec![fill(gradient_paint(sunset(), Some(turned), None))]); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let in_tile = painted(&mut doc, shapes::rectangle(Rect::new(0.0, 0.0, 120.0, 60.0)), vec![fill(gradient_paint(radial, Some(off_center), None))]); + let slant = painted(&mut doc, triangle, vec![fill(gradient_paint(sunset(), Some(turned), None))]); + let mut tile = vectorcraft_doc::PatternDef::new("Tile", vec![Arc::new(in_tile), Arc::new(slant)]); + tile.tile = Rect::new(0.0, 0.0, 200.0, 60.0); + doc.patterns.push(tile); + swatches_plus( + &mut doc, + vec![Swatch { name: "Tile".into(), paint: Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY }, global: false, spot: false }], + ); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(130.0, 50.0, 190.0, 90.0)), + vec![fill(Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY })], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let text = program(&doc); + let art = text.split("%AI5_BeginLayer").nth(1).unwrap(); + assert!(art.contains("Bb\n0 0 0 0 Bh\n1 (Gradient) 0.25 -0.1667 0 0.5657 20 0 0 20 0 0 1 Bg\n"), "{art}"); + assert!(art.contains("Bb\n1 (Gradient 2) 0.25 0 -45 0.5 1 0 0 1 0 0 1 Bg\n"), "{art}"); + let setup = text.split("%AI3_BeginPattern: (Tile)").nth(1).unwrap(); + assert!(setup.contains("%_Bb\n%_0 0 0 0 Bh\n%_1 (Gradient) 0.25 0.1667 0 0.7845 20 0 0 20 0 0 1 Bg\n"), "{setup}"); + assert!(setup.contains("%_Bb\n%_1 (Gradient 2) 0.25 0 45 0.5 1 0 0 1 0 0 1 Bg\n"), "{setup}"); + same_lines(&gradient_looks(&read_back(&doc)), &gradient_looks(&doc)); +} + +/// A definition of a gradient that isn't a swatch takes a name that no swatch and no pattern has, +/// so that its instances don't read back linked to another swatch. +#[test] +fn gradient_definitions_skip_the_names_of_swatches_and_patterns() { + let mut doc = gradients_and_patterns(); + let check = square(&mut doc, Rect::new(0.0, 0.0, 5.0, 5.0), Color::BLACK); + let mut taken = vectorcraft_doc::PatternDef::new("Gradient 2", vec![Arc::new(check)]); + taken.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.push(taken); + swatches_plus( + &mut doc, + vec![ + Swatch { name: "Gradient".into(), paint: solid(Color::rgb(0.0, 0.5, 0.0)), global: false, spot: false }, + Swatch { + name: "Gradient 2".into(), + paint: Paint::Pattern { pattern: "Gradient 2".into(), xf: Affine::IDENTITY }, + global: false, + spot: false, + }, + ], + ); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let text = program(&doc); + let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect(); + assert_eq!(names, ["(Sunset)", "(Gradient 3)", "(Gradient 4)", "(Gradient 5)", "(Glow)"]); + same_lines(&gradient_looks(&read_back(&doc)), &gradient_looks(&doc)); +} + +/// Each search for a new gradient name starts after the last name given, so naming many gradients +/// tries each name once. +#[test] +fn gradient_names_are_searched_from_the_last_one_given() { + let mut taken: std::collections::HashSet = ["Gradient 2", "Gradient 5"].map(String::from).into(); + let (mut next, mut tries) = (1, 0); + let mut names = vec![]; + for _ in 0..1000 { + let name = writer::free_gradient_name(&mut next, |name| { + tries += 1; + taken.contains(name) + }); + taken.insert(name.clone()); + names.push(name); + } + assert_eq!(names[..4], ["Gradient", "Gradient 3", "Gradient 4", "Gradient 6"]); + assert_eq!(names.last().map(String::as_str), Some("Gradient 1002")); + assert_eq!(tries, 1002); + assert_eq!(next, 1003); +} + +/// Many gradients that no swatch names each get their own name, in order, skipping the names of +/// swatches and patterns, and the same names when the document is written again. +#[test] +fn many_gradient_definitions_take_distinct_names_in_order() { + let mut doc = one_object(shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), vec![]); + let check = square(&mut doc, Rect::new(0.0, 0.0, 5.0, 5.0), Color::BLACK); + let mut taken = vectorcraft_doc::PatternDef::new("Gradient 7", vec![Arc::new(check)]); + taken.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.push(taken); + swatches_plus(&mut doc, vec![Swatch { name: "Gradient 3".into(), paint: solid(Color::rgb(0.0, 0.5, 0.0)), global: false, spot: false }]); + let layer = doc.layers[0].id; + for i in 0..300u16 { + let shade = f32::from(i) / 300.0; + let g = ramp(GradientKind::Linear, &[(0.0, Color::rgb(shade, 0.0, 0.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 1.0), 1.0, 0.5)]); + let x = f64::from(i % 20) * 10.0; + let y = f64::from(i / 20) * 6.0; + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(x, y, x + 8.0, y + 5.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let text = program(&doc); + let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect(); + let expected: Vec = + std::iter::once("(Gradient)".to_string()).chain((2..=302).filter(|&i| i != 3 && i != 7).map(|i| format!("(Gradient {i})"))).collect(); + assert_eq!(names, expected); + assert_eq!(text, program(&doc)); +} + +/// A hard edge: a linear gradient whose stops all lie at one place is written from its last stop, +/// and reads back with each stop on its side. +#[test] +fn a_linear_gradient_with_every_stop_at_one_place_keeps_its_sides() { + let edge = ramp(GradientKind::Linear, &[(0.3, Color::rgb(1.0, 0.0, 0.0), 1.0, 0.4), (0.3, Color::rgb(0.0, 0.0, 1.0), 1.0, 0.7)]); + let doc = one_object( + shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 50.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(edge, None, None)))], + ); + let text = program(&doc); + let (blue, red) = (text.find(" 0 0 1 2 1 6 70 30 Bs\n").unwrap(), text.find(" 1 0 0 2 1 6 40 30 Bs\n").unwrap()); + assert!(blue < red, "{text}"); + same_lines(&art_looks(&read_back(&doc)), &art_looks(&doc)); +} + +/// Gradients without stops or with more than 256, without a ramp's length or flattened to a line +/// are written as their average color with a warning that says so, not the one for freeform +/// gradients. +#[test] +fn gradients_that_cant_be_placed_are_reported_as_such() { + use vectorcraft_color::gradient::GradientGeom; + let point = GradientGeom { start: (20.0, 20.0).into(), end: (20.0, 20.0).into(), aspect: 1.0, focal: None }; + let flat = GradientGeom { start: (20.0, 20.0).into(), end: (40.0, 20.0).into(), aspect: 0.0, focal: None }; + let radial = ramp(GradientKind::Radial, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + // More stops than the `.ai` reader reads. + let many: Vec<(f32, Color, f32, f32)> = (0..257).map(|i| (i as f32 / 256.0, Color::gray(i as f32 / 256.0), 1.0, 0.5)).collect(); + for p in [ + gradient_paint(sunset(), Some(point), None), + gradient_paint(radial, Some(flat), None), + gradient_paint(Gradient::new(GradientKind::Linear, vec![]), None, None), + gradient_paint(ramp(GradientKind::Linear, &many), None, None), + ] { + let doc = one_object(shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), vec![AppearanceItem::Fill(FillLayer::new(p.clone()))]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::GRADIENT_SHAPES], "{p:?}"); + let back = read_back(&doc); + assert!(matches!(back.layers[0].children().unwrap()[0].appearance.items[0].paint(), Paint::Solid { .. }), "{p:?}"); + } +} + +/// A gradient across a stroke is written as the stroke's outline in its average color, with the +/// warning. +#[test] +fn a_gradient_across_a_stroke_is_its_average_color() { + let mut st = StrokeLayer::new(gradient_paint(sunset(), None, None), 4.0); + st.gradient_mode = vectorcraft_doc::StrokeGradientMode::Across; + let doc = one_object(shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), vec![AppearanceItem::Stroke(st)]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::GRADIENTS), "{:?}", out.warnings); + assert!(!program(&doc).contains("Bb\n")); + let mut all = vec![]; + paths(read_back(&doc).layers[0].children().unwrap(), &mut all); + assert!(!all.is_empty() && all.iter().all(|p| p.appearance.items.iter().all(|i| matches!(i.paint(), Paint::Solid { .. }))), "{all:?}"); +} + +/// Patterns whose tiles are hexagons or bricks are written as their tiles cut to the shape, with the +/// warning, and aren't defined. +#[test] +fn hex_and_brick_patterns_are_written_as_their_tiles() { + for tile_type in [ + vectorcraft_doc::TileType::HexByRow, + vectorcraft_doc::TileType::HexByColumn, + vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, + vectorcraft_doc::TileType::BrickByColumn { offset: 0.5 }, + ] { + let mut doc = one_object( + shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), + vec![AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: "Cells".into(), xf: Affine::IDENTITY }))], + ); + let dot = square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), Color::rgb(1.0, 0.0, 0.0)); + doc.patterns.push(vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 10.0, 10.0), + tile_type, + ..vectorcraft_doc::PatternDef::new("Cells", vec![Arc::new(dot)]) + }); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PATTERNS), "{tile_type:?}: {:?}", out.warnings); + assert!(!program(&doc).contains("%AI3_BeginPattern"), "{tile_type:?}"); + let mut all = vec![]; + paths(read_back(&doc).layers[0].children().unwrap(), &mut all); + let red = paint(&solid(Color::rgb(1.0, 0.0, 0.0))); + assert!(all.iter().any(|p| p.appearance.items.iter().any(|i| paint(i.paint()) == red)), "{tile_type:?}"); + } +} + +/// An open path filled and stroked with gradients: the fill's instance ends `1 BB`, the stroke's +/// `1 Bb` follows, and the open path's `B` ends `1 BB`. +#[test] +fn an_open_path_keeps_its_gradient_fill_and_stroke() { + let two = ramp(GradientKind::Linear, &[(0.0, Color::rgb(1.0, 1.0, 0.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + let mut open = shapes::line((20.0, 80.0).into(), (100.0, 20.0).into()); + if let Some(sp) = open.subpaths.first_mut() { + sp.anchors.push(vectorcraft_geom::Anchor::corner((150.0, 70.0).into())); + sp.closed = false; + } + let doc = one_object( + open, + vec![ + AppearanceItem::Fill(FillLayer::new(gradient_paint(sunset(), None, None))), + AppearanceItem::Stroke(StrokeLayer::new(gradient_paint(two, None, None), 3.0)), + ], + ); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("\n1 BB\n1 Bb\n1 (Gradient 2) ") && text.contains("\nB\n1 BB\n"), "{text}"); + same_lines(&art_looks(&read_back(&doc)), &art_looks(&doc)); +} + +/// A clipping path stroked with a gradient keeps it. +#[test] +fn a_clipping_path_keeps_its_gradient_stroke() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::ellipse(Rect::new(10.0, 10.0, 90.0, 60.0))); + clip.appearance = Appearance::basic(Paint::None, gradient_paint(sunset(), None, None), 3.0).into(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 50.0, 40.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("h\nW\n1 Bb\n0 (Gradient) "), "{text}"); + let back = read_back(&doc); + let mut want = vec![]; + paints_of(&doc, doc.layers[0].children().unwrap(), 0, &mut want); + let mut got = vec![]; + paints_of(&back, back.layers[0].children().unwrap(), 0, &mut got); + let strokes = |v: &[String]| { + v.iter().filter(|l| l.contains(" stroke(Linear")).map(|l| l.split(" stroke(").nth(1).unwrap_or_default().to_string()).collect::>() + }; + assert_eq!(strokes(&got), strokes(&want), "{got:#?}"); +} + +/// In a CMYK document the gradient's CMYK stops are written as CMYK and read back the same. +#[test] +fn a_cmyk_documents_gradients_keep_their_stops() { + let cmyk = ramp(GradientKind::Linear, &[(0.0, Color::cmyk(0.0, 0.6, 1.0, 0.0), 1.0, 0.5), (1.0, Color::cmyk(1.0, 0.0, 0.0, 0.2), 0.5, 0.25)]); + let mut doc = one_object( + shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 50.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(cmyk, None, None)))], + ); + doc.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let text = program(&doc); + assert!(text.contains("%AI9_ColorModel: 2\n"), "{text}"); + assert!(text.contains("%_1 0 0 0.2 1 0.5 6 25 100 Bs\n%_0 0.6 1 0 1 1 6 50 0 Bs\n"), "{text}"); + same_lines(&art_looks(&read_back(&doc)), &art_looks(&doc)); +} + +/// A compound path's gradient instance is on its last subpath only. +#[test] +fn a_compound_paths_gradient_is_on_its_last_subpath() { + let text = program(&gradients_and_patterns()); + let compound = text.split("*u\n").nth(1).and_then(|s| s.split("*U\n").next()).unwrap(); + assert_eq!(compound.matches("Bb\n").count(), 1, "{compound}"); + let last_subpath = compound.rfind(" m\n").unwrap(); + assert!(compound.find("Bb\n").unwrap() > last_subpath, "{compound}"); + assert_eq!(compound.matches(" m\n").count(), 2, "{compound}"); +} + +/// Freeform gradient swatches and swatches of patterns that can't be defined are left out with the +/// warning; a color group counts only the swatches written. +#[test] +fn swatches_the_data_cant_hold_are_left_out() { + let mut doc = gradients_and_patterns(); + let dot = square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), Color::rgb(1.0, 0.0, 0.0)); + doc.patterns.push(vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 10.0, 10.0), + tile_type: vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, + ..vectorcraft_doc::PatternDef::new("Brick", vec![Arc::new(dot)]) + }); + let free = ramp(GradientKind::Freeform, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + let swatch = |name: &str, paint: Paint| Swatch { name: name.into(), paint, global: false, spot: false }; + doc.swatch_groups = vec![SwatchGroup { + name: "Mixed".into(), + swatches: vec![ + swatch("Free", gradient_paint(free.clone(), None, None)), + swatch("Dawn", gradient_paint(sunset(), None, None)), + swatch("Brick", Paint::Pattern { pattern: "Brick".into(), xf: Affine::IDENTITY }), + swatch("Dots 2", Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }), + ], + }] + .into(); + swatches_plus(&mut doc, vec![swatch("Free 2", gradient_paint(free, None, None))]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SWATCHES], "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("0 (Mixed) 2 Pg\n"), "{text}"); + for name in ["(Free) Pc", "(Free 2) Pc", "(Brick) Pc", "%AI3_BeginPattern: (Brick)"] { + assert!(!text.contains(name), "{name}"); + } + let back = read_back(&doc); + let group = back.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(group.swatches.iter().map(|s| s.name.as_str()).collect::>(), ["Dawn", "Dots 2"]); +} + +/// A pattern swatch that moves, turns or scales its pattern is written with its pattern, and the +/// placement is reported left out. +#[test] +fn a_pattern_swatchs_own_placement_is_reported_left_out() { + let mut doc = gradients_and_patterns(); + let moved = Paint::Pattern { pattern: "Dots".into(), xf: Affine::scale(2.0) }; + swatches_plus(&mut doc, vec![Swatch { name: "Big Dots".into(), paint: moved, global: false, spot: false }]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SWATCH_PLACEMENT]); + assert!(program(&doc).contains("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Big Dots) Pc\n")); +} + +// ---------- images and placed files ---------- + +/// `img` as PNG bytes. +fn png_of(img: image::DynamicImage) -> Vec { + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + png +} + +/// An image object of `blob`'s pixels (`w` × `h`) placed by `xf`, its blob kept in `doc`. +fn image_node(doc: &mut Document, blob: ImageBlob, (w, h): (u32, u32), xf: Affine, link: Option) -> Node { + let key = blob.content_key(); + doc.images.insert(key.clone(), blob); + let im = ImageObject { key, width: w, height: h, xf, link, placement: Default::default(), pixels: None }; + Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))) +} + +/// A 3 × 2 RGB image, every pixel a different color. +fn rgb_png() -> Vec { + let px = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [0, 255, 255], [12, 34, 56]]; + png_of(image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(3, 2, |x, y| image::Rgb(px[(y * 3 + x) as usize])))) +} + +/// A 200 × 100 document of images: on a layer `Pictures`, an RGB image `Photo` turned, scaled and +/// moved, at half opacity in Multiply; a locked RGBA image whose pixels are see-through in part; a +/// hidden gray image; a CMYK image; a clipping group of the RGB image cut by a rectangle; a square +/// whose opacity mask is a gray image. On a layer `Links`, a linked image in a folder next to the +/// document's. +fn images_doc() -> Document { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let turned = Affine::translate((40.0, 30.0)) * Affine::rotate(0.5) * Affine::scale_non_uniform(8.0, 6.0); + let mut photo = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), turned, None); + photo.name = Some("Photo".into()); + photo.opacity = 0.5; + photo.blend = BlendMode::Multiply; + doc.insert(Some(layer), usize::MAX, photo).unwrap(); + let alpha = [0, 128, 255, 200]; + let rgba = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba([200, 100, (x * 50) as u8, alpha[(y * 2 + x) as usize]])); + let mut see = image_node(&mut doc, ImageBlob::png(png_of(rgba.into())), (2, 2), Affine::new([10.0, 0.0, 0.0, 10.0, 60.0, 10.0]), None); + see.locked = true; + doc.insert(Some(layer), usize::MAX, see).unwrap(); + let gray = image::GrayImage::from_fn(4, 1, |x, _| image::Luma([(x * 60) as u8])); + let mut gray = image_node(&mut doc, ImageBlob::png(png_of(gray.into())), (4, 1), Affine::new([5.0, 0.0, 0.0, 5.0, 90.0, 60.0]), None); + gray.visible = false; + doc.insert(Some(layer), usize::MAX, gray).unwrap(); + let inks = vectorcraft_doc::cmyk::Inks::new(2, 1, vec![255, 0, 0, 0, 10, 20, 30, 40]).unwrap(); + let cmyk = image_node(&mut doc, ImageBlob::cmyk_tiff(&inks).unwrap(), (2, 1), Affine::new([10.0, 0.0, 0.0, 10.0, 120.0, 10.0]), None); + doc.insert(Some(layer), usize::MAX, cmyk).unwrap(); + let clip = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(150.0, 10.0, 170.0, 25.0)), Appearance::default()); + let inside = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([10.0, 0.0, 0.0, 10.0, 145.0, 5.0]), None); + let group = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(inside)], clip: true }); + doc.insert(Some(layer), usize::MAX, group).unwrap(); + let ramp = image::GrayImage::from_fn(3, 3, |x, y| image::Luma([(x * 100 + y * 20) as u8])); + let mask_art = image_node(&mut doc, ImageBlob::png(png_of(ramp.into())), (3, 3), Affine::new([10.0, 0.0, 0.0, 10.0, 10.0, 60.0]), None); + let mut square = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(10.0, 60.0, 40.0, 90.0)), + Appearance::basic(solid(Color::rgb(0.0, 0.5, 1.0)), Paint::None, 0.0), + ); + square.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, false))); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let links = Node::layer(doc.alloc_id(), "Links", LayerColor::Preset(1)); + let links_id = links.id; + doc.layers.push(Arc::new(links)); + let pic = image::RgbaImage::from_fn(3, 3, |x, y| image::Rgba([(x * 80) as u8, (y * 80) as u8, 30, 255])); + let mut link = vectorcraft_doc::LinkInfo::new("/Users/someone/Job (1)/art/pic.png"); + link.relative = Some("art/pic.png".into()); + let placed = image_node(&mut doc, ImageBlob::png(png_of(pic.into())), (3, 3), Affine::new([4.0, 1.0, -1.0, 4.0, 60.0, 50.0]), Some(link)); + doc.insert(Some(links_id), usize::MAX, placed).unwrap(); + doc +} + +/// Each image in `nodes` (opacity masks' art included), in order: where it is, its state, size, +/// placement, link and pixels (RGBA, or a CMYK image's ink amounts). +fn pictures(doc: &Document, nodes: &[Arc], path: &str, out: &mut Vec) { + for (i, n) in nodes.iter().enumerate() { + let at = format!("{path}/{i}"); + if let NodeKind::Image(im) = &n.kind { + let blob = doc.image_blob(im).unwrap(); + let pixels = match blob.cmyk() { + Some(inks) if blob.is_cmyk() => format!("cmyk {:?}", inks.data), + _ => format!("rgba {:?}", image::load_from_memory(&blob.bytes).unwrap().to_rgba8().into_raw()), + }; + let xf: Vec = im.xf.as_coeffs().iter().map(|v| r3(*v)).collect(); + let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone())); + out.push(format!( + "{at} {:?} shown={} locked={} opacity={} {:?} {}x{} [{}] {link:?} {pixels}", + n.name, + n.visible, + n.locked, + r3(f64::from(n.opacity)), + n.blend, + im.width, + im.height, + xf.join(" ") + )); + } + if let Some(m) = &n.extras().mask { + pictures(doc, std::slice::from_ref(&m.art), &format!("{at}/mask"), out); + } + if let Some(c) = n.children() { + pictures(doc, c, &at, out); + } + } +} + +fn images_of(doc: &Document) -> Vec { + let mut out = vec![]; + pictures(doc, &doc.layers, "", &mut out); + out +} + +#[test] +fn images_come_back_with_their_pixels_and_places() { + let doc = images_doc(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + let want = images_of(&doc); + let got = images_of(&back); + assert_eq!(want.len(), 7); + for (g, w) in got.iter().zip(&want) { + assert_eq!(g, w); + } + assert_eq!(got.len(), want.len(), "{got:?}"); + // The clipping group and the masked square are there as themselves. + assert_eq!(lines(&back).len(), lines(&doc).len(), "{:?}", lines(&back)); +} + +/// An image whose opacity defines the knockout shape comes back with it, embedded or linked. The +/// image after it and their layer do not take it. +#[test] +fn an_images_knockout_shape_comes_back() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let at = |x: f64| Affine::new([10.0, 0.0, 0.0, 10.0, x, 10.0]); + let mut shaped = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), at(10.0), None); + (shaped.opacity, shaped.knockout_shape) = (0.5, true); + doc.insert(Some(layer), usize::MAX, shaped).unwrap(); + let plain = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), at(50.0), None); + doc.insert(Some(layer), usize::MAX, plain).unwrap(); + let mut link = vectorcraft_doc::LinkInfo::new("/Users/someone/Job/art/pic.png"); + link.relative = Some("art/pic.png".into()); + let mut linked = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), at(90.0), Some(link)); + linked.knockout_shape = true; + doc.insert(Some(layer), usize::MAX, linked).unwrap(); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + let got: Vec<_> = art.iter().map(|n| (matches!(n.kind, NodeKind::Image(_)), n.opacity, n.knockout_shape)).collect(); + assert_eq!(got, [(true, 0.5, true), (true, 1.0, false), (true, 1.0, true)]); + assert_eq!((back.layers[0].opacity, back.layers[0].knockout_shape), (1.0, false)); +} + +#[test] +fn images_are_written_again_as_the_same_bytes() { + let mut doc = images_doc(); + // The default swatches' RGB colors come back a ten-thousandth off in their CMYK equivalents. + doc.swatches.retain(|s| matches!(s.paint, Paint::None)); + doc.swatches.push(Swatch { name: "Gold".into(), paint: solid(GOLD), global: false, spot: false }); + doc.swatch_groups = Default::default(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + let again = export_ai_editing(&read_back(&doc), &opts()).unwrap().program; + for (a, b) in shown(&again).lines().zip(shown(&first.program).lines()) { + assert_eq!(a, b); + } + assert_eq!(again, first.program); +} + +/// The program of `doc` with LF line ends, and each image's samples (from after `XI` and its line +/// end to `%%EndData`, a `%_` before it kept) and each preview's rows (from after `32 17 ` to the +/// line end before `%AI26_EndPlacedObjectPreview`) shown as ``. +fn program_shown(doc: &Document) -> String { + shown(&export_ai_editing(doc, &opts()).unwrap().program) +} + +/// Program `p` as [`program_shown`] shows it. +fn shown(p: &[u8]) -> String { + let find = |from: usize, what: &[u8]| p.get(from..).and_then(|r| r.windows(what.len()).position(|w| w == what)).map(|i| i + from); + let mut out = Vec::new(); + let mut at = 0; + loop { + let xi = find(at, b"\r\nXI\r\n").map(|i| (i + 6, b"%%EndData".as_slice())); + let pv = find(at, b" 32 17 ").map(|i| (i + 7, b"\r\n%AI26_EndPlacedObjectPreview".as_slice())); + let Some((start, end)) = [xi, pv].into_iter().flatten().min_by_key(|(s, _)| *s) else { break }; + let mut stop = find(start, end).unwrap(); + if end.starts_with(b"%%") && p.get(stop - 2..stop) == Some(b"%_") { + stop -= 2; + } + out.extend_from_slice(&p[at..start]); + out.extend_from_slice(format!("<{} bytes>", stop - start).as_bytes()); + at = stop; + } + out.extend_from_slice(&p[at..]); + String::from_utf8(out).unwrap().replace("\r\n", "\n") +} + +#[test] +fn an_image_is_a_raster_with_binary_samples() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 30.0]), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let p = export_ai_editing(&doc, &opts()).unwrap().program; + // `XI`, CR LF and the 18 samples, which are counted, follow the count's line. + let at = p.windows(17).position(|w| w == b"%%BeginData: 22\r\n").unwrap(); + let samples: Vec = vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0, 0, 255, 255, 12, 34, 56]; + let mut want = b"XI\r\n".to_vec(); + want.extend_from_slice(&samples); + want.extend_from_slice(b"%%EndData\r\nXH\r\n%AI5_EndRaster\r\nN\r\n"); + assert_eq!(p.get(at + 17..at + 17 + want.len()), Some(want.as_slice())); + let text = program_shown(&doc); + // Art space is y up from the artboard's top-left corner, the pixels' rows run downwards. + assert!( + text.contains( + "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceRGB XN\n[10 0 0 10 20 -30] 3 2 0 Xh\n[10 0 0 10 20 -30] 0 0 3 2 3 2 8 3 0 1 1 0 4 4 0 0\n" + ), + "{text}" + ); +} + +#[test] +fn see_through_gray_and_cmyk_images_have_their_flags() { + let doc = images_doc(); + let text = program_shown(&doc); + // RGBA: the alpha channel follows the color samples, which the count doesn't take in. + assert!(text.contains(" 0 0 2 2 2 2 8 3 1 17 1 0 4 4 0 0\n%%BeginData: 16\nXI\n<16 bytes>%%EndData\n"), "{text}"); + assert!(text.contains("/DeviceGray XN\n"), "{text}"); + assert!(text.contains(" 0 0 4 1 4 1 8 1 0 0 1 0 4 4 0 0\n"), "{text}"); + assert!(text.contains("/DeviceCMYK XN\n"), "{text}"); + assert!(text.contains(" 0 0 2 1 2 1 8 4 0 2 1 0 4 4 0 0\n%%BeginData: 12\nXI\n<8 bytes>%%EndData\n"), "{text}"); + // In an opacity mask: on `%_` lines but for `XI` and its samples. + assert!(text.contains("%_%%BeginData: 13\nXI\n<9 bytes>%_%%EndData\n%_XH\n%_%AI5_EndRaster\n%_N\n"), "{text}"); +} + +#[test] +fn a_linked_image_is_a_placed_file_with_a_preview() { + let doc = images_doc(); + let text = program_shown(&doc); + let begin = text.find("%AI5_BeginPlace\n").unwrap(); + let place = &text[begin..text[begin..].find("%AI5_EndPlace\n").unwrap() + begin]; + let lines: Vec<&str> = place.lines().collect(); + assert_eq!(lines[1], "%%FileType: 1"); + assert!(lines[2].ends_with("] 8091 8141 8094 8144 4 4 0"), "{place}"); + assert_eq!(lines[3], "(/Users/someone/Job \\(1\\)/art/pic.png)`"); + assert_eq!(lines[4], "%%IncludeFile:/Users/someone/Job (1)/art/pic.png"); + assert_eq!( + &lines[5..10], + [ + "%AI17_Begin_Content_if_version_gt:24 12", + "%AI28_BeginPlacedRelativePath", + "(art/)", + "%AI28_EndPlacedRelativePath", + "%AI17_Alternate_Content" + ] + ); + assert_eq!(&lines[11..13], ["%AI17_Begin_Content_if_version_gt:24 5", "%AI26_BeginPlacedObjectPreview"]); + // 3 × 3 pixels of premultiplied ARGB. + assert_eq!(lines[13], "3 3 12 32 17 <36 bytes>"); + assert_eq!(&lines[14..], ["%AI26_EndPlacedObjectPreview", "%AI17_End_Versioned_Content", "~"]); +} + +/// The relative folder goes with the path's file name, so a relative path to a file of another +/// name isn't written. +#[test] +fn a_relative_path_to_a_file_of_another_name_is_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut link = vectorcraft_doc::LinkInfo::new("/old/original.png"); + link.relative = Some("assets/current.png".into()); + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), Some(link)); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + assert!(!program_shown(&doc).contains("%AI28_BeginPlacedRelativePath")); + let back = read_back(&doc); + let NodeKind::Image(im) = &back.layers[0].children().unwrap()[0].kind else { panic!("not an image") }; + let link = im.link.as_ref().unwrap(); + assert_eq!((link.path.as_str(), link.relative.as_deref()), ("/old/original.png", None)); + // Names that differ only in letter case keep the folder where file names ignore case. + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut link = vectorcraft_doc::LinkInfo::new("C:\\Job\\art\\PHOTO.PNG"); + link.relative = Some("art/photo.png".into()); + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), Some(link)); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let kept = program_shown(&doc).contains("%AI28_BeginPlacedRelativePath\n(art/)\n"); + assert_eq!(kept, cfg!(any(windows, target_os = "macos"))); + // A relative path with `\` separators keeps its folder. + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut link = vectorcraft_doc::LinkInfo::new("C:\\Job\\art\\photo.png"); + link.relative = Some("art\\photo.png".into()); + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), Some(link)); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + assert!(program_shown(&doc).contains("%AI28_BeginPlacedRelativePath\n(art/)\n")); +} + +#[test] +fn a_large_linked_image_has_a_smaller_preview_over_its_pixels() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let big = image::RgbaImage::from_fn(1024, 512, |x, y| image::Rgba([(x / 4) as u8, (y / 2) as u8, 0, 255])); + let xf = Affine::new([0.1, 0.0, 0.0, 0.1, 20.0, 30.0]); + let im = image_node(&mut doc, ImageBlob::png(png_of(big.into())), (1024, 512), xf, Some(vectorcraft_doc::LinkInfo::new("/tmp/big.png"))); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + assert!(program_shown(&doc).contains("\n256 128 1024 32 17 <131072 bytes>\n")); + let back = read_back(&doc); + let NodeKind::Image(im) = &back.layers[0].children().unwrap()[0].kind else { panic!("not an image") }; + assert_eq!((im.width, im.height), (256, 128)); + let bounds = im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, 256.0, 128.0)); + assert_eq!((r3(bounds.x0), r3(bounds.y0), r3(bounds.x1), r3(bounds.y1)), (r3(20.0), r3(30.0), r3(122.4), r3(81.2))); + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some("/tmp/big.png")); +} + +/// Samples that hold the bytes of `%%EndData` without a line end after them are read whole. +#[test] +fn samples_holding_the_end_marker_are_read_whole() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + // The color samples end `%%En` and the alpha channel starts `dData`. + let rgb = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, b'%'], *b"%En"]; + let alpha = *b"dData"; + let img = image::RgbaImage::from_fn(5, 1, |x, _| { + let [r, g, b] = rgb[x as usize]; + image::Rgba([r, g, b, alpha[x as usize]]) + }); + let im = image_node(&mut doc, ImageBlob::png(png_of(img.into())), (5, 1), Affine::scale(10.0), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + // The alpha channel holds the marker, a line end and the operator that follows the samples. + let alpha = *b"%%EndData\r\nXH\r\nZZ"; + let img = image::RgbaImage::from_fn(17, 1, |x, _| image::Rgba([x as u8, 9, 9, alpha[x as usize]])); + let marked = ImageBlob::png(png_of(img.into())); + let im = image_node(&mut doc, marked.clone(), (17, 1), Affine::translate((0.0, 20.0)), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + // The same image as an opacity mask's art, on `%_` lines. + let art = image_node(&mut doc, marked, (17, 1), Affine::translate((0.0, 40.0)), None); + let mut square = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 40.0, 17.0, 41.0)), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); + square.extras_mut().mask = Some(Box::new(OpacityMask::new(Node::group(doc.alloc_id(), vec![Arc::new(art)]), false))); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let back = read_back(&doc); + assert_eq!(images_of(&back), images_of(&doc)); +} + +/// A preview scaled down mixes no color from pixels that don't show. +#[test] +fn a_smaller_preview_takes_no_color_from_see_through_pixels() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let half = image::RgbaImage::from_fn(511, 3, |x, _| if x % 2 == 0 { image::Rgba([255, 0, 0, 0]) } else { image::Rgba([0, 0, 255, 255]) }); + let im = image_node( + &mut doc, + ImageBlob::png(png_of(half.into())), + (511, 3), + Affine::scale(0.2), + Some(vectorcraft_doc::LinkInfo::new("/tmp/half.png")), + ); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let back = read_back(&doc); + let NodeKind::Image(im) = &back.layers[0].children().unwrap()[0].kind else { panic!("not an image") }; + assert_eq!(im.width, 256); + let px = image::load_from_memory(&back.image_blob(im).unwrap().bytes).unwrap().to_rgba8(); + assert!(px.pixels().all(|p| p.0[0] == 0), "{:?}", px.pixels().take(4).collect::>()); + assert!(px.pixels().filter(|p| p.0[3] > 0).count() > 400); +} + +#[test] +fn linked_images_in_masks_and_tiles_are_embedded() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let link = Some(vectorcraft_doc::LinkInfo::new("/tmp/ramp.png")); + let art = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), link); + let mut square = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 20.0)), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); + square.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::LINKS_EMBEDDED]); + let text = program_shown(&doc); + assert!(!text.contains("BeginPlace") && text.contains("%_%AI5_BeginRaster"), "{text}"); +} + +/// An image in an opacity mask's art inside a pattern's tile is hidden once: its samples end +/// `%_%%EndData`. +#[test] +fn an_image_in_a_mask_in_a_pattern_tile_ends_its_samples_once() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let art = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), None); + let mut square = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 20.0)), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); + square.extras_mut().mask = Some(Box::new(OpacityMask::new(Node::group(doc.alloc_id(), vec![Arc::new(art)]), false))); + doc.patterns.push(vectorcraft_doc::PatternDef::new("Masked", vec![Arc::new(square)])); + let filled = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(40.0, 40.0, 100.0, 80.0)), + Appearance::basic(Paint::Pattern { pattern: "Masked".into(), xf: Affine::IDENTITY }, Paint::None, 0.0), + ); + doc.insert(Some(layer), usize::MAX, filled).unwrap(); + let text = program_shown(&doc); + assert!(text.contains("XI\n<18 bytes>%_%%EndData\n%_XH\n"), "{text}"); + assert!(!text.contains("%_%_%%EndData"), "{text}"); +} + +#[test] +fn an_image_in_art_cut_to_a_clipping_object_is_clipped_by_that_region() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + // Type clips: its art is cut to the glyphs' region, which can't cut an image. + let ring = Node::new( + doc.alloc_id(), + NodeKind::Compound { + children: vec![ + Arc::new(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), Appearance::default())), + Arc::new(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), Appearance::default())), + ], + rule: FillRule::EvenOdd, + }, + ); + let ring = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(ring)], clip: false }); + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(20.0), None); + let group = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(ring), Arc::new(im)], clip: true }); + doc.insert(Some(layer), usize::MAX, group).unwrap(); + let back = read_back(&doc); + let mut found = vec![]; + pictures(&back, &back.layers, "", &mut found); + assert_eq!(found.len(), 1, "{:?}", lines(&back)); + let text = program_shown(&doc); + let at = text.find("%AI5_EndRaster\nN\n").unwrap(); + assert!(text[at..].contains("h\nW\nn\n") && text[..at].contains("q\n"), "{text}"); + // The ring's two subpaths clip as one compound path, not as one cut by the other. + let tail = &text[at..]; + assert!(tail.contains("0 XR\n*u\n") && tail.contains("h\nW\nn\n*U\n"), "{text}"); + fn clipping(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + if let NodeKind::Group { children, clip: true } = &n.kind { + out.extend(children.first().map(|c| match &c.kind { + NodeKind::Path { path, .. } => path.subpaths.len(), + NodeKind::Compound { children, .. } => children.len(), + _ => 0, + })); + } + clipping(n.children().map(Vec::as_slice).unwrap_or_default(), out); + } + } + let mut subpaths = vec![]; + clipping(&back.layers, &mut subpaths); + assert_eq!(subpaths, [2], "{:?}", lines(&back)); +} + +/// Art cut to a region with nothing left in it (two clipping objects that don't overlap) leaves the +/// image out. +#[test] +fn an_image_cut_to_nothing_is_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let boxed = |doc: &mut Document, r: Rect| { + let p = Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::default()); + Arc::new(Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(p)], clip: false })) + }; + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(20.0), None); + let far = boxed(&mut doc, Rect::new(50.0, 0.0, 60.0, 10.0)); + let inner = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![far, Arc::new(im)], clip: true }); + let near = boxed(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0)); + let outer = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![near, Arc::new(inner)], clip: true }); + doc.insert(Some(layer), usize::MAX, outer).unwrap(); + assert!(!program_shown(&doc).contains("%AI5_BeginRaster")); +} + +#[test] +fn images_that_cant_be_decoded_are_mid_gray_boxes() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let im = image_node(&mut doc, ImageBlob::png(b"not an image".to_vec()), (2, 1), Affine::scale(10.0), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::IMAGES]); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + assert_eq!(paint(n.appearance.items[0].paint()), paint(&solid(Color::gray(0.5)))); +} + +#[test] +fn sixteen_bit_images_are_written_at_eight_bits() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let deep = image::ImageBuffer::, Vec>::from_fn(2, 1, |x, _| image::Rgb([65535 * x as u16, 257 * 10, 0])); + let im = image_node(&mut doc, ImageBlob::png(png_of(image::DynamicImage::ImageRgb16(deep))), (2, 1), Affine::scale(10.0), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::IMAGE_DEPTH]); + let back = read_back(&doc); + let mut found = vec![]; + pictures(&back, &back.layers, "", &mut found); + assert!(found[0].ends_with("rgba [0, 10, 0, 255, 255, 10, 0, 255]"), "{found:?}"); +} + +/// A little-endian, uncompressed CMYK TIFF of 16 bits a sample, `w` × 1 pixels, each pixel's inks +/// `inks[x]`. +fn cmyk16_tiff(inks: &[[u16; 4]]) -> Vec { + let w = inks.len() as u32; + let data: Vec = inks.iter().flatten().flat_map(|v| v.to_le_bytes()).collect(); + // Tags: width, height, bits (an offset), compression, photometric, strip offset, samples, rows, + // strip bytes, planar configuration. + let bits_at = 8 + 2 + 12 * 10 + 4; + let data_at = bits_at + 8; + let entries: [(u16, u16, u32, u32); 10] = [ + (256, 4, 1, w), + (257, 4, 1, 1), + (258, 3, 4, bits_at), + (259, 3, 1, 1), + (262, 3, 1, 5), + (273, 4, 1, data_at), + (277, 3, 1, 4), + (278, 4, 1, 1), + (279, 4, 1, data.len() as u32), + (284, 3, 1, 1), + ]; + let mut out = b"II*\0".to_vec(); + out.extend_from_slice(&8u32.to_le_bytes()); + out.extend_from_slice(&10u16.to_le_bytes()); + for (tag, kind, count, value) in entries { + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&kind.to_le_bytes()); + out.extend_from_slice(&count.to_le_bytes()); + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&0u32.to_le_bytes()); + for _ in 0..4 { + out.extend_from_slice(&16u16.to_le_bytes()); + } + out.extend_from_slice(&data); + out +} + +#[test] +fn sixteen_bit_cmyk_images_are_written_at_eight_bits() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let blob = ImageBlob::new("image/tiff", cmyk16_tiff(&[[65535, 0, 0, 0], [0, 0x8000, 0, 0x1234]])); + assert!(blob.is_cmyk() && blob.is_cmyk16()); + let im = image_node(&mut doc, blob, (2, 1), Affine::scale(10.0), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::IMAGE_DEPTH]); + assert!(program_shown(&doc).contains("/DeviceCMYK XN\n")); +} + +// ---------- type ---------- + +fn style(size: f64, fill: Color) -> vectorcraft_doc::CharStyle { + vectorcraft_doc::CharStyle { size, fill: solid(fill), ..vectorcraft_doc::CharStyle::default() } +} + +fn text_node(doc: &mut Document, t: vectorcraft_doc::TextObject) -> Node { + Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))) +} + +/// A 300 × 200 document of the type the slice writes as text, on a layer `Type`: two paragraphs +/// of point type (the second centered, with space before, a fixed leading) named `Greeting`; point +/// type turned 30° in CMYK; area type in two columns with a gutter and a first baseline at its +/// leading, its runs plain, then bold, tracked, shifted, scaled, stroked and in capitals, then a +/// right-to-left paragraph; type on an open curve from a tenth of its length; vertical point type; +/// hidden, locked point type at half opacity multiplied; and area type threaded through two frames. +fn typed() -> Document { + use vectorcraft_doc::{CharStyle, FirstBaseline, Justify, ParaDirection, ParaStyle, TextKind, TextObject, TextRun}; + use vectorcraft_geom::Point; + let mut doc = Document::new(300.0, 200.0); + // One CMYK swatch, not the default ones: their CMYK equivalents round differently once read back. + doc.swatches = vec![ + Swatch { name: "[None]".into(), paint: Paint::None, global: false, spot: false }, + Swatch { name: "Ink".into(), paint: solid(BRAND), global: false, spot: false }, + ] + .into(); + doc.swatch_groups = vec![].into(); + doc.layers.clear(); + let layer = doc.add_layer(Some("Type")); + + let mut greet = TextObject::point(Point::new(20.0, 40.0), "Hello\nWorld", CharStyle { leading: Some(30.0), ..style(24.0, SKY) }); + let centered = ParaStyle { justify: Justify::Center, space_before: 6.0, ..ParaStyle::default() }; + greet.set_paragraph_styles(vec![ParaStyle { first_line_indent: 10.0, ..ParaStyle::default() }, centered]); + let greet = named(text_node(&mut doc, greet), "Greeting"); + doc.insert(Some(layer), usize::MAX, greet).unwrap(); + + let mut turned = TextObject::point(Point::ZERO, "Turned", style(18.0, BRAND)); + turned.xf = Affine::translate((150.0, 100.0)) * Affine::rotate(-std::f64::consts::FRAC_PI_6); + let turned = text_node(&mut doc, turned); + doc.insert(Some(layer), usize::MAX, turned).unwrap(); + + let regular = style(10.0, Color::BLACK); + let bold = CharStyle { + font_style: "Bold".into(), + tracking: 50.0, + baseline_shift: 3.0, + h_scale: 120.0, + v_scale: 90.0, + stroke: solid(Color::rgb(0.0, 0.5, 0.0)), + stroke_width: 0.5, + all_caps: true, + ..regular.clone() + }; + let mut area = TextObject::point(Point::ZERO, "", regular.clone()); + area.runs = vec![ + TextRun::new("Area type flows in two columns ", regular.clone()), + TextRun::new("and wraps", bold), + TextRun::new(" onto the next line.\nRight to left", regular.clone()), + ]; + area.set_paragraph_styles(vec![ + ParaStyle { left_indent: 4.0, right_indent: 2.0, space_after: 3.0, hyphenate: false, ..ParaStyle::default() }, + ParaStyle { direction: Some(ParaDirection::RightToLeft), justify: Justify::JustifyAll, ..ParaStyle::default() }, + ]); + area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(20.0, 80.0, 140.0, 160.0)) }; + area.xf = Affine::IDENTITY; + area.area.columns = 2; + area.area.gutter = 12.0; + area.area.first_baseline = FirstBaseline::Leading; + area.area.first_baseline_min = 4.0; + let area = text_node(&mut doc, area); + doc.insert(Some(layer), usize::MAX, area).unwrap(); + + let mut on_path = TextObject::point(Point::ZERO, "On a curve", style(12.0, Color::gray(0.6))); + let mut curve = PathData::from_bezpath(&kurbo::BezPath::from_vec(vec![ + kurbo::PathEl::MoveTo((160.0, 150.0).into()), + kurbo::PathEl::CurveTo((190.0, 110.0).into(), (250.0, 110.0).into(), (280.0, 150.0).into()), + ])); + curve.subpaths.iter_mut().for_each(|sp| sp.closed = false); + on_path.kind = TextKind::OnPath { path: curve, start: 0.1, end: None }; + on_path.xf = Affine::IDENTITY; + let on_path = text_node(&mut doc, on_path); + doc.insert(Some(layer), usize::MAX, on_path).unwrap(); + + let mut down = TextObject::point(Point::new(280.0, 20.0), "Down", style(14.0, Color::BLACK)); + down.vertical = true; + let down = text_node(&mut doc, down); + doc.insert(Some(layer), usize::MAX, down).unwrap(); + + let quiet = TextObject::point(Point::new(20.0, 190.0), "Quiet", style(9.0, Color::BLACK)); + let mut quiet = see_through(text_node(&mut doc, quiet), 0.5, BlendMode::Multiply); + quiet.visible = false; + quiet.locked = true; + doc.insert(Some(layer), usize::MAX, quiet).unwrap(); + + let mut first = TextObject::point(Point::ZERO, "A story that runs from one frame into the next one.", regular.clone()); + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(160.0, 20.0, 220.0, 40.0)) }; + first.xf = Affine::IDENTITY; + let mut second = first.clone(); + second.runs = vec![TextRun::new("", regular)]; + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(160.0, 50.0, 220.0, 90.0)) }; + let (first, second) = (text_node(&mut doc, first), text_node(&mut doc, second)); + doc.text_threads.push(vec![first.id, second.id]); + doc.insert(Some(layer), usize::MAX, first).unwrap(); + doc.insert(Some(layer), usize::MAX, second).unwrap(); + doc +} + +/// What the reader's view of type is made of, one line per text object: its name, state, +/// transparency, kind and frame, matrix, orientation, area options and path span; each paragraph's +/// attributes; each run's characters and attributes. Lengths to three decimals. +fn type_lines(doc: &Document) -> Vec { + use vectorcraft_doc::TextKind; + let mut out = vec![]; + let mut all = vec![]; + paths(&doc.layers, &mut all); + for n in all { + let NodeKind::Text(t) = &n.kind else { + out.push(format!("not type: {:?}", n.name)); + continue; + }; + let pts = |p: &PathData| { + p.subpaths + .iter() + .map(|sp| { + format!("[{} {}]", sp.closed, sp.anchors.iter().map(|a| format!("{},{}", r3(a.p.x), r3(a.p.y))).collect::>().join(" ")) + }) + .collect::() + }; + let kind = match &t.kind { + TextKind::Point => "point".to_string(), + TextKind::Area { frame } => format!("area {}", pts(frame)), + TextKind::OnPath { path, start, end } => format!("path {} {} {:?}", pts(path), r3(*start), end.map(r3)), + }; + let a = &t.area; + out.push(format!( + "{:?} shown={} locked={} {} {:?} {kind} xf={:?} vertical={} area {} {} {} {:?} {:?} {}", + n.name, + n.visible, + n.locked, + r3(f64::from(n.opacity)), + n.blend, + t.xf.as_coeffs().map(r3), + t.vertical, + a.rows, + a.columns, + r3(a.gutter), + a.row_gutter.map(r3), + a.first_baseline, + r3(a.first_baseline_min), + )); + for p in t.paragraph_styles() { + out.push(format!( + " para {:?} {} {} {} {} {} {} {:?}", + p.justify, + r3(p.first_line_indent), + r3(p.left_indent), + r3(p.right_indent), + r3(p.space_before), + r3(p.space_after), + p.hyphenate, + p.direction + )); + } + for r in &t.runs { + let s = &r.style; + out.push(format!( + " run {:?} {} {} {} {:?} {} {} {} {} fill {} stroke {} {} caps={} small={:?} tcy={} roman={}", + r.text, + s.font_family, + s.font_style, + r3(s.size), + s.leading.map(r3), + r3(s.tracking), + r3(s.baseline_shift), + r3(s.h_scale), + r3(s.v_scale), + paint(&s.fill), + paint(&s.stroke), + r3(s.stroke_width), + s.all_caps, + s.small_caps.map(r3), + s.tate_chu_yoko, + s.standard_vertical_roman, + )); + } + } + out +} + +// ---------- symbols ---------- + +const LEAF: Color = Color::Cmyk { c: 0.6, m: 0.0, y: 0.9, k: 0.1 }; + +fn instance(doc: &mut Document, symbol: &str, xf: Affine) -> Node { + Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf }) +} + +/// A `w` × `h` document whose swatches are one CMYK color (the default swatches' CMYK equivalents +/// change at the fourth decimal when read back, so a second write would differ there). +fn one_swatch_document(w: f64, h: f64) -> Document { + let mut doc = Document::new(w, h); + doc.swatches = vec![Swatch { name: "Leaf".into(), paint: solid(LEAF), global: false, spot: false }].into(); + doc.swatch_groups = vec![].into(); + doc +} + +/// A 300 × 200 document of symbols. Its symbols, in the Symbols panel's order: `Spare`, a path no +/// instance uses; `Pair`, a group of a red square and an instance of `Leaf` at half its size; `Leaf`, +/// a group of a square in `LEAF` and an ellipse, its registration point the top left; `Shade`, a +/// group of a rectangle filled with a gradient, a clipping group and an image, its registration +/// point the bottom right; `Solo`, a group of one square, which no instance uses. Layer `Art` +/// holds, bottom first: `Leaf` moved; `Leaf` turned 30° and scaled 1.5 by 0.5, named `Turned`; a +/// hidden one; a locked one; one at 50% in Multiply; `Pair`; a group holding `Leaf`; a clipping +/// group holding `Leaf`; `Leaf` with an opacity mask whose art holds an instance of `Leaf`; `Shade`; +/// and sublayer `Inner` (60%, Screen), which holds `Pair` mirrored. +fn symbols_document() -> Document { + use vectorcraft_color::gradient::GradientGeom; + let mut doc = Document::new(300.0, 200.0); + doc.swatches = vec![Swatch { name: "Leaf".into(), paint: solid(LEAF), global: false, spot: false }].into(); + doc.swatch_groups = vec![].into(); + doc.layers.clear(); + let art_layer = doc.add_layer(Some("Art")); + // The symbols. + let spare = square(&mut doc, Rect::new(-5.0, -5.0, 5.0, 5.0), Color::gray(0.4)); + let leaf_square = square(&mut doc, Rect::new(0.0, 0.0, 20.0, 20.0), LEAF); + let ellipse = + Node::path(doc.alloc_id(), shapes::ellipse(Rect::new(5.0, 10.0, 25.0, 30.0)), Appearance::basic(Paint::None, solid(Color::BLACK), 1.5)); + let leaf = group(&mut doc, vec![leaf_square, ellipse], false); + let red = square(&mut doc, Rect::new(-10.0, -10.0, 10.0, 10.0), Color::rgb(1.0, 0.0, 0.0)); + let small = instance(&mut doc, "Leaf", Affine::translate((15.0, -5.0)) * Affine::scale(0.5)); + let pair = group(&mut doc, vec![red, small], false); + let geom = GradientGeom { start: (0.0, 0.0).into(), end: (40.0, 10.0).into(), aspect: 1.0, focal: None }; + let shaded = painted( + &mut doc, + shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 20.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(sunset(), Some(geom), None)))], + ); + let edge = clipping(&mut doc, shapes::ellipse(Rect::new(0.0, 20.0, 20.0, 40.0))); + let inside = square(&mut doc, Rect::new(0.0, 25.0, 40.0, 35.0), Color::rgb(0.0, 0.0, 1.0)); + let clipped = group(&mut doc, vec![edge, inside], true); + let pixels = png_of(image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 128, 255, 255]).unwrap())); + let picture = image_node(&mut doc, ImageBlob::new("image/png", pixels), (2, 1), Affine::new([10.0, 0.0, 0.0, 10.0, 25.0, 25.0]), None); + let shade = group(&mut doc, vec![shaded, clipped, picture], false); + let lone = square(&mut doc, Rect::new(0.0, 0.0, 8.0, 8.0), Color::gray(0.2)); + let solo = group(&mut doc, vec![lone], false); + for (name, art) in [("Spare", spare), ("Pair", pair), ("Leaf", leaf), ("Shade", shade), ("Solo", solo)] { + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + doc.set_symbol_registration("Leaf", vectorcraft_doc::SymbolRegistration(0)); + doc.set_symbol_registration("Shade", vectorcraft_doc::SymbolRegistration(8)); + // The instances. + let mut art = vec![instance(&mut doc, "Leaf", Affine::translate((10.0, 10.0)))]; + let turned = Affine::translate((80.0, 20.0)) * Affine::rotate(30f64.to_radians()) * Affine::scale_non_uniform(1.5, 0.5); + art.push(named(instance(&mut doc, "Leaf", turned), "Turned")); + let mut hidden = instance(&mut doc, "Leaf", Affine::translate((130.0, 10.0))); + hidden.visible = false; + art.push(hidden); + let mut locked = instance(&mut doc, "Leaf", Affine::translate((160.0, 10.0))); + locked.locked = true; + art.push(locked); + art.push(see_through(instance(&mut doc, "Leaf", Affine::translate((190.0, 10.0))), 0.5, BlendMode::Multiply)); + art.push(instance(&mut doc, "Pair", Affine::translate((240.0, 30.0)))); + let grouped = instance(&mut doc, "Leaf", Affine::translate((10.0, 60.0))); + art.push(group(&mut doc, vec![grouped], false)); + let window = clipping(&mut doc, shapes::rectangle(Rect::new(50.0, 60.0, 65.0, 75.0))); + let clipped = instance(&mut doc, "Leaf", Affine::translate((50.0, 60.0))); + art.push(group(&mut doc, vec![window, clipped], true)); + let mask_leaf = instance(&mut doc, "Leaf", Affine::translate((90.0, 60.0))); + let mask_art = group(&mut doc, vec![mask_leaf], false); + let mut masked = instance(&mut doc, "Leaf", Affine::translate((90.0, 60.0))); + masked.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(mask_art), clip: true, invert: false, disabled: false, linked: true })); + art.push(masked); + art.push(instance(&mut doc, "Shade", Affine::translate((130.0, 60.0)))); + for n in art { + doc.insert(Some(art_layer), usize::MAX, n).unwrap(); + } + let inner = doc.add_layer(Some("Inner")); + let inner_node = doc.layers.iter().position(|l| l.id == inner).map(|i| doc.layers.remove(i)).unwrap(); + doc.insert(Some(art_layer), usize::MAX, (*inner_node).clone()).unwrap(); + let mirrored = instance(&mut doc, "Pair", Affine::new([-1.0, 0.0, 0.0, 1.0, 260.0, 120.0])); + doc.insert(Some(inner), usize::MAX, mirrored).unwrap(); + // The sublayer's own transparency, after its last object, an instance. + let sub = doc.node_mut(inner).unwrap(); + (sub.opacity, sub.blend) = (0.6, BlendMode::Screen); + doc +} + +/// Each symbol of `doc` in its order: its name and registration point, then what its art draws, its +/// objects as [`view`] shows them (points, handles, paint, strokes and instances), its images, and +/// its objects' names, transparency and clipping. +fn symbol_looks(doc: &Document) -> Vec { + let mut out = vec![]; + for s in doc.symbols.iter() { + out.push(format!("symbol {} {:?}", s.name, doc.symbol_registration(&s.name))); + let art = std::slice::from_ref(&s.art); + paints_of(doc, art, 1, &mut out); + let mut objects = vec![]; + view(art, 1, &mut objects); + // Images are compared by `pictures`, gradients by `paints_of`. + out.extend(objects.into_iter().filter(|l| !l.contains(" Image(")).map(|l| match l.find(" fill(Gradient(") { + Some(at) => format!("{} fill(gradient)", &l[..at]), + None => l, + })); + pictures(doc, art, &s.name, &mut out); + looks(art, 1, &mut out); + } + out +} + +#[test] +fn type_comes_back_as_type() { + let doc = typed(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + same_lines(&type_lines(&back), &type_lines(&doc)); + assert_eq!(back.text_threads.len(), 1, "the thread comes back"); +} + +#[test] +fn type_is_written_again_as_the_same_bytes() { + let doc = typed(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + let again = export_ai_editing(&read_back(&doc), &opts()).unwrap(); + let text = |p: &[u8]| text_document(&String::from_utf8_lossy(p).replace("\r\n", "\n")); + assert_eq!(text(&again.program), text(&first.program)); + assert_eq!(String::from_utf8_lossy(&again.program), String::from_utf8_lossy(&first.program)); +} + +/// Standard Vertical Roman Alignment comes back on or off, in vertical type and in horizontal +/// type, and Tate-chu-yoko stays as it was: each run's key 35 is 1 (Standard) when it's on, 2 +/// (rotated) when it's off and 3 for Tate-chu-yoko, and the document's defaults and the normal +/// character style carry 1. Each object lays out as it did. A Tate-chu-yoko run with the +/// setting on comes back without it, and that is reported. +#[test] +fn standard_vertical_roman_alignment_comes_back() { + use vectorcraft_doc::{CharStyle, TextObject, TextRun}; + let plain = style(14.0, Color::BLACK); + let roman = CharStyle { standard_vertical_roman: true, ..plain.clone() }; + let tcy = CharStyle { tate_chu_yoko: true, ..plain.clone() }; + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers[0].id; + let mut down = TextObject::point(vectorcraft_geom::Point::new(150.0, 20.0), "", plain.clone()); + down.runs = vec![TextRun::new("Up AB ", roman.clone()), TextRun::new("turned CD ", plain.clone()), TextRun::new("12", tcy.clone())]; + down.vertical = true; + let mut across = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "", plain.clone()); + across.runs = vec![TextRun::new("Marked ", roman.clone()), TextRun::new("plain", plain.clone())]; + for t in [down, across] { + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + same_lines(&type_lines(&back), &type_lines(&doc)); + let texts = |d: &Document| -> Vec { + d.layers[0].children().unwrap().iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect() + }; + let flags = |t: &TextObject| t.runs.iter().map(|r| (r.style.standard_vertical_roman, r.style.tate_chu_yoko)).collect::>(); + let (written, read) = (texts(&doc), texts(&back)); + assert_eq!(read.iter().map(flags).collect::>(), [vec![(true, false), (false, false), (false, true)], vec![(true, false), (false, false)]]); + let origins = |t: &TextObject| { + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.iter().map(|g| (r3(g.origin.x), r3(g.origin.y))).collect::>() + }; + for (w, r) in written.iter().zip(&read) { + assert_eq!(origins(r), origins(w), "vertical={}", w.vertical); + } + let decoded = text_document(&program(&doc)); + // Two runs on, two off and one Tate-chu-yoko; the defaults and the normal style add a 1 each. + for (key, count) in [("/35 1 ", 4), ("/35 2 ", 2), ("/35 3 ", 1)] { + assert_eq!(decoded.matches(key).count(), count, "{key}: {decoded}"); + } + let normal = decoded.find("[Normal Character Style]").unwrap(); + let sheet = &decoded[normal..decoded.find("[Normal Paragraph Style]").unwrap()]; + assert!(sheet.contains("/35 1 "), "{sheet}"); + // Key 35 holds one value: Tate-chu-yoko wins, and the setting it leaves out is reported. + let mut both = doc.clone(); + let id = both.layers[0].children().unwrap()[0].id; + if let Some(NodeKind::Text(t)) = both.node_mut(id).map(|n| &mut n.kind) { + t.runs[2].style.standard_vertical_roman = true; + } + assert_eq!(export_ai_editing(&both, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]); + assert_eq!(flags(&texts(&read_back(&both))[0])[2], (false, true)); +} + +/// The text document of program `text` (LF line ends), decoded, with its UTF-16 strings' zero +/// bytes left out. +fn text_document(text: &str) -> String { + let Some(start) = text.find("%AI11_BeginTextDocument\n") else { return String::new() }; + let end = text.find("%AI11_EndTextDocument").unwrap(); + let packed: String = text[start..end].lines().skip(2).filter(|l| *l != ";").map(|l| l.strip_prefix('%').unwrap_or(l)).collect(); + String::from_utf8_lossy(&crate::ps::ascii85_decode(&packed).unwrap()).replace('\0', "") +} + +/// The text document: its section after the document data, ASCII85 on comment lines none of which +/// is a `%_` line; a stub for each text object, area type and type on a path with their paths. +#[test] +fn type_is_a_text_document_and_stubs() { + let text = program(&typed()); + let doc_data = text.find("%AI9_EndDocumentData").unwrap(); + let start = text.find("%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n").unwrap(); + let end = text.find(";\n%AI11_EndTextDocument\n%%EndSetup\n").unwrap(); + assert!(doc_data < start && start < end); + let body = &text[start..end]; + for l in body.lines().skip(2) { + assert!(l.starts_with('%') && !l.starts_with("%_"), "{l}"); + } + assert_eq!(text.matches("/AI11Text :\n0 /FreeUndo ,\n").count(), 8); + assert_eq!(text.matches("; /ConfiningPath ,\n").count(), 4); + assert!(text.contains("0 /FrameIndex ,\n6 /StoryIndex ,") && text.contains("1 /FrameIndex ,\n6 /StoryIndex ,"), "{text}"); + // The decoded document: the version, a font of each face and the hidden characters' font, the + // stories, the normal sheets and the document's text settings. + let decoded = text_document(&text); + assert!(decoded.starts_with("/98 << /0 14 >> /0 <<"), "{decoded}"); + for want in + ["SourceSans3-Regular", "SourceSans3-Bold", "AdobeInvisFont", "[Normal Character Style]", "[Normal Paragraph Style]", "Hello\rWorld\r"] + { + assert!(decoded.contains(want), "{want}: {decoded}"); + } + // Tracking is a whole number, and colors are simple paints. + assert!(decoded.contains("/8 50 ") && !decoded.contains("/8 50."), "{decoded}"); + assert!(decoded.contains("/53 << /99 /SimplePaint") && !decoded.contains("CAITextPaint"), "{decoded}"); +} + +/// Point type scaled 150% comes back at its size: its scale is in its sizes, its matrix only turns +/// it. Type that ends in an empty paragraph keeps it. +#[test] +fn scaled_point_type_and_a_last_empty_paragraph_come_back() { + use vectorcraft_doc::{CharStyle, ParaStyle, TextObject}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut big = TextObject::point(vectorcraft_geom::Point::ZERO, "Big", CharStyle { leading: Some(20.0), ..style(12.0, Color::BLACK) }); + big.xf = Affine::translate((20.0, 40.0)) * Affine::rotate(0.3) * Affine::scale(1.5); + big.set_all_paras(ParaStyle { left_indent: 4.0, ..ParaStyle::default() }); + let ends = TextObject::point(vectorcraft_geom::Point::new(20.0, 80.0), "Ends\n", style(12.0, Color::BLACK)); + let (big, ends) = (text_node(&mut doc, big), text_node(&mut doc, ends)); + doc.insert(Some(layer), usize::MAX, big).unwrap(); + doc.insert(Some(layer), usize::MAX, ends).unwrap(); + let back = read_back(&doc); + let texts: Vec<&vectorcraft_doc::TextObject> = + back.layers[0].children().unwrap().iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(t.as_ref()) } else { None }).collect(); + let [big, ends] = texts.as_slice() else { panic!("two text objects: {texts:?}") }; + let s = big.xf.determinant().sqrt(); + let st = &big.runs[0].style; + assert_eq!((r3(s), r3(st.size), st.leading.map(r3), r3(big.para.left_indent)), (r3(1.0), r3(18.0), Some(r3(30.0)), r3(6.0))); + assert_eq!(big.xf.as_coeffs().map(r3), (Affine::translate((20.0, 40.0)) * Affine::rotate(0.3)).as_coeffs().map(r3)); + assert_eq!(ends.plain_text(), "Ends\n"); + // A tiny size, and a stroke of no width that keeps its paint. + let mut d = Document::new(200.0, 100.0); + let layer = d.layers[0].id; + let st = CharStyle { stroke: solid(Color::rgb(1.0, 0.0, 0.0)), stroke_width: 0.0, ..style(0.00001, Color::BLACK) }; + let n = text_node(&mut d, TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "Tiny", st)); + d.insert(Some(layer), usize::MAX, n).unwrap(); + let back = read_back(&d); + let NodeKind::Text(t) = &back.layers[0].children().unwrap()[0].kind else { panic!("type") }; + let s = &t.runs[0].style; + assert_eq!( + (format!("{:.6}", s.size), paint(&s.stroke), r3(s.stroke_width)), + ("0.000010".into(), paint(&solid(Color::rgb(1.0, 0.0, 0.0))), r3(0.0)) + ); +} + +/// A threaded story whose frames each hold their slice of it, a paragraph split between them, +/// comes back as one story in its first frame with each paragraph's attributes once. +#[test] +fn a_story_split_between_frames_comes_back_whole() { + use vectorcraft_doc::{Justify, ParaStyle, TextKind, TextObject, TextRun}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let st = style(10.0, Color::BLACK); + let (p1, p2, p3) = ( + ParaStyle { justify: Justify::Center, ..ParaStyle::default() }, + ParaStyle { left_indent: 5.0, ..ParaStyle::default() }, + ParaStyle { space_before: 4.0, ..ParaStyle::default() }, + ); + let mut first = TextObject::point(vectorcraft_geom::Point::ZERO, "", st.clone()); + first.runs = vec![TextRun::new("One two\nthree ", st.clone())]; + first.set_paragraph_styles(vec![p1.clone(), p2.clone()]); + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 40.0)) }; + first.xf = Affine::IDENTITY; + let p4 = ParaStyle { right_indent: 7.0, ..ParaStyle::default() }; + let mut second = first.clone(); + second.runs = vec![TextRun::new("four\nFive\n", st)]; + second.set_paragraph_styles(vec![p2.clone(), p3.clone(), p4.clone()]); + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(110.0, 10.0, 190.0, 40.0)) }; + let (first, second) = (text_node(&mut doc, first), text_node(&mut doc, second)); + doc.text_threads.push(vec![first.id, second.id]); + doc.insert(Some(layer), usize::MAX, first).unwrap(); + doc.insert(Some(layer), usize::MAX, second).unwrap(); + let back = read_back(&doc); + let texts: Vec<&TextObject> = + back.layers[0].children().unwrap().iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(t.as_ref()) } else { None }).collect(); + let [a, b] = texts.as_slice() else { panic!("two frames: {texts:?}") }; + assert_eq!((a.plain_text().as_str(), b.plain_text().as_str()), ("One two\nthree four\nFive\n", "")); + let attrs = |p: &ParaStyle| (p.justify, r3(p.left_indent), r3(p.right_indent), r3(p.space_before)); + let got: Vec<_> = a.paragraph_styles().iter().map(attrs).collect(); + assert_eq!(got, [&p1, &p2, &p3, &p4].into_iter().map(attrs).collect::>(), "the last, empty paragraph keeps its own"); + assert_eq!(back.text_threads.len(), 1); + assert!(export_ai_editing(&doc, &opts()).unwrap().warnings.is_empty()); + // An attribute the text document doesn't hold in a later frame is reported. + let second_id = doc.text_threads[0][1]; + let mut lossy = doc.clone(); + if let NodeKind::Text(t) = &mut lossy.node_mut(second_id).unwrap().kind { + t.runs[0].style.underline = true; + } + assert_eq!(export_ai_editing(&lossy, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]); + // So is a paragraph split between the frames whose second part has other attributes. + let mut split = doc.clone(); + if let NodeKind::Text(t) = &mut split.node_mut(second_id).unwrap().kind { + t.set_paragraph_styles(vec![ParaStyle { left_indent: 9.0, ..ParaStyle::default() }, p3, p4]); + } + assert_eq!(export_ai_editing(&split, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]); +} + +/// A story longer than the reader reads is written as its outlines. +#[test] +fn a_story_longer_than_the_reader_reads_is_written_as_its_outlines() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let long = format!("A{}", " ".repeat(crate::import::MAX_STORY)); + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 50.0), &long, style(12.0, Color::BLACK)); + let short = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 90.0), "Short", style(12.0, Color::BLACK)); + let (t, short) = (text_node(&mut doc, t), text_node(&mut doc, short)); + doc.insert(Some(layer), usize::MAX, t).unwrap(); + doc.insert(Some(layer), usize::MAX, short).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::TYPE]); + assert_eq!(program(&doc).matches("/AI11Text :").count(), 1, "the short story is text"); +} + +/// Stories that together make a text document larger than the reader reads: the ones past it are +/// written as their outlines, and what is written reads back. +#[test] +fn stories_past_the_text_document_the_reader_reads_are_written_as_their_outlines() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let long = format!("A{}", " ".repeat(900_000)); + for i in 0..9 { + // A font of its own, which no other story names. + let st = vectorcraft_doc::CharStyle { font_family: format!("Probe Family {i}"), ..style(8.0, Color::BLACK) }; + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 10.0 + f64::from(i) * 10.0), &long, st); + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::TYPE]); + let text = String::from_utf8_lossy(&out.program).replace("\r\n", "\n"); + let stubs = text.matches("/AI11Text :").count(); + assert!((1..9).contains(&stubs), "{stubs}"); + // The font set holds the fonts of the stories written, and the hidden characters' font. + assert_eq!(text_document(&text).matches("/CoolTypeFont").count(), stubs + 1); + let back = read_back(&doc); + let texts = back.layers[0].children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).count(); + assert_eq!(texts, stubs, "every story written comes back"); +} + +/// A thread whose frames differ in orientation is written as its outlines: a story's frames share +/// one. +#[test] +fn a_thread_of_horizontal_and_vertical_frames_is_written_as_its_outlines() { + use vectorcraft_doc::{TextKind, TextObject}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut first = TextObject::point(vectorcraft_geom::Point::ZERO, "Across, then down", style(10.0, Color::BLACK)); + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 40.0)) }; + first.xf = Affine::IDENTITY; + let mut second = first.clone(); + second.runs[0].text.clear(); + second.vertical = true; + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(110.0, 10.0, 190.0, 90.0)) }; + let (first, second) = (text_node(&mut doc, first), text_node(&mut doc, second)); + doc.text_threads.push(vec![first.id, second.id]); + doc.insert(Some(layer), usize::MAX, first).unwrap(); + doc.insert(Some(layer), usize::MAX, second).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::TYPE]); + assert!(!program(&doc).contains("/AI11Text")); +} + +/// Area type in an open frame whose ends meet is written as its outlines, alone or as a frame of a +/// thread: as text it would be read back in a closed frame. +#[test] +fn an_open_frame_whose_ends_meet_is_written_as_its_outlines() { + use vectorcraft_doc::{TextKind, TextObject}; + let open = |r: Rect| { + let mut frame = shapes::rectangle(r); + frame.subpaths[0].closed = false; + let start = frame.subpaths[0].anchors[0]; + frame.subpaths[0].anchors.push(start); + frame + }; + let mut alone = TextObject::point(vectorcraft_geom::Point::ZERO, "Open", style(10.0, Color::BLACK)); + alone.kind = TextKind::Area { frame: open(Rect::new(10.0, 10.0, 90.0, 40.0)) }; + alone.xf = Affine::IDENTITY; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let n = text_node(&mut doc, alone.clone()); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::TYPE]); + assert!(!program(&doc).contains("/AI11Text")); + + let mut first = alone; + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 40.0)) }; + let mut second = first.clone(); + second.runs[0].text.clear(); + second.kind = TextKind::Area { frame: open(Rect::new(110.0, 10.0, 190.0, 90.0)) }; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let (first, second) = (text_node(&mut doc, first), text_node(&mut doc, second)); + doc.text_threads.push(vec![first.id, second.id]); + doc.insert(Some(layer), usize::MAX, first).unwrap(); + doc.insert(Some(layer), usize::MAX, second).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::TYPE]); + assert!(!program(&doc).contains("/AI11Text")); +} + +/// A thread with a frame in a clipping group whose clipping object is a path stays type, every frame +/// of it, and comes back as one thread: the art of such a group isn't cut. +#[test] +fn a_thread_with_a_frame_in_a_clipping_group_stays_type() { + use vectorcraft_doc::{TextKind, TextObject}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut first = TextObject::point(vectorcraft_geom::Point::ZERO, "A story in two frames", style(10.0, Color::BLACK)); + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 40.0)) }; + first.xf = Affine::IDENTITY; + let mut second = first.clone(); + second.runs[0].text.clear(); + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(110.0, 10.0, 190.0, 40.0)) }; + let (first, second) = (text_node(&mut doc, first), text_node(&mut doc, second)); + doc.text_threads.push(vec![first.id, second.id]); + let clipper = clipping(&mut doc, shapes::rectangle(Rect::new(100.0, 0.0, 200.0, 50.0))); + let clipped = group(&mut doc, vec![clipper, second], true); + doc.insert(Some(layer), usize::MAX, first).unwrap(); + doc.insert(Some(layer), usize::MAX, clipped).unwrap(); + assert!(export_ai_editing(&doc, &opts()).unwrap().warnings.is_empty()); + assert_eq!(program(&doc).matches("/AI11Text :").count(), 2); + assert_eq!(read_back(&doc).text_threads.len(), 1); +} + +/// A thread with a frame in art cut to a clipping object that isn't a path is written as its +/// outlines, every frame of it; so is type whose size is past what the reader reads. +#[test] +fn a_thread_with_a_frame_in_cut_art_and_type_past_the_readers_sizes_are_outlines() { + use vectorcraft_doc::{TextKind, TextObject}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut first = TextObject::point(vectorcraft_geom::Point::ZERO, "A story in two frames", style(10.0, Color::BLACK)); + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 40.0)) }; + first.xf = Affine::IDENTITY; + let mut second = first.clone(); + second.runs[0].text.clear(); + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(110.0, 10.0, 190.0, 40.0)) }; + let (first, second) = (text_node(&mut doc, first), text_node(&mut doc, second)); + doc.text_threads.push(vec![first.id, second.id]); + // The second frame is clipped by type: its art is cut to the type's outlines. + let clipper = text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(110.0, 30.0), "CUT", style(30.0, Color::BLACK))); + let cut = group(&mut doc, vec![clipper, second], true); + doc.insert(Some(layer), usize::MAX, first).unwrap(); + doc.insert(Some(layer), usize::MAX, cut).unwrap(); + let huge = TextObject::point(vectorcraft_geom::Point::new(10.0, 90.0), "Huge", style(12.0, Color::BLACK)); + let huge = TextObject { xf: Affine::translate((10.0, 90.0)) * Affine::scale(1e5), ..huge }; + let huge = text_node(&mut doc, huge); + doc.insert(Some(layer), usize::MAX, huge).unwrap(); + let text = program(&doc); + assert!(!text.contains("/AI11Text"), "{text}"); + // Tracking that rounds to the reader's limit, 100,000, is written as outlines. + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut wide = TextObject::point(vectorcraft_geom::Point::new(10.0, 50.0), "Wide", style(12.0, Color::BLACK)); + wide.runs[0].style.tracking = 99_999.6; + let wide = text_node(&mut doc, wide); + doc.insert(Some(layer), usize::MAX, wide).unwrap(); + let text = program(&doc); + assert!(!text.contains("/AI11Text"), "{text}"); + // A frame that is the clipping object of a clipping group is written as the clipping outline. + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut first = TextObject::point(vectorcraft_geom::Point::ZERO, "A story in two frames", style(10.0, Color::BLACK)); + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 40.0)) }; + first.xf = Affine::IDENTITY; + let mut second = first.clone(); + second.runs[0].text.clear(); + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(110.0, 10.0, 190.0, 40.0)) }; + let (first, second) = (text_node(&mut doc, first), text_node(&mut doc, second)); + doc.text_threads.push(vec![first.id, second.id]); + let backing = square(&mut doc, Rect::new(100.0, 0.0, 200.0, 50.0), Color::rgb(1.0, 0.0, 0.0)); + let clipped = group(&mut doc, vec![second, backing], true); + doc.insert(Some(layer), usize::MAX, first).unwrap(); + doc.insert(Some(layer), usize::MAX, clipped).unwrap(); + let text = program(&doc); + assert!(!text.contains("/AI11Text"), "{text}"); +} + +#[test] +fn type_the_data_cant_hold_is_written_as_its_outlines() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::rgb(1.0, 0.0, 0.0))]); + let fill = Paint::Gradient(Box::new(GradientPaint::new(g))); + let t = vectorcraft_doc::TextObject::point( + vectorcraft_geom::Point::new(10.0, 70.0), + "Shaded", + vectorcraft_doc::CharStyle { size: 18.0, fill, ..vectorcraft_doc::CharStyle::default() }, + ); + let mirrored = vectorcraft_doc::TextObject { + xf: Affine::new([-1.0, 0.0, 0.0, 1.0, 150.0, 70.0]), + ..vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "Mirror", style(18.0, Color::BLACK)) + }; + // Area type in a frame of two subpaths: a frame of the text document is one path. + let mut holed = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "Two rings", style(10.0, Color::BLACK)); + let mut rings = shapes::rectangle(Rect::new(100.0, 10.0, 190.0, 90.0)); + rings.subpaths.extend(shapes::rectangle(Rect::new(120.0, 30.0, 170.0, 70.0)).subpaths); + holed.kind = vectorcraft_doc::TextKind::Area { frame: rings }; + holed.xf = Affine::IDENTITY; + // A carriage return in the characters: a story ends its paragraphs with it. Area type that + // flows around a wrap object: the wrap object's settings aren't written. + let returned = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 90.0), "A\rB", style(10.0, Color::BLACK)); + let mut wrapped = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "Wrapped round", style(10.0, Color::BLACK)); + wrapped.kind = vectorcraft_doc::TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 60.0)) }; + wrapped.xf = Affine::IDENTITY; + wrapped.wrap = vec![vectorcraft_doc::WrapShape { path: shapes::rectangle(Rect::new(30.0, 20.0, 50.0, 40.0)), wrap: Default::default() }]; + let wrapped = text_node(&mut doc, wrapped); + doc.insert(Some(layer), usize::MAX, wrapped).unwrap(); + // Type on an open path whose ends meet: it would be read back on a closed path. + let mut ring = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "Round", style(10.0, Color::BLACK)); + let mut open_ring = shapes::ellipse(Rect::new(120.0, 10.0, 180.0, 70.0)); + if let Some(first) = open_ring.subpaths[0].anchors.first().copied() { + open_ring.subpaths[0].anchors.push(first); + } + open_ring.subpaths[0].closed = false; + ring.kind = vectorcraft_doc::TextKind::OnPath { path: open_ring, start: 0.0, end: None }; + ring.xf = Affine::IDENTITY; + let ring = text_node(&mut doc, ring); + doc.insert(Some(layer), usize::MAX, ring).unwrap(); + let (t, mirrored, holed, returned) = + (text_node(&mut doc, t), text_node(&mut doc, mirrored), text_node(&mut doc, holed), text_node(&mut doc, returned)); + doc.insert(Some(layer), usize::MAX, t).unwrap(); + doc.insert(Some(layer), usize::MAX, mirrored).unwrap(); + doc.insert(Some(layer), usize::MAX, holed).unwrap(); + doc.insert(Some(layer), usize::MAX, returned).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::TYPE]); + assert!(!program(&doc).contains("%AI11_BeginTextDocument")); + let back = read_back(&doc); + let kinds: Vec = back.layers[0].children().unwrap().iter().map(|n| matches!(n.kind, NodeKind::Group { .. })).collect(); + assert_eq!(kinds, [true; 6]); +} + +#[test] +fn type_attributes_the_data_cant_hold_are_reported() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let st = vectorcraft_doc::CharStyle { underline: true, ..style(18.0, Color::BLACK) }; + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "Under", st); + let t = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, t).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::TYPE_ATTRIBUTES]); + let back = read_back(&doc); + assert!(matches!(back.layers[0].children().unwrap()[0].kind, NodeKind::Text(_))); + // Any other attribute the text document doesn't hold is reported too: No Break, a paragraph's + // left-to-right direction set on it, Optical Margin Alignment, a font version, a font that isn't + // installed whose name doesn't come back (a hyphen in its family), a Lab color, + // small capitals at another size, right-to-left letters aligned to the start of a paragraph + // without a direction of its own, tracking that isn't a whole number. + for edit in [ + (|t: &mut vectorcraft_doc::TextObject| t.runs[0].style.no_break = true) as fn(&mut vectorcraft_doc::TextObject), + |t| t.runs[0].style.tracking = 12.5, + |t| t.para.direction = Some(vectorcraft_doc::ParaDirection::LeftToRight), + |t| t.optical_margin = true, + |t| t.runs[0].style.font_version = Some("2.0".into()), + |t| t.runs[0].style.font_family = "my-missing font".into(), + |t| t.runs[0].style.fill = Paint::solid(MINT), + |t| t.runs[0].style.small_caps = Some(80.0), + |t| { + t.runs[0].text = "\u{645}\u{631}\u{62d}\u{628}\u{627}".into(); + t.para.justify = vectorcraft_doc::Justify::Auto; + }, + ] { + let with = |t: vectorcraft_doc::TextObject| { + let mut d = Document::new(200.0, 100.0); + let layer = d.layers[0].id; + let n = text_node(&mut d, t); + d.insert(Some(layer), usize::MAX, n).unwrap(); + export_ai_editing(&d, &opts()).unwrap().warnings + }; + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "Kept", style(18.0, Color::BLACK)); + assert!(with(t.clone()).is_empty()); + // A font that isn't installed keeps its family and style as its name. + let mut missing = t.clone(); + missing.runs[0].style.font_family = "Missing Sans Probe".into(); + missing.runs[0].style.font_style = "Bold Italic".into(); + assert!(with(missing).is_empty()); + edit(&mut t); + assert_eq!(with(t), [writer::TYPE_ATTRIBUTES]); + } +} + +/// On a large canvas, area type, threaded frames and type on a path stay type: the frames and +/// lengths are written at the canvas's scale. Frames of a thread at two scales, and area type +/// scaled by two factors, are written as outlines. +#[test] +fn scaled_area_type_and_type_on_a_path_stay_type() { + use vectorcraft_doc::{TextKind, TextObject}; + let mut doc = Document::new(20_000.0, 10_000.0); + let layer = doc.layers[0].id; + let framed = |text: &str, r: Rect| { + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, text, style(100.0, Color::BLACK)); + t.kind = TextKind::Area { frame: shapes::rectangle(r) }; + t.xf = Affine::IDENTITY; + t + }; + let mut area = framed("Area", Rect::new(1000.0, 1000.0, 5000.0, 3000.0)); + area.area.columns = 2; + area.area.gutter = 200.0; + let mut on_path = TextObject::point(vectorcraft_geom::Point::ZERO, "Along", style(100.0, Color::BLACK)); + let mut curve = PathData::from_bezpath(&kurbo::BezPath::from_vec(vec![ + kurbo::PathEl::MoveTo((1000.0, 5000.0).into()), + kurbo::PathEl::CurveTo((3000.0, 4000.0).into(), (7000.0, 4000.0).into(), (9000.0, 5000.0).into()), + ])); + curve.subpaths.iter_mut().for_each(|sp| sp.closed = false); + on_path.kind = TextKind::OnPath { path: curve, start: 0.0, end: None }; + on_path.xf = Affine::IDENTITY; + let first = text_node(&mut doc, framed("A story in two frames", Rect::new(1000.0, 6000.0, 5000.0, 8000.0))); + let second = text_node(&mut doc, framed("", Rect::new(6000.0, 6000.0, 10_000.0, 8000.0))); + doc.text_threads.push(vec![first.id, second.id]); + let (area, on_path) = (text_node(&mut doc, area), text_node(&mut doc, on_path)); + for n in [area, on_path, first, second] { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + let texts: Vec<&TextObject> = art.iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(t.as_ref()) } else { None }).collect(); + assert_eq!(texts.len(), 4); + assert_eq!(back.text_threads.len(), 1); + let TextKind::Area { frame } = &texts[0].kind else { panic!("area type") }; + let b = frame.transformed(texts[0].xf).bounds().unwrap(); + assert_eq!([b.x0, b.y0, b.x1, b.y1].map(r3), ["1000.000", "1000.000", "5000.000", "3000.000"].map(String::from)); + // The reader scales the document back: its matrix holds the canvas's scale, and its lengths + // through that matrix are the ones written. + let k = |t: &TextObject| t.xf.as_coeffs()[0]; + assert_eq!( + (r3(texts[0].runs[0].style.size * k(texts[0])), texts[0].area.columns, r3(texts[0].area.gutter * k(texts[0]))), + ("100.000".to_string(), 2, "200.000".to_string()) + ); + assert!(matches!(texts[1].kind, TextKind::OnPath { .. })); + assert_eq!(r3(texts[1].runs[0].style.size * k(texts[1])), "100.000"); + + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut uneven = framed("Uneven", Rect::new(10.0, 10.0, 50.0, 30.0)); + uneven.xf = Affine::new([2.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + let uneven = text_node(&mut doc, uneven); + doc.insert(Some(layer), usize::MAX, uneven).unwrap(); + assert!(!program(&doc).contains("/AI11Text")); + + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let first = framed("A story in two frames", Rect::new(10.0, 10.0, 50.0, 30.0)); + let mut second = framed("", Rect::new(30.0, 20.0, 50.0, 30.0)); + second.xf = Affine::scale(2.0); + let (first, second) = (text_node(&mut doc, first), text_node(&mut doc, second)); + doc.text_threads.push(vec![first.id, second.id]); + doc.insert(Some(layer), usize::MAX, first).unwrap(); + doc.insert(Some(layer), usize::MAX, second).unwrap(); + assert!(!program(&doc).contains("/AI11Text")); +} + +/// See-through type with the knockout shape flag comes back with the flag and writes no warning. +#[test] +fn the_knockout_shape_of_type_comes_back() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut text = text_node(&mut doc, vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 40.0), "Hi", style(10.0, Color::BLACK))); + (text.opacity, text.knockout_shape) = (0.5, true); + doc.insert(Some(layer), usize::MAX, text).unwrap(); + assert!(export_ai_editing(&doc, &opts()).unwrap().warnings.is_empty()); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + assert!(matches!(n.kind, NodeKind::Text(_))); + assert_eq!((n.opacity, n.knockout_shape), (0.5, true)); +} + +/// The kinds of object that write no paint before their `Xy` or no state block after them, and a +/// group, which writes a state block. +#[derive(Clone, Copy, Debug)] +enum Beside { + Type, + Compound, + Image, + Guide, + Group, +} + +/// An object of `kind` at `x`, with opacity, blending mode and knockout shape flag `state`. +fn beside(doc: &mut Document, kind: Beside, x: f64, state: (f32, BlendMode, bool)) -> Node { + let r = Rect::new(x, 10.0, x + 20.0, 30.0); + let mut n = match kind { + Beside::Type => { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(x, 40.0), "Hi", style(10.0, Color::BLACK)); + text_node(doc, t) + } + Beside::Compound => { + let outer = Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::default()); + let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x + 5.0, 15.0, x + 15.0, 25.0)), Appearance::default()); + let mut ring = + Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance::basic(solid(BRAND), Paint::None, 0.0).into(); + ring + } + Beside::Image => { + let mut png = vec![]; + let img = image::RgbaImage::from_raw(1, 1, vec![255, 0, 0, 255]).unwrap(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let blob = ImageBlob::new("image/png", png); + let key = blob.content_key(); + doc.images.insert(key.clone(), blob); + let xf = Affine::new([10.0, 0.0, 0.0, 10.0, x, 10.0]); + let im = ImageObject { key, width: 1, height: 1, xf, link: None, placement: Default::default(), pixels: None }; + Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))) + } + Beside::Guide => Node::new( + doc.alloc_id(), + NodeKind::Path { path: shapes::rectangle(r), rule: FillRule::NonZero, live: None, clipping: false, guide: true }, + ), + Beside::Group => { + let member = square(doc, r, BRAND); + group(doc, vec![member], false) + } + }; + (n.opacity, n.blend, n.knockout_shape) = state; + n +} + +/// Two objects next to each other come back with their own opacity, blending mode and knockout +/// shape flag, whichever is first and whichever is opaque: an `Xy` right after a text object or a +/// compound path is theirs when no other operator comes between. The layer's stays its own. +#[test] +fn objects_next_to_each_other_keep_their_own_transparency() { + use Beside::{Compound, Group, Guide, Image, Type}; + let (clear, screen, plain) = ((0.5, BlendMode::Multiply, true), (0.25, BlendMode::Screen, false), (1.0, BlendMode::Normal, false)); + let pairs = [ + (Type, Type), + (Compound, Type), + (Group, Type), + (Type, Group), + (Type, Compound), + (Type, Image), + (Type, Guide), + (Compound, Image), + (Compound, Guide), + ]; + for (a, b) in pairs { + for (first, second) in [(clear, plain), (plain, clear), (clear, screen), (clear, clear)] { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let (x, y) = (beside(&mut doc, a, 10.0, first), beside(&mut doc, b, 60.0, second)); + doc.insert(Some(layer), usize::MAX, x).unwrap(); + doc.insert(Some(layer), usize::MAX, y).unwrap(); + let back = read_back(&doc); + let at = format!("{a:?} {first:?} then {b:?} {second:?}"); + let kids = back.layers[0].children().unwrap(); + assert_eq!(kids.len(), 2, "{at}"); + for (n, want) in kids.iter().zip([first, second]) { + assert_eq!((n.opacity, n.blend, n.knockout_shape), want, "{at}"); + } + let l = &back.layers[0]; + assert_eq!((l.opacity, l.blend, l.knockout_shape), plain, "the layer's own: {at}"); + } + } +} + +/// A layer whose last object is type keeps its own transparency, and the type keeps its. +#[test] +fn type_last_in_a_transparent_layer_keeps_its_own_transparency() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let text = beside(&mut doc, Beside::Type, 10.0, (0.5, BlendMode::Multiply, true)); + doc.insert(Some(layer), usize::MAX, text).unwrap(); + let l = Arc::make_mut(&mut doc.layers[0]); + (l.opacity, l.blend) = (0.75, BlendMode::Screen); + let back = read_back(&doc); + let (l, n) = (&back.layers[0], &back.layers[0].children().unwrap()[0]); + assert_eq!((l.opacity, l.blend), (0.75, BlendMode::Screen)); + assert_eq!((n.opacity, n.blend, n.knockout_shape), (0.5, BlendMode::Multiply, true)); +} + +/// Isolate Blending and the Knockout Group state of type come back, named or not and whatever +/// follows it, as outlines kept them on their group, and are written again as the same bytes. +#[test] +fn the_isolation_and_knockout_of_type_come_back() { + for name in [None, Some("Title")] { + let cases = [(true, Knockout::On), (false, Knockout::On), (false, Knockout::Off), (true, Knockout::Neutral), (false, Knockout::Neutral)]; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + for (i, (isolate, knockout)) in cases.into_iter().enumerate() { + let mut n = beside(&mut doc, Beside::Type, 10.0 + 30.0 * i as f64, (0.5, BlendMode::Multiply, false)); + (n.isolate, n.knockout) = (isolate, knockout); + n.name = name.map(|s| format!("{s} {i}")); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let after = beside(&mut doc, Beside::Compound, 170.0, (1.0, BlendMode::Normal, false)); + doc.insert(Some(layer), usize::MAX, after).unwrap(); + let back = read_back(&doc); + let kids = back.layers[0].children().unwrap(); + assert_eq!(kids.len(), cases.len() + 1); + for (i, (n, (isolate, knockout))) in kids.iter().zip(cases).enumerate() { + assert!(matches!(n.kind, NodeKind::Text(_))); + assert_eq!((n.isolate, n.knockout, n.opacity, n.blend), (isolate, knockout, 0.5, BlendMode::Multiply), "{i}"); + assert_eq!(n.name, name.map(|s| format!("{s} {i}"))); + } + assert_eq!(kids[cases.len()].opacity, 1.0); + let art = |d: &Document| program(d).split_once("%%EndSetup").map(|(_, art)| art.to_string()).unwrap(); + assert_eq!(art(&back), art(&doc)); + } +} + +/// The end marker of the text document stays on one line wherever the ASCII85 ends: the reader +/// looks for `~>` in the lines as they are, before it joins them. +#[test] +fn the_end_marker_of_the_text_document_stays_on_one_line() { + let mut at_the_boundary = 0; + // A character is two bytes: sizes of more digits reach the lengths that characters don't. + for size in [10.0, 10.25, 10.125, 10.0625] { + for len in 1..=60 { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let text = "x".repeat(len); + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 40.0), &text, style(size, Color::BLACK)); + let t = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, t).unwrap(); + let p = program(&doc); + assert!(!p.contains("~\n%>"), "{size} {len}"); + // A full line (`%` and 100 characters) that the `>` goes past. + at_the_boundary += usize::from(p.lines().any(|l| l.len() == 102 && l.ends_with("~>"))); + let back = read_back(&doc); + let NodeKind::Text(read) = &back.layers[0].children().unwrap()[0].kind else { panic!("{size} {len}: not type") }; + assert_eq!(read.plain_text(), text); + } + } + assert!(at_the_boundary > 0, "no length put the `~` at the end of a line"); +} + +/// An empty frame after a slice that ends with a paragraph break holds the story's last paragraph, +/// and that paragraph comes back with the empty frame's style. +#[test] +fn an_empty_last_frame_keeps_the_style_of_the_last_paragraph() { + use vectorcraft_doc::{Justify, ParaStyle, TextKind, TextObject}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut first = TextObject::point(vectorcraft_geom::Point::ZERO, "Ends\n", style(10.0, Color::BLACK)); + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 40.0)) }; + first.xf = Affine::IDENTITY; + let mut second = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(10.0, Color::BLACK)); + second.set_all_paras(ParaStyle { justify: Justify::Right, ..ParaStyle::default() }); + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(110.0, 10.0, 190.0, 40.0)) }; + second.xf = Affine::IDENTITY; + let (first, second) = (text_node(&mut doc, first), text_node(&mut doc, second)); + doc.text_threads.push(vec![first.id, second.id]); + doc.insert(Some(layer), usize::MAX, first).unwrap(); + doc.insert(Some(layer), usize::MAX, second).unwrap(); + let back = read_back(&doc); + let NodeKind::Text(t) = &back.layers[0].children().unwrap()[0].kind else { panic!("type") }; + assert_eq!(t.plain_text(), "Ends\n"); + let justify: Vec = t.paragraph_styles().iter().map(|p| p.justify).collect(); + assert_eq!(justify, [Justify::Left, Justify::Right]); +} + +/// A minimum first baseline with the Ascent first baseline is reported, and kept with the others. +/// An end bracket of an open path that the reader would read as none is reported, and one further +/// from the path's end comes back. +#[test] +fn a_first_baseline_minimum_and_a_path_end_the_reader_cant_read_are_reported() { + use vectorcraft_doc::{FirstBaseline, TextKind, TextObject}; + let with = |t: TextObject| { + let mut d = Document::new(300.0, 200.0); + let layer = d.layers[0].id; + let n = text_node(&mut d, t); + d.insert(Some(layer), usize::MAX, n).unwrap(); + let warnings = export_ai_editing(&d, &opts()).unwrap().warnings; + (warnings, read_back(&d)) + }; + let mut area = TextObject::point(vectorcraft_geom::Point::ZERO, "Area", style(12.0, Color::BLACK)); + area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(20.0, 20.0, 140.0, 160.0)) }; + area.xf = Affine::IDENTITY; + area.area.first_baseline_min = 40.0; + let (warnings, _) = with(area.clone()); + assert_eq!(warnings, [writer::TYPE_ATTRIBUTES]); + area.area.first_baseline = FirstBaseline::Fixed; + let (warnings, back) = with(area); + assert!(warnings.is_empty(), "{warnings:?}"); + let NodeKind::Text(t) = &back.layers[0].children().unwrap()[0].kind else { panic!("type") }; + assert_eq!((t.area.first_baseline, t.area.first_baseline_min), (FirstBaseline::Fixed, 40.0)); + + let on_path = |end: Option| { + let mut curve = PathData::from_bezpath(&kurbo::BezPath::from_vec(vec![ + kurbo::PathEl::MoveTo((20.0, 150.0).into()), + kurbo::PathEl::CurveTo((50.0, 110.0).into(), (110.0, 110.0).into(), (140.0, 150.0).into()), + ])); + curve.subpaths.iter_mut().for_each(|sp| sp.closed = false); + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "On", style(12.0, Color::BLACK)); + t.kind = TextKind::OnPath { path: curve, start: 0.0, end }; + t.xf = Affine::IDENTITY; + t + }; + assert_eq!(with(on_path(Some(0.999))).0, [writer::TYPE_ATTRIBUTES]); + assert!(with(on_path(None)).0.is_empty()); + let (warnings, back) = with(on_path(Some(0.5))); + assert!(warnings.is_empty(), "{warnings:?}"); + let NodeKind::Text(t) = &back.layers[0].children().unwrap()[0].kind else { panic!("type") }; + let TextKind::OnPath { end: Some(end), .. } = t.kind else { panic!("an end bracket") }; + assert!((end - 0.5).abs() < 1e-3, "{end}"); +} + +/// A right-to-left paragraph aligned to the start of its direction comes back aligned right, as +/// it draws; Latin type aligned to the start comes back aligned left. +#[test] +fn type_aligned_to_the_start_of_its_direction_keeps_its_side() { + use vectorcraft_doc::{Justify, ParaDirection, ParaStyle, TextObject}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut rtl = TextObject::point(vectorcraft_geom::Point::new(150.0, 40.0), "\u{5e9}\u{5dc}\u{5d5}\u{5dd}", style(12.0, Color::BLACK)); + rtl.set_all_paras(ParaStyle { justify: Justify::Auto, direction: Some(ParaDirection::RightToLeft), ..ParaStyle::default() }); + let mut ltr = TextObject::point(vectorcraft_geom::Point::new(20.0, 80.0), "Start", style(12.0, Color::BLACK)); + ltr.set_all_paras(ParaStyle { justify: Justify::Auto, ..ParaStyle::default() }); + let (rtl, ltr) = (text_node(&mut doc, rtl), text_node(&mut doc, ltr)); + doc.insert(Some(layer), usize::MAX, rtl).unwrap(); + doc.insert(Some(layer), usize::MAX, ltr).unwrap(); + assert!(export_ai_editing(&doc, &opts()).unwrap().warnings.is_empty()); + let back = read_back(&doc); + let sides: Vec = + back.layers[0].children().unwrap().iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(t.para.justify) } else { None }).collect(); + assert_eq!(sides, [Justify::Right, Justify::Left]); +} + +/// Type in an opacity mask is written as its outlines; the type beside it as text. +#[test] +fn type_in_opacity_masks_is_written_as_its_outlines() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let label = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 40.0), "Mask", style(18.0, Color::BLACK)); + let label = text_node(&mut doc, label); + let mut square = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(1.0, 0.0, 0.0)); + square.extras_mut().mask = Some(Box::new(OpacityMask::new(label, false))); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let plain = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 90.0), "Plain", style(18.0, Color::BLACK)); + let plain = text_node(&mut doc, plain); + doc.insert(Some(layer), usize::MAX, plain).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::TYPE]); + let text = program(&doc); + assert_eq!(text.matches("/AI11Text :").count(), 1); +} + +/// Type with an opacity mask of its own is written as its outlines, which keep the mask. +#[test] +fn type_with_an_opacity_mask_is_written_as_its_outlines() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "Masked", style(18.0, Color::BLACK)); + let mut t = text_node(&mut doc, t); + let art = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(1.0, 1.0, 1.0)); + t.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + doc.insert(Some(layer), usize::MAX, t).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::TYPE]); + assert_eq!(program(&doc).matches("/AI11Text :").count(), 0); + let back = read_back(&doc); + let top = &back.layers[0].children().unwrap()[0]; + assert!(!matches!(top.kind, NodeKind::Text(_))); + assert!(top.extras().mask.is_some()); +} + +#[test] +fn symbols_and_their_instances_are_read_back() { + let doc = symbols_document(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + same_lines(&lines(&back), &lines(&doc)); + same_lines(&all_looks(&back), &all_looks(&doc)); + same_lines(&symbol_looks(&back), &symbol_looks(&doc)); + // Each instance draws where it did: the symbols' art and the instances' places agree. + let boxes = |d: &Document| -> Vec { + let b = d.symbol_boxes(); + let mut ids = vec![]; + d.walk(|n| { + if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + ids.push(n.id); + } + }); + ids.iter().map(|id| format!("{:?}", d.bounds_of_with(&[*id], true, &b).map(|r| [r.x0, r.y0, r.x1, r.y1].map(r3)))).collect() + }; + same_lines(&boxes(&back), &boxes(&doc)); +} + +#[test] +fn symbols_write_the_same_bytes_again() { + let doc = symbols_document(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + assert_eq!(private_data(&doc, &opts()).unwrap().0, private_data(&doc, &opts()).unwrap().0); + let again = export_ai_editing(&read_back(&doc), &opts()).unwrap().program; + same_lines(&shown(&again).lines().map(String::from).collect::>(), &shown(&first.program).lines().map(String::from).collect::>()); + assert_eq!(again, first.program); +} + +#[test] +fn symbols_are_written_in_their_forms() { + let p = program_shown(&symbols_document()); + // The definitions in a non-printing block after the patterns, in the order the art first uses + // them (each after those its art uses), the others after them; and the list after the palette + // in the panel's order. + let defs = ["(Leaf)", "(Pair)", "(Shade)", "(Spare)", "(Solo)"].map(|n| p.find(&format!("%AI14_BeginSymbol\n{n}\n0 A\n0 Xw\n0 Ae\n")).unwrap()); + assert!(defs.windows(2).all(|w| w[0] < w[1]), "{p}"); + assert!(p.contains("%AI5_Begin_NonPrinting\nNp\n%AI14_BeginSymbol\n(Leaf)\n"), "{p}"); + let list = + "%AI5_Begin_NonPrinting\nNp\n%AI24_BeginSymbolList\n(Spare)\n(Pair)\n(Leaf)\n(Shade)\n(Solo)\n%AI24_EndSymbolList\n%AI5_End_NonPrinting--\n"; + let at = p.find(list).unwrap(); + assert!(p.find("%AI5_EndPalette").unwrap() < at && at < p.find("%AI9_BeginDocumentData").unwrap(), "{p}"); + // A group's registration point in its dictionary, before its state block; a path is written in + // a group of its own. + assert!(p.contains("U\n%_/ArtDictionary :\n%_1 /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n"), "{p}"); + assert!(p.contains("%_/ArtDictionary :\n%_9 /Int (AI13PatternRegistrationType) ,\n"), "{p}"); + assert!(p.contains("%AI14_BeginSymbol\n(Spare)\n0 A\n0 Xw\n0 Ae\nu\n"), "{p}"); + // A plain group of one object in a group of its own. + assert!(p.contains("%AI14_BeginSymbol\n(Solo)\n0 A\n0 Xw\n0 Ae\nu\nu\n"), "{p}"); + assert!(p.contains("f\nU\n%_/ArtDictionary :\n%_5 /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n"), "{p}"); + // An instance on the page: its matrix takes the art to art space (y up from the artboard's top + // left), then its state block. + assert!(p.contains("/SymbolInstance :\n(Leaf) /SymbolRef ,\n1 0 0 -1 10 -10 /RTransformMatrix\n;\n9 () XW\n"), "{p}"); + // Its name between the two, and its transparency as a group's. + assert!(p.contains("/RTransformMatrix\n;\n%_/ArtDictionary :\n%_/XMLUID : (Turned) ; (AI10_ArtUID) ,\n%_;\n%_\n9 () XW\n"), "{p}"); + assert!(p.contains("1 0 0 -1 190 -10 /RTransformMatrix\n;\n1 0.5 0 2 0 Xy\n0 0 Xd\n6 () XW\n"), "{p}"); + // In a symbol's art, about the canvas point of art space's origin (the template box's center + // is the canvas's). + let t: Vec = p.lines().find_map(|l| l.strip_prefix("%AI3_TemplateBox: ")).unwrap().split(' ').map(|v| v.parse().unwrap()).collect(); + let (ox, oy) = (f64::from(CANVAS_SIZE) / 2.0 - t[0], f64::from(CANVAS_SIZE) / 2.0 + t[1]); + let nested = format!("(Leaf) /SymbolRef ,\n0.5 0 0 -0.5 {} {} /RTransformMatrix\n", ps::num(15.0 - ox), ps::num(oy + 5.0)); + assert!(p.contains(&nested), "{nested}\n{p}"); +} + +/// Instances that the data can't hold as instances are written as their art, with a warning: a +/// stained one, one of a symbol with 9-slice guides, one scaled almost flat, every one on the +/// layers of a large canvas (whose symbols are still defined), one in a pattern's tile, one with a +/// dynamic symbol's appearance changes and one in art cut to a clipping object that isn't a path. +/// A symbol whose art holds an instance of itself is defined once, that instance as art. +#[test] +fn instances_the_data_cant_hold_are_written_as_their_art() { + let leaf = |doc: &mut Document| { + let art = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); + }; + let kinds = |d: &Document| -> Vec<&'static str> { + d.layers[0].children().unwrap().iter().map(|n| if matches!(n.kind, NodeKind::SymbolInstance { .. }) { "instance" } else { "art" }).collect() + }; + // Stained. + let mut doc = Document::new(200.0, 100.0); + leaf(&mut doc); + let mut stained = instance(&mut doc, "Leaf", Affine::translate((50.0, 10.0))); + stained.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into(); + let plain = instance(&mut doc, "Leaf", Affine::translate((80.0, 10.0))); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, stained).unwrap(); + doc.insert(Some(layer), usize::MAX, plain).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART]); + assert_eq!(kinds(&read_back(&doc)), ["art", "instance"]); + // 9-slice guides. + doc.set_symbol_nine_slice("Leaf", Some(vectorcraft_doc::SymbolNineSlice::default())); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SYMBOL_ART, writer::SYMBOL_OPTIONS]); + let back = read_back(&doc); + assert_eq!((kinds(&back), back.symbols.len()), (vec!["art", "art"], 1)); + // Scaled so flat that its matrix to ten decimals has no area. + let mut doc = Document::new(200.0, 100.0); + leaf(&mut doc); + let flat = instance(&mut doc, "Leaf", Affine::new([1e-11, 0.0, 0.0, 1.0, 50.0, 10.0])); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, flat).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART]); + assert_eq!(kinds(&read_back(&doc)), ["art"]); + // A large canvas. + let mut doc = Document::new(20000.0, 100.0); + leaf(&mut doc); + let one = instance(&mut doc, "Leaf", Affine::translate((50.0, 10.0))); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, one).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART]); + // The symbol is still defined, at its own size: the canvas's scale doesn't touch its art. + let back = read_back(&doc); + assert_eq!(kinds(&back), ["art"]); + assert_eq!(symbol_looks(&back), symbol_looks(&doc)); + // A pattern a symbol's art and the layers both paint with: the layers' fill keeps it, the + // symbol's art has its tiles. + let dot = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), Color::BLACK)); + let mut dots = vectorcraft_doc::PatternDef::new("Dots", vec![dot]); + dots.tile = Rect::new(0.0, 0.0, 8.0, 8.0); + doc.patterns.push(dots); + let fill = || Appearance::basic(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, Paint::None, 0.0); + let patch = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 16.0, 16.0)), fill()); + doc.symbols.push(Symbol { dynamic: false, name: "Patch".into(), art: Arc::new(patch) }); + let filled = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 10.0, 132.0, 42.0)), fill()); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, filled).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SYMBOL_ART, writer::PATTERNS]); + let back = read_back(&doc); + let on_layer = back.layers[0].children().unwrap()[1].appearance.items[0].paint().clone(); + assert!(matches!(on_layer, Paint::Pattern { .. }), "{on_layer:?}"); + let patch = &back.symbols.iter().find(|s| s.name == "Patch").unwrap().art; + assert!(matches!(patch.kind, NodeKind::Group { .. }), "the symbol's art is its tiles: {:?}", patch.kind); + // A pattern's tile: the tile holds the symbol's art. + let mut doc = Document::new(200.0, 100.0); + leaf(&mut doc); + let tiled = instance(&mut doc, "Leaf", Affine::IDENTITY); + doc.patterns.push(vectorcraft_doc::PatternDef::new("Tiles", vec![Arc::new(tiled)])); + let fill = Appearance::basic(Paint::Pattern { pattern: "Tiles".into(), xf: Affine::IDENTITY }, Paint::None, 0.0); + let filled = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), fill); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, filled).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART]); + let back = read_back(&doc); + let tile = &back.patterns.iter().find(|p| p.name == "Tiles").unwrap().art; + assert_eq!(tile.len(), 1); + assert_eq!(instances(&tile[0]), 0, "{:?}", tile[0].kind); + let NodeKind::Group { children, .. } = &tile[0].kind else { panic!("{:?}", tile[0].kind) }; + assert_eq!(paints_of_nodes(&back, children), paints_of_nodes(&back, &[Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF))])); + // A symbol holding an instance of itself: defined once, that instance as its art. + let mut doc = Document::new(200.0, 100.0); + let looped_art = { + let me = instance(&mut doc, "Loop", Affine::translate((20.0, 0.0))); + let dot = square(&mut doc, Rect::new(0.0, 0.0, 5.0, 5.0), LEAF); + group(&mut doc, vec![dot, me], false) + }; + doc.symbols.push(Symbol { dynamic: false, name: "Loop".into(), art: Arc::new(looped_art) }); + let looped = instance(&mut doc, "Loop", Affine::translate((100.0, 10.0))); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, looped).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART]); + let p = program(&doc); + assert_eq!(p.matches("%AI14_BeginSymbol\n(Loop)\n").count(), 1, "{p}"); + assert_eq!(kinds(&read_back(&doc)), ["instance"]); + // Appearance changes of a dynamic symbol's instance. + let mut doc = Document::new(200.0, 100.0); + leaf(&mut doc); + doc.symbols[0].dynamic = true; + let mut changed = instance(&mut doc, "Leaf", Affine::translate((50.0, 10.0))); + changed.extras_mut().symbol_overrides = + vec![vectorcraft_doc::SymbolOverride { fill: Some(solid(Color::rgb(0.0, 1.0, 0.0))), ..Default::default() }]; + let plain = instance(&mut doc, "Leaf", Affine::translate((80.0, 10.0))); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, changed).unwrap(); + doc.insert(Some(layer), usize::MAX, plain).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART, writer::SYMBOL_OPTIONS]); + let back = read_back(&doc); + assert_eq!(kinds(&back), ["art", "instance"]); + let green = back.layers[0].children().unwrap()[0].clone(); + let drawn = paints_of_nodes(&back, &[green]); + assert!(drawn.iter().any(|l| l.contains("rgb 0.000 1.000 0.000")), "the change is drawn: {drawn:?}"); + // Art cut to a clipping object that isn't a path. + let mut doc = Document::new(200.0, 100.0); + leaf(&mut doc); + let pixels = png_of(image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 0, 255, 255])))); + let frame = image_node(&mut doc, ImageBlob::new("image/png", pixels), (2, 2), Affine::new([20.0, 0.0, 0.0, 20.0, 40.0, 0.0]), None); + let cut = instance(&mut doc, "Leaf", Affine::translate((45.0, 5.0))); + let clipped = group(&mut doc, vec![frame, cut], true); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, clipped).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(back.layers.iter().map(|l| instances(l)).sum::(), 0); + assert_eq!(back.symbols.len(), 1); +} + +/// Symbols whose art paints with a pattern, directly, through a nested symbol, in an opacity mask +/// and through an inline graphic: their definitions hold the pattern fills as tiles cut to the shape (the reader keeps no +/// symbol whose art paints with a pattern), and their instances are written as their art, whose +/// pattern fills keep the document's placement as the canvas draws them, each with a warning. An +/// instance of a symbol without pattern paint stays an instance. +#[test] +fn symbols_with_pattern_fills_are_defined_with_tiles_and_placed_as_art() { + let mut doc = Document::new(200.0, 100.0); + // Tiles that cover the shape, so its tiles cut to it draw its box. + let dot = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 8.0, 8.0), Color::BLACK)); + let mut dots = vectorcraft_doc::PatternDef::new("Dots", vec![dot]); + dots.tile = Rect::new(0.0, 0.0, 8.0, 8.0); + doc.patterns.push(dots); + let fill = || Appearance::basic(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, Paint::None, 0.0); + let patch = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 16.0, 16.0)), fill()); + doc.symbols.push(Symbol { dynamic: false, name: "Patch".into(), art: Arc::new(patch) }); + let inner = instance(&mut doc, "Patch", Affine::translate((20.0, 0.0))); + let edge = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let outer = group(&mut doc, vec![edge, inner], false); + doc.symbols.push(Symbol { dynamic: false, name: "Outer".into(), art: Arc::new(outer) }); + let mask_art = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 12.0, 12.0)), fill()); + let mut masked = square(&mut doc, Rect::new(0.0, 0.0, 12.0, 12.0), LEAF); + masked.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(mask_art), clip: true, invert: false, disabled: false, linked: true })); + doc.symbols.push(Symbol { dynamic: false, name: "Masked".into(), art: Arc::new(masked) }); + let plain = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Plain".into(), art: Arc::new(plain) }); + // Type holding `Patch` as an inline graphic. + let style = vectorcraft_doc::CharStyle { size: 18.0, fill: solid(Color::BLACK), ..vectorcraft_doc::CharStyle::default() }; + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(0.0, 20.0), "A", style.clone()); + t.runs.push(vectorcraft_doc::TextRun::inline(vectorcraft_doc::InlineArt::new("Patch"), style)); + let typed = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.symbols.push(Symbol { dynamic: false, name: "Typed".into(), art: Arc::new(typed) }); + let layer = doc.layers[0].id; + // Two instances of `Patch` a part of a tile apart. + for (name, x) in [("Patch", 10.0), ("Patch", 33.0), ("Outer", 60.0), ("Masked", 120.0), ("Plain", 140.0), ("Typed", 10.0)] { + let one = instance(&mut doc, name, Affine::translate((x, 10.0))); + doc.insert(Some(layer), usize::MAX, one).unwrap(); + } + let filled = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(150.0, 10.0, 182.0, 42.0)), fill()); + doc.insert(Some(layer), usize::MAX, filled).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART) && out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings); + let back = read_back(&doc); + let names: Vec<&str> = back.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["Patch", "Outer", "Masked", "Plain", "Typed"]); + let patch = &back.symbols[0].art; + assert!(matches!(patch.kind, NodeKind::Group { .. }), "the symbol's art is its tiles: {:?}", patch.kind); + assert_eq!(instances(&back.symbols[1].art), 0, "the nested instance is its art"); + let kids = back.layers[0].children().unwrap(); + let kinds: Vec = kids.iter().map(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })).collect(); + assert_eq!(kinds, [false, false, false, false, true, false, false]); + // The pattern fills of both `Patch` instances and of the layers' path keep one placement. + let placements = |n: &Node| { + let mut out = vec![]; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + for it in m.appearance.items.iter() { + if let Paint::Pattern { xf, .. } = it.paint() { + out.push(xf.as_coeffs().map(r3)); + } + } + }); + out + }; + let layer_fill = placements(&kids[6]); + assert_eq!(layer_fill.len(), 1); + assert_eq!(placements(&kids[0]), layer_fill); + assert_eq!(placements(&kids[1]), layer_fill); + // Each instance draws where it did. + let boxes = |d: &Document| -> Vec { + let b = d.symbol_boxes(); + let ids: Vec<_> = d.layers[0].children().unwrap().iter().take(5).map(|n| n.id).collect(); + ids.iter().map(|id| format!("{:?}", d.bounds_of_with(&[*id], true, &b).map(|r| [r.x0, r.y0, r.x1, r.y1].map(r3)))).collect() + }; + same_lines(&boxes(&back), &boxes(&doc)); +} + +/// A symbol whose art paints with a pattern only through a brushed stroke, whose brush's art is +/// filled with a pattern: the definition holds the tiles, and its instance is written as its art. +#[test] +fn symbols_painting_patterns_through_brush_art_are_placed_as_art() { + let mut doc = Document::new(200.0, 100.0); + let dot = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 8.0, 8.0), Color::BLACK)); + let mut dots = vectorcraft_doc::PatternDef::new("Dots", vec![dot]); + dots.tile = Rect::new(0.0, 0.0, 8.0, 8.0); + doc.patterns.push(dots); + let fill = Appearance::basic(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, Paint::None, 0.0); + let art = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 8.0)), fill); + let brush = vectorcraft_brush::Brush { + name: "Dotted".into(), + kind: vectorcraft_brush::BrushKind::Art(vectorcraft_brush::ArtBrush { + art, + colorization: vectorcraft_brush::Colorization::None, + ..Default::default() + }), + }; + vectorcraft_brush::store(&mut doc, &[brush]); + let mut line = + Node::path(doc.alloc_id(), shapes::line((0.0, 0.0).into(), (60.0, 0.0).into()), Appearance::basic(Paint::None, solid(Color::BLACK), 4.0)); + line.appearance.stroke_mut().unwrap().brush = Some("Dotted".into()); + doc.symbols.push(Symbol { dynamic: false, name: "Brushed".into(), art: Arc::new(line) }); + let layer = doc.layers[0].id; + let one = instance(&mut doc, "Brushed", Affine::translate((10.0, 40.0))); + doc.insert(Some(layer), usize::MAX, one).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(back.symbols.iter().map(|s| s.name.as_str()).collect::>(), ["Brushed"]); + assert_eq!(instances(&back.layers[0]), 0, "the instance is its art"); +} + +/// A symbol first defined from the drawn look of a group with a style, through a member's scatter +/// brush, still warns that its art's own effects are left out, and so does a later instance of it. +#[test] +fn a_symbol_defined_inside_a_drawn_look_warns_of_its_own_effects() { + let mut doc = Document::new(200.0, 100.0); + let mut shadowed = square(&mut doc, Rect::new(0.0, 0.0, 6.0, 6.0), Color::BLACK); + shadowed.appearance = Appearance { effects: vec![drop_shadow()], ..Appearance::basic(black_fill(), Paint::None, 0.0) }.into(); + doc.symbols.push(Symbol { dynamic: false, name: "Shadowed".into(), art: Arc::new(shadowed) }); + let dot = square(&mut doc, Rect::new(0.0, 0.0, 6.0, 6.0), Color::BLACK); + let placed = instance(&mut doc, "Shadowed", Affine::translate((8.0, 0.0))); + let art = group(&mut doc, vec![dot, placed], false); + let brush = vectorcraft_brush::Brush { + name: "Scattered".into(), + kind: vectorcraft_brush::BrushKind::Scatter(vectorcraft_brush::Scatter { + art, + size: (100.0, 100.0), + spacing: (100.0, 100.0), + scatter: (0.0, 0.0), + rotation: (0.0, 0.0), + colorization: vectorcraft_brush::Colorization::None, + ..Default::default() + }), + }; + vectorcraft_brush::store(&mut doc, &[brush]); + let mut line = + Node::path(doc.alloc_id(), shapes::line((10.0, 50.0).into(), (90.0, 50.0).into()), Appearance::basic(Paint::None, solid(Color::BLACK), 1.0)); + line.appearance.stroke_mut().unwrap().brush = Some("Scattered".into()); + let edge = square(&mut doc, Rect::new(10.0, 60.0, 30.0, 80.0), LEAF); + let mut styled = group(&mut doc, vec![line, edge], false); + styled.appearance = Appearance { effects: vec![drop_shadow()], ..Appearance::default() }.into(); + put(&mut doc, named(styled, "Styled")); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let p = shown(&out.program); + assert!(p.contains("%AI14_BeginSymbol") && p.contains("1 (Anon 1) XW"), "{p}"); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); + + let later = instance(&mut doc, "Shadowed", Affine::translate((150.0, 20.0))); + put(&mut doc, later); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); +} + +/// A symbol whose stroke is written as its outline (an outside stroke): a scaled instance, a scaled +/// instance of a symbol holding it and a turned and mirrored instance are written as their art, +/// which keeps the stroke the canvas draws; a moved instance stays an instance. +#[test] +fn scaled_instances_of_symbols_with_outlined_strokes_are_written_as_their_art() { + let mut doc = Document::new(200.0, 100.0); + let mut look = Appearance::basic(Paint::None, solid(Color::BLACK), 4.0); + look.stroke_mut().unwrap().align = vectorcraft_doc::StrokeAlign::Outside; + let framed = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), look); + doc.symbols.push(Symbol { dynamic: false, name: "Framed".into(), art: Arc::new(framed) }); + let inner = instance(&mut doc, "Framed", Affine::IDENTITY); + let edge = square(&mut doc, Rect::new(20.0, 0.0, 30.0, 10.0), LEAF); + let outer = group(&mut doc, vec![inner, edge], false); + doc.symbols.push(Symbol { dynamic: false, name: "Outer".into(), art: Arc::new(outer) }); + let layer = doc.layers[0].id; + let turned = Affine::translate((150.0, 20.0)) * Affine::rotate(0.5) * Affine::new([-1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + for (name, xf) in [ + ("Framed", Affine::translate((40.0, 40.0)) * Affine::scale(2.0)), + ("Outer", Affine::translate((80.0, 10.0)) * Affine::scale(2.0)), + ("Framed", turned), + ("Framed", Affine::translate((170.0, 60.0))), + ] { + let one = instance(&mut doc, name, xf); + doc.insert(Some(layer), usize::MAX, one).unwrap(); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(back.symbols.iter().map(|s| s.name.as_str()).collect::>(), ["Framed", "Outer"]); + let kids = back.layers[0].children().unwrap(); + let kinds: Vec = kids.iter().map(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })).collect(); + assert_eq!(kinds, [false, false, false, true]); + // Each draws where it did, with the stroke the canvas draws: 4 pt wide whatever the scale. + let boxes = |d: &Document| -> Vec { + let b = d.symbol_boxes(); + let ids: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + ids.iter().map(|id| format!("{:?}", d.bounds_of_with(&[*id], true, &b).map(|r| [r.x0, r.y0, r.x1, r.y1].map(r3)))).collect() + }; + let (got, want) = (boxes(&back), boxes(&doc)); + same_lines(&[got[0].clone(), got[2].clone(), got[3].clone()], &[want[0].clone(), want[2].clone(), want[3].clone()]); + // `Outer` at twice its size from (80, 10): the frame's square is 20 pt from 80 with its 4 pt + // stroke outside, and the plain square is 40 to 60 pt in from it. + assert_eq!(got[1], format!("{:?}", Some([76.0, 6.0, 140.0, 34.0].map(r3)))); +} + +/// Scaled instances of a symbol holding a rounded rectangle with live corners, of one clipped by +/// it, of one holding type, of one holding a blend and of one holding an instance written as its +/// art (of a symbol with 9-slice guides), and instances that scale their symbol more than 100 +/// times (tiny, thin and stroked tiny objects, and a 10 pt square), are written as their art; +/// instances that scale a 10 pt square a thousandth, scale an ellipse unevenly or only move stay +/// instances. +#[test] +fn scaled_instances_of_symbols_drawn_only_at_their_own_size_are_written_as_their_art() { + let mut doc = Document::new(200.0, 100.0); + let live = vectorcraft_doc::LiveShape::Rectangle { + w: 100.0, + h: 100.0, + radii: [10.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::IDENTITY, + }; + let mut rounded = Node::new( + doc.alloc_id(), + NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false }, + ); + rounded.appearance = Appearance::basic(solid(LEAF), Paint::None, 0.0).into(); + // The same rounded rectangle clipping a square. + let mut frame = rounded.clone(); + frame.id = doc.alloc_id(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), LEAF); + let clipped = group(&mut doc, vec![frame, inside], true); + doc.symbols.push(Symbol { dynamic: false, name: "Rounded".into(), art: Arc::new(rounded) }); + doc.symbols.push(Symbol { dynamic: false, name: "Clipped".into(), art: Arc::new(clipped) }); + // A tiny square with a 1 pt stroke. + let mut dot = square(&mut doc, Rect::new(0.0, 0.0, 0.00001, 0.00001), LEAF); + dot.appearance = Appearance::basic(solid(LEAF), solid(Color::BLACK), 1.0).into(); + doc.symbols.push(Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(dot) }); + // A blend of two squares 20 pt apart with a step every 10 pt. + let keys = + vec![Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 2.0, 2.0), LEAF)), Arc::new(square(&mut doc, Rect::new(20.0, 0.0, 22.0, 2.0), LEAF))]; + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(10.0), ..Default::default() }; + let blend = Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }); + doc.symbols.push(Symbol { dynamic: false, name: "Steps".into(), art: Arc::new(blend) }); + // A symbol holding an instance of one with 9-slice guides. + let frame = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), LEAF)); + let corner = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), Color::BLACK)); + let sliced = Node::group(doc.alloc_id(), vec![frame, corner]); + doc.symbols.push(Symbol { dynamic: false, name: "Sliced".into(), art: Arc::new(sliced) }); + doc.set_symbol_nine_slice("Sliced", Some(vectorcraft_doc::SymbolNineSlice::default())); + let inner = instance(&mut doc, "Sliced", Affine::IDENTITY); + let holder = group(&mut doc, vec![inner], false); + doc.symbols.push(Symbol { dynamic: false, name: "Holder".into(), art: Arc::new(holder) }); + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(0.0, 10.0), "Hi", style(10.0, Color::BLACK)); + let typed = text_node(&mut doc, t); + doc.symbols.push(Symbol { dynamic: false, name: "Typed".into(), art: Arc::new(typed) }); + let tiny = square(&mut doc, Rect::new(0.0, 0.0, 0.00001, 0.00001), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Tiny".into(), art: Arc::new(tiny) }); + let thin = square(&mut doc, Rect::new(0.0, 0.0, 0.00001, 1.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Thin".into(), art: Arc::new(thin) }); + let plain = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Plain".into(), art: Arc::new(plain) }); + let oval = vectorcraft_doc::LiveShape::Ellipse { w: 10.0, h: 6.0, pie: (0.0, 360.0), xf: Affine::IDENTITY }; + let mut ellipse = Node::new( + doc.alloc_id(), + NodeKind::Path { path: oval.to_path(), rule: FillRule::NonZero, live: Some(Box::new(oval)), clipping: false, guide: false }, + ); + ellipse.appearance = Appearance::basic(solid(LEAF), Paint::None, 0.0).into(); + doc.symbols.push(Symbol { dynamic: false, name: "Oval".into(), art: Arc::new(ellipse) }); + let layer = doc.layers[0].id; + for (name, xf) in [ + ("Rounded", Affine::new([0.3, 0.0, 0.0, 0.1, 10.0, 10.0])), + ("Typed", Affine::translate((50.0, 50.0)) * Affine::scale(3.0)), + ("Tiny", Affine::translate((100.0, 50.0)) * Affine::scale(1e6)), + ("Plain", Affine::translate((150.0, 50.0)) * Affine::scale(1e-3)), + ("Plain", Affine::translate((150.0, 60.0)) * Affine::scale(1e3)), + ("Oval", Affine::translate((170.0, 20.0)) * Affine::new([3.0, 0.0, 0.0, 1.0, 0.0, 0.0])), + ("Thin", Affine::translate((100.0, 70.0)) * Affine::new([1e6, 0.0, 0.0, 10.0, 0.0, 0.0])), + ("Clipped", Affine::new([0.3, 0.0, 0.0, 0.1, 10.0, 30.0])), + ("Dot", Affine::translate((120.0, 70.0)) * Affine::scale(1e6)), + ("Steps", Affine::translate((10.0, 80.0)) * Affine::scale(5.0)), + ("Holder", Affine::scale(2.0)), + ("Holder", Affine::translate((5.0, 5.0))), + ] { + let one = instance(&mut doc, name, xf); + doc.insert(Some(layer), usize::MAX, one).unwrap(); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings); + let back = read_back(&doc); + let kids = back.layers[0].children().unwrap(); + let kinds: Vec = kids.iter().map(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })).collect(); + assert_eq!(kinds, [false, false, false, true, false, true, false, false, false, false, false, true]); + let b = kids[6].visual_bounds().map(|r| [r.x0, r.y0, r.x1, r.y1].map(r3)); + assert_eq!(b, Some([100.0, 70.0, 110.0, 80.0].map(r3))); + // The tiny square comes back 10 pt across, where the instance put it. + let b = kids[2].visual_bounds().map(|r| [r.x0, r.y0, r.x1, r.y1].map(r3)); + assert_eq!(b, Some([100.0, 50.0, 110.0, 60.0].map(r3))); +} + +/// A symbol whose art is a hidden path with two fills: the canvas draws a symbol's art even when +/// its root is hidden, so the definition's root is written shown and the instance still draws. +#[test] +fn a_symbol_whose_root_is_hidden_still_draws() { + let mut doc = Document::new(200.0, 100.0); + let mut look = Appearance::basic(solid(LEAF), Paint::None, 0.0); + look.items.push(AppearanceItem::Fill(FillLayer::new(solid(Color::BLACK)))); + let mut art = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), look); + art.visible = false; + doc.symbols.push(Symbol { dynamic: false, name: "Hidden".into(), art: Arc::new(art) }); + let layer = doc.layers[0].id; + let one = instance(&mut doc, "Hidden", Affine::translate((20.0, 20.0))); + doc.insert(Some(layer), usize::MAX, one).unwrap(); + let back = read_back(&doc); + let kids = back.layers[0].children().unwrap(); + assert!(matches!(kids[0].kind, NodeKind::SymbolInstance { .. })); + let mut shown = 0; + vectorcraft_doc::swatches::walk_with_masks(&back.symbols[0].art, &mut |m| { + shown += usize::from(m.visible && matches!(m.kind, NodeKind::Path { .. })) + }); + assert!(back.symbols[0].art.visible && shown > 0, "{:?}", back.symbols[0].art); +} + +/// The number of symbol instances in `n` and its subtree. +fn instances(n: &Node) -> usize { + let mut count = 0; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| count += usize::from(matches!(m.kind, NodeKind::SymbolInstance { .. }))); + count +} + +/// What `nodes` draw ([`paints_of`]). +fn paints_of_nodes(doc: &Document, nodes: &[Arc]) -> Vec { + let mut out = vec![]; + paints_of(doc, nodes, 1, &mut out); + out +} + +/// An instance with isolation, knockout or knockout shape of its own is written as its art, which +/// keeps them as a group's; a plain one beside it stays an instance. +#[test] +fn instances_with_a_groups_transparency_are_written_as_their_art() { + let mut doc = Document::new(200.0, 100.0); + let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); + let mut shape = instance(&mut doc, "Leaf", Affine::translate((10.0, 10.0))); + shape.knockout_shape = true; + let mut isolated = instance(&mut doc, "Leaf", Affine::translate((30.0, 10.0))); + isolated.isolate = true; + let mut knocks = instance(&mut doc, "Leaf", Affine::translate((50.0, 10.0))); + knocks.knockout = Knockout::On; + let plain = instance(&mut doc, "Leaf", Affine::translate((70.0, 10.0))); + let mut outer = group(&mut doc, vec![shape, isolated, knocks, plain], false); + outer.knockout = Knockout::On; + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, outer).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART]); + let back = read_back(&doc); + let kids = back.layers[0].children().unwrap()[0].children().unwrap().clone(); + let states: Vec<_> = kids.iter().map(|n| (matches!(n.kind, NodeKind::SymbolInstance { .. }), n.knockout_shape, n.isolate, n.knockout)).collect(); + assert_eq!( + states, + [ + (false, true, false, Knockout::Neutral), + (false, false, true, Knockout::Neutral), + (false, false, false, Knockout::On), + (true, false, false, Knockout::Neutral) + ] + ); + // Each group holds the symbol's art where the instance placed it. + for (i, k) in kids[..3].iter().enumerate() { + let b = k.geometric_bounds().unwrap(); + assert_eq!([b.x0, b.y0, b.x1, b.y1].map(r3), [10.0 + 20.0 * i as f64, 10.0, 20.0 + 20.0 * i as f64, 20.0].map(r3)); + } +} + +/// A symbol's definition is the same wherever its first instance lies: one first met deep in +/// opacity masks keeps its own masks and instances. +#[test] +fn a_symbol_first_used_deep_in_masks_is_defined_whole() { + let mut doc = Document::new(200.0, 100.0); + let leaf = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(leaf) }); + // `Deep`: a square with an opacity mask, and an instance of `Leaf`. + let mask_art = square(&mut doc, Rect::new(0.0, 0.0, 5.0, 5.0), Color::WHITE); + let mut veiled = square(&mut doc, Rect::new(0.0, 0.0, 20.0, 20.0), Color::BLACK); + veiled.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(mask_art), clip: true, invert: false, disabled: false, linked: true })); + let inner = instance(&mut doc, "Leaf", Affine::translate((5.0, 5.0))); + let deep = group(&mut doc, vec![veiled, inner], false); + doc.symbols.push(Symbol { dynamic: false, name: "Deep".into(), art: Arc::new(deep) }); + // Its only instance, in the art of an opacity mask seven masks deep. + let mut art = instance(&mut doc, "Deep", Affine::translate((50.0, 20.0))); + for _ in 0..7 { + let mut holder = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::gray(0.5)); + holder.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(art), clip: false, invert: false, disabled: false, linked: true })); + art = holder; + } + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, art).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::DEEP_MASKS || w == writer::SYMBOL_ART), "{:?}", out.warnings); + let back = read_back(&doc); + same_lines(&symbol_looks(&back), &symbol_looks(&doc)); + let deep = &back.symbols.iter().find(|s| s.name == "Deep").unwrap().art; + assert_eq!(instances(deep), 1); + let mut masks = 0; + deep.walk(&mut |n| masks += usize::from(n.extras().mask.is_some())); + assert_eq!(masks, 1); +} + +/// Symbols past the 4,096 the reader keeps are left out, their instances written as their art. +#[test] +fn symbols_past_the_readers_count_are_left_out() { + let mut doc = Document::new(200.0, 100.0); + for i in 0..=crate::import::MAX_SYMBOLS { + let art = square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), Color::gray(0.5)); + doc.symbols.push(Symbol { dynamic: false, name: format!("S{i}"), art: Arc::new(art) }); + } + // An instance of each, in the panel's order: the last one's symbol is past the count. + let layer = doc.layers[0].id; + for i in 0..=crate::import::MAX_SYMBOLS { + let one = instance(&mut doc, &format!("S{i}"), Affine::translate((10.0, 10.0))); + doc.insert(Some(layer), usize::MAX, one).unwrap(); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SYMBOL_COUNT, writer::SYMBOL_ART]); + let back = read_back(&doc); + assert_eq!(back.symbols.len(), crate::import::MAX_SYMBOLS); + assert!(back.symbols.iter().all(|s| s.name != format!("S{}", crate::import::MAX_SYMBOLS))); + let live = back.layers[0].children().unwrap().iter().map(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })).collect::>(); + assert_eq!(live.len(), crate::import::MAX_SYMBOLS + 1); + assert!(live[..crate::import::MAX_SYMBOLS].iter().all(|l| *l) && !live[crate::import::MAX_SYMBOLS]); +} + +/// With one place left under the reader's count, a symbol whose type holds an inline graphic with +/// an instance of another symbol (found only as its art is written) takes the last place, and that +/// instance is written as its art: no more definitions are written than the reader keeps. +#[test] +fn a_symbol_found_while_its_holder_is_written_keeps_within_the_readers_count() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + for i in 0..crate::import::MAX_SYMBOLS - 1 { + let art = square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), Color::gray(0.5)); + doc.symbols.push(Symbol { dynamic: false, name: format!("S{i}"), art: Arc::new(art) }); + let one = instance(&mut doc, &format!("S{i}"), Affine::translate((10.0, 10.0))); + doc.insert(Some(layer), usize::MAX, one).unwrap(); + } + let style = vectorcraft_doc::CharStyle { size: 18.0, fill: solid(Color::BLACK), ..vectorcraft_doc::CharStyle::default() }; + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(0.0, 20.0), "A", style.clone()); + t.runs.push(vectorcraft_doc::TextRun::inline(vectorcraft_doc::InlineArt::new("Inner"), style)); + let typed = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.symbols.push(Symbol { dynamic: false, name: "Typed".into(), art: Arc::new(typed) }); + // The inline graphic's art holds an instance of a symbol of its own. + let deeper = square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Deeper".into(), art: Arc::new(deeper) }); + let nested = instance(&mut doc, "Deeper", Affine::translate((1.0, 1.0))); + let edge = square(&mut doc, Rect::new(0.0, 0.0, 2.0, 2.0), LEAF); + let inner = group(&mut doc, vec![edge, nested], false); + doc.symbols.push(Symbol { dynamic: false, name: "Inner".into(), art: Arc::new(inner) }); + let one = instance(&mut doc, "Typed", Affine::translate((50.0, 50.0))); + doc.insert(Some(layer), usize::MAX, one).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let program = String::from_utf8_lossy(&out.program); + assert_eq!(program.matches("%AI14_BeginSymbol").count(), crate::import::MAX_SYMBOLS); + let back = read_back(&doc); + assert_eq!(back.symbols.len(), crate::import::MAX_SYMBOLS); + assert!(back.symbols.iter().any(|s| s.name == "Typed")); + assert!(matches!(back.layers[0].children().unwrap().last().unwrap().kind, NodeKind::SymbolInstance { .. })); +} + +/// A linked image in a symbol's art is embedded; a dynamic symbol and a symbol's export type are +/// reported left out. +#[test] +fn symbol_options_and_linked_images_in_symbols_are_reported() { + let mut doc = Document::new(200.0, 100.0); + let pixels = png_of(image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 0, 255, 255])))); + let link = vectorcraft_doc::LinkInfo { path: "/tmp/blue.png".into(), ..Default::default() }; + let picture = image_node(&mut doc, ImageBlob::new("image/png", pixels), (2, 2), Affine::scale(5.0), Some(link)); + doc.symbols.push(Symbol { dynamic: true, name: "Picture".into(), art: Arc::new(picture) }); + let one = instance(&mut doc, "Picture", Affine::translate((50.0, 10.0))); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, one).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SYMBOL_OPTIONS, writer::LINKS_EMBEDDED]); + let p = program_shown(&doc); + assert!(p.contains("%AI5_BeginRaster") && !p.contains("%AI5_BeginPlace"), "{p}"); + let back = read_back(&doc); + let NodeKind::Image(im) = &back.symbols[0].art.kind else { panic!("the symbol's image") }; + assert!(im.link.is_none()); + doc.symbols[0].dynamic = false; + doc.set_symbol_export_type("Picture", vectorcraft_doc::SymbolExportType::Graphic); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_OPTIONS, writer::LINKS_EMBEDDED]); +} + +/// Each of the nine registration points is written 1 to 9 by its place on the grid, row by row +/// from the top left, and read back. +#[test] +fn every_registration_point_is_written_by_its_place() { + for (point, written, read) in (0..9).map(|r| (r, r + 1, r)) { + let mut doc = Document::new(200.0, 100.0); + let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(art) }); + doc.set_symbol_registration("Mark", vectorcraft_doc::SymbolRegistration(point)); + let p = program_shown(&doc); + assert!(p.contains(&format!("%_{written} /Int (AI13PatternRegistrationType) ,\n")), "{point}: {p}"); + assert_eq!(read_back(&doc).symbol_registration("Mark"), vectorcraft_doc::SymbolRegistration(read), "{point}"); + } +} + +/// Symbols whose art is a group with a state of its own (a name, transparency, an opacity mask, a +/// clipping group) come back with it; the registration point shares the group's dictionary. +#[test] +fn symbols_whose_art_is_a_group_with_a_state_come_back() { + let mut doc = one_swatch_document(200.0, 100.0); + let pair = |doc: &mut Document| { + let a = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + let b = square(doc, Rect::new(5.0, 5.0, 15.0, 15.0), Color::rgb(1.0, 0.0, 0.0)); + vec![a, b] + }; + let kids = pair(&mut doc); + let labeled = named(group(&mut doc, kids, false), "Label"); + let kids = pair(&mut doc); + let faded = see_through(group(&mut doc, kids, false), 0.5, BlendMode::Multiply); + let kids = pair(&mut doc); + let mut masked = group(&mut doc, kids, false); + let mask_art = square(&mut doc, Rect::new(0.0, 0.0, 8.0, 8.0), Color::WHITE); + masked.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(mask_art), clip: true, invert: true, disabled: false, linked: true })); + let edge = clipping(&mut doc, shapes::ellipse(Rect::new(0.0, 0.0, 12.0, 12.0))); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 20.0, 20.0), Color::rgb(0.0, 0.0, 1.0)); + let window = group(&mut doc, vec![edge, inside], true); + let lone = square(&mut doc, Rect::new(0.0, 0.0, 6.0, 6.0), Color::gray(0.3)); + let lone_named = named(group(&mut doc, vec![lone], false), "Lone"); + for (name, art) in [("Labeled", labeled), ("Faded", faded), ("Masked", masked), ("Window", window), ("Lone", lone_named)] { + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + let one = instance(&mut doc, name, Affine::translate((20.0, 20.0))); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, one).unwrap(); + } + doc.set_symbol_registration("Labeled", vectorcraft_doc::SymbolRegistration(2)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + same_lines(&symbol_looks(&back), &symbol_looks(&doc)); + same_lines(&all_looks(&back), &all_looks(&doc)); + assert_eq!(export_ai_editing(&back, &opts()).unwrap().program, out.program); + let p = program_shown(&doc); + // The name and the registration point in one dictionary, the group not wrapped again. + assert!(p.contains("%AI14_BeginSymbol\n(Labeled)\n0 A\n0 Xw\n0 Ae\nu\n0.6 0 0.9 0.1 k\n"), "{p}"); + assert!(p.contains("%_/ArtDictionary :\n%_3 /Int (AI13PatternRegistrationType) ,\n%_/XMLUID : (Label) ; (AI10_ArtUID) ,\n%_;\n"), "{p}"); +} + +/// The names of symbols in every form a string takes: parentheses, a backslash, a slash, text +/// outside ASCII, an empty name (which the reader names `Symbol`); two symbols of one name keep the +/// first; an instance of a symbol the document doesn't have is an empty group, with a warning that +/// says so. +#[test] +fn symbol_names_and_missing_symbols() { + let mut doc = Document::new(200.0, 100.0); + let names = ["Paren (a)", "Back\\slash", "Path/To", "Hoja ñ 葉", "", "Twice"]; + for (i, name) in names.iter().chain(["Twice"].iter()).enumerate() { + let art = square(&mut doc, Rect::new(0.0, 0.0, 4.0 + i as f64, 4.0), Color::gray(0.5)); + doc.symbols.push(Symbol { dynamic: false, name: (*name).into(), art: Arc::new(art) }); + } + let layer = doc.layers[0].id; + for name in names { + let one = instance(&mut doc, name, Affine::translate((10.0, 10.0))); + doc.insert(Some(layer), usize::MAX, one).unwrap(); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + let names = names.map(|n| if n.is_empty() { "Symbol" } else { n }); + assert_eq!(back.symbols.iter().map(|s| s.name.as_str()).collect::>(), names); + let refs: Vec = back.layers[0] + .children() + .unwrap() + .iter() + .map(|n| match &n.kind { + NodeKind::SymbolInstance { symbol, .. } => symbol.clone(), + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!(refs, names); + // The first symbol of a name is the one defined. + let twice = &back.symbols.iter().find(|s| s.name == "Twice").unwrap().art; + assert_eq!(paints_of_nodes(&back, std::slice::from_ref(twice)), paints_of_nodes(&doc, std::slice::from_ref(&doc.symbols[5].art))); + // A missing symbol. + let lost = instance(&mut doc, "Gone", Affine::translate((40.0, 10.0))); + doc.insert(Some(layer), usize::MAX, lost).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::MISSING_SYMBOL]); + let back = read_back(&doc); + let last = back.layers[0].children().unwrap().last().unwrap().clone(); + assert!(matches!(&last.kind, NodeKind::Group { children, clip: false } if children.is_empty()), "{:?}", last.kind); +} + +/// On a large canvas, a symbol's art holding a gradient and a nested instance is defined at its own +/// size and comes back as it was. +#[test] +fn a_symbol_with_a_gradient_and_an_instance_on_a_large_canvas_comes_back() { + use vectorcraft_color::gradient::GradientGeom; + let mut doc = Document::new(20000.0, 100.0); + let leaf = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(leaf) }); + let geom = GradientGeom { start: (0.0, 0.0).into(), end: (40.0, 10.0).into(), aspect: 1.0, focal: None }; + let shaded = painted( + &mut doc, + shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 20.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(sunset(), Some(geom), None)))], + ); + let nested = instance(&mut doc, "Leaf", Affine::translate((25.0, 5.0)) * Affine::rotate(0.4)); + let both = group(&mut doc, vec![shaded, nested], false); + doc.symbols.push(Symbol { dynamic: false, name: "Both".into(), art: Arc::new(both) }); + let one = instance(&mut doc, "Both", Affine::translate((100.0, 10.0))); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, one).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART]); + let back = read_back(&doc); + same_lines(&symbol_looks(&back), &symbol_looks(&doc)); +} + +/// Instance matrices of every kind (turned, sheared, mirrored, scaled near the smallest area the +/// data keeps), nested in one another, are read back as written, and written again as the same +/// bytes. The matrices come from a fixed seed. +#[test] +fn generated_instance_matrices_come_back() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 + }; + for round in 0..40 { + let mut doc = one_swatch_document(300.0, 300.0); + let base = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "S0".into(), art: Arc::new(base) }); + let matrix = |next: &mut dyn FnMut() -> f64| { + // Four nested matrices together scale by at most 64, within the 100 an instance may. + let scale = 10f64.powf(next() * 3.0 - 3.0); + Affine::new([ + (next() * 4.0 - 2.0) * scale, + (next() * 4.0 - 2.0) * scale, + (next() * 4.0 - 2.0) * scale, + (next() * 4.0 - 2.0) * scale, + next() * 300.0, + next() * 300.0, + ]) + }; + // A chain of symbols, each holding an instance of the one before. + for level in 1..4 { + let xf = matrix(&mut next); + let inner = instance(&mut doc, &format!("S{}", level - 1), xf); + let dot = square(&mut doc, Rect::new(0.0, 0.0, 3.0, 3.0), Color::gray(0.4)); + let art = group(&mut doc, vec![dot, inner], false); + doc.symbols.push(Symbol { dynamic: false, name: format!("S{level}"), art: Arc::new(art) }); + } + let layer = doc.layers[0].id; + for _ in 0..6 { + let pick = format!("S{}", (next() * 4.0) as usize % 4); + let xf = matrix(&mut next); + let one = instance(&mut doc, &pick, xf); + doc.insert(Some(layer), usize::MAX, one).unwrap(); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + let back = read_back(&doc); + // Each instance written as one comes back with its matrix to ten decimals. + let written = |d: &Document| { + let mut all = vec![]; + for n in d.layers[0].children().unwrap().iter().chain(d.symbols.iter().map(|s| &s.art)) { + n.walk(&mut |m| { + if let NodeKind::SymbolInstance { symbol, xf } = &m.kind { + all.push((symbol.clone(), *xf)); + } + }); + } + all + }; + assert!(out.warnings.is_empty(), "round {round}: {:?}", out.warnings); + let (got, want) = (written(&back), written(&doc)); + assert_eq!(got.len(), want.len(), "round {round}"); + for (g, w) in got.iter().zip(&want) { + assert_eq!(g.0, w.0, "round {round}"); + for (a, b) in g.1.as_coeffs().iter().zip(w.1.as_coeffs()) { + assert!((a - b).abs() <= 1e-9 * b.abs().max(1.0), "round {round}: {:?} {:?}", g.1, w.1); + } + } + let again = export_ai_editing(&back, &opts()).unwrap().program; + same_lines(&shown(&again).lines().map(String::from).collect::>(), &shown(&out.program).lines().map(String::from).collect::>()); + assert_eq!(again, out.program, "round {round}"); + } + // About the smallest area the data keeps: an instance whose matrix keeps it stays one, one + // whose matrix (to ten decimals) loses it is written as its art. + for (xf, live) in [ + (Affine::new([1e-6, 0.0, 0.0, 1.1e-6, 50.0, 10.0]), true), + (Affine::new([1e-6, 0.0, 0.0, 0.9e-6, 50.0, 10.0]), false), + (Affine::new([1.0, 0.4, 2.5, 1.0000000001, 50.0, 10.0]), true), + (Affine::new([4e-11, 0.0, 0.0, 1e6, 50.0, 10.0]), false), + ] { + let mut doc = Document::new(200.0, 100.0); + let base = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "S0".into(), art: Arc::new(base) }); + let one = instance(&mut doc, "S0", xf); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, one).unwrap(); + let back = read_back(&doc); + assert_eq!(matches!(back.layers[0].children().unwrap()[0].kind, NodeKind::SymbolInstance { .. }), live, "{xf:?}"); + } +} + +/// Type in a symbol's art is written as its outlines (the reader reads no type there), so the +/// symbol and its instance come back; type on the layers stays type. +#[test] +fn type_in_a_symbols_art_is_written_as_its_outlines() { + let mut doc = Document::new(200.0, 100.0); + let label = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(0.0, 20.0), "Tag", style(18.0, Color::BLACK)); + let label = text_node(&mut doc, label); + doc.symbols.push(Symbol { dynamic: false, name: "Tag".into(), art: Arc::new(label) }); + let one = instance(&mut doc, "Tag", Affine::translate((20.0, 20.0))); + let plain = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 90.0), "Plain", style(18.0, Color::BLACK)); + let plain = text_node(&mut doc, plain); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, one).unwrap(); + doc.insert(Some(layer), usize::MAX, plain).unwrap(); + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::TYPE]); + assert_eq!(program(&doc).matches("/AI11Text :").count(), 1); + let back = read_back(&doc); + assert_eq!(back.symbols.len(), 1); + assert!(matches!(back.layers[0].children().unwrap()[0].kind, NodeKind::SymbolInstance { .. })); +} + +// ---------- art styles ---------- + +/// Effect `id` with its defaults and `params` over them. +fn fx(id: &str, params: serde_json::Value) -> vectorcraft_doc::Effect { + vectorcraft_effects::new_effect(id, ¶ms).unwrap() +} + +/// A path `name` over `r` filled with `fill` and stroked 2 pt in `stroke` (none when `Paint::None`), +/// with `effects`. +fn styled_rect(doc: &mut Document, name: &str, r: Rect, fill: Paint, stroke: Paint, effects: Vec) -> Node { + let mut ap = Appearance::basic(fill, stroke, 2.0); + ap.effects = effects; + named(Node::path(doc.alloc_id(), shapes::rectangle(r), ap), name) +} + +/// A 400 × 300 document whose objects keep their live effects as art styles: a drop shadow in a +/// color and one by darkness, an inner and an outer glow in that order, Feather, Round Corners, +/// Scribble, Convert to Shape, Offset Path, Outline Stroke on an open path, a drop shadow on a +/// gradient fill and on a group with transparency, a hidden effect, Pathfinder › Add on a group, a +/// hidden locked object, an opacity mask, an object linked to a graphic style; and a graphic style +/// of its own with two fills, a stroke, item transparency and effects. +fn styles_document() -> Document { + let mut doc = Document::new(400.0, 300.0); + let layer = doc.layers[0].id; + let add = |doc: &mut Document, n: Node| { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + }; + let red = solid(Color::rgb(0.9, 0.2, 0.1)); + let blue = solid(Color::rgb(0.1, 0.3, 0.8)); + let shadow = fx("stylize.dropShadow", serde_json::json!({"x": 6.0, "y": 4.0, "blur": 8.0, "opacity": 60.0, "color": "#203040"})); + let n = styled_rect(&mut doc, "Shadowed", Rect::new(10.0, 10.0, 60.0, 50.0), red.clone(), blue.clone(), vec![shadow.clone()]); + add(&mut doc, n); + let dark = fx("stylize.dropShadow", serde_json::json!({"shade": "darkness", "darkness": 40.0, "mode": "darken"})); + let n = styled_rect(&mut doc, "Darkened", Rect::new(70.0, 10.0, 120.0, 50.0), blue.clone(), Paint::None, vec![dark]); + add(&mut doc, n); + let glows = vec![ + fx("stylize.innerGlow", serde_json::json!({"source": "center", "blur": 3.0})), + fx("stylize.outerGlow", serde_json::json!({"blur": 9.0, "opacity": 50.0})), + ]; + let n = styled_rect(&mut doc, "Glowing", Rect::new(130.0, 10.0, 180.0, 50.0), red.clone(), Paint::None, glows); + add(&mut doc, n); + let n = styled_rect( + &mut doc, + "Soft", + Rect::new(190.0, 10.0, 240.0, 50.0), + blue.clone(), + Paint::None, + vec![fx("stylize.feather", serde_json::json!({"radius": 7.0}))], + ); + add(&mut doc, n); + let round = fx("stylize.roundCorners", serde_json::json!({"radius": 9.0})); + let n = styled_rect(&mut doc, "Rounded", Rect::new(250.0, 10.0, 300.0, 50.0), red.clone(), blue.clone(), vec![round]); + add(&mut doc, n); + let n = styled_rect( + &mut doc, + "Scribbled", + Rect::new(310.0, 10.0, 360.0, 50.0), + blue.clone(), + Paint::None, + vec![fx("stylize.scribble", serde_json::json!({}))], + ); + add(&mut doc, n); + let shape = fx("convertToShape.roundedRectangle", serde_json::json!({"relative": true, "extraW": 12.0, "extraH": 8.0, "radius": 5.0})); + let n = styled_rect(&mut doc, "Shaped", Rect::new(10.0, 70.0, 60.0, 110.0), red.clone(), Paint::None, vec![shape]); + add(&mut doc, n); + let offset = fx("path.offsetPath", serde_json::json!({"offset": 4.0, "joins": "miter", "miterLimit": 6.0})); + let n = styled_rect(&mut doc, "Offset", Rect::new(70.0, 70.0, 120.0, 110.0), blue.clone(), red.clone(), vec![offset]); + add(&mut doc, n); + let mut open = PathData::from_bezpath(&kurbo::BezPath::from_vec(vec![ + kurbo::PathEl::MoveTo((130.0, 110.0).into()), + kurbo::PathEl::LineTo((180.0, 70.0).into()), + ])); + open.subpaths.iter_mut().for_each(|sp| sp.closed = false); + let mut ap = Appearance::basic(Paint::None, red.clone(), 6.0); + ap.effects = vec![fx("path.outlineStroke", serde_json::json!({}))]; + let n = named(Node::path(doc.alloc_id(), open, ap), "Outlined"); + add(&mut doc, n); + let ramp = Gradient { + kind: GradientKind::Linear, + stops: vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.6, 0.2))], + ..Gradient::default() + }; + let graded = Paint::Gradient(Box::new(GradientPaint::new(ramp))); + let n = styled_rect(&mut doc, "Graded", Rect::new(190.0, 70.0, 240.0, 110.0), graded, Paint::None, vec![shadow.clone()]); + add(&mut doc, n); + let mut hidden_fx = fx("stylize.outerGlow", serde_json::json!({})); + hidden_fx.visible = false; + let mut quiet = styled_rect(&mut doc, "Quiet", Rect::new(250.0, 70.0, 300.0, 110.0), blue.clone(), Paint::None, vec![hidden_fx]); + quiet.visible = false; + quiet.locked = true; + add(&mut doc, quiet); + // A group with a shadow, transparency and a mask; a group merged by Pathfinder › Add. + let a = square(&mut doc, Rect::new(10.0, 130.0, 50.0, 170.0), Color::rgb(0.2, 0.6, 0.3)); + let b = square(&mut doc, Rect::new(30.0, 150.0, 70.0, 190.0), Color::rgb(0.6, 0.2, 0.5)); + let mut shaded = see_through(group(&mut doc, vec![a, b], false), 0.5, BlendMode::Multiply); + shaded.appearance = Appearance { effects: vec![shadow.clone()], ..Appearance::default() }.into(); + let mask_art = square(&mut doc, Rect::new(10.0, 130.0, 70.0, 160.0), Color::gray(0.0)); + shaded.extras_mut().mask = Some(OpacityMask { art: Arc::new(mask_art), clip: true, invert: false, disabled: false, linked: true }.into()); + add(&mut doc, named(shaded, "Shaded group")); + let a = square(&mut doc, Rect::new(90.0, 130.0, 130.0, 170.0), Color::rgb(0.9, 0.6, 0.1)); + let b = square(&mut doc, Rect::new(110.0, 150.0, 150.0, 190.0), Color::rgb(0.9, 0.6, 0.1)); + let mut merged = group(&mut doc, vec![a, b], false); + merged.appearance = Appearance { effects: vec![fx("pathfinder.add", serde_json::json!({}))], ..Appearance::default() }.into(); + add(&mut doc, named(merged, "Merged")); + // A graphic style of its own, and an object linked to one. + let mut fill_top = FillLayer::new(solid(Color::rgb(0.2, 0.2, 0.9))); + fill_top.opacity = 0.5; + fill_top.blend = BlendMode::Screen; + fill_top.effects = vec![fx("distort.twist", serde_json::json!({"angle": 30.0}))]; + let style_ap = Appearance { + items: vec![ + AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.9, 0.9, 0.1)))), + AppearanceItem::Fill(fill_top), + AppearanceItem::Stroke(StrokeLayer::new(solid(Color::BLACK), 3.0)), + ], + effects: vec![fx("warp.arc", serde_json::json!({"bend": 30.0})), shadow], + // The contents over every fill and stroke. + contents_index: Some(3), + }; + let mut layered = vectorcraft_doc::GraphicStyle::new("Layered", style_ap); + layered.id = 9; + layered.opacity = 0.8; + doc.graphic_styles.push(layered); + let sunshine = doc.graphic_style("Sunshine").unwrap().clone(); + let mut linked_obj = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(170.0, 130.0, 220.0, 170.0)), + sunshine.appearance_on(&Node::group(vectorcraft_doc::NodeId(0), vec![])).into_owned(), + ); + linked_obj.extras_mut().graphic_style = Some(sunshine.id); + add(&mut doc, named(linked_obj, "Sunny")); + doc +} + +/// Each object's name, kind, transparency, state, mask and appearance, and whether it is linked to a +/// graphic style (by name), compared with [`writer::same_appearance`] apart. +fn style_view(doc: &Document) -> Vec<(String, Appearance)> { + let mut out = vec![]; + for n in doc.layers.iter().flat_map(|l| l.children().cloned().unwrap_or_default()) { + let kind = match &n.kind { + NodeKind::Group { .. } => "group", + NodeKind::Path { .. } => "path", + NodeKind::Compound { .. } => "compound", + _ => "other", + }; + let link = n.extras().graphic_style.and_then(|id| doc.graphic_style_by_id(id)).map(|g| g.name.clone()); + let head = format!( + "{:?} {kind} {} {:?} isolate={} {:?} shown={} locked={} mask={} link={link:?} members={}", + n.name, + r3(f64::from(n.opacity)), + n.blend, + n.isolate, + n.knockout, + n.visible, + n.locked, + n.extras().mask.is_some(), + n.children().map_or(0, Vec::len) + ); + out.push((head, (*n.appearance).clone())); + } + out +} + +/// `ap` with its gradients' stops and kind only: their placement is the slice of gradients' (a +/// gradient comes back placed on the object, named after its definition). +fn unplaced(ap: &Appearance) -> Appearance { + let mut ap = ap.clone(); + for item in ap.items.iter_mut() { + let paint = match item { + AppearanceItem::Fill(f) => &mut f.paint, + AppearanceItem::Stroke(s) => &mut s.paint, + }; + if let Paint::Gradient(g) = paint { + (g.geom, g.swatch, g.angle) = (None, None, 0.0); + } + } + ap +} + +fn same_styles(got: &Document, want: &Document) { + let (g, w) = (style_view(got), style_view(want)); + same_lines(&g.iter().map(|(h, _)| h.clone()).collect::>(), &w.iter().map(|(h, _)| h.clone()).collect::>()); + for ((h, a), (_, b)) in g.iter().zip(&w) { + assert!(writer::same_appearance(&unplaced(a), &unplaced(b)), "{h}:\n got {a:?}\n want {b:?}"); + } + same_lines(&outlines(got), &outlines(want)); +} + +/// The points of `doc`'s objects and of their opacity masks, each path's fill rule and each +/// object's nesting, to the written precision. +fn outlines(doc: &Document) -> Vec { + fn walk(n: &Node, depth: usize, out: &mut Vec) { + let mut points = |path: &PathData, rule: Option| { + let mut s = format!("{depth} {:?} {rule:?}", n.name); + for sp in &path.subpaths { + s += &format!(" [closed={}", sp.closed); + for a in &sp.anchors { + s += &format!(" {:.2},{:.2}", a.p.x + 0.0, a.p.y + 0.0); + } + s += "]"; + } + out.push(s); + }; + match &n.kind { + NodeKind::Path { path, rule, .. } => points(path, Some(*rule)), + NodeKind::Compound { rule, children } => { + for c in children { + points(c.path_data().unwrap(), Some(*rule)); + } + } + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => { + out.push(format!("{depth} {:?} container", n.name)); + for c in children { + walk(c, depth + 1, out); + } + } + other => out.push(format!("{depth} {other:?}")), + } + if let Some(mask) = &n.extras().mask { + out.push(format!("{depth} mask clip={} invert={} disabled={} linked={}", mask.clip, mask.invert, mask.disabled, mask.linked)); + // The reader holds a mask's art in a group. + match &mask.art.kind { + NodeKind::Group { children, .. } if children.len() == 1 => walk(&children[0], depth + 1, out), + _ => walk(&mask.art, depth + 1, out), + } + } + } + let mut out = vec![]; + for l in doc.layers.iter() { + walk(l, 0, &mut out); + } + out +} + +/// Fails with the lines where `got` and `want` differ in more than their numbers' last written +/// decimal (a color read back from four decimals gives its other model's values again from them). +fn near_lines(got: &str, want: &str) { + let near = |a: &str, b: &str| { + let (a, b): (Vec<&str>, Vec<&str>) = (a.split(' ').collect(), b.split(' ').collect()); + a.len() == b.len() + && a.iter().zip(&b).all(|(x, y)| match (x.trim_start_matches("%_").parse::(), y.trim_start_matches("%_").parse::()) { + (Ok(x), Ok(y)) => (x - y).abs() <= 2e-3, + _ => x == y, + }) + }; + let (g, w): (Vec<&str>, Vec<&str>) = (got.lines().collect(), want.lines().collect()); + let differ: Vec = (0..g.len().max(w.len())) + .filter(|&i| !matches!((g.get(i), w.get(i)), (Some(a), Some(b)) if near(a, b))) + .map(|i| format!("line {i}:\n got {:?}\n want {:?}", g.get(i), w.get(i))) + .collect(); + assert!(differ.is_empty(), "{}", differ.join("\n")); +} + +#[test] +fn objects_with_live_effects_and_graphic_styles_are_read_back() { + let doc = styles_document(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::EFFECTS || w == writer::PANEL_STYLES), "{:?}", out.warnings); + let back = read_back(&doc); + same_styles(&back, &doc); + // The panel's styles, in its order, with their appearance and transparency. + let names = |d: &Document| d.graphic_styles.iter().map(|g| g.name.clone()).collect::>(); + assert_eq!(names(&back), names(&doc)); + for (g, w) in back.graphic_styles.iter().zip(doc.graphic_styles.iter()) { + assert!(writer::same_appearance(&g.appearance, &w.appearance), "{}:\n got {:?}\n want {:?}", w.name, g.appearance, w.appearance); + assert_eq!( + (r3(f64::from(g.opacity)), g.blend, g.isolate, g.knockout), + (r3(f64::from(w.opacity)), w.blend, w.isolate, w.knockout), + "{}", + w.name + ); + } + // A group's members come back as they were. + let members = |d: &Document, name: &str| { + let mut out = vec![]; + let g = d.layers[0].children().unwrap().iter().find(|n| n.name.as_deref() == Some(name)).unwrap().clone(); + view(g.children().unwrap(), 0, &mut out); + out + }; + same_lines(&members(&back, "Shaded group"), &members(&doc, "Shaded group")); + same_lines(&members(&back, "Merged"), &members(&doc, "Merged")); +} + +/// In a document with only a new document's graphic styles, an object linked to one of them keeps +/// its link: the panel's styles are written. +#[test] +fn a_link_to_a_built_in_graphic_style_is_read_back() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let sunshine = doc.graphic_style("Sunshine").unwrap().clone(); + let ap = sunshine.appearance_on(&Node::group(vectorcraft_doc::NodeId(0), vec![])).into_owned(); + // Without a link, a new document's styles are not written. + let mut plain = doc.clone(); + let unlinked = Node::path(plain.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 50.0)), ap.clone()); + plain.insert(Some(layer), usize::MAX, unlinked).unwrap(); + assert!(!program(&plain).contains("%AI9_BeginArtStyleList")); + let mut sunny = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 50.0)), ap); + sunny.extras_mut().graphic_style = Some(sunshine.id); + doc.insert(Some(layer), usize::MAX, named(sunny, "Sunny")).unwrap(); + assert_eq!(doc.graphic_styles, Document::new(1.0, 1.0).graphic_styles); + let back = read_back(&doc); + same_styles(&back, &doc); + let n = &back.layers[0].children().unwrap()[0]; + assert_eq!(n.extras().graphic_style.and_then(|id| back.graphic_style_by_id(id)).map(|g| g.name.as_str()), Some("Sunshine")); +} + +#[test] +fn art_styles_are_written_in_their_forms() { + let p = program_shown(&styles_document()); + // The styles in a non-printing block after the symbols' and before the palette; the panel's in + // its order first, then the objects' own. + let styles = p.find("%AI5_Begin_NonPrinting\nNp\n%AI9_BeginArtStyles\n/KnownStyle :\n(Default Graphic Style) /Name ,\n/ActiveStyle :\n").unwrap(); + assert!(styles < p.find("%AI5_BeginPalette").unwrap(), "{p}"); + let list = "%AI5_Begin_NonPrinting\nNp\n%AI9_BeginArtStyleList\n(Default Graphic Style)\n(Black Outline)\n(Heavy Ink)\n(Sunshine)\n(Layered)\n%AI9_EndArtStyleList\n%AI5_End_NonPrinting--\n"; + let at = p.find(list).unwrap(); + assert!(p.find("%AI5_EndPalette").unwrap() < at && at < p.find("%AI9_BeginDocumentData").unwrap(), "{p}"); + // A drop shadow on the object, after its stack and before its transparency. + assert!( + p.contains( + "/BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n1 /Int (blnd) ,\n0.6 /Real (opac) ,\n\ + 4 /Real (vert) ,\n6 /Real (horz) ,\n4 /Real (blur) ,\n/FillStyle : 0 O\n" + ), + "{p}" + ); + // The drawn look, its state block with the object's transparency, the object on `%_` lines + // painted with nothing, its name, and its style. + assert!(p.contains("U\n0 1 0 2 0 Xy\n0 0 Xd\n6 () XW\n%_0 XR\n%_0 1 0 0 0 Xy\n%_10 -10 m\n"), "{p}"); + assert!(p.contains("%_n\n%_/ArtDictionary :\n%_/XMLUID : (Shadowed) ; (AI10_ArtUID) ,\n%_;\n%_\n1 (Anon 1) XW\n"), "{p}"); + assert!(p.contains("%_n\n%_/ArtDictionary :\n%_/XMLUID : (Offset) ; (AI10_ArtUID) ,\n%_;\n%_\n1 (Anon "), "{p}"); + // The object linked to a graphic style names it. + assert!(p.contains("%_/XMLUID : (Sunny) ; (AI10_ArtUID) ,\n%_;\n%_\n1 (Sunshine) XW\n"), "{p}"); + // A group's members on `%_` lines, then its name and style. + assert!(p.contains("6 () XW\n%_u\n"), "{p}"); + assert!(p.contains("%_U\n%_/ArtDictionary :\n%_/XMLUID : (Merged) ; (AI10_ArtUID) ,\n%_;\n%_\n1 (Anon "), "{p}"); + // Objects of the same appearance share their style. + let two = { + let mut doc = Document::new(200.0, 100.0); + let shadow = fx("stylize.dropShadow", serde_json::json!({})); + for x in [10.0, 60.0] { + let n = styled_rect(&mut doc, "Twin", Rect::new(x, 10.0, x + 30.0, 40.0), solid(Color::BLACK), Paint::None, vec![shadow.clone()]); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + program(&doc) + }; + assert_eq!((two.matches("/KnownStyle :").count(), two.matches("1 (Anon 1) XW\n").count()), (1, 2), "{two}"); + assert!(!two.contains("%AI9_BeginArtStyleList"), "{two}"); +} + +/// Objects whose appearance the reader wouldn't read with their style are written as their +/// drawn look, with the warnings they were written with before; graphic styles it wouldn't read +/// are left out with a warning; and a document without effects or styles of its own has no art +/// styles. +#[test] +fn appearances_the_reader_wouldnt_read_are_their_drawn_look() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let shadow = fx("stylize.dropShadow", serde_json::json!({})); + // Two fills and an effect: the reader keeps such an object's drawn look. + let mut two = styled_rect(&mut doc, "Two fills", Rect::new(10.0, 10.0, 40.0, 40.0), solid(Color::BLACK), Paint::None, vec![shadow.clone()]); + let mut ap = (*two.appearance).clone(); + ap.items.push(AppearanceItem::Fill(FillLayer { opacity: 0.5, ..FillLayer::new(solid(Color::WHITE)) })); + two.appearance = ap.into(); + doc.insert(Some(layer), usize::MAX, two).unwrap(); + // A warp on a path: the reader keeps a path's drawn look for it. + let warped = styled_rect( + &mut doc, + "Warped", + Rect::new(50.0, 10.0, 80.0, 40.0), + solid(Color::BLACK), + Paint::None, + vec![fx("warp.arc", serde_json::json!({}))], + ); + doc.insert(Some(layer), usize::MAX, warped).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); + let p = String::from_utf8(out.program).unwrap(); + assert!(!p.contains("%AI9_BeginArtStyles") && !p.lines().any(|l| l.starts_with("1 (")), "{p}"); + let back = read_back(&doc); + assert!(back.layers[0].children().unwrap().iter().all(|n| n.appearance.effects.is_empty())); + // A graphic style with a gradient: left out, the others listed. + let ramp = Gradient { stops: vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)], ..Gradient::default() }; + let graded = Appearance::basic(Paint::Gradient(Box::new(GradientPaint::new(ramp))), Paint::None, 0.0); + doc.graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Graded", graded)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PANEL_STYLES), "{:?}", out.warnings); + let p = String::from_utf8(out.program).unwrap().replace("\r\n", "\n"); + assert!(p.contains("(Sunshine)\n%AI9_EndArtStyleList") && !p.contains("(Graded)"), "{p}"); + // Nothing styled: no art styles. + assert!(!program(&sample()).contains("ArtStyle")); +} + +/// A graphic style's opacity is read back within the written number's precision: the style and an +/// object's link to it stay. +#[test] +fn a_graphic_styles_opacity_is_compared_at_the_written_precision() { + let mut doc = Document::new(200.0, 100.0); + let ap = Appearance::basic(solid(Color::BLACK), Paint::None, 1.0); + let mut g = vectorcraft_doc::GraphicStyle::new("Fine", ap.clone()); + g.id = 1; + g.opacity = 0.123456; + *doc.graphic_styles = vec![g]; + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 50.0)), ap); + n.opacity = 0.123456; + n.extras_mut().graphic_style = Some(1); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::PANEL_STYLES), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(back.graphic_styles.len(), 1); + assert!((back.graphic_styles[0].opacity - 0.123456).abs() < 1e-3); + assert_eq!(back.layers[0].children().unwrap()[0].extras().graphic_style, Some(back.graphic_styles[0].id)); +} + +/// A compound shape draws as one area, which an art style's object wouldn't keep: it and a group +/// holding one are written as their drawn look, with a warning. +#[test] +fn compound_shapes_are_not_written_with_an_art_style() { + let shadow = || fx("stylize.dropShadow", serde_json::json!({})); + let shape = |doc: &mut Document| { + let a = square(doc, Rect::new(10.0, 10.0, 50.0, 50.0), Color::BLACK); + let b = square(doc, Rect::new(30.0, 30.0, 70.0, 70.0), Color::BLACK); + let mut g = group(doc, vec![a, b], false); + g.extras_mut().compound_shape = true; + g + }; + let mut own = Document::new(200.0, 100.0); + let mut n = shape(&mut own); + n.appearance = Appearance { effects: vec![shadow()], ..Appearance::default() }.into(); + let layer = own.layers[0].id; + own.insert(Some(layer), usize::MAX, n).unwrap(); + let mut nested = Document::new(200.0, 100.0); + let member = shape(&mut nested); + let mut n = group(&mut nested, vec![member], false); + n.appearance = Appearance { effects: vec![shadow()], ..Appearance::default() }.into(); + let layer = nested.layers[0].id; + nested.insert(Some(layer), usize::MAX, n).unwrap(); + for doc in [own, nested] { + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); + assert!(!shown(&out.program).contains("1 (Anon 1) XW")); + } +} + +/// Graphic styles the reader's style list wouldn't hold (a name over its limit, styles past its +/// count) are left out with a warning, and an object linked to one has no link. +#[test] +fn graphic_styles_past_the_lists_limits_are_left_out() { + let plain = || Appearance::basic(solid(Color::BLACK), Paint::None, 1.0); + let styled = |name: String, id: u32| { + let mut g = vectorcraft_doc::GraphicStyle::new(name, plain()); + g.id = id; + g + }; + // A name one byte over the limit, among others. + let mut doc = Document::new(200.0, 100.0); + let long = "n".repeat(1025); + *doc.graphic_styles = vec![styled("Before".into(), 1), styled(long.clone(), 2), styled("After".into(), 3)]; + let mut linked = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 50.0)), plain()); + linked.extras_mut().graphic_style = Some(2); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, linked).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PANEL_STYLES), "{:?}", out.warnings); + assert!(!shown(&out.program).contains(&long)); + let back = read_back(&doc); + let names: Vec<&str> = back.graphic_styles.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, ["Before", "After"]); + assert_eq!(back.layers[0].children().unwrap()[0].extras().graphic_style, None); + // A name at the limit is kept. + let at_limit = "n".repeat(1024); + doc.graphic_styles[1].name = at_limit.clone(); + assert!(read_back(&doc).graphic_styles.iter().any(|g| g.name == at_limit)); + // Styles past the count. + let mut many = Document::new(200.0, 100.0); + *many.graphic_styles = (1..=4097).map(|i| styled(format!("Style {i}"), i)).collect(); + let out = export_ai_editing(&many, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PANEL_STYLES), "{:?}", out.warnings); + let back = read_back(&many); + assert_eq!(back.graphic_styles.len(), 4096); + assert_eq!(back.graphic_styles.last().map(|g| g.name.as_str()), Some("Style 4096")); +} + +/// A member of a group whose Transform effect moves it is written where baking put it, not with +/// its own effects where it was. +#[test] +fn a_styled_member_of_a_moved_group_stays_where_it_draws() { + fn left_of_paths(n: &Node) -> f64 { + let own = n.path_data().map_or(f64::INFINITY, |p| kurbo::Shape::bounding_box(&p.to_bezpath()).x0); + n.children().map_or(own, |c| c.iter().map(|m| left_of_paths(m)).fold(own, f64::min)) + } + let mut doc = Document::new(300.0, 100.0); + let layer = doc.layers[0].id; + let shadow = fx("stylize.dropShadow", serde_json::json!({})); + let member = styled_rect(&mut doc, "Member", Rect::new(10.0, 10.0, 40.0, 40.0), solid(Color::BLACK), Paint::None, vec![shadow]); + let mut moved = group(&mut doc, vec![member], false); + moved.appearance = Appearance { effects: vec![fx("distort.transform", serde_json::json!({"moveH": 70.0}))], ..Appearance::default() }.into(); + doc.insert(Some(layer), usize::MAX, moved).unwrap(); + let back = read_back(&doc); + let left = left_of_paths(&back.layers[0]); + assert!((left - 80.0).abs() < 1e-3, "the art starts at x = {left}"); +} + +/// A hidden, locked styled group keeps its state when its members are shown and unlocked. +#[test] +fn a_styled_group_keeps_its_state_after_members_in_another() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let member = square(&mut doc, Rect::new(10.0, 10.0, 40.0, 40.0), Color::BLACK); + let mut shaded = group(&mut doc, vec![member], false); + shaded.appearance = Appearance { effects: vec![fx("stylize.dropShadow", serde_json::json!({}))], ..Appearance::default() }.into(); + shaded.visible = false; + shaded.locked = true; + doc.insert(Some(layer), usize::MAX, shaded).unwrap(); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + assert!(matches!(n.kind, NodeKind::Group { .. })); + assert_eq!(n.appearance.effects.len(), 1); + assert!(!n.visible && n.locked, "visible {} locked {}", n.visible, n.locked); +} + +/// Effects in a styled object's opacity mask are not its style's: leaving them out warns. +#[test] +fn effects_in_a_styled_objects_mask_are_warned_about() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let shadow = fx("stylize.dropShadow", serde_json::json!({})); + let mut n = styled_rect(&mut doc, "Masked", Rect::new(10.0, 10.0, 40.0, 40.0), solid(Color::BLACK), Paint::None, vec![shadow]); + let blurred = styled_rect( + &mut doc, + "Mask art", + Rect::new(10.0, 10.0, 40.0, 25.0), + solid(Color::gray(0.0)), + Paint::None, + vec![fx("blur.gaussian", serde_json::json!({}))], + ); + n.extras_mut().mask = Some(OpacityMask { art: Arc::new(blurred), clip: true, invert: false, disabled: false, linked: true }.into()); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); + assert!(shown(&out.program).contains("\n1 (Anon 1) XW\n")); +} + +/// On a large canvas no art style is written (the reader scales the styles of a large canvas): +/// objects with effects are written as their vector art with their geometry effects applied, with a +/// warning. +#[test] +fn a_large_canvas_writes_no_art_styles() { + let mut doc = Document::new(20000.0, 100.0); + let n = styled_rect( + &mut doc, + "Far", + Rect::new(10.0, 10.0, 40.0, 40.0), + solid(Color::BLACK), + Paint::None, + vec![fx("stylize.feather", serde_json::json!({}))], + ); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::LARGE_CANVAS_STYLES), "{:?}", out.warnings); + assert!(!String::from_utf8(out.program).unwrap().contains("ArtStyle")); +} + +#[test] +fn art_styles_write_the_same_bytes_again() { + let doc = styles_document(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert!(shown(&first.program).contains("\n1 (Anon 1) XW\n")); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + assert_eq!(private_data(&doc, &opts()).unwrap().0, private_data(&doc, &opts()).unwrap().0); + // What is read back is written as it was. + let again = export_ai_editing(&read_back(&doc), &opts()).unwrap().program; + near_lines(&rgb_without_cmyk(&shown(&again)), &rgb_without_cmyk(&shown(&first.program))); +} + +/// `program` with the CMYK equivalents of plain RGB colors blanked out: the first four numbers of +/// `c m y k r g b Xa` (or `XA`) and of an RGB gradient stop's `c m y k r g b 2 ... Bs`. Named and +/// spot RGB colors (`... (name) tint Xk`, `Xx` and spot stops) are not blanked; the document this +/// is used on has none. The Generic CMYK separation of a color at the edge of the press gamut can +/// land on one of two results that differ by up to 0.01 when the RGB changes in its last float +/// bits, as it does between the first save and the save of the reopened file, and the platform's +/// float math decides which. The RGB values stay compared. +fn rgb_without_cmyk(program: &str) -> String { + let blank = |line: &str| { + let (prefix, rest) = line.strip_prefix("%_").map_or(("", line), |r| ("%_", r)); + let t: Vec<&str> = rest.split(' ').collect(); + let color = t.len() == 8 && matches!(t[7], "Xa" | "XA"); + let stop = t.len() > 8 && t[7] == "2" && t.last() == Some(&"Bs"); + if color || stop { format!("{prefix}_ _ _ _ {}", t[4..].join(" ")) } else { line.to_string() } + }; + program.lines().map(blank).collect::>().join("\n") +} + +/// `n` on the first layer of `doc`. +fn put(doc: &mut Document, n: Node) { + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); +} + +fn drop_shadow() -> vectorcraft_doc::Effect { + fx("stylize.dropShadow", serde_json::json!({})) +} + +fn black_fill() -> Paint { + solid(Color::BLACK) +} + +/// An even-odd compound path of a square inside a square, with `ap`. +fn ring(doc: &mut Document, ap: Appearance) -> Node { + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(70.0, 10.0, 110.0, 50.0)), Appearance::default()); + let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(80.0, 20.0, 100.0, 40.0)), Appearance::default()); + let mut n = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + n.appearance = ap.into(); + n +} + +/// A path filled black with no stroke and `effects`. +fn plain_rect(doc: &mut Document, name: &str, effects: Vec) -> Node { + styled_rect(doc, name, Rect::new(10.0, 10.0, 50.0, 40.0), black_fill(), Paint::None, effects) +} + +/// A 200 × 100 document's first object as it reads back from a document of only `n`. +fn read_one(make: impl FnOnce(&mut Document) -> Node) -> (Arc, Vec, String) { + let mut doc = Document::new(200.0, 100.0); + let n = make(&mut doc); + put(&mut doc, n); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let back = read_back(&doc); + (back.layers[0].children().unwrap()[0].clone(), out.warnings, shown(&out.program)) +} + +/// A filled path or compound path with live effects that fills by the even-odd rule is written as its +/// drawn look with a warning, since a style's fill fills by the non-zero rule. A stroke-only object +/// keeps its style and its own fill rule. A filled even-odd object linked to a graphic style isn't +/// written with that style, and its link is left out with a warning. +#[test] +fn a_filled_even_odd_object_is_written_as_its_drawn_look() { + let mut doc = Document::new(300.0, 100.0); + let mut odd = plain_rect(&mut doc, "Odd", vec![drop_shadow()]); + if let NodeKind::Path { rule, .. } = &mut odd.kind { + *rule = FillRule::EvenOdd; + } + put(&mut doc, odd); + let ap = Appearance { effects: vec![drop_shadow()], ..Appearance::basic(black_fill(), Paint::None, 0.0) }; + let n = named(ring(&mut doc, ap), "Ring"); + put(&mut doc, n); + let n = plain_rect(&mut doc, "Even", vec![drop_shadow()]); + put(&mut doc, n); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); + let p = shown(&out.program); + assert_eq!((p.matches("/KnownStyle :").count(), p.matches("\n1 (Anon 1) XW\n").count()), (1, 1), "{p}"); + assert!(!p.contains("1 /Bool (UseEvenOdd)"), "{p}"); + + let mut doc = Document::new(300.0, 100.0); + let ap = Appearance { effects: vec![drop_shadow()], ..Appearance::basic(Paint::None, solid(Color::BLACK), 2.0) }; + let n = named(ring(&mut doc, ap), "Stroked"); + put(&mut doc, n); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); + let back = read_back(&doc); + same_styles(&back, &doc); + assert!(matches!(back.layers[0].children().unwrap()[0].kind, NodeKind::Compound { rule: FillRule::EvenOdd, .. })); + + let mut doc = Document::new(200.0, 100.0); + let ap = Appearance::basic(black_fill(), Paint::None, 0.0); + let mut g = vectorcraft_doc::GraphicStyle::new("Solid", ap.clone()); + g.id = 7; + doc.graphic_styles.push(g); + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap); + n.extras_mut().graphic_style = Some(7); + if let NodeKind::Path { rule, .. } = &mut n.kind { + *rule = FillRule::EvenOdd; + } + put(&mut doc, n); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::STYLE_LINKS), "{:?}", out.warnings); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + assert!(matches!(n.kind, NodeKind::Path { rule: FillRule::EvenOdd, .. }), "{n:?}"); + assert_eq!(n.extras().graphic_style, None); +} + +/// A compound path filled by the non-zero rule keeps its effects, its gradient fill and its link to +/// a graphic style. +#[test] +fn a_compound_path_keeps_its_style() { + let mut doc = Document::new(300.0, 100.0); + let non_zero = |mut n: Node| { + if let NodeKind::Compound { rule, .. } = &mut n.kind { + *rule = FillRule::NonZero; + } + n + }; + let ap = Appearance { effects: vec![drop_shadow()], ..Appearance::basic(black_fill(), solid(Color::WHITE), 2.0) }; + let n = named(non_zero(ring(&mut doc, ap)), "Shadowed"); + put(&mut doc, n); + let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)]; + let graded = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let ap = Appearance { effects: vec![drop_shadow()], ..Appearance::basic(graded, Paint::None, 0.0) }; + let n = named(non_zero(ring(&mut doc, ap)), "Graded"); + put(&mut doc, n); + let sunshine = doc.graphic_style("Sunshine").unwrap().clone(); + let ap = sunshine.appearance_on(&Node::group(vectorcraft_doc::NodeId(0), vec![])).into_owned(); + let mut linked_ring = named(ring(&mut doc, ap), "Linked"); + if let NodeKind::Compound { rule, .. } = &mut linked_ring.kind { + *rule = FillRule::NonZero; + } + linked_ring.extras_mut().graphic_style = Some(sunshine.id); + put(&mut doc, linked_ring); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::EFFECTS || w == writer::STYLE_LINKS), "{:?}", out.warnings); + let back = read_back(&doc); + same_styles(&back, &doc); + assert!(back.layers[0].children().unwrap().iter().all(|n| matches!(n.kind, NodeKind::Compound { .. }))); +} + +/// A group holding an image is written as its drawn look: the image stays a placed file, once. +#[test] +fn a_group_holding_an_image_is_written_as_its_drawn_look() { + let mut doc = Document::new(200.0, 100.0); + let link = Some(vectorcraft_doc::LinkInfo::new("/tmp/ramp.png")); + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), link); + let mut g = group(&mut doc, vec![im], false); + g.appearance = Appearance { effects: vec![drop_shadow()], ..Appearance::default() }.into(); + put(&mut doc, g); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == writer::LINKS_EMBEDDED), "{:?}", out.warnings); + assert!(!shown(&out.program).contains("(Anon 1)")); + let back = read_back(&doc); + let g = &back.layers[0].children().unwrap()[0]; + let member = g.children().map_or(g, |c| &c[0]); + let NodeKind::Image(im) = &member.kind else { panic!("{member:?}") }; + assert!(im.link.is_some()); +} + +/// A link to a graphic style that isn't written warns; one that is written doesn't. +#[test] +fn a_link_left_out_warns() { + let warns = |make: &dyn Fn(&mut Document, u32) -> Node| { + let mut doc = Document::new(200.0, 100.0); + let ap = Appearance { + items: vec![AppearanceItem::Fill(FillLayer::new(black_fill())), AppearanceItem::Fill(FillLayer::new(solid(Color::WHITE)))], + ..Appearance::default() + }; + let mut layered = vectorcraft_doc::GraphicStyle::new("Layered", ap); + layered.id = 7; + doc.graphic_styles.push(layered); + let mut plain = vectorcraft_doc::GraphicStyle::new("Plain", Appearance::basic(black_fill(), Paint::None, 0.0)); + plain.id = 8; + doc.graphic_styles.push(plain); + let n = make(&mut doc, 7); + put(&mut doc, n); + let warned = export_ai_editing(&doc, &opts()).unwrap().warnings.iter().any(|w| w == writer::STYLE_LINKS); + (warned, read_back(&doc)) + }; + let linked = |mut n: Node, id: u32| { + n.extras_mut().graphic_style = Some(id); + n + }; + // A style of two fills: a path isn't read with it. + let (warned, back) = warns(&|doc, id| { + let ap = doc.graphic_style_by_id(id).unwrap().appearance.clone(); + linked(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap), id) + }); + assert!(warned); + assert_eq!(back.layers[0].children().unwrap()[0].extras().graphic_style, None); + assert!(back.graphic_style("Layered").is_some()); + // An image, a symbol instance and a knockout shape are never written with a style. + let (warned, _) = warns(&|doc, _| { + let art = square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), Color::BLACK); + doc.symbols.push(Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); + linked(Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::translate((50.0, 20.0)) }), 8) + }); + assert!(warned); + let (warned, _) = warns(&|doc, _| { + let mut n = plain_rect(doc, "Out", vec![]); + n.knockout_shape = true; + linked(n, 8) + }); + assert!(warned); + // A group with a member the style can't hold. + let (warned, _) = warns(&|doc, _| { + let member = plain_rect(doc, "Member", vec![drop_shadow()]); + linked(group(doc, vec![member], false), 8) + }); + assert!(warned); + // A group with an effect and a member linked to a style: the group keeps its effect, and the + // member's link is left out. + let (warned, back) = warns(&|doc, _| { + let member = linked(plain_rect(doc, "Member", vec![]), 8); + let mut g = group(doc, vec![member], false); + g.appearance = Appearance { effects: vec![drop_shadow()], ..Appearance::default() }.into(); + g + }); + assert!(warned); + let g = &back.layers[0].children().unwrap()[0]; + assert_eq!(g.appearance.effects.len(), 1, "{g:?}"); + assert_eq!(g.children().unwrap()[0].extras().graphic_style, None); + // A group whose link isn't written: its member keeps its own. + let (warned, back) = warns(&|doc, id| { + let plain = doc.graphic_style_by_id(id + 1).unwrap().appearance.clone(); + let member = linked(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), plain), id + 1); + linked(group(doc, vec![member], false), id) + }); + assert!(warned); + let g = &back.layers[0].children().unwrap()[0]; + assert_eq!(g.extras().graphic_style, None); + let member = g.children().unwrap()[0].extras().graphic_style.unwrap(); + assert_eq!(back.graphic_style_by_id(member).map(|s| s.name.as_str()), Some("Plain")); + // A link in a symbol's art. + let (warned, _) = warns(&|doc, _| { + let art = linked(square(doc, Rect::new(0.0, 0.0, 10.0, 10.0), Color::BLACK), 8); + doc.symbols.push(Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) }); + Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::translate((50.0, 20.0)) }) + }); + assert!(warned); + // A link that is kept. + let (warned, back) = warns(&|doc, id| { + let plain = doc.graphic_style_by_id(id + 1).unwrap().appearance.clone(); + linked(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), plain), id + 1) + }); + assert!(!warned); + let id = back.layers[0].children().unwrap()[0].extras().graphic_style.unwrap(); + assert_eq!(back.graphic_style_by_id(id).map(|g| g.name.as_str()), Some("Plain")); +} + +/// A panel with no style written warns that a new document's styles come back. +#[test] +fn an_empty_graphic_styles_panel_warns() { + let mut doc = Document::new(200.0, 100.0); + doc.graphic_styles.clear(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PANEL_EMPTY), "{:?}", out.warnings); + assert!(!shown(&out.program).contains("ArtStyle")); + assert_eq!(read_back(&doc).graphic_styles, Document::new(1.0, 1.0).graphic_styles); + // Every style left out. + let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)]; + let graded = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + doc.graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Graded", Appearance::basic(graded, Paint::None, 0.0))); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PANEL_EMPTY) && out.warnings.iter().any(|w| w == writer::PANEL_STYLES), "{:?}", out.warnings); + // A new document's styles aren't written and don't warn. + let out = export_ai_editing(&Document::new(200.0, 100.0), &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::PANEL_EMPTY), "{:?}", out.warnings); +} + +/// A second style of one name is left out with a warning, and an object linked to it has no link. +#[test] +fn a_graphic_style_of_a_name_another_has_is_left_out() { + let mut doc = Document::new(200.0, 100.0); + let style = |id: u32, c: Color| { + let mut g = vectorcraft_doc::GraphicStyle::new("Twin", Appearance::basic(solid(c), Paint::None, 0.0)); + g.id = id; + g + }; + *doc.graphic_styles = vec![style(1, Color::BLACK), style(2, Color::WHITE)]; + let mut n = styled_rect(&mut doc, "Second", Rect::new(10.0, 10.0, 50.0, 40.0), solid(Color::WHITE), Paint::None, vec![]); + n.extras_mut().graphic_style = Some(2); + put(&mut doc, n); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PANEL_STYLES) && out.warnings.iter().any(|w| w == writer::STYLE_LINKS), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(back.graphic_styles.len(), 1); + assert_eq!(back.graphic_styles[0].appearance.fill().and_then(|f| f.paint.color()), Some(Color::BLACK)); + assert_eq!(back.layers[0].children().unwrap()[0].extras().graphic_style, None); +} + +/// A path or compound path with no points writes nothing, with or without a style; a group with no +/// members keeps its effects. +#[test] +fn objects_with_nothing_to_write_are_left_out() { + let mut doc = Document::new(200.0, 100.0); + let mut empty = plain_rect(&mut doc, "Empty", vec![drop_shadow()]); + if let NodeKind::Path { path, .. } = &mut empty.kind { + path.subpaths.clear(); + } + put(&mut doc, empty); + let mut hollow = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![], rule: FillRule::NonZero }); + hollow.appearance = Appearance { effects: vec![drop_shadow()], ..Appearance::basic(black_fill(), Paint::None, 0.0) }.into(); + put(&mut doc, named(hollow, "Hollow")); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); + let p = shown(&out.program); + assert!(!p.contains("(Anon 1)") && !p.contains("(Empty)") && !p.contains("6 () XW"), "{p}"); + assert_eq!(read_back(&doc).layers[0].children().unwrap().len(), 0); + + let (n, ..) = read_one(|doc| { + let mut g = group(doc, vec![], false); + g.appearance = Appearance { effects: vec![drop_shadow()], ..Appearance::default() }.into(); + named(g, "Bare") + }); + assert_eq!((n.name.as_deref(), n.appearance.effects.len(), n.children().map(Vec::len)), (Some("Bare"), 1, Some(0))); +} + +/// Outline Object, every Convert to Shape form and size, Offset Path's joins, Inner Glow's sources +/// and a stroke's width profile, each on an object, read back as they are. Drop Shadow and the glows +/// keep their colors, in CMYK too. +#[test] +fn every_effect_setting_written_on_an_object_is_read_back() { + use serde_json::json; + let cases = [ + ("path.outlineObject", json!({})), + ("path.outlineStroke", json!({})), + ("convertToShape.rectangle", json!({"relative": true, "extraW": 6.0, "extraH": 4.0})), + ("convertToShape.rectangle", json!({"relative": false, "width": 30.0, "height": 20.0})), + ("convertToShape.roundedRectangle", json!({"relative": false, "width": 30.0, "height": 20.0, "radius": 3.0})), + ("convertToShape.roundedRectangle", json!({"relative": true, "extraW": 6.0, "extraH": 4.0, "radius": 3.0})), + ("convertToShape.ellipse", json!({"relative": false, "width": 30.0, "height": 20.0})), + ("path.offsetPath", json!({"offset": 3.0, "joins": "round", "miterLimit": 4.0})), + ("path.offsetPath", json!({"offset": -3.0, "joins": "bevel", "miterLimit": 4.0})), + ("path.offsetPath", json!({"offset": 3.0, "joins": "miter", "miterLimit": 9.0})), + ("stylize.innerGlow", json!({"source": "edge", "blur": 2.5, "opacity": 40.0, "mode": "screen", "color": "#102030"})), + ("stylize.innerGlow", json!({"source": "center", "blur": 2.5})), + ("stylize.outerGlow", json!({"blur": 7.5, "opacity": 33.333, "mode": "normal", "color": "#a0b0c0"})), + ("stylize.dropShadow", json!({"x": 1.25, "y": -2.5, "blur": 3.5, "opacity": 12.5, "mode": "overlay", "color": "#405060"})), + ("stylize.dropShadow", json!({"shade": "darkness", "darkness": 62.5, "x": 0.0, "y": 0.0, "blur": 0.0})), + ("stylize.feather", json!({"radius": 11.5})), + ("stylize.roundCorners", json!({"radius": 0.5})), + ( + "stylize.scribble", + json!({"angle": 15.0, "overlap": 2.0, "overlapVariation": 1.0, "strokeWidth": 1.5, "curviness": 12.5, "curvinessVariation": 7.5, "spacing": 4.0, "spacingVariation": 1.5}), + ), + ]; + for (id, params) in cases { + let effect = fx(id, params.clone()); + let (n, warnings, p) = read_one(|doc| plain_rect(doc, "One", vec![effect.clone()])); + assert!(!warnings.iter().any(|w| w == writer::EFFECTS), "{id} {params}: {warnings:?}\n{p}"); + assert_eq!(n.appearance.effects.len(), 1, "{id} {params}"); + let (got, want) = (&n.appearance.effects[0], &effect); + assert_eq!(got.id, want.id); + let (g, w) = (vectorcraft_effects::merged_params(&got.id, &got.params), vectorcraft_effects::merged_params(&want.id, &want.params)); + for (key, value) in w.as_object().unwrap() { + let read = g.get(key).unwrap_or(&serde_json::Value::Null); + match (key.as_str(), value.as_f64()) { + // A case the file doesn't keep: `seed` and the like, which the reader fills in as their defaults. + ("mode" | "shade" | "source" | "joins", _) => { + let lower = |v: &serde_json::Value| v.as_str().unwrap_or_default().to_ascii_lowercase(); + assert_eq!(lower(read), lower(value), "{id} {key}"); + } + ("color", _) => { + let color = |p: &serde_json::Value| vectorcraft_effects::color_param(p, Color::BLACK).to_hex(); + assert_eq!(color(&g), color(&w), "{id}"); + } + (_, Some(v)) => assert!((read.as_f64().unwrap() - v).abs() < 6e-3, "{id} {key}: {read} for {v}"), + _ => assert_eq!(read, value, "{id} {key}"), + } + } + } + // A relative Ellipse: the reader keeps the drawn look, which is the effect's result. + let effect = fx("convertToShape.ellipse", json!({"relative": true, "extraW": 6.0, "extraH": 4.0})); + let (n, _, p) = read_one(|doc| plain_rect(doc, "One", vec![effect.clone()])); + assert!(!p.contains("%AI9_BeginArtStyles"), "{p}"); + assert!(n.appearance.effects.is_empty()); + // A stroke's width profile. + let profile = vectorcraft_doc::WidthProfile { points: vec![(0.0, 1.0, 0.5), (0.5, 0.25, 0.75), (1.0, 0.0, 1.0)] }; + let (n, warnings, p) = read_one(|doc| { + let mut stroke = StrokeLayer::new(black_fill(), 4.0); + stroke.profile = Some(profile.clone()); + let ap = Appearance { items: vec![AppearanceItem::Stroke(stroke)], effects: vec![drop_shadow()], contents_index: None }; + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap) + }); + assert!(!warnings.iter().any(|w| w == writer::EFFECTS), "{warnings:?}"); + assert!(p.contains("(BSVariableWidthTValuesArray)") && p.contains("(BSLeftWidthsArray)") && p.contains("(BSRightWidthsArray)"), "{p}"); + assert_eq!(n.appearance.stroke().and_then(|s| s.profile.clone()), Some(profile)); + // A CMYK document: a CMYK and a spot fill, a CMYK stroke, and an effect's CMYK color stay as they are. + let mut doc = Document::new(200.0, 100.0); + doc.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let mut swatches = (*doc.swatches).clone(); + swatches.push(Swatch { name: "Ink".into(), paint: solid(INK), global: true, spot: true }); + swatches.push(Swatch { name: "Brand".into(), paint: solid(BRAND), global: true, spot: false }); + doc.swatches = swatches.into(); + let shadow = fx("stylize.dropShadow", json!({"color": serde_json::to_value(GOLD).unwrap()})); + let n = styled_rect(&mut doc, "Process", Rect::new(10.0, 10.0, 40.0, 40.0), solid(GOLD), solid(BRAND), vec![shadow.clone()]); + put(&mut doc, n); + let n = styled_rect(&mut doc, "Spot", Rect::new(50.0, 10.0, 80.0, 40.0), linked("Ink", INK, 0.5), Paint::None, vec![shadow.clone()]); + put(&mut doc, n); + let n = styled_rect(&mut doc, "Global", Rect::new(90.0, 10.0, 120.0, 40.0), linked("Brand", BRAND, 1.0), Paint::None, vec![shadow]); + put(&mut doc, n); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); + let back = read_back(&doc); + same_styles(&back, &doc); + for n in back.layers[0].children().unwrap() { + assert!(matches!(vectorcraft_effects::color_param(&n.appearance.effects[0].params, Color::BLACK), Color::Cmyk { .. }), "{n:?}"); + } + let spot = &back.layers[0].children().unwrap()[1]; + assert!(matches!(&spot.appearance.fill().unwrap().paint, Paint::Solid { swatch: Some(s), .. } if s == "Ink"), "{spot:?}"); +} + +/// Each effect a graphic style can hold, in a style of its own, reads back with its settings, whatever +/// the writer's conversions to the file's units. +#[test] +fn every_effect_a_graphic_style_holds_is_read_back() { + use serde_json::json; + let mut cases = vec![ + ( + "distort.transform", + json!({"scaleH": 50.0, "scaleV": 150.0, "moveH": 12.5, "moveV": -7.5, "rotate": 30.0, "copies": 2, "reference": 8, "reflectX": true, "objects": false, "strokes": true, "patterns": true}), + ), + ("distort.freeDistort", json!({"corners": [[0.1, 0.05], [0.9, 0.1], [1.0, 1.0], [0.0, 0.8]]})), + ("distort.puckerBloat", json!({"amount": -40.0})), + ("distort.puckerBloat", json!({"amount": 60.0})), + ("distort.twist", json!({"angle": -45.0})), + ("distort.zigZag", json!({"size": 7.5, "relative": false, "ridges": 6, "points": "corner"})), + ("distort.zigZag", json!({"size": 25.0, "relative": true, "ridges": 3, "points": "smooth"})), + ("blur.gaussian", json!({"radius": 2.5})), + ]; + let warps = [ + "arc", + "arcLower", + "arcUpper", + "arch", + "bulge", + "shellLower", + "shellUpper", + "flag", + "wave", + "fish", + "rise", + "fisheye", + "inflate", + "squeeze", + "twist", + ]; + let ids: Vec = warps.iter().map(|w| format!("warp.{w}")).collect(); + for id in &ids { + cases.push((id, json!({"bend": 30.0, "horizontal": -10.0, "vertical": 20.0, "orientation": "vertical"}))); + cases.push((id, json!({"bend": -30.0, "horizontal": 0.0, "vertical": 0.0, "orientation": "horizontal"}))); + } + for (id, params) in cases { + let effect = fx(id, params.clone()); + let mut doc = Document::new(200.0, 100.0); + let mut g = vectorcraft_doc::GraphicStyle::new( + "Held", + Appearance { effects: vec![effect.clone()], ..Appearance::basic(black_fill(), Paint::None, 0.0) }, + ); + g.id = 3; + *doc.graphic_styles = vec![g]; + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::PANEL_STYLES), "{id} {params}: {:?}", out.warnings); + let back = read_back(&doc); + let got = &back.graphic_styles[0].appearance.effects; + assert_eq!(got.len(), 1, "{id} {params}"); + assert_eq!(got[0].id, effect.id); + let (g, w) = (vectorcraft_effects::merged_params(&got[0].id, &got[0].params), vectorcraft_effects::merged_params(&effect.id, &effect.params)); + for (key, value) in w.as_object().unwrap() { + // Random isn't written, and a style with it isn't read; its seed is the default. + let read = g.get(key).unwrap_or(&serde_json::Value::Null); + match value { + serde_json::Value::Array(rows) => { + let got = read.as_array().unwrap(); + assert_eq!(got.len(), rows.len(), "{id}"); + for (r, w) in got.iter().zip(rows) { + for (r, w) in r.as_array().unwrap().iter().zip(w.as_array().unwrap()) { + assert!((r.as_f64().unwrap() - w.as_f64().unwrap()).abs() < 6e-3, "{id} {key}: {read} for {value}"); + } + } + } + serde_json::Value::Number(v) => assert!((read.as_f64().unwrap() - v.as_f64().unwrap()).abs() < 6e-3, "{id} {key}: {read} for {v}"), + serde_json::Value::String(v) => assert_eq!(read.as_str().map(str::to_ascii_lowercase), Some(v.to_ascii_lowercase()), "{id} {key}"), + _ => assert_eq!(read, value, "{id} {key}"), + } + } + } + // A Zig Zag with its 0 to 1 settings written under the size's own key, and a turn in radians. + let mut doc = Document::new(200.0, 100.0); + let effects = vec![ + fx("distort.zigZag", json!({"size": 7.5, "relative": false, "ridges": 6, "points": "corner"})), + fx("distort.transform", json!({"moveV": -7.5, "rotate": 30.0})), + ]; + doc.graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Forms", Appearance { effects, ..Appearance::default() })); + let p = program_shown(&doc); + assert!(p.contains("7.5 /Real (amount) ,") && p.contains("0 /Real (roundness) ,"), "{p}"); + assert!(p.contains("7.5 /Real (moveV_Pts) ,") && p.contains("0.5236 /Real (rotate_Radians) ,"), "{p}"); +} + +/// Every kind of appearance a style isn't written for is written as its drawn look, with a warning. +#[test] +fn appearances_written_as_their_drawn_look() { + type Make = Box Node>; + let cases: Vec<(&str, Make)> = vec![ + ( + "a pattern fill", + Box::new(|doc| { + let tile = square(doc, Rect::new(0.0, 0.0, 5.0, 5.0), Color::BLACK); + let mut dots = vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(tile)]); + dots.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.push(dots); + let fill = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }; + styled_rect(doc, "P", Rect::new(10.0, 10.0, 50.0, 40.0), fill, Paint::None, vec![drop_shadow()]) + }), + ), + ( + "an overprinting fill", + Box::new(|doc| { + let ap = Appearance { + items: vec![AppearanceItem::Fill(FillLayer { overprint: true, ..FillLayer::new(black_fill()) })], + effects: vec![drop_shadow()], + contents_index: None, + }; + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap) + }), + ), + ( + "an overprinting stroke", + Box::new(|doc| { + let ap = Appearance { + items: vec![AppearanceItem::Stroke(StrokeLayer { overprint: true, ..StrokeLayer::new(black_fill(), 2.0) })], + effects: vec![drop_shadow()], + contents_index: None, + }; + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap) + }), + ), + ( + "a gradient stroke", + Box::new(|doc| { + let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)]; + let graded = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + styled_rect(doc, "G", Rect::new(10.0, 10.0, 50.0, 40.0), Paint::None, graded, vec![drop_shadow()]) + }), + ), + ( + "a fill with an opacity of its own", + Box::new(|doc| { + let ap = Appearance { + items: vec![AppearanceItem::Fill(FillLayer { opacity: 0.5, ..FillLayer::new(black_fill()) })], + effects: vec![drop_shadow()], + contents_index: None, + }; + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap) + }), + ), + ( + "a fill with an effect of its own", + Box::new(|doc| { + let fill = FillLayer { effects: vec![fx("stylize.feather", serde_json::json!({}))], ..FillLayer::new(black_fill()) }; + let ap = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Appearance::default() }; + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap) + }), + ), + ("Pathfinder on a path", Box::new(|doc| plain_rect(doc, "P", vec![fx("pathfinder.add", serde_json::json!({}))]))), + ( + "a group with a fill of its own", + Box::new(|doc| { + let member = square(doc, Rect::new(10.0, 10.0, 40.0, 40.0), Color::BLACK); + let mut g = group(doc, vec![member], false); + g.appearance = Appearance { effects: vec![drop_shadow()], ..Appearance::basic(solid(Color::WHITE), Paint::None, 0.0) }.into(); + g + }), + ), + ("an effect the style doesn't hold", Box::new(|doc| plain_rect(doc, "B", vec![fx("blur.gaussian", serde_json::json!({}))]))), + ( + "a group whose member's stroke is written as its outline", + Box::new(|doc| { + let mut stroke = StrokeLayer::new(solid(Color::BLACK), 4.0); + stroke.profile = Some(vectorcraft_doc::WidthProfile { points: vec![(0.0, 1.0, 0.5), (0.5, 0.25, 0.75), (1.0, 0.0, 1.0)] }); + let ap = Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Appearance::default() }; + let member = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 40.0, 40.0)), ap); + let mut g = group(doc, vec![member], false); + let effects = vec![fx("stylize.roundCorners", serde_json::json!({})), drop_shadow()]; + g.appearance = Appearance { effects, ..Appearance::default() }.into(); + g + }), + ), + ( + "a group whose effects reshape a member filled with pattern tiles", + Box::new(|doc| { + let big = square(doc, Rect::new(-2.0, -2.0, 6.0, 6.0), Color::rgb(1.0, 0.0, 0.0)); + let mut over = vectorcraft_doc::PatternDef::new("Over", vec![Arc::new(big)]); + over.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.push(over); + let tiles = Paint::Pattern { pattern: "Over".into(), xf: Affine::IDENTITY }; + let member = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::basic(tiles, Paint::None, 0.0)); + let mut g = group(doc, vec![member], false); + let offset = fx("path.offsetPath", serde_json::json!({"offset": 3.0})); + g.appearance = Appearance { effects: vec![offset, drop_shadow()], ..Appearance::default() }.into(); + g + }), + ), + ( + "a group whose effects reshape a member with a gradient that fits it", + Box::new(|doc| { + let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)]; + let graded = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let member = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(30.0, 10.0, 100.0, 40.0)), Appearance::basic(graded, Paint::None, 0.0)); + let mut g = group(doc, vec![member], false); + let offset = fx("path.offsetPath", serde_json::json!({"offset": 15.0})); + g.appearance = Appearance { effects: vec![offset, drop_shadow()], ..Appearance::default() }.into(); + g + }), + ), + ( + "Define Knockout Shape", + Box::new(|doc| { + let mut n = plain_rect(doc, "K", vec![drop_shadow()]); + n.knockout_shape = true; + n + }), + ), + ]; + for (what, make) in cases { + let mut doc = Document::new(200.0, 100.0); + let n = make(&mut doc); + put(&mut doc, n); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{what}: {:?}", out.warnings); + let p = shown(&out.program); + assert!(!p.contains("%AI9_BeginArtStyles") && !p.contains("(Anon 1) XW"), "{what}:\n{p}"); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + assert!(n.appearance.effects.is_empty(), "{what}: {n:?}"); + } +} + +/// A link to a graphic style whose Transform moves the outline is kept on a path the reader reads +/// that style on, and left out with a warning on a path with an opacity mask, which keeps its mask. +#[test] +fn a_link_to_a_style_that_moves_the_outline_is_kept_where_the_reader_reads_it() { + let make = |masked: bool| { + let mut doc = Document::new(200.0, 100.0); + let moved = fx("distort.transform", serde_json::json!({"copies": 0, "scaleH": 50.0})); + let ap = Appearance { effects: vec![moved], ..Appearance::basic(black_fill(), Paint::None, 0.0) }; + let mut g = vectorcraft_doc::GraphicStyle::new("Moved", ap.clone()); + g.id = 9; + doc.graphic_styles.push(g); + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap); + n.extras_mut().graphic_style = Some(9); + if masked { + let art = square(&mut doc, Rect::new(10.0, 10.0, 50.0, 25.0), Color::gray(0.5)); + n.extras_mut().mask = Some(OpacityMask { art: Arc::new(art), clip: true, invert: false, disabled: false, linked: true }.into()); + } + put(&mut doc, n); + doc + }; + let doc = make(false); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::STYLE_LINKS), "{:?}", out.warnings); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + assert_eq!(n.extras().graphic_style.and_then(|id| back.graphic_style_by_id(id)).map(|g| g.name.as_str()), Some("Moved")); + + let doc = make(true); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::STYLE_LINKS), "{:?}", out.warnings); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + assert_eq!(n.extras().graphic_style, None); + assert!(n.extras().mask.is_some(), "{n:?}"); +} + +/// Twist and Transform on an object that isn't linked to a graphic style are not written as a style +/// of its own: the object reads back without live effects. +#[test] +fn distort_effects_on_an_unlinked_object_write_no_style() { + let cases = [fx("distort.twist", serde_json::json!({"angle": 30.0})), fx("distort.transform", serde_json::json!({"copies": 0, "moveH": 5.0}))]; + for e in cases { + let what = e.id.clone(); + let mut doc = Document::new(200.0, 100.0); + let n = plain_rect(&mut doc, "D", vec![e]); + put(&mut doc, n); + let p = shown(&export_ai_editing(&doc, &opts()).unwrap().program); + assert!(!p.contains("%AI9_BeginArtStyles") && !p.contains("(Anon 1) XW"), "{what}:\n{p}"); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + assert!(n.appearance.effects.is_empty(), "{what}: {n:?}"); + } +} + +/// A gradient fill that fits its object is placed on the outline its geometry effects draw: an +/// object with Offset Path reads back with the gradient a plain object of the drawn size has. +#[test] +fn a_styled_objects_gradient_fits_its_drawn_outline() { + let stops = || vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)]; + let graded = || Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops())))); + let first = |doc: &Document| doc.layers[0].children().unwrap()[0].clone(); + let mut doc = Document::new(200.0, 100.0); + let offset = fx("path.offsetPath", serde_json::json!({"offset": 20.0, "joins": "miter"})); + let n = styled_rect(&mut doc, "G", Rect::new(50.0, 30.0, 100.0, 60.0), graded(), Paint::None, vec![offset]); + put(&mut doc, n); + let styled = first(&read_back(&doc)); + assert_eq!(styled.appearance.effects.len(), 1); + let mut doc = Document::new(200.0, 100.0); + let n = styled_rect(&mut doc, "P", Rect::new(30.0, 10.0, 120.0, 80.0), graded(), Paint::None, vec![]); + put(&mut doc, n); + let plain = first(&read_back(&doc)); + let geom = |n: &Node| match &n.appearance.fill().unwrap().paint { + Paint::Gradient(g) => { + let g = g.geom.unwrap(); + format!("{:.2} {:.2} {:.2} {:.2} {:.2}", g.start.x, g.start.y, g.end.x, g.end.y, g.aspect) + } + other => panic!("{other:?}"), + }; + assert_eq!(geom(&styled), geom(&plain)); +} + +/// The effects of a pattern's tile art are its own: a styled group's drawn look that first uses the +/// pattern still warns that the tile's Gaussian Blur is left out. +#[test] +fn effects_in_a_pattern_a_styled_look_uses_are_warned_about() { + let mut doc = Document::new(200.0, 100.0); + let dot = styled_rect( + &mut doc, + "Dot", + Rect::new(2.0, 2.0, 8.0, 8.0), + solid(Color::BLACK), + Paint::None, + vec![fx("blur.gaussian", serde_json::json!({}))], + ); + let mut grid = vectorcraft_doc::PatternDef::new("Grid", vec![Arc::new(dot)]); + grid.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.push(grid); + let tiles = Paint::Pattern { pattern: "Grid".into(), xf: Affine::IDENTITY }; + let member = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::basic(tiles, Paint::None, 0.0)); + let mut g = group(&mut doc, vec![member], false); + g.appearance = Appearance { effects: vec![drop_shadow()], ..Appearance::default() }.into(); + put(&mut doc, g); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let p = shown(&out.program); + assert!(p.contains("%AI3_BeginPattern") && p.contains("\n1 (Anon 1) XW\n"), "{p}"); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); +} + +/// A style that isn't written defines no gradient: a hidden gradient fill that only the style +/// would have held leaves no gradient the art uses. +#[test] +fn a_style_that_isnt_written_defines_no_gradient() { + let mut doc = Document::new(200.0, 100.0); + let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)]; + let graded = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let ap = Appearance { + items: vec![ + AppearanceItem::Fill(FillLayer { visible: false, ..FillLayer::new(graded) }), + AppearanceItem::Stroke(StrokeLayer::new(solid(Color::BLACK), 2.0)), + ], + effects: vec![fx("blur.gaussian", serde_json::json!({}))], + contents_index: None, + }; + let n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap); + put(&mut doc, n); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let p = shown(&out.program); + assert!(!p.contains("(Anon 1) XW"), "{p}"); + assert!(p.contains("%%BeginSetup\n0 Bn\n"), "{p}"); +} + +/// An object in a plain group, a sublayer or a clipping group by a path keeps its style there. One +/// in a symbol's art, in an opacity mask or in art cut to a clipping object other than a path is +/// written as its drawn look, with a warning. +#[test] +fn where_a_styled_object_keeps_its_style() { + let inside = |doc: &mut Document| plain_rect(doc, "Inside", vec![drop_shadow()]); + let found = |doc: &Document| { + fn find(nodes: &[Arc]) -> Option<&Arc> { + nodes.iter().find_map(|n| if n.name.as_deref() == Some("Inside") { Some(n) } else { n.children().and_then(|c| find(c)) }) + } + find(&doc.layers).cloned() + }; + // In a plain group. + let mut doc = Document::new(200.0, 100.0); + let n = inside(&mut doc); + let g = group(&mut doc, vec![n], false); + put(&mut doc, g); + assert_eq!(found(&read_back(&doc)).unwrap().appearance.effects.len(), 1); + same_styles(&read_back(&doc), &doc); + // In a sublayer. + let mut doc = Document::new(200.0, 100.0); + let n = inside(&mut doc); + let mut sub = Node::layer(doc.alloc_id(), "Sub", LayerColor::Preset(1)); + sub.children_mut().unwrap().push(Arc::new(n)); + put(&mut doc, sub); + assert_eq!(found(&read_back(&doc)).unwrap().appearance.effects.len(), 1); + // In a clipping group. + let mut doc = Document::new(200.0, 100.0); + let clip = Node::new( + doc.alloc_id(), + NodeKind::Path { + path: shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 60.0)), + rule: FillRule::NonZero, + live: None, + clipping: true, + guide: false, + }, + ); + let n = inside(&mut doc); + let g = group(&mut doc, vec![clip, n], true); + put(&mut doc, g); + assert_eq!(found(&read_back(&doc)).unwrap().appearance.effects.len(), 1); + // In a symbol's art: the instance keeps the symbol, the effects are left out. + let mut doc = Document::new(200.0, 100.0); + let n = inside(&mut doc); + doc.symbols.push(Symbol { dynamic: false, name: "S".into(), art: Arc::new(n) }); + let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::translate((50.0, 20.0)) }); + put(&mut doc, instance); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); + assert!(!shown(&out.program).contains("(Anon 1) XW")); + // In an opacity mask. + let mut doc = Document::new(200.0, 100.0); + let art = inside(&mut doc); + let mut n = square(&mut doc, Rect::new(10.0, 10.0, 60.0, 60.0), Color::BLACK); + n.extras_mut().mask = Some(OpacityMask { art: Arc::new(art), clip: true, invert: false, disabled: false, linked: true }.into()); + put(&mut doc, n); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); + assert!(!shown(&out.program).contains("(Anon 1) XW")); + // In art cut to a clipping object other than a path: type. + let mut doc = Document::new(200.0, 100.0); + let t = vectorcraft_doc::TextObject::point( + vectorcraft_geom::Point::new(10.0, 70.0), + "Type", + vectorcraft_doc::CharStyle { size: 18.0, fill: solid(Color::BLACK), ..vectorcraft_doc::CharStyle::default() }, + ); + let t = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + let n = inside(&mut doc); + let g = group(&mut doc, vec![t, n], true); + put(&mut doc, g); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); + assert!(!shown(&out.program).contains("(Anon 1) XW")); +} + +/// A styled group's members of every kind allowed come back as they were: a compound path, a named +/// path, a hidden and a locked path, a nested group and a clipping group. +#[test] +fn a_styled_groups_members_of_each_kind_are_read_back() { + let mut doc = Document::new(200.0, 100.0); + let solid_ap = Appearance::basic(solid(Color::rgb(0.2, 0.4, 0.6)), Paint::None, 0.0); + let compound = named(ring(&mut doc, solid_ap.clone()), "Compound"); + let plain = named(square(&mut doc, Rect::new(10.0, 10.0, 30.0, 30.0), Color::rgb(0.8, 0.1, 0.1)), "Named"); + let mut quiet = named(square(&mut doc, Rect::new(30.0, 10.0, 50.0, 30.0), Color::rgb(0.1, 0.8, 0.1)), "Hidden"); + quiet.visible = false; + let mut fixed = named(square(&mut doc, Rect::new(50.0, 10.0, 70.0, 30.0), Color::rgb(0.1, 0.1, 0.8)), "Locked"); + fixed.locked = true; + let a = square(&mut doc, Rect::new(10.0, 40.0, 30.0, 60.0), Color::BLACK); + let nested = named(group(&mut doc, vec![a], false), "Nested"); + let clip = Node::new( + doc.alloc_id(), + NodeKind::Path { + path: shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), + rule: FillRule::NonZero, + live: None, + clipping: true, + guide: false, + }, + ); + let b = square(&mut doc, Rect::new(40.0, 40.0, 80.0, 80.0), Color::WHITE); + let cut = named(group(&mut doc, vec![clip, b], true), "Cut"); + let mut g = named(group(&mut doc, vec![compound, plain, quiet, fixed, nested, cut], false), "Holder"); + g.appearance = Appearance { effects: vec![drop_shadow()], ..Appearance::default() }.into(); + put(&mut doc, g); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings); + let back = read_back(&doc); + same_styles(&back, &doc); + let members = |d: &Document| { + let mut out = vec![]; + view(d.layers[0].children().unwrap()[0].children().unwrap(), 0, &mut out); + out + }; + same_lines(&members(&back), &members(&doc)); +} + +/// What compares two appearances for the writer's checks and for these tests tells them apart. +#[test] +fn same_appearance_tells_appearances_apart() { + use serde_json::json; + let base = || Appearance { + items: vec![ + AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.5, 0.25, 0.75)))), + AppearanceItem::Stroke(StrokeLayer::new(black_fill(), 2.0)), + ], + effects: vec![fx("stylize.dropShadow", json!({"x": 10.0, "mode": "Multiply", "color": "#102030"}))], + contents_index: None, + }; + let same = writer::same_appearance; + assert!(same(&base(), &base())); + // Within the written precision, a mode in another case and a color in another form. + let mut other = base(); + other.effects[0].params["x"] = json!(10.005); + other.effects[0].params["mode"] = json!("multiply"); + other.effects[0].params["color"] = serde_json::to_value(Color::from_hex("#102030").unwrap()).unwrap(); + assert!(same(&other, &base())); + // A fill or stroke that doesn't paint. + let mut other = base(); + other.items.push(AppearanceItem::Fill(FillLayer::new(Paint::None))); + assert!(same(&other, &base())); + type Change = Box; + let change: Vec = vec![ + Box::new(|a| a.effects[0].params["x"] = json!(10.01)), + Box::new(|a| a.effects[0].params["color"] = json!("#102031")), + Box::new(|a| a.effects[0].params["mode"] = json!("screen")), + Box::new(|a| a.effects[0].visible = false), + Box::new(|a| a.effects[0].id = "stylize.outerGlow".into()), + Box::new(|a| a.effects.clear()), + Box::new(|a| a.items.truncate(1)), + Box::new(|a| a.items.swap(0, 1)), + Box::new(|a| a.contents_index = Some(2)), + Box::new(|a| { + if let AppearanceItem::Fill(f) = &mut a.items[0] { + f.paint = solid(Color::rgb(0.5, 0.25, 0.76)); + } + }), + Box::new(|a| { + if let AppearanceItem::Fill(f) = &mut a.items[0] { + f.opacity = 0.5; + } + }), + Box::new(|a| { + if let AppearanceItem::Stroke(s) = &mut a.items[1] { + s.width = 2.5; + } + }), + ]; + for (i, f) in change.iter().enumerate() { + let mut other = base(); + f(&mut other); + assert!(!same(&other, &base()), "change {i}"); + } +} + +/// A gradient fill in a style is placed as on an object without a style: a turned linear gradient +/// and a radial one with a focal point, and on a first artboard away from the origin among several. +#[test] +fn a_styled_objects_gradient_is_placed_as_a_plain_objects_is() { + use vectorcraft_color::gradient::GradientGeom; + let stops = || vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::rgb(0.1, 0.2, 0.8))]; + let turned = GradientGeom { start: (120.0, 60.0).into(), end: (170.0, 90.0).into(), aspect: 1.0, focal: None }; + let mut focal = GradientGeom { start: (140.0, 70.0).into(), end: (170.0, 70.0).into(), aspect: 0.5, focal: None }; + focal.set_focal(Some((150.0, 65.0).into())); + let boards = [Rect::new(0.0, 0.0, 300.0, 200.0), Rect::new(100.0, 50.0, 400.0, 250.0)]; + for (kind, geom) in [(GradientKind::Linear, turned), (GradientKind::Radial, focal)] { + for board in boards { + let paint = gradient_paint(Gradient::new(kind, stops()), Some(geom), None); + let make = |effects: Vec| { + let mut doc = Document::new(300.0, 200.0); + doc.artboards[0].rect = board; + let second = doc.artboards[0].clone(); + doc.artboards.push(Artboard { rect: board + vectorcraft_geom::Vec2::new(400.0, 0.0), ..second }); + let n = styled_rect(&mut doc, "G", Rect::new(120.0, 60.0, 180.0, 100.0), paint.clone(), Paint::None, effects); + put(&mut doc, n); + doc + }; + let (with, without) = (read_back(&make(vec![drop_shadow()])), read_back(&make(vec![]))); + let (a, b) = (&with.layers[0].children().unwrap()[0], &without.layers[0].children().unwrap()[0]); + assert_eq!(a.appearance.effects.len(), 1); + let geom = |n: &Node| match &n.appearance.fill().unwrap().paint { + Paint::Gradient(g) => { + let g = g.geom.unwrap(); + format!( + "{:.2} {:.2} {:.2} {:.2} {:.2} {:?}", + g.start.x, + g.start.y, + g.end.x, + g.end.y, + g.aspect, + g.focal.map(|f| (r3(f.x), r3(f.y))) + ) + } + other => panic!("{other:?}"), + }; + assert_eq!(geom(a), geom(b)); + same_lines(&outlines(&with), &outlines(&without)); + } + } +} + +/// On a large canvas a document with only graphic styles, an object linked to one and an object with +/// an effect all warn, and the object comes back as its drawn look at its place. +#[test] +fn a_large_canvas_writes_every_object_as_its_look() { + let warns = |doc: &Document| export_ai_editing(doc, &opts()).unwrap().warnings.iter().any(|w| w == writer::LARGE_CANVAS_STYLES); + let mut styles_only = Document::new(20000.0, 100.0); + styles_only.graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Mine", Appearance::basic(black_fill(), Paint::None, 0.0))); + assert!(warns(&styles_only)); + assert_eq!(read_back(&styles_only).graphic_style("Mine"), None); + let mut plain = Document::new(20000.0, 100.0); + let n = plain_rect(&mut plain, "None", vec![]); + put(&mut plain, n); + assert!(!warns(&plain)); + let mut linked_doc = Document::new(20000.0, 100.0); + let id = linked_doc.graphic_style("Sunshine").unwrap().id; + let mut n = plain_rect(&mut linked_doc, "Linked", vec![]); + n.extras_mut().graphic_style = Some(id); + put(&mut linked_doc, n); + assert!(warns(&linked_doc)); + assert_eq!(read_back(&linked_doc).layers[0].children().unwrap()[0].extras().graphic_style, None); + let mut shaded = Document::new(20000.0, 100.0); + let n = plain_rect(&mut shaded, "Shaded", vec![drop_shadow()]); + put(&mut shaded, n); + assert!(warns(&shaded)); + let back = read_back(&shaded); + let n = &back.layers[0].children().unwrap()[0]; + assert!(n.appearance.effects.is_empty()); + let p = n.path_data().unwrap().subpaths[0].anchors[0].p; + assert!((p.x - 10.0).abs() < 1e-2 && (p.y - 10.0).abs() < 1e-2, "{p:?}"); +} + +// ---------- variables ---------- + +/// A 200 × 100 document with variables: a text variable `name` bound to point type, a visibility +/// variable `show` bound to an unnamed square and to a rectangle `Badge`, an image variable +/// `picture` bound to a linked image, a graph variable `chart` and a variable of unknown kind +/// `other`; the data sets `First` (two lines of text, hidden, a linked file in a folder with a space +/// and a `%`) and `Second` (empty text, shown, a linked file on a drive), `Second` shown; the +/// variables locked. +fn variables_doc() -> Document { + use vectorcraft_doc::{DataSet, DataValue, Variable, VariableKind}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let square = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), Appearance::basic(solid(GOLD), Paint::None, 0.0)); + let mut badge = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(40.0, 10.0, 90.0, 30.0)), Appearance::basic(solid(BRAND), Paint::None, 0.0)); + badge.name = Some("Badge".into()); + let pic = image_node( + &mut doc, + ImageBlob::png(rgb_png()), + (3, 2), + Affine::new([10.0, 0.0, 0.0, 10.0, 100.0, 10.0]), + Some(vectorcraft_doc::LinkInfo::new("/tmp/a b/one.png")), + ); + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 70.0), "Ann", style(18.0, Color::BLACK)); + let t = text_node(&mut doc, t); + let ids = [square.id, badge.id, pic.id, t.id]; + for n in [square, badge, pic, t] { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let vars = &mut doc.variables; + for (name, kind) in [ + ("name", VariableKind::Text), + ("show", VariableKind::Visibility), + ("picture", VariableKind::Image), + ("chart", VariableKind::Graph), + ("other", VariableKind::Unknown), + ] { + vars.variables.push(Variable { name: name.into(), kind }); + } + vars.bind(ids[0], "show"); + vars.bind(ids[1], "show"); + vars.bind(ids[2], "picture"); + vars.bind(ids[3], "name"); + let row = |name: &str, text: &str, show: bool, file: &str| DataSet { + name: name.into(), + values: [ + ("name".to_string(), DataValue::Text(text.into())), + ("show".to_string(), DataValue::Visible(show)), + ("picture".to_string(), DataValue::Image(file.into())), + ] + .into(), + }; + vars.datasets = vec![row("First", "Ann (one)\nLee & é", false, "/Users/test/Job 100%/pic.png"), row("Second", "", true, "C:\\Art\\two.png")]; + vars.active_dataset = Some("Second".into()); + vars.locked = true; + doc +} + +/// The objects of `doc` bound to each variable, by kind and name, in document order. +fn bound_objects(doc: &Document) -> Vec { + let mut out = vec![]; + for v in &doc.variables.variables { + for id in doc.variables.objects_of(&v.name) { + let n = doc.node(id).unwrap(); + let kind = match &n.kind { + NodeKind::Image(im) => format!("image {:?}", im.link.as_ref().map(|l| l.path.clone())), + NodeKind::Path { .. } => "path".to_string(), + NodeKind::Text(t) => format!("type {:?}", t.runs.iter().map(|r| r.text.as_str()).collect::()), + _ => "other".to_string(), + }; + out.push(format!("{} → {kind} {:?}", v.name, n.name)); + } + } + out +} + +/// The warnings the reader gives about the variable library of `doc`'s editing data. +fn library_notes(doc: &Document) -> Vec { + let (_, warnings) = crate::ai_alone(&private_data(doc, &opts()).unwrap().0.data).unwrap(); + warnings.into_iter().filter(|w| w.contains("variable")).collect() +} + +#[test] +fn variables_data_sets_and_bindings_are_read_back() { + let doc = variables_doc(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(back.variables.variables, doc.variables.variables); + assert_eq!(back.variables.datasets, doc.variables.datasets); + assert_eq!(back.variables.active_dataset.as_deref(), Some("Second")); + assert!(back.variables.locked); + assert_eq!(bound_objects(&back), bound_objects(&doc)); + assert_eq!( + bound_objects(&back), + ["name → type \"Ann\" None", "show → path None", "show → path Some(\"Badge\")", "picture → image Some(\"/tmp/a b/one.png\") None"] + ); + assert_eq!(library_notes(&doc), Vec::::new()); + // The document read back is written the same way again. + let library = |p: String| p[p.find("%_/XMLNode :").unwrap()..p.find("(#document)").unwrap()].to_string(); + assert_eq!(library(program_shown(&back)), library(program_shown(&doc))); +} + +#[test] +fn variables_and_data_sets_past_the_readers_caps_are_left_out() { + use vectorcraft_doc::{DataSet, Variable, VariableKind}; + let mut doc = variables_doc(); + for i in 0..300 { + doc.variables.variables.push(Variable { name: format!("extra{i}"), kind: VariableKind::Text }); + } + for i in 0..1_000 { + doc.variables.datasets.push(DataSet { name: format!("Row {i}"), values: Default::default() }); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::LIMITS), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(back.variables.variables[..], doc.variables.variables[..256]); + assert_eq!(back.variables.datasets[..], doc.variables.datasets[..1_000]); + assert_eq!(bound_objects(&back).len(), 4); + assert_eq!(library_notes(&doc), Vec::::new()); +} + +/// Bindings that fill the reader's byte budget: the bindings past it are left out, and every +/// variable and every binding written reads back. +#[test] +fn bindings_that_fill_the_readers_budget_keep_every_variable() { + use vectorcraft_doc::{Variable, VariableKind}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut ids = vec![]; + for i in 0..170 { + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(1.0, 1.0, 2.0, 2.0)), Appearance::basic(solid(GOLD), Paint::None, 0.0)); + n.name = Some(format!("o{i:0>249}")); + ids.push(n.id); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + for v in 0..120 { + let name = format!("v{v:0>254}"); + doc.variables.variables.push(Variable { name: name.clone(), kind: VariableKind::Visibility }); + for id in &ids { + doc.variables.bind(*id, &name); + } + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::LIMITS), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(back.variables.variables, doc.variables.variables); + let bound: usize = back.variables.bindings.values().map(|names| names.len()).sum(); + assert!(bound > 0 && bound < 120 * 170, "{bound}"); + assert_eq!(library_notes(&doc), Vec::::new()); +} + +#[test] +fn long_xml_ids_and_text_of_many_lines_are_left_out() { + use vectorcraft_doc::DataValue; + let mut doc = variables_doc(); + let badge = doc.variables.objects_of("show")[1]; + doc.node_mut(badge).unwrap().name = Some("_".repeat(60)); + let lines = "\n".repeat(150_000); + doc.variables.datasets[0].values.insert("name".into(), DataValue::Text(lines)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::LIMITS), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(bound_objects(&back), ["name → type \"Ann\" None", "show → path None", "picture → image Some(\"/tmp/a b/one.png\") None"]); + assert_eq!(back.variables.datasets[0].values.get("name"), None); + assert_eq!(back.variables.datasets[1].values.get("name"), Some(&DataValue::Text(String::new()))); + // Nothing is written that the reader leaves out. + assert_eq!(library_notes(&doc), Vec::::new()); +} + +#[test] +fn a_layer_bound_to_a_visibility_variable_is_reported_left_out() { + let mut doc = variables_doc(); + assert!(export_ai_editing(&doc, &opts()).unwrap().warnings.iter().all(|w| w != writer::BINDINGS)); + let layer = doc.layers[0].id; + doc.variables.bind(layer, "show"); + assert!(export_ai_editing(&doc, &opts()).unwrap().warnings.iter().any(|w| w == writer::BINDINGS)); + assert_eq!(bound_objects(&read_back(&doc)).len(), 4); +} + +#[test] +fn a_binding_to_an_object_no_longer_in_the_document_is_not_reported() { + let mut doc = variables_doc(); + let gone = doc.alloc_id(); + doc.variables.bind(gone, "show"); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert_eq!(bound_objects(&read_back(&doc)), bound_objects(&variables_doc())); +} + +#[test] +fn a_data_set_shown_that_is_not_written_is_reported_left_out() { + for active in [" Second", "Nope"] { + let mut doc = variables_doc(); + doc.variables.active_dataset = Some(active.into()); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::ACTIVE], "{active:?}"); + assert_eq!(read_back(&doc).variables.active_dataset, None, "{active:?}"); + } +} + +#[test] +fn a_locked_library_without_variables_stays_locked() { + let mut doc = Document::new(200.0, 100.0); + doc.variables.locked = true; + assert!(read_back(&doc).variables.locked); +} + +#[test] +fn names_the_reader_does_not_read_as_they_are_are_left_out() { + use vectorcraft_doc::{DataSet, Variable, VariableKind}; + let mut doc = variables_doc(); + for name in ["x".repeat(256), " padded".into(), String::new(), "show".into()] { + doc.variables.variables.push(Variable { name: name.clone(), kind: VariableKind::Text }); + doc.variables.datasets.push(DataSet { name, values: Default::default() }); + } + doc.variables.datasets.push(DataSet { name: "First".into(), values: Default::default() }); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::LIMITS), "{:?}", out.warnings); + let back = read_back(&doc); + let expected = variables_doc(); + assert_eq!(back.variables.variables, expected.variables.variables); + let mut datasets = expected.variables.datasets.clone(); + datasets.push(DataSet { name: "show".into(), values: Default::default() }); + assert_eq!(back.variables.datasets, datasets); + assert_eq!(library_notes(&doc), Vec::::new()); +} + +#[test] +fn a_document_without_variables_has_no_library() { + let p = program(&sample()); + assert!(!p.contains("XMLNode")); +} + +#[test] +fn an_unlocked_library_without_a_data_set_is_read_back() { + let mut doc = variables_doc(); + doc.variables.datasets.clear(); + doc.variables.active_dataset = None; + doc.variables.locked = false; + let back = read_back(&doc); + let expected = vectorcraft_doc::Variables { bindings: back.variables.bindings.clone(), ..(*doc.variables).clone() }; + assert_eq!(*back.variables, expected); + assert_eq!(bound_objects(&back), bound_objects(&doc)); +} + +#[test] +fn bindings_and_values_the_reader_cant_take_are_left_out() { + use vectorcraft_doc::{DataValue, VariableKind}; + let mut doc = variables_doc(); + let layer = doc.layers[0].id; + // Type of only white space is written as its outlines. + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 90.0), " ", style(18.0, Color::BLACK)); + let t = text_node(&mut doc, t); + let text_id = t.id; + doc.insert(Some(layer), usize::MAX, t).unwrap(); + doc.variables.bind(text_id, "name"); + doc.variables.variables.push(vectorcraft_doc::Variable { name: "a:b".into(), kind: VariableKind::Text }); + let first = &mut doc.variables.datasets[0].values; + first.insert("chart".into(), DataValue::Graph("a,b\n1,2".into())); + first.insert("a:b".into(), DataValue::Text("lost".into())); + first.insert("picture".into(), DataValue::Image("/a:b/pic.png".into())); + let second = &mut doc.variables.datasets[1].values; + second.insert("picture".into(), DataValue::Image("relative/pic.png".into())); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BINDINGS), "{:?}", out.warnings); + assert!(out.warnings.iter().any(|w| w == writer::VALUES), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(back.variables.objects_of("name").len(), 1); + assert_eq!(back.variables.datasets[0].values.get("chart"), None); + assert_eq!(back.variables.datasets[0].values.get("a:b"), None); + assert_eq!(back.variables.datasets[0].values.get("picture"), None); + assert_eq!(back.variables.datasets[1].values.get("picture"), None); + assert_eq!(bound_objects(&back).len(), 4); +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs new file mode 100644 index 0000000000..8dd98415f4 --- /dev/null +++ b/crates/eps/src/ai_editing/writer.rs @@ -0,0 +1,1418 @@ +//! The program's art and swatches (see [`super`] for the form). + +use std::collections::{HashMap, HashSet}; +use std::fmt::Write; +use std::sync::Arc; + +use vectorcraft_color::cms::Cms; +use vectorcraft_color::swatch::{REGISTRATION, Swatch}; +use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LAYER_COLORS, LayerColor, Node, NodeId, NodeKind, OpacityMask, StrokeLayer}; +use vectorcraft_effects::stroke; +use vectorcraft_geom::{Affine, FillRule, PathData, Shape, SubPath}; +use vectorcraft_pathops::BoolOp; + +use crate::ai_ops::{self, unit}; +use crate::ps; + +mod images; +mod paints; +mod styles; +mod symbols; +mod texts; +mod variables; + +pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_objects}; +#[cfg(test)] +pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, same_appearance}; + +pub(super) use images::PAYLOAD; +#[cfg(test)] +pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED}; +#[cfg(test)] +pub(super) use paints::{GRADIENT_MIX, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name}; +#[cfg(test)] +pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS}; +#[cfg(test)] +pub(super) use texts::TYPE_ATTRIBUTES; +#[cfg(test)] +pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES}; + +/// How deep symbols, live objects and pattern tiles may nest in one another (deeper art is left +/// out). Groups and layers need no limit of their own: a document is never deeper than +/// [`vectorcraft_doc::MAX_DEPTH`]. +const MAX_NEST: u32 = 8; + +pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type that flows around a text wrap, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps"; +pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps"; +pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fill places are written filled gray in the editing data for other apps"; +pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps"; +pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps"; +pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps"; +pub(super) const LIVE: &str = + "blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps"; +const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; +pub(super) const ITEM_TRANSPARENCY: &str = + "the opacity and blending modes of single fills and strokes are left out of the editing data for other apps"; +pub(super) const LAYER_MASKS: &str = "opacity masks on layers are left out of the editing data for other apps"; +pub(super) const DEEP_MASKS: &str = + "opacity masks more than 8 deep in opacity masks, symbols, live objects and pattern tiles are left out of the editing data for other apps"; +const GROUPED_LAYER: &str = + "the transparency and opacity masks of layers that an effect made into a group are left out of the editing data for other apps"; +pub(super) const EFFECTS: &str = "live effects other than geometry effects are left out of the editing data for other apps"; +pub(super) const SWATCHES: &str = "freeform gradient swatches, gradient swatches of more than 256 stops, and pattern swatches whose patterns the data can't define, are left out of the editing data for other apps"; +pub(super) const SYMBOL_LIMIT: &str = "symbol instances past 16,000,000 objects of symbol art in all are left out of the editing data for other apps"; +const TEMPLATES: &str = "template layers are written as dimmed layers that don't print in the editing data for other apps"; + +/// The transparency `mode opacity isolate knockout shape Xy` sets: the blending mode ([`blend_code`]), +/// the opacity, Isolate Blending, Knockout Group (0 off, 1 on, 2 neutral) and Opacity & Mask Define +/// Knockout Shape. It stays set for the objects that follow, as the lock and hidden state do; a +/// group, a clipping group or a layer takes it after its end. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Xy { + blend: BlendMode, + opacity: f32, + isolate: bool, + knockout: Knockout, + shape: bool, +} + +impl Xy { + /// The state before any `Xy`, and an opaque path's. + const OPAQUE: Xy = Xy { blend: BlendMode::Normal, opacity: 1.0, isolate: false, knockout: Knockout::Off, shape: false }; + /// A group's or a layer's without transparency of its own (no `Xy` after its end). + const PLAIN: Xy = Xy { knockout: Knockout::Neutral, ..Self::OPAQUE }; + + /// `n`'s transparency. + fn of(n: &Node) -> Xy { + let opacity = if n.opacity.is_finite() { n.opacity.clamp(0.0, 1.0) } else { 1.0 }; + Xy { blend: n.blend, opacity, isolate: n.isolate, knockout: n.knockout, shape: n.knockout_shape } + } + + /// As a path's own: isolation and knockout are a group's. + fn object(self) -> Xy { + Xy { isolate: false, knockout: Knockout::Off, ..self } + } +} + +/// The number `Xy` gives blending mode `b`. +fn blend_code(b: BlendMode) -> u8 { + match b { + BlendMode::Normal => 0, + BlendMode::Multiply => 1, + BlendMode::Screen => 2, + BlendMode::Overlay => 3, + BlendMode::SoftLight => 4, + BlendMode::HardLight => 5, + BlendMode::ColorDodge => 6, + BlendMode::ColorBurn => 7, + BlendMode::Darken => 8, + BlendMode::Lighten => 9, + BlendMode::Difference => 10, + BlendMode::Exclusion => 11, + BlendMode::Hue => 12, + BlendMode::Saturation => 13, + BlendMode::Color => 14, + BlendMode::Luminosity => 15, + } +} + +pub(super) struct Writer<'a> { + doc: &'a Document, + /// The document → art space. + to_art: Affine, + cms: Arc, + pub(super) body: String, + pub(super) warnings: Vec, + /// The lock and hidden state (`A`, `Xw`) the last operators set; `None` at a layer's start. + state: Option<(bool, bool)>, + /// The transparency the last `Xy` set; `None` when it isn't known (after an opacity mask, whose + /// art's last `Xy` stays set). + gs: Option, + /// Where the state block of the group ended last starts and ends in [`Self::body`]. + block_start: usize, + block_end: usize, + /// The region the art being written is cut to (a clipping path's, in document space). + clip: Option, + /// Symbols, live objects and pattern tiles being written inside one another. + nest: u32, + /// The XML ids objects are named with so far. + ids: HashSet, + /// The number the next object named after each XML id tries first. + next: HashMap, + /// The document's brushes, read the first time a brushed stroke is written. + brushes: Option>, + /// The objects of the symbol art written so far, within [`vectorcraft_doc::MAX_SYMBOL_NODES`]. + symbol_nodes: u64, + /// The document → the space gradients' matrices (`Xm`, `Bm`, `Bc`) and focal points are + /// written in: art space, and in a pattern's definition [`Self::tile_grad_space`]. + grad_space: Affine, + /// The pattern's space (y down) → the space a pattern's definition writes gradients' matrices + /// in: the canvas's (y down), from art space's origin there. + tile_grad_space: Affine, + /// The document → the canvas (y down), the space of a gradient's transformation in `Bg`; in a + /// pattern's definition, the pattern's space turned y up. + canvas: Affine, + /// The gradient definitions, in the order they are first used. + gradients: Vec, + /// The number the next new gradient definition's name tries first (1 is `Gradient`). + next_gradient: u64, + /// The pattern definitions written, each after those its art uses. + patterns: Vec, + /// The patterns whose definitions are being written. + defining: Vec, + /// Writing the palette: the definitions it adds are for its swatches only. + in_palette: bool, + /// Art space's origin on the canvas (y down), where a placed file's box starts. + canvas_origin: (f64, f64), + /// The binary parts of the program (images' samples, placed files' previews), each in the + /// text as a mark ([`PAYLOAD`], its index, [`PAYLOAD`]). + pub(super) payloads: Vec>, + /// How many parts of the data written on `%_` lines (opacity masks' art, patterns' tiles) the + /// art being written is in. + hidden: u32, + /// The image just written was written as a placed file. + placed: bool, + /// The type just written was written as type, not as its outlines. + typed: bool, + /// The objects bound to variables so far, in the order they are written: each one's id, its XML + /// id and the variables it is bound to ([`Self::bound_variables`]). + bound: Vec<(vectorcraft_doc::NodeId, String, Vec)>, + /// The text document: the stories of the type written as text. + pub(super) texts: texts::TextDoc, + /// Symbol instances on the layers may be written as instances ([`Self::live_instance`]); false + /// on a large canvas, where they are written as their art. + pub(super) symbols_live: bool, + /// The document symbols are defined from: on a large canvas, the document at its own size + /// (symbols' art is in its own space, which the canvas's scale doesn't change). + pub(super) symbol_doc: &'a Document, + /// A symbol's art is being written ([`Self::define_symbol`]). + in_symbol: bool, + /// The document → the space an instance's `RTransformMatrix` takes its symbol's art to: art + /// space, and in a symbol's art the canvas's turned y up about art space's origin there. + instance_space: Affine, + /// The symbol definitions written (`%AI14_BeginSymbol` … `%AI10_EndSymbol`), each after those + /// its art uses, and their names. + symbol_defs: Vec, + defined_symbols: HashSet, + /// The symbols whose definitions are being written. + defining_symbols: Vec, + /// Whether each symbol's own art paints with a pattern, and the symbols its instances use + /// ([`Self::symbol_own_patterns`]). + pattern_symbols: HashMap)>, + /// Whether each symbol's art paints with a pattern, nested symbols included + /// ([`Self::symbol_paints_pattern`]). + patterned_symbols: HashMap, + /// Pattern tiles were written in the art being written ([`Self::define_symbol`] starts it over + /// for each symbol's art). + wrote_pattern: bool, + /// The symbols whose definitions hold pattern tiles: a brushed stroke's brush art or a live + /// object's art can paint with a pattern that the symbol's own objects don't name. + pattern_written: HashSet, + /// Art that draws as it should only where it is was written in the art being written + /// ([`Self::define_symbol`] starts it over for each symbol's art): a stroke as its outline or its + /// brush's art, type as its outlines, a live object or a symbol instance as its art, or a shape + /// with rounded live corners. + wrote_fixed: bool, + /// The symbols whose definitions hold such art, nested symbols' included + /// ([`Self::keeps_scale`]). + fixed_symbols: HashSet, + /// The largest scale a live instance in the art being written applies, nested symbols' scales + /// included, and that of each symbol's definition. + inner_scale: f64, + symbol_scales: HashMap, + /// The entries a symbol's dictionary adds to its art's dictionary, and the art's id. + root_entries: Option<(vectorcraft_doc::NodeId, String)>, + /// The objects that may be written with an art style, as they were before baking, by id + /// ([`styles::styled_objects`]). + pub(super) styled: HashMap>, + /// The art styles written ([`styles`]). + styles: styles::Styles, + /// An object's drawn look is being written: no object in it is written with a style, and its + /// effects are the style's. + in_look: bool, +} + +impl<'a> Writer<'a> { + /// A writer of `doc`'s art through `to_art`; `origin` is art space's origin on the canvas. + pub(super) fn new(doc: &'a Document, to_art: Affine, origin: (f64, f64)) -> Self { + Self { + doc, + to_art, + grad_space: to_art, + tile_grad_space: Affine::translate((-origin.0, origin.1)), + canvas: Affine::new([1.0, 0.0, 0.0, -1.0, origin.0, origin.1]) * to_art, + gradients: vec![], + next_gradient: 1, + patterns: vec![], + defining: vec![], + in_palette: false, + canvas_origin: origin, + payloads: vec![], + hidden: 0, + placed: false, + typed: false, + bound: vec![], + texts: texts::TextDoc::default(), + cms: vectorcraft_color::cms::active(), + body: String::new(), + warnings: vec![], + state: None, + gs: Some(Xy::OPAQUE), + block_start: 0, + block_end: usize::MAX, + clip: None, + nest: 0, + ids: HashSet::new(), + next: HashMap::new(), + brushes: None, + symbol_nodes: 0, + symbols_live: true, + symbol_doc: doc, + in_symbol: false, + instance_space: to_art, + symbol_defs: vec![], + defined_symbols: HashSet::new(), + defining_symbols: vec![], + pattern_symbols: HashMap::new(), + patterned_symbols: HashMap::new(), + wrote_pattern: false, + pattern_written: HashSet::new(), + wrote_fixed: false, + fixed_symbols: HashSet::new(), + inner_scale: 1.0, + symbol_scales: HashMap::new(), + root_entries: None, + styled: HashMap::new(), + styles: styles::Styles::default(), + in_look: false, + } + } + + /// Whether the art of a symbol, `art`, may be written: the objects of the symbol art written + /// so far stay within [`vectorcraft_doc::MAX_SYMBOL_NODES`], as in the PDF part (instances of + /// symbols that hold instances multiply). Past it the art is left out, with a warning. + fn take_symbol(&mut self, art: &Node) -> bool { + let total = self.symbol_nodes.saturating_add(art.count() as u64); + if total > vectorcraft_doc::MAX_SYMBOL_NODES { + self.warn(SYMBOL_LIMIT); + return false; + } + self.symbol_nodes = total; + true + } + + fn warn(&mut self, w: &str) { + if !self.warnings.iter().any(|x| x == w) { + self.warnings.push(w.to_string()); + } + } + + fn line(&mut self, s: &str) { + self.body.push_str(s); + self.body.push('\n'); + } + + // ---------- layers and objects ---------- + + /// A top-level layer. A layer that baking its effects made a group of the layer and the art an + /// effect adds (Crop Marks) is written as that layer holding the added art too, and any other + /// object at the top level in a layer of its own. + pub(super) fn layer(&mut self, n: &Node) { + if n.is_layer() { + return self.write_layer(n, &[]); + } + let members = n.children().map(Vec::as_slice).unwrap_or_default(); + self.effects(n); + match members.iter().find(|c| c.is_layer()) { + Some(l) => { + if Xy::of(n) != Xy::PLAIN || n.extras().mask.is_some() { + self.warn(GROUPED_LAYER); + } + // The group took the layer's name. The added art is outside the layer's clipping. + let layer = Node { name: l.name.clone().or_else(|| n.name.clone()), ..(**l).clone() }; + let added: Vec> = members.iter().filter(|c| !c.is_layer()).cloned().collect(); + self.write_layer(&layer, &added); + } + None => { + let mut layer = Node::layer(n.id, n.name.as_deref().unwrap_or("Layer"), LayerColor::Preset(0)); + (layer.visible, layer.locked) = (n.visible, n.locked); + self.write_layer(&layer, &[Arc::new(n.clone())]); + } + } + } + + /// A layer or sublayer: `%AI5_BeginLayer`, its options `Lb`, its name `Ln` and as an XML id, its art (its + /// clipping path last, with `W`, when it clips), `after` (outside the clipping path), its transparency + /// (`Xy`, `0 0 Xd`, `7 () XW`) when it has any, `LB`, `%AI5_EndLayer--`. + fn write_layer(&mut self, n: &Node, after: &[Arc]) { + let NodeKind::Layer { color, template, printable, children, clip, preview, dim_images } = &n.kind else { return }; + let [r, g, b] = match color { + LayerColor::Preset(i) => LAYER_COLORS.get(usize::from(*i)).map_or([79, 128, 255], |c| c.1), + LayerColor::Custom(rgb) => *rgb, + }; + let index = match color { + LayerColor::Preset(i) if usize::from(*i) < LAYER_COLORS.len() => i64::from(*i), + _ => -1, + }; + if *template { + self.warn(TEMPLATES); + } + self.effects(n); + if n.extras().mask.is_some() { + self.warn(LAYER_MASKS); + } + let flag = |b: bool| u8::from(b); + let dim = dim_images.unwrap_or(50); + let name = n.name.as_deref().unwrap_or("Layer"); + // The last flag makes the layer a clipping layer: its top object clips the rest. Only a + // clipping path or compound path, outside any art cut to a clipping object, is written as + // one ([`Self::clip_group`] writes the others). + let clips = *clip && after.is_empty() && self.clip.is_none() && children.first().is_some_and(|c| clip_path(c).is_some()); + let _ = writeln!( + self.body, + "%AI5_BeginLayer\n{} {} {} {} {} 0 1 {index} {r} {g} {b} 0 {dim} {} Lb\n{} Ln", + flag(n.visible), + flag(*preview), + flag(!n.locked), + flag(*printable && !*template), + flag(dim_images.is_some() || *template), + flag(clips), + ps::bytes(name.as_bytes()), + ); + self.xml_id(if name.is_empty() { "Layer" } else { name }); + self.state = None; + if clips { + self.clipped(children); + } else if *clip && !children.is_empty() { + // The added art lies outside the clipping path, or the clipping object isn't a path: + // the clipped art is a clipping group, or a group of the art cut to the object. + self.clip_group(children, Xy::PLAIN); + } else { + for c in children { + self.node(c); + } + } + for c in after { + self.node(c); + } + let xy = Xy::of(n); + if xy != Xy::PLAIN { + // Always written: the layer takes the `Xy` its own state block has. + self.write_xy(xy); + self.line("0 0 Xd\n7 () XW"); + } + self.line("LB\n%AI5_EndLayer--"); + // The reader's state carries over into the art that follows. + self.state = None; + } + + /// Set the lock and hidden state of the object that follows. + fn state(&mut self, locked: bool, hidden: bool) { + let (was_locked, was_hidden) = match self.state { + Some((l, h)) => (Some(l), Some(h)), + None => (None, None), + }; + if was_locked != Some(locked) { + self.line(if locked { "1 A" } else { "0 A" }); + } + if was_hidden != Some(hidden) { + self.line(if hidden { "1 Xw" } else { "0 Xw" }); + } + self.state = Some((locked, hidden)); + } + + /// Set the transparency of the object that follows to `xy` (`Xy`, when it isn't set already). + fn set_xy(&mut self, xy: Xy) { + if self.gs != Some(xy) { + self.write_xy(xy); + } + } + + /// [`Self::set_xy`] for an object that writes no paint before its transparency (type, an image, + /// a guide): `XR` comes first, as in [`Self::paint_state`], because an `Xy` right after a compound + /// path or a text object would be theirs. + fn set_object_xy(&mut self, xy: Xy) { + if self.gs != Some(xy) { + self.line("0 XR"); + self.write_xy(xy); + } + } + + /// `mode opacity isolate knockout shape Xy`. + fn write_xy(&mut self, xy: Xy) { + let knockout = match xy.knockout { + Knockout::Off => 0, + Knockout::On => 1, + Knockout::Neutral => 2, + }; + let _ = write!(self.body, "{} ", blend_code(xy.blend)); + ps::push_num(&mut self.body, f64::from(xy.opacity)); + let _ = writeln!(self.body, " {} {knockout} {} Xy", u8::from(xy.isolate), u8::from(xy.shape)); + self.gs = Some(xy); + } + + /// The end `close` (`U` or `Q`) of a group of transparency `xy`, then its state block: when it + /// has transparency of its own, `Xy`, `0 0 Xd` and `6 () XW`; else `9 () XW`. The group's + /// dictionary goes between the two ([`Self::node`]). + fn end_group(&mut self, close: &str, xy: Xy) { + self.line(close); + self.state_block(xy); + } + + /// The state block of the group or text object just written ([`Self::end_group`]). + fn state_block(&mut self, xy: Xy) { + self.block_start = self.body.len(); + if xy == Xy::PLAIN { + self.line("9 () XW"); + } else { + self.write_xy(xy); + self.line("0 0 Xd\n6 () XW"); + } + self.block_end = self.body.len(); + } + + /// Warn when `n` has effects the data leaves out. + fn effects(&mut self, n: &Node) { + if self.in_look { + return; + } + let items = n.appearance.items.iter().filter(|i| i.visible()).flat_map(|i| i.effects()); + if n.appearance.effects.iter().chain(items).any(|e| e.visible) { + self.warn(EFFECTS); + } + } + + /// One object: its state before it, its transparency, and its name and opacity mask after it. + fn node(&mut self, n: &Node) { + if let NodeKind::Layer { .. } = n.kind { + return self.write_layer(n, &[]); + } + if self.in_symbol { + self.wrote_fixed |= symbols::redrawn(n); + } + // On the layers, outside art cut to a clipping object: with its art style, when it has one. + if !self.in_look + && self.hidden == 0 + && self.nest == 0 + && self.clip.is_none() + && !self.in_symbol + && let Some(orig) = self.styled.get(&n.id).cloned() + && let Some(name) = self.object_style(n, &orig) + { + return self.styled_object(n, &orig, &name); + } + self.effects(n); + self.state(n.locked, !n.visible); + let xy = Xy::of(n); + let start = self.body.len(); + match &n.kind { + NodeKind::Layer { .. } => {} + NodeKind::Group { children, clip: true } => self.clip_group(children, xy), + NodeKind::Group { children, clip: false } => { + self.line("u"); + for c in children { + self.node(c); + } + self.end_group("U", xy); + } + NodeKind::Path { path, rule, guide, .. } => { + if *guide { + // Its own transparency, not the one the object before it set. + if path.subpaths.iter().any(|sp| !sp.anchors.is_empty()) { + self.set_object_xy(xy.object()); + } + ai_ops::guide(&mut self.body, self.to_art, path, true); + } else { + self.shape(n, path, *rule, xy); + } + } + NodeKind::Compound { rule, .. } => self.shape(n, &compound_path(n), *rule, xy), + NodeKind::Text(_) => self.text(n, xy), + NodeKind::Image(im) => self.image(im, xy), + NodeKind::SymbolInstance { symbol, xf } if self.live_instance(n, symbol, *xf) => self.symbol_instance(symbol, *xf, xy), + NodeKind::SymbolInstance { symbol, xf } => { + // The canvas places an instance inside a symbol's art where the outer instance puts + // it (9-slice guides, stains and patterns included), and this art doesn't move with it. + self.wrote_fixed |= self.in_symbol; + let doc = self.doc; + if doc.symbols.iter().any(|s| &s.name == symbol) { + self.warn(symbols::SYMBOL_ART); + } else { + self.warn(symbols::MISSING_SYMBOL); + } + self.line("u"); + if let Some(sym) = doc.symbols.iter().find(|s| &s.name == symbol) + && self.nest < MAX_NEST + { + // Stained by the instance's fill, as the canvas draws it. + let stained = vectorcraft_brush::instance_art(&sym.art, n); + // Through the symbol's 9-slice guides when it has them, as the canvas draws it; + // placing through them needs room for the most objects it can make, and the + // objects it makes count. + let map = doc.symbol_slice_map(symbol, *xf); + let most = map.map_or(stained.count() as u64, |m| m.most_placed(&stained, doc)); + let placed = vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, most, || { + let art = match map { + Some(m) => m.place(&stained, doc), + None => { + let mut a = stained.clone(); + a.transform(*xf, false); + a + } + }; + let count = if map.is_some() { art.count_with_masks() } else { art.count() } as u64; + (art, count) + }); + if let Some(mut art) = placed { + art.visible = true; + art.locked = false; + art.name = None; + self.nest += 1; + self.node(&art); + self.nest -= 1; + } else { + self.warn(SYMBOL_LIMIT); + } + } + self.end_group("U", xy); + } + NodeKind::Blend { .. } + | NodeKind::Envelope { .. } + | NodeKind::Mesh(_) + | NodeKind::Repeat(_) + | NodeKind::PlacedDocument(_) + | NodeKind::Intertwine { .. } => { + self.warn(LIVE); + self.line("u"); + if self.nest < MAX_NEST { + let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); + self.nest += 1; + for c in g.children().map(Vec::as_slice).unwrap_or_default() { + self.node(c); + } + self.nest -= 1; + } + self.end_group("U", xy); + } + } + if self.body.len() > start { + // A group's dictionary goes between its end and its state block. + let block = (self.block_end == self.body.len() && self.block_start >= start).then(|| self.body.split_off(self.block_start)); + self.block_end = usize::MAX; + self.dictionary(n); + if let Some(b) = block { + self.body.push_str(&b); + } + } + } + + /// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]), + /// is bound to variables ([`Self::bound_variables`]; without a name, it gets an XML id and an + /// empty `AIArtName`), has an opacity mask (`AI9_Mask`, see [`Self::mask`]), or is a symbol's + /// art (its symbol's entries first, see [`Self::define_symbol`]). + fn dictionary(&mut self, n: &Node) { + let name = n.name.as_deref().filter(|s| !s.is_empty()); + let placed = std::mem::take(&mut self.placed); + let typed = std::mem::take(&mut self.typed); + let bound = self.bound_variables(n, placed, typed); + let mut mask = n.extras().mask.as_deref(); + // Masks nested too deep are left out (an empty mask would hide the object). + if mask.is_some() && self.nest >= MAX_NEST { + self.warn(DEEP_MASKS); + mask = None; + } + let entries = match &self.root_entries { + Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e), + _ => None, + }; + if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() { + return; + } + self.body.push_str("%_/ArtDictionary :\n"); + if let Some(e) = entries { + self.body.push_str(&e); + } + if name.is_some() || !bound.is_empty() { + let id = self.take_id(name.unwrap_or("XMLID")); + let _ = writeln!(self.body, "%_/XMLUID : {} ; (AI10_ArtUID) ,", ps::bytes(id.as_bytes())); + if name.is_none() { + // The XML id names the object unless the dictionary gives it another name. + self.body.push_str("%_() /String (AIArtName) ,\n"); + } + if !bound.is_empty() { + self.bound.push((n.id, id, bound)); + } + } + if let Some(m) = mask { + self.mask(m); + } + self.body.push_str("%_;\n%_\n"); + } + + /// An `/ArtDictionary` whose `AI10_ArtUID` is `name` as an XML id. + fn xml_id(&mut self, name: &str) { + let id = self.take_id(name); + let _ = writeln!(self.body, "%_/ArtDictionary :\n%_/XMLUID : {} ; (AI10_ArtUID) ,\n%_;\n%_", ps::bytes(id.as_bytes())); + } + + /// `name` as an XML id no layer or object has yet, numbered (`_` and 20 digits, `_`) when one + /// has it. + fn take_id(&mut self, name: &str) -> String { + let base = vectorcraft_doc::xml_id::from_object_name(name); + let mut id = base.clone(); + let next = self.next.entry(base.clone()).or_insert(0); + while self.ids.contains(&id) { + *next += 1; + id = format!("{base}_{next:020}_"); + } + self.ids.insert(id.clone()); + id + } + + /// An opacity mask, as an entry of its object's dictionary: `/Mask :`, `X=`, its art on `%_` + /// lines (from the state a dictionary's art starts in: unlocked, shown, opaque), `X+`, `(Art) ,`, + /// its options as the `/Bool` entries `Clipping`, `Inverted`, `Disabled` and `Linked`, and + /// `; (AI9_Mask) ,`. The art is in document coordinates, as the object's is. + fn mask(&mut self, m: &OpacityMask) { + let outer = std::mem::take(&mut self.body); + let (state, clip) = (self.state, self.clip.take()); + (self.state, self.gs) = (Some((false, false)), Some(Xy::OPAQUE)); + // The canvas draws the art's root even when it is hidden, and the reader puts a hidden object + // in a group that doesn't draw it, so a hidden root is written shown. + let shown; + let art = if m.art.visible { + &m.art + } else { + let mut a = (*m.art).clone(); + a.visible = true; + shown = Arc::new(a); + &shown + }; + // A plain group of two or more objects, or of none, is the group the art is read into. A group + // of one object is written as a group, because the reader makes one shown object the art. + let plain = matches!(art.kind, NodeKind::Group { clip: false, .. }) + && Xy::of(art) == Xy::PLAIN + && art.visible + && !art.locked + && art.name.as_deref().is_none_or(str::is_empty) + && art.extras().mask.is_none(); + let members = match art.children() { + Some(c) if plain && c.len() != 1 => c.as_slice(), + _ => std::slice::from_ref(art), + }; + self.nest += 1; + self.hidden += 1; + for c in members { + self.node(c); + } + self.hidden -= 1; + self.nest -= 1; + let lines = std::mem::replace(&mut self.body, outer); + self.body.push_str("%_/Mask :\n%_X=\n"); + hide(&lines, &mut self.body); + self.body.push_str("%_X+\n%_(Art) ,\n"); + for (key, on) in [("Clipping", m.clip), ("Inverted", m.invert), ("Disabled", m.disabled), ("Linked", m.linked)] { + let _ = writeln!(self.body, "%_{} /Bool ({key}) ,", u8::from(on)); + } + self.body.push_str("%_; (AI9_Mask) ,\n"); + // The dictionary ends with the state before it, except the transparency its art set last. + (self.state, self.gs, self.clip, self.block_end) = (state, None, clip, usize::MAX); + } + + /// Warn that art is cut to clipping object `first` when it isn't a path or compound path (a path + /// without points cuts everything away, as it clips everything away). + fn warn_cut(&mut self, first: Option<&Arc>) { + if first.is_some_and(|c| !matches!(c.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. })) { + self.warn(CLIPPING); + } + } + + /// A clipping group: `q`, its members, its clipping path or compound path last (the top object: + /// a mask shows the objects beneath it, §5.6.2) with `W`, `Q`, then the group's transparency. + /// `Q` sets back the state at `q`. A clipping object of another kind cuts the members instead, + /// in a group ([`Self::clip_contents`]). A clipping group without members is an empty group. + fn clip_group(&mut self, children: &[Arc], xy: Xy) { + if self.clip.is_some() || children.first().is_none_or(|c| clip_path(c).is_none()) { + self.warn_cut(children.first()); + // Inside art cut to a clipping object, a clipping path cuts its art too. + if self.clip.is_some() && !children.is_empty() { + self.warn(CLIPPING); + } + self.line("u"); + self.clip_contents(children); + return self.end_group("U", xy); + } + let at_q = (self.state, self.gs); + self.line("q"); + self.clipped(children); + (self.state, self.gs) = at_q; + self.end_group("Q", xy); + } + + /// The members of a clipping group or layer, the first one clipping the others: the others, + /// then the first one as the clipping path (see [`Self::clip_group`]), its name after it. Fills + /// and strokes the clipping path can't paint itself are paths of their own, the fills under the + /// others and the strokes over them. + fn clipped(&mut self, children: &[Arc]) { + let Some((first, rest)) = children.split_first() else { return }; + let Some((path, rule)) = clip_path(first) else { + self.warn_cut(Some(first)); + return self.clip_contents(children); + }; + let items = self.items(first, path.to_bezpath().bounding_box()); + let painted = self.plain_paint(&items); + if items.iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) { + self.warn(ITEM_TRANSPARENCY); + } + // Paint the clipping path can't carry: its fills under the others, its strokes over them. + let (fills, strokes): (Vec<&AppearanceItem>, Vec<&AppearanceItem>) = + if painted.is_none() { items.iter().partition(|i| matches!(i, AppearanceItem::Fill(_))) } else { (vec![], vec![]) }; + if painted.is_none() { + self.warn(CLIP_PAINT); + if first.extras().mask.is_some() && !items.is_empty() { + self.warn(CLIP_PAINT_MASKS); + } + } + self.clip_paint_part(first, &path, rule, &fills); + for c in rest { + self.node(c); + } + self.clip_paint_part(first, &path, rule, &strokes); + let (fill, stroke) = painted.unwrap_or_default(); + self.state(first.locked, !first.visible); + let start = self.body.len(); + self.paint_state(fill, stroke, Xy::of(first).object(), rule); + let op = paint_op(fill.is_some(), stroke.is_some()); + let subpaths: Vec<&SubPath> = path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).collect(); + let several = subpaths.len() > 1; + if several { + self.line("*u"); + } + let last = subpaths.len().saturating_sub(1); + let outline = path.to_bezpath(); + for (i, sp) in subpaths.into_iter().enumerate() { + ai_ops::subpath(&mut self.body, self.to_art, sp); + let _ = writeln!(self.body, "{}\nW", if sp.closed { 'h' } else { 'H' }); + let gradients = if i == last { (gradient(fill.map(|f| &f.paint)), gradient(stroke.map(|s| &s.paint))) } else { (None, None) }; + self.painted(op, sp.closed, gradients, stroke.is_some(), true, &outline); + } + if several { + self.line("*U"); + } + if self.body.len() > start { + self.dictionary(first); + } + } + + /// The fills or the strokes `items` of clipping path `first` (outline `path`) that it can't paint + /// itself, locked and hidden as it is, with its transparency once for all of them: one object, + /// or a group of an object for each (as the canvas draws them, [`Node::clip_paint`]). + fn clip_paint_part(&mut self, first: &Node, path: &PathData, rule: FillRule, items: &[&AppearanceItem]) { + if items.is_empty() { + return; + } + self.state(first.locked, !first.visible); + let xy = Xy::of(first); + if let [one] = items { + return self.item(path, rule, one, xy); + } + self.line("u"); + for i in items { + self.item(path, rule, i, Xy::PLAIN); + } + self.end_group("U", xy); + } + + /// A container's members, the first one's outline cutting the others: its fills painted + /// behind them (cut to the region outside too), its strokes over them, not cut by it. + fn clip_contents(&mut self, children: &[Arc]) { + let Some((first, rest)) = children.split_first() else { return }; + // Nothing to clip by hides the clipped art. + let Some((outline, rule)) = vectorcraft_effects::clip_outline(first) else { return }; + let paint = first.clip_paint(); + let outer = self.clip.clone(); + let region = self.cut(&PathData::from_bezpath(&outline), rule); + self.clip = Some(region); + if let Some(fill) = &paint.fill { + self.node(fill); + } + for c in rest { + self.node(c); + } + self.clip = outer; + if let Some(stroke) = &paint.stroke { + self.node(stroke); + } + } + + /// `path` (filled by `rule`) cut to the region the art is cut to, as a non-zero path. + fn cut(&self, path: &PathData, rule: FillRule) -> PathData { + match &self.clip { + Some(clip) => vectorcraft_pathops::boolean(path, rule, clip, FillRule::NonZero, BoolOp::Intersect), + None => vectorcraft_pathops::boolean(path, rule, path, rule, BoolOp::Intersect), + } + } + + // ---------- paths ---------- + + /// A path's fills and strokes, with the path's transparency `xy`: one object with one fill and + /// a plain stroke over it where it can be, else a group of an object for each (in paint order). + fn shape(&mut self, n: &Node, path: &PathData, rule: FillRule, xy: Xy) { + if path.is_empty() { + return; + } + let items = self.items(n, path.to_bezpath().bounding_box()); + if items.iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) { + self.warn(ITEM_TRANSPARENCY); + } + match (self.plain_paint(&items), items.as_slice()) { + (Some((fill, stroke)), _) => self.path_object(path, rule, fill, stroke, xy), + (None, [one]) => self.item(path, rule, one, xy), + (None, items) => { + self.line("u"); + for i in items { + self.item(path, rule, i, Xy::PLAIN); + } + self.end_group("U", xy); + } + } + } + + /// One fill or stroke of a path as an object of its own, of transparency `xy`. + fn item(&mut self, path: &PathData, rule: FillRule, item: &AppearanceItem, xy: Xy) { + match item { + AppearanceItem::Fill(f) => self.fill_object(path, rule, f, xy), + AppearanceItem::Stroke(s) if self.direct_stroke(s) => self.path_object(path, rule, None, Some(s), xy), + AppearanceItem::Stroke(s) => { + self.warn(STROKES); + self.wrote_fixed = true; + if self.brush_art(path, s, xy) { + return; + } + let outline = stroke::outline_region(path, rule, s); + let fill = FillLayer { overprint: s.overprint, ..FillLayer::new(s.paint.clone()) }; + self.fill_object(&outline, FillRule::NonZero, &fill, xy); + } + } + } + + /// A brushed stroke `st` of `path` as a group of its brush's art, of transparency `xy`. False + /// when it has no brush the document knows (or brushes nest too deep). + fn brush_art(&mut self, path: &PathData, st: &StrokeLayer, xy: Xy) -> bool { + if self.nest >= MAX_NEST { + return false; + } + let doc = self.doc; + let brushes = self.brushes.get_or_insert_with(|| vectorcraft_brush::library(doc)); + let Some(b) = st.brush.as_deref().and_then(|name| brushes.iter().find(|b| b.name == name)) else { return false }; + let art = vectorcraft_brush::stroke_pieces(doc, b, &path.to_bezpath(), st); + let state = self.state; + self.nest += 1; + self.line("u"); + for piece in &art { + self.node(piece); + } + if let Some((locked, hidden)) = state { + self.state(locked, hidden); + } + self.end_group("U", xy); + self.nest -= 1; + true + } + + /// A fill as an object of its own, of transparency `xy`: a color, a placed gradient or a + /// pattern the data can define as the path's fill, another pattern as its tiles cut to the path. + fn fill_object(&mut self, path: &PathData, rule: FillRule, f: &FillLayer, xy: Xy) { + if !matches!(f.paint, Paint::None) && self.direct(&f.paint) { + return self.path_object(path, rule, Some(f), None, xy); + } + match &f.paint { + // A gradient not placed yet: placed on the path, or its average color. + Paint::Solid { .. } | Paint::Gradient(_) => { + let flat = self.placed(&f.paint, path.to_bezpath().bounding_box()); + self.path_object(path, rule, Some(&FillLayer { paint: flat, ..f.clone() }), None, xy); + } + Paint::Pattern { pattern, xf } => { + self.warn(PATTERNS); + let doc = self.doc; + let Some(def) = doc.pattern(pattern).filter(|_| self.nest < MAX_NEST) else { + let flat = FillLayer { paint: Paint::solid(Color::gray(0.5)), ..f.clone() }; + return self.path_object(path, rule, Some(&flat), None, xy); + }; + let tiles = def.instances_in(*xf, path.to_bezpath().bounding_box()); + // More tiles than a fill places come back as none: the shape is filled gray, as a + // pattern that isn't found is. + if tiles.is_empty() && !def.art.is_empty() { + self.warn(PATTERN_TILES); + let flat = FillLayer { paint: Paint::solid(Color::gray(0.5)), ..f.clone() }; + return self.path_object(path, rule, Some(&flat), None, xy); + } + self.wrote_pattern = true; + let outer = self.clip.clone(); + let region = self.cut(path, rule); + self.clip = Some(region); + self.nest += 1; + let state = self.state; + self.line("u"); + for t in &tiles { + self.node(t); + } + if let Some((locked, hidden)) = state { + self.state(locked, hidden); + } + self.end_group("U", xy); + self.nest -= 1; + self.clip = outer; + } + Paint::None => {} + } + } + + /// A path object of transparency `xy` painted with `fill` (a color) and `stroke` (a plain line + /// of a color) over it; several subpaths make a compound path. Where the art is cut to a + /// clipping path, the fill is the path's region cut to it and the stroke its outline cut to it, + /// filled. + fn path_object(&mut self, path: &PathData, rule: FillRule, fill: Option<&FillLayer>, stroke: Option<&StrokeLayer>, xy: Xy) { + if self.clip.is_none() { + return self.plain_object(path, rule, fill, stroke, xy.object()); + } + let both = fill.is_some() && stroke.is_some(); + let own = if both { Xy::OPAQUE } else { xy.object() }; + if both { + self.line("u"); + } + if fill.is_some() || stroke.is_none() { + let region = self.cut(path, rule); + self.plain_object(®ion, FillRule::NonZero, fill, None, own); + } + if let Some(s) = stroke { + self.wrote_fixed = true; + let outline = stroke::outline_region(path, rule, s); + let region = self.cut(&outline, FillRule::NonZero); + let fill = FillLayer { overprint: s.overprint, ..FillLayer::new(s.paint.clone()) }; + self.plain_object(®ion, FillRule::NonZero, Some(&fill), None, own); + } + if both { + self.end_group("U", xy); + } + } + + /// The paint of a path of transparency `xy` filled by `rule`: its fill color and `O`, its stroke + /// color and `R`, `Xy`, the line style, `XR`. Without paint, `XR` comes first: an `Xy` right + /// after a compound path or a text object would be theirs. + fn paint_state(&mut self, fill: Option<&FillLayer>, stroke: Option<&StrokeLayer>, xy: Xy, rule: FillRule) { + let rule = if rule == FillRule::EvenOdd { "1 XR" } else { "0 XR" }; + if let Some(f) = fill { + self.color(&f.paint, false); + self.line(if f.overprint { "1 O" } else { "0 O" }); + } + if let Some(s) = stroke { + self.color(&s.paint, true); + self.line(if s.overprint { "1 R" } else { "0 R" }); + } + if fill.is_none() && stroke.is_none() { + self.line(rule); + return self.set_xy(xy); + } + self.set_xy(xy); + if let Some(s) = stroke { + ai_ops::line_style(&mut self.body, s); + } + self.line(rule); + } + + /// [`Self::path_object`] without cutting: the paint ([`Self::paint_state`]), each subpath's + /// points and painting operator (`*u` … `*U` around several). + fn plain_object(&mut self, path: &PathData, rule: FillRule, fill: Option<&FillLayer>, stroke: Option<&StrokeLayer>, xy: Xy) { + let subpaths: Vec<&SubPath> = path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).collect(); + if subpaths.is_empty() { + return; + } + self.paint_state(fill, stroke, xy, rule); + let op = paint_op(fill.is_some(), stroke.is_some()); + let several = subpaths.len() > 1; + if several { + self.line("*u"); + } + // A gradient's instance paints the last subpath; the compound path takes its paint. + let last = subpaths.len().saturating_sub(1); + let outline = path.to_bezpath(); + for (i, sp) in subpaths.into_iter().enumerate() { + ai_ops::subpath(&mut self.body, self.to_art, sp); + let gradients = if i == last { (gradient(fill.map(|f| &f.paint)), gradient(stroke.map(|s| &s.paint))) } else { (None, None) }; + self.painted(op, sp.closed, gradients, stroke.is_some(), false, &outline); + } + if several { + self.line("*U"); + } + } + + // ---------- type ---------- + + /// Type `n`: a text object stub naming its story in the text document ([`texts`]) when the + /// text document can hold it, outside opacity masks, pattern tiles, symbols' art and art cut to + /// a clipping object; else its outlines ([`Self::outlined_text`]). A frame of threaded area type + /// names the story of its thread, which its first frame holds. + fn text(&mut self, n: &Node, xy: Xy) { + let NodeKind::Text(t) = &n.kind else { return }; + let doc = self.doc; + let placed = if self.hidden > 0 || self.clip.is_some() || self.in_symbol { + None + } else if let Some(thread) = doc.text_threads.iter().find(|th| th.contains(&n.id)) { + // A thread is checked for what it loses, in every frame, when its story is written. + let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id)); + placed.map(|p| (p, self.texts.take_lost())) + } else if texts::holds(n, t) { + self.texts.add(t, self.canvas).map(|story| ((story, 0), texts::loses(t))) + } else { + None + }; + let Some(((story, frame), lost)) = placed else { return self.outlined_text(n, xy) }; + self.typed = true; + if lost { + self.warn(texts::TYPE_ATTRIBUTES); + } + // The stub takes the transparency set before it, as a path does. Its isolation and knockout + // are read only from a state block after it, as a group's are. + self.set_object_xy(xy.object()); + texts::stub(&mut self.body, story, frame, t, self.to_art); + if xy.isolate || xy.knockout != Knockout::Neutral { + self.state_block(xy); + } + } + + /// Type `n` as a group of what Type › Create Outlines makes of it + /// ([`vectorcraft_effects::outline_text`]): each run's glyphs with their underline and + /// strikethrough, its color glyphs, and the object's own fills and strokes; then its inline + /// graphics as their symbols' art where the layout places them, as the PDF page draws them; + /// the group has the type's transparency `xy`. + fn outlined_text(&mut self, n: &Node, xy: Xy) { + self.warn(TYPE); + self.line("u"); + let doc = self.doc; + let resolved = match &n.kind { + NodeKind::Text(t) => Some(doc.inline_resolved(t).into_owned()), + _ => None, + }; + let node = match &resolved { + Some(t) => Node { kind: NodeKind::Text(Box::new(t.clone())), ..n.clone() }, + None => n.clone(), + }; + let state = self.state; + let outlined = vectorcraft_effects::outline_text(&node); + let pieces = outlined.as_ref().and_then(|o| o.children()).map(Vec::as_slice).unwrap_or_default(); + // The object's fills and strokes above the Characters row, when they paint, are the last + // piece: the inline graphics go under it, as the PDF page draws them. + let above = !node.appearance.split_contents().1.is_empty() && { + let bare = Node { appearance: Default::default(), ..node.clone() }; + let glyphs = vectorcraft_effects::outline_text(&bare).and_then(|o| o.children().map(Vec::len)).unwrap_or_default(); + pieces.len() > glyphs + }; + let (under, over) = pieces.split_at(pieces.len() - usize::from(above)); + for c in under { + self.node(c); + } + if let Some(t) = resolved.as_ref().filter(|_| self.nest < MAX_NEST) { + let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + for ig in &layout.inlines { + let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue }; + let Some(sym) = doc.symbols.iter().find(|x| x.name == art.symbol) else { continue }; + if !self.take_symbol(&sym.art) { + continue; + } + self.warn(LIVE); + let mut art_node = (*sym.art).clone(); + // Strokes scale with the art, as on the canvas. + art_node.transform(t.xf * ig.xf * doc.symbol_natural_xf(&art.symbol), true); + (art_node.visible, art_node.locked, art_node.name) = (true, false, None); + self.nest += 1; + self.node(&art_node); + self.nest -= 1; + } + } + for c in over { + self.node(c); + } + if let Some((locked, hidden)) = state { + self.state(locked, hidden); + } + self.end_group("U", xy); + } + + // ---------- color ---------- + + /// Set the fill (or with `stroke`, the stroke) to paint `p`: a spot or global swatch by its + /// name, Registration, the color itself, or a pattern ([`Self::pattern_paint`]). A gradient sets + /// nothing: its instance paints ([`Self::painted`]). + fn color(&mut self, p: &Paint, stroke: bool) { + let (color, swatch, tint) = match p { + Paint::Solid { color, swatch, tint } => (color, swatch, tint), + Paint::Pattern { pattern, xf } => return self.pattern_paint(pattern, *xf, stroke), + Paint::Gradient(_) => return, + Paint::None => return self.plain_color(Color::gray(1.0), stroke), + }; + if swatch.as_deref() == Some(REGISTRATION) { + let mut s = String::from("1 1 1 1 "); + s.push_str(&ps::bytes(REGISTRATION.as_bytes())); + s.push(' '); + ps::push_num(&mut s, f64::from(1.0 - unit(*tint))); + s.push_str(if stroke { " XS" } else { " Xs" }); + return self.line(&s); + } + let doc = self.doc; + if let Some(name) = swatch + && let Some(sw) = doc.swatch(name).filter(|s| s.global || s.spot) + && let Paint::Solid { color: full, swatch: None, .. } = sw.paint + { + let mut s = String::new(); + self.named(&mut s, name, full, *tint, sw.spot, stroke); + return self.body.push_str(&s); + } + self.plain_color(*color, stroke); + } + + /// A color that names no swatch: `g` (gray), `k` (CMYK), else `c m y k r g b Xa` (RGB, and + /// Lab as RGB), with its CMYK equivalent. + fn plain_color(&mut self, color: Color, stroke: bool) { + let s = &mut self.body; + let op = |fill: &'static str, line: &'static str| if stroke { line } else { fill }; + match color { + // Gray is ink coverage; the format's gray is lightness. + Color::Gray { k } => { + ps::push_num(s, f64::from(1.0 - unit(k))); + let _ = writeln!(s, " {}", op("g", "G")); + } + Color::Cmyk { c, m, y, k } => { + ps::push_nums(s, &[c, m, y, k].map(|v| f64::from(unit(v)))); + let _ = writeln!(s, "{}", op("k", "K")); + } + Color::Rgb { .. } | Color::Lab { .. } => { + let cmyk = self.cms.to_cmyk(&color, self.cms.settings().intent).map(unit); + ps::push_nums(s, &cmyk.map(f64::from)); + ps::push_nums(s, &color.to_rgb().map(|v| f64::from(unit(v)))); + let _ = writeln!(s, "{}", op("Xa", "XA")); + } + } + } + + /// A spot (`spot`) or global process color `name` of full color `full` at `tint`, written to + /// `s`: its CMYK equivalent, its RGB or Lab values, the name, how much lighter than the full + /// color, and for any but a CMYK spot color (`x`) the model (0 CMYK, 1 RGB, 2 Lab) before + /// `Xx` (spot) or `Xk` (global process). + fn named(&self, s: &mut String, name: &str, full: Color, tint: f32, spot: bool, stroke: bool) { + let cmyk = self.cms.to_cmyk(&self.doc.linked_color(full, spot), self.cms.settings().intent).map(unit); + ps::push_nums(s, &cmyk.map(f64::from)); + let model = match full { + Color::Rgb { r, g, b } => { + ps::push_nums(s, &[r, g, b].map(|v| f64::from(unit(v)))); + Some(1) + } + Color::Lab { l, a, b } => { + ps::push_nums(s, &[f64::from(l), f64::from(a), f64::from(b)]); + Some(2) + } + _ if spot => None, + _ => Some(0), + }; + s.push_str(&ps::bytes(name.as_bytes())); + s.push(' '); + ps::push_num(s, f64::from(1.0 - unit(tint))); + let op = match (model, spot) { + (None, _) => "x", + (Some(_), true) => "Xx", + (Some(_), false) => "Xk", + }; + if let Some(m) = model { + let _ = write!(s, " {m}"); + } + let op = if stroke { op.to_ascii_uppercase() } else { op.to_string() }; + let _ = writeln!(s, " {op}"); + } + + // ---------- swatches ---------- + + /// The swatches: `%AI5_BeginPalette`, `0 0 Pb`, the Registration swatch, each color swatch's color and `(name) Pc` + /// (the ungrouped ones first, then each color group's after `0 (name) count Pg`), `PB`, + /// `%AI5_EndPalette`. + pub(super) fn palette(&mut self, s: &mut String) { + self.in_palette = true; + s.push_str("%AI5_BeginPalette\n0 0 Pb\n"); + self.registration_cell(s); + let doc = self.doc; + for sw in doc.swatches.iter() { + self.swatch(s, sw); + } + for g in doc.swatch_groups.iter() { + let mut cells = String::new(); + let count = g.swatches.iter().filter(|sw| self.swatch(&mut cells, sw)).count(); + let _ = writeln!(s, "0 {} {count} Pg", ps::bytes(g.name.as_bytes())); + s.push_str(&cells); + } + s.push_str("PB\n%AI5_EndPalette\n"); + self.in_palette = false; + } + + /// The Registration swatch, which every palette in the files users sent starts with: in a + /// CMYK document `1 1 1 1 ([Registration]) 0 Xs`, in an RGB one black's CMYK equivalent, + /// `0 0 0 ([Registration]) 0 1 Xz`; then `([Registration]) Pc`. + fn registration_cell(&self, s: &mut String) { + let name = ps::bytes(REGISTRATION.as_bytes()); + if self.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { + let _ = writeln!(s, "1 1 1 1 {name} 0 Xs"); + } else { + let black = Color::rgb(0.0, 0.0, 0.0); + let cmyk = self.cms.to_cmyk(&black, self.cms.settings().intent).map(unit); + ps::push_nums(s, &cmyk.map(f64::from)); + let _ = writeln!(s, "0 0 0 {name} 0 1 Xz"); + } + let _ = writeln!(s, "{name} Pc"); + } + + /// One swatch of the palette: a color swatch's color, a gradient swatch's or pattern swatch's + /// paint ([`Self::swatch_paint`]), then `(name) Pc`. False when it isn't written: Registration + /// (written first), the None swatch, and paint the data can't hold (with a warning). + fn swatch(&mut self, s: &mut String, sw: &Swatch) -> bool { + if sw.name == REGISTRATION || matches!(sw.paint, Paint::None) { + return false; + } + match &sw.paint { + Paint::Solid { color, swatch, .. } => { + if swatch.is_none() && (sw.global || sw.spot) { + self.named(s, &sw.name, *color, 1.0, sw.spot, false); + } else { + let body = std::mem::take(&mut self.body); + self.plain_color(*color, false); + s.push_str(&std::mem::replace(&mut self.body, body)); + } + } + _ if self.swatch_paint(s, sw) => {} + _ => { + self.warn(SWATCHES); + return false; + } + } + let _ = writeln!(s, "{} Pc", ps::bytes(sw.name.as_bytes())); + true + } + + /// The spot color swatches, with their full colors' CMYK equivalents, for the header. + pub(super) fn spot_swatches(&self) -> Vec<(String, [f32; 4])> { + let intent = self.cms.settings().intent; + self.doc + .swatches_iter() + .filter(|sw| sw.spot) + .filter_map(|sw| match sw.paint { + Paint::Solid { color, swatch: None, .. } => { + Some((sw.name.clone(), self.cms.to_cmyk(&self.doc.linked_color(color, true), intent).map(unit))) + } + _ => None, + }) + .collect() + } +} + +/// The gradient of paint `p`, when it has one. +fn gradient(p: Option<&Paint>) -> Option<&vectorcraft_color::GradientPaint> { + match p { + Some(Paint::Gradient(g)) => Some(g), + _ => None, + } +} + +/// `n`'s fills and strokes that paint. +fn visible_items(n: &Node) -> Vec<&AppearanceItem> { + n.appearance + .items + .iter() + .filter(|i| match i { + AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(), + AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.width > 0.0 && s.width.is_finite(), + }) + .collect() +} + +/// The painting operator of a closed subpath (§5.3.3): `b` fill and stroke, `f` fill, `s` +/// stroke, `n` neither; an open one's is upper case. +fn paint_op(fill: bool, stroke: bool) -> char { + match (fill, stroke) { + (true, true) => 'b', + (true, false) => 'f', + (false, true) => 's', + (false, false) => 'n', + } +} + +/// The subpaths of compound path `n`'s members, as one path. +fn compound_path(n: &Node) -> PathData { + let mut subpaths = vec![]; + for p in n.children().map(Vec::as_slice).unwrap_or_default().iter().filter_map(|c| c.path_data()) { + subpaths.extend(p.subpaths.iter().cloned()); + } + PathData::new(subpaths) +} + +/// Is object `id` of `doc` in (or inside) a clipping group or clipping layer whose clipping object +/// isn't a path or compound path (its art is written cut to that object, [`Writer::clip_group`])? +/// Type that is a clipping object is one of these: it isn't a path. +fn cut_to_clipping_object(doc: &Document, id: NodeId) -> bool { + let ancestry = doc.ancestry(id).unwrap_or_default(); + let above = ancestry.split_last().map(|(_, a)| a).unwrap_or_default(); + above.iter().filter_map(|a| doc.node(*a)).any(|p| { + matches!(p.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }) + && p.children().and_then(|c| c.first()).is_none_or(|c| clip_path(c).is_none()) + }) +} + +/// The outline and fill rule a clipping path or compound path `n` clips by; `None` for other +/// clipping objects and for a path without points (it clips everything away, see +/// [`Writer::clip_contents`]). +fn clip_path(n: &Node) -> Option<(PathData, FillRule)> { + let (path, rule) = match &n.kind { + NodeKind::Path { path, rule, guide: false, .. } => (path.clone(), *rule), + NodeKind::Compound { rule, .. } => (compound_path(n), *rule), + _ => return None, + }; + path.subpaths.iter().any(|sp| !sp.anchors.is_empty()).then_some((path, rule)) +} + +/// `text`'s lines on `%_` lines, as a part of the data that readers of the printed form skip (an +/// opacity mask's art, a pattern's tile) has them. An image's samples stay as they are after an +/// `XI` without `%_`, and `%_%%EndData` ends them, as in the files users sent. Samples hidden +/// already (an opacity mask's art in a pattern's tile) keep their one `%_`. +pub(super) fn hide(text: &str, out: &mut String) { + for l in text.lines() { + if l.starts_with(images::SAMPLES_LINE) { + match l.strip_suffix("%%EndData") { + Some(samples) if !samples.ends_with("%_") => { + out.push_str(samples); + out.push_str("%_%%EndData"); + } + _ => out.push_str(l), + } + } else { + if !l.starts_with("%_") { + out.push_str("%_"); + } + out.push_str(l); + } + out.push('\n'); + } +} + +/// The image `bytes` decoded, when its header gives at most `max` pixels; the decoder may allocate +/// at most 8 bytes a pixel. +fn decode_bounded(bytes: &[u8], max: u64) -> Option { + let reader = || -> image::ImageResult>> { + let mut r = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?; + let mut limits = image::Limits::default(); + limits.max_alloc = Some(max * 8); + r.limits(limits); + Ok(r) + }; + let (w, h) = reader().and_then(|r| r.into_dimensions()).ok()?; + if u64::from(w) * u64::from(h) > max { + return None; + } + reader().and_then(|r| r.decode()).ok() +} diff --git a/crates/eps/src/ai_editing/writer/images.rs b/crates/eps/src/ai_editing/writer/images.rs new file mode 100644 index 0000000000..898c91aa7b --- /dev/null +++ b/crates/eps/src/ai_editing/writer/images.rs @@ -0,0 +1,333 @@ +//! Images: embedded ones as a raster with its samples, linked ones as a placed file with a preview +//! (see [`crate::ai_editing`] for the form). + +use std::fmt::Write; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{FillLayer, ImageBlob, ImageObject, LinkInfo}; +use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape}; + +use super::{Writer, Xy}; +use crate::ps; + +pub(in crate::ai_editing) const IMAGES: &str = "images that can't be decoded or have more than 33,554,432 pixels are written as their outlines filled mid gray in the editing data for other apps"; +pub(in crate::ai_editing) const IMAGE_DEPTH: &str = "images of 16 bits a channel are written at 8 bits a channel in the editing data for other apps"; +pub(in crate::ai_editing) const LINKS_EMBEDDED: &str = + "linked images in opacity masks, pattern tiles and symbols are written as embedded images in the editing data for other apps"; + +/// The most pixels an image is written with: as many as the reader reads. +pub(super) const MAX_PIXELS: u64 = 1 << 25; +/// The longer side of a placed file's preview at most (a smaller image's preview is its own +/// pixels): the files users sent have previews 256 pixels wide. +const PREVIEW_SIDE: u32 = 256; +/// What marks a binary payload in the program text: `\u{1}`, its index, `\u{1}` +/// ([`super::super::splice`] puts the bytes in its place). Strings never hold the byte unescaped. +pub(in crate::ai_editing) const PAYLOAD: char = '\u{1}'; +/// What starts the line of an image's samples: `XI` and its payload, then `%%EndData`. +pub(super) const SAMPLES_LINE: &str = "XI\u{1}"; + +/// An image's pixels as the data holds them. +struct Samples { + /// `/DeviceGray`, `/DeviceRGB` or `/DeviceCMYK`. + space: &'static str, + /// The image type of `XI` (§8.1): 1 gray, 3 RGB, 4 CMYK. + kind: u8, + width: u32, + height: u32, + /// The color samples, 8 bits each, rows from the top. + color: Vec, + /// The alpha channel, a byte a pixel, when a pixel isn't opaque. + alpha: Option>, +} + +impl Samples { + /// The pixels of `blob`: a CMYK image's ink amounts, else gray samples when every pixel is gray + /// or RGB samples, with an alpha channel when they need one. `None` when they can't be decoded or are more than + /// [`MAX_PIXELS`]; the flag is set when the image had 16 bits a channel. + fn of(blob: &ImageBlob) -> Option<(Samples, bool)> { + // The header's size is checked before the inks are decoded. + if blob.is_cmyk() + && blob.header_size().is_some_and(|(w, h)| u64::from(w) * u64::from(h) <= MAX_PIXELS) + && let Some(inks) = blob.cmyk() + && u64::from(inks.width) * u64::from(inks.height) <= MAX_PIXELS + { + let s = Samples { space: "/DeviceCMYK", kind: 4, width: inks.width, height: inks.height, color: inks.data, alpha: None }; + return Some((s, blob.is_cmyk16())); + } + let img = super::decode_bounded(&blob.bytes, MAX_PIXELS)?; + let deep = matches!( + img.color(), + image::ColorType::L16 + | image::ColorType::La16 + | image::ColorType::Rgb16 + | image::ColorType::Rgba16 + | image::ColorType::Rgb32F + | image::ColorType::Rgba32F + ); + let rgba = img.to_rgba8(); + // Gray when every pixel is, whatever the file's color type (an image read back from the data + // is RGBA): the same pixels are written the same way. + let gray = rgba.pixels().all(|p| p.0[0] == p.0[1] && p.0[1] == p.0[2]); + let (width, height) = rgba.dimensions(); + if width == 0 || height == 0 { + return None; + } + let opaque = rgba.pixels().all(|p| p.0[3] == 255); + let alpha = (!opaque).then(|| rgba.pixels().map(|p| p.0[3]).collect()); + let color = if gray { rgba.pixels().map(|p| p.0[0]).collect() } else { rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect() }; + let (space, kind) = if gray { ("/DeviceGray", 1) } else { ("/DeviceRGB", 3) }; + Some((Samples { space, kind, width, height, color, alpha }, deep)) + } + + /// `XI`'s fourth flag as the files users sent have it: 0 gray, 1 RGB, 2 CMYK, 16 more with an + /// alpha channel. + fn reserved(&self) -> u8 { + let space = match self.kind { + 1 => 0, + 4 => 2, + _ => 1, + }; + space + if self.alpha.is_some() { 16 } else { 0 } + } +} + +impl Writer<'_> { + /// Image object `im` of transparency `xy`: embedded, a raster ([`Self::raster`]); linked, a + /// placed file with a preview ([`Self::placed_file`]), except in a part of the data written on + /// `%_` lines and in a symbol's art. One whose pixels can't be read is its outline filled mid gray. Where the art is + /// cut to a clipping path, the image is in a clipping group of that path. + pub(super) fn image(&mut self, im: &ImageObject, xy: Xy) { + let doc = self.doc; + let Some((samples, deep)) = doc.image_blob(im).and_then(Samples::of) else { + let bounds = PathData::from_bezpath(&(im.xf * Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1))); + self.warn(IMAGES); + return self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(Color::gray(0.5))), xy); + }; + // A region that has nothing left hides the image. + if self.clip.as_ref().is_some_and(|c| c.subpaths.iter().all(|sp| sp.anchors.is_empty())) { + return; + } + if deep { + self.warn(IMAGE_DEPTH); + } + let cut = self.clip.take(); + let at_q = (self.state, self.gs); + if cut.is_some() { + self.line("q"); + } + self.set_object_xy(xy.object()); + // The object places the image's own pixel grid (its width × height) wherever the file's is. + let fit = + Affine::scale_non_uniform(f64::from(im.width.max(1)) / f64::from(samples.width), f64::from(im.height.max(1)) / f64::from(samples.height)); + match &im.link { + Some(link) if self.hidden == 0 && !self.in_symbol => { + // Cut to a region, the placed file is in a clipping group. + self.placed = cut.is_none(); + self.placed_file(link, &samples, (im.width.max(1), im.height.max(1)), im.xf); + } + other => { + if other.is_some() { + self.warn(LINKS_EMBEDDED); + } + self.raster(&samples, im.xf * fit); + } + } + if let Some(region) = &cut { + self.line("0 XR"); + // Several subpaths clip as one compound path (`*u` … `*U`), as a clipping group's do. + let subpaths: Vec<_> = region.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).collect(); + let several = subpaths.len() > 1; + if several { + self.line("*u"); + } + for sp in subpaths { + crate::ai_ops::subpath(&mut self.body, self.to_art, sp); + self.line("h\nW\nn"); + } + if several { + self.line("*U"); + } + (self.state, self.gs) = at_q; + self.end_group("Q", Xy::PLAIN); + } + self.clip = cut; + } + + /// An embedded image whose pixels `xf` places in the document: `%AI5_File:`, + /// `%AI5_BeginRaster`, `() 1 XG` (no file), the color space `XN`, `[matrix] w h 0 Xh`, + /// `[matrix] 0 0 w h w h 8 type alpha reserved 1 0 4 4 0 0`, `%%BeginData:` counting `XI`, its + /// line end and the color samples, `XI`, the color samples then the alpha channel in binary, + /// `%%EndData`, `XH`, `%AI5_EndRaster`, `N`. The matrix is an art-space matrix applied to the + /// pixels with their rows running downwards, `(u, -v)`, as §8.1's image matrix; in a symbol's + /// art (outside a pattern's tile in it), a matrix in the canvas's space turned y up about art + /// space's origin there, as an instance's matrix in it is. + fn raster(&mut self, s: &Samples, xf: Affine) { + let space = if self.in_symbol && self.defining.is_empty() { self.instance_space } else { self.to_art }; + let m = matrix(space * xf * Affine::FLIP_Y); + let (w, h) = (s.width, s.height); + let alpha = u8::from(s.alpha.is_some()); + let mut payload = Vec::with_capacity(2 + s.color.len() + s.alpha.as_ref().map_or(0, Vec::len)); + payload.extend_from_slice(b"\r\n"); + payload.extend_from_slice(&s.color); + if let Some(a) = &s.alpha { + payload.extend_from_slice(a); + } + let mark = self.payload(payload); + let _ = writeln!( + self.body, + "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n{} XN\n{m} {w} {h} 0 Xh\n{m} 0 0 {w} {h} {w} {h} 8 {} {alpha} {} 1 0 4 4 0 0\n%%BeginData: {}\nXI{mark}%%EndData\nXH\n%AI5_EndRaster\nN", + s.space, + s.kind, + s.reserved(), + // `XI`, CR LF. + 4 + s.color.len(), + ); + } + + /// A linked image whose pixels `xf` places in the document: `%AI5_BeginPlace`, + /// `%%FileType: 1`, `[matrix] llx lly urx ury 4 4 0` and the file's path with `` ` ``, + /// `%%IncludeFile:` and the path, the folder relative to the document's between + /// `%AI28_BeginPlacedRelativePath` and its end (`()` for the document's own folder), the preview between + /// `%AI26_BeginPlacedObjectPreview` and its end (`w h rowBytes 32 17 ` and rows of + /// premultiplied ARGB, the top one first, of the pixels `s`), `~`, `%AI5_EndPlace`. The box is + /// as large as the file has pixels (`w` × `h`, the object's pixel grid, which `xf` places in the + /// document), at art space's origin on the canvas (y down); the matrix takes it from there into + /// art space. Each marked part newer releases read is in versioned content, as in the files + /// users sent. + fn placed_file(&mut self, link: &LinkInfo, s: &Samples, (w, h): (u32, u32), xf: Affine) { + let (x, y) = self.canvas_origin; + let m = matrix(self.to_art * xf * Affine::translate((-x, -y))); + let (w, h) = (f64::from(w), f64::from(h)); + let path = ps::bytes(link.path.as_bytes()); + let _ = write!(self.body, "%AI5_BeginPlace\n%%FileType: 1\n{m} "); + ps::push_nums(&mut self.body, &[x, y, x + w, y + h, 4.0, 4.0, 0.0]); + self.body.pop(); + let _ = writeln!(self.body, "\n{path}`"); + if !link.path.chars().any(char::is_control) { + let _ = writeln!(self.body, "%%IncludeFile:{}", link.path); + } + // The section holds a folder only, the file's name comes from the path: a relative path to a + // file of another name isn't written. On Windows and macOS, whose file names ignore letter + // case, names that differ only in case are the same file. + let same_name = |r: &&str| r.rsplit(['/', '\\']).next().is_some_and(|n| same_file_name(n, link.name())); + if let Some(folder) = link.relative.as_deref().filter(same_name).map(relative_folder) { + let _ = writeln!( + self.body, + "%AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n{}\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content", + ps::bytes(folder.as_bytes()) + ); + } + let (pw, ph, rows) = preview(s); + let mark = self.payload(rows); + let _ = writeln!( + self.body, + "%AI17_Begin_Content_if_version_gt:24 5\n%AI26_BeginPlacedObjectPreview\n{pw} {ph} {} 32 17 {mark}\n%AI26_EndPlacedObjectPreview\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace", + pw * 4 + ); + } + + /// Keep `bytes` to go in the program where the mark this returns is. + fn payload(&mut self, bytes: Vec) -> String { + self.payloads.push(bytes); + format!("{PAYLOAD}{}{PAYLOAD}", self.payloads.len() - 1) + } +} + +/// `[a b c d tx ty]`, each number to ten decimals ([`ps::num`] writes four). +fn matrix(m: Affine) -> String { + let n: Vec = m.as_coeffs().iter().map(|v| precise(*v)).collect(); + format!("[{}]", n.join(" ")) +} + +/// `v` rounded to ten decimals, without trailing zeros (0 when not finite). +pub(super) fn precise(v: f64) -> String { + let r = (v * 1e10).round() / 1e10; + if !r.is_finite() { + return if v.is_finite() { format!("{}", v + 0.0) } else { "0".into() }; + } + format!("{}", r + 0.0) +} + +/// The folder of a path relative to the document's (`src/checker.png` → `src/`); empty when the file +/// is in the document's own folder. `\` separators are read as `/`. +fn relative_folder(relative: &str) -> String { + match relative.replace('\\', "/").rsplit_once('/') { + Some((folder, _)) if !folder.is_empty() => format!("{folder}/"), + _ => String::new(), + } +} + +/// Do file names `a` and `b` name the same file in one folder: equal, or on Windows and macOS equal +/// but for letter case? +fn same_file_name(a: &str, b: &str) -> bool { + a == b || (cfg!(any(windows, target_os = "macos")) && a.to_lowercase() == b.to_lowercase()) +} + +/// A placed file's preview of `s`: its width, height and rows of premultiplied ARGB, the top one +/// first; the image's own pixels when neither side is longer than [`PREVIEW_SIDE`], else scaled +/// down to it, each preview pixel the average of the premultiplied pixels it covers. +fn preview(s: &Samples) -> (u32, u32, Vec) { + let (w, h) = (u64::from(s.width), u64::from(s.height)); + let longer = s.width.max(s.height); + let (pw, ph) = if longer > PREVIEW_SIDE { + let k = f64::from(PREVIEW_SIDE) / f64::from(longer); + let side = |v: u32| ((f64::from(v) * k).round() as u32).clamp(1, PREVIEW_SIDE); + (side(s.width), side(s.height)) + } else { + (s.width, s.height) + }; + let n = usize::from(channels(s.kind)); + let cmyk_memo = std::cell::RefCell::new(std::collections::HashMap::new()); + // Pixel `i` premultiplied: r, g, b, a. + let pixel = |i: usize| -> [u64; 4] { + let c = |k: usize| s.color.get(i * n + k).copied().unwrap_or(0); + let rgb = match s.kind { + 1 => [c(0); 3], + 4 => { + let mut memo = cmyk_memo.borrow_mut(); + if memo.len() > 1 << 16 { + memo.clear(); + } + *memo.entry([c(0), c(1), c(2), c(3)]).or_insert_with(|| { + let f = |v: u8| f32::from(v) / 255.0; + let [r, g, b, _] = Color::cmyk(f(c(0)), f(c(1)), f(c(2)), f(c(3))).to_rgba8(1.0); + [r, g, b] + }) + } + _ => [c(0), c(1), c(2)], + }; + let a = u64::from(s.alpha.as_ref().and_then(|a| a.get(i)).copied().unwrap_or(255)); + let pre = |v: u8| (u64::from(v) * a + 127) / 255; + [pre(rgb[0]), pre(rgb[1]), pre(rgb[2]), a] + }; + let (pw64, ph64) = (u64::from(pw), u64::from(ph)); + let mut rows = Vec::with_capacity((pw64 * ph64 * 4) as usize); + for py in 0..ph64 { + let (y0, y1) = (py * h / ph64, ((py + 1) * h / ph64).max(py * h / ph64 + 1)); + for px in 0..pw64 { + let (x0, x1) = (px * w / pw64, ((px + 1) * w / pw64).max(px * w / pw64 + 1)); + let mut sum = [0u64; 4]; + for y in y0..y1.min(h) { + for x in x0..x1.min(w) { + let p = pixel((y * w + x) as usize); + for (t, v) in sum.iter_mut().zip(p) { + *t += v; + } + } + } + let count = ((y1.min(h) - y0) * (x1.min(w) - x0)).max(1); + let [r, g, b, a] = sum.map(|t| ((t + count / 2) / count).min(255) as u8); + rows.extend_from_slice(&[a, r, g, b]); + } + } + (pw, ph, rows) +} + +/// The samples a pixel of image type `kind` has. +fn channels(kind: u8) -> u8 { + match kind { + 1 => 1, + 4 => 4, + _ => 3, + } +} diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs new file mode 100644 index 0000000000..b4966968e2 --- /dev/null +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -0,0 +1,594 @@ +//! Gradients and patterns: their definitions in the setup, gradient instances on paths and the +//! pattern operators (see [`crate::ai_editing`] for the form). + +use std::fmt::Write; + +use vectorcraft_color::gradient::GradientGeom; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{AppearanceItem, FillLayer, PatternDef, StrokeLayer, TileType}; +use vectorcraft_effects::stroke; +use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2}; + +use super::{MAX_NEST, Writer, Xy}; +use crate::ai_ops::{average, unit}; +use crate::ps; + +pub(in crate::ai_editing) const GRADIENTS: &str = + "freeform gradients, and gradients along or across strokes, are written as their average color in the editing data for other apps"; +pub(in crate::ai_editing) const GRADIENT_SHAPES: &str = "gradients without stops or with more than 256, gradients whose ramp has no length and radial gradients flattened to a line are written as their average color in the editing data for other apps"; +pub(in crate::ai_editing) const SWATCH_PLACEMENT: &str = + "the placement of pattern swatches that move, turn or scale their pattern is left out of the editing data for other apps"; +pub(in crate::ai_editing) const GRADIENT_MIX: &str = + "gradients that mix their colors perceptually or dither are written as classic gradients in the editing data for other apps"; +pub(in crate::ai_editing) const STOP_LINKS: &str = + "gradient stops linked to global process colors are written as their colors in the editing data for other apps"; +/// The length of a linear gradient's caps (`Bc`): the canvas's side. +const CAP: f64 = super::super::CANVAS_SIZE as f64; + +/// A gradient definition: its name, its gradient, whether it is a gradient swatch's (named after +/// the swatch) and whether the art uses it (else only the palette does). +pub(super) struct GradientDef { + name: String, + gradient: Gradient, + swatch: bool, + used: bool, +} + +/// A pattern definition written: its name, its text (`%AI3_BeginPattern` to `%AI3_EndPattern`) +/// and whether the art uses it. +pub(super) struct PatternOut { + name: String, + text: String, + used: bool, +} + +/// Can `g` be written as a gradient (a linear or radial one with stops, no more than the `.ai` +/// reader reads)? +fn writable_gradient(g: &Gradient) -> bool { + g.kind != GradientKind::Freeform && !g.stops.is_empty() && g.stops.len() <= crate::import::MAX_GRADIENT_STOPS +} + +/// The first name of `Gradient`, `Gradient 2`, `Gradient 3`, … numbered `next` or higher for +/// which `taken` returns false (`Gradient` is number 1); `next` is set past it. +pub(in crate::ai_editing) fn free_gradient_name(next: &mut u64, mut taken: impl FnMut(&str) -> bool) -> String { + loop { + let name = if *next <= 1 { String::from("Gradient") } else { format!("Gradient {next}") }; + *next = next.saturating_add(1); + if !taken(&name) { + return name; + } + } +} + +/// The stops of `g` in order of their place on the ramp. +fn sorted_stops(g: &Gradient) -> Vec<&GradientStop> { + let mut stops: Vec<&GradientStop> = g.stops.iter().collect(); + stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + stops +} + +impl Writer<'_> { + /// Each gradient swatch's definition, named after the swatch, before the art is written. + pub(in crate::ai_editing) fn reserve_swatch_gradients(&mut self) { + let doc = self.doc; + for sw in doc.swatches_iter() { + if let Paint::Gradient(g) = &sw.paint + && writable_gradient(&g.gradient) + && !self.gradients.iter().any(|d| d.name == sw.name) + { + self.gradients.push(GradientDef { name: sw.name.clone(), gradient: g.gradient.clone(), swatch: true, used: false }); + } + } + } + + /// The name of the definition of `g`: the swatch `swatch` names when it is a gradient swatch + /// of the same gradient, else a definition of the same gradient that no swatch names, else a + /// new one ([`free_gradient_name`]: `Gradient`, numbered when taken by another definition, a + /// swatch or a pattern). + fn define_gradient(&mut self, g: &Gradient, swatch: Option<&str>) -> String { + let used = !self.in_palette; + let found = swatch + .and_then(|s| self.gradients.iter().position(|d| d.swatch && d.name == s && d.gradient == *g)) + .or_else(|| self.gradients.iter().position(|d| !d.swatch && d.gradient == *g)); + if let Some(d) = found.and_then(|i| self.gradients.get_mut(i)) { + d.used |= used; + return d.name.clone(); + } + let (doc, gradients) = (self.doc, &self.gradients); + let name = free_gradient_name(&mut self.next_gradient, |name| { + gradients.iter().any(|d| d.name == name) || doc.swatch(name).is_some() || doc.pattern(name).is_some() + }); + self.gradients.push(GradientDef { name: name.clone(), gradient: g.clone(), swatch: false, used }); + name + } + + /// The gradient definitions' state, for [`Self::gradient_rollback`]: their count, which ones the + /// art uses, and the next name's number. + pub(super) fn gradient_mark(&self) -> (usize, Vec, u64) { + (self.gradients.len(), self.gradients.iter().map(|d| d.used).collect(), self.next_gradient) + } + + /// The gradient definitions as they were at `mark` ([`Self::gradient_mark`]). + pub(super) fn gradient_rollback(&mut self, mark: (usize, Vec, u64)) { + let (len, used, next) = mark; + self.gradients.truncate(len); + for (d, u) in self.gradients.iter_mut().zip(used) { + d.used = u; + } + self.next_gradient = next; + } + + /// `p` as the paint of a fill or stroke whose gradient is placed on `bounds`: a gradient is + /// placed there (it then no longer depends on the shape it paints, which may be cut); one the + /// data can't hold is its average color, with a warning. + pub(super) fn placed(&mut self, p: &Paint, bounds: Rect) -> Paint { + let Paint::Gradient(g) = p else { return p.clone() }; + let geom = g.resolve(bounds); + let finite = [geom.start.x, geom.start.y, geom.end.x, geom.end.y, geom.aspect].iter().all(|v| v.is_finite()); + let radial = g.gradient.kind == GradientKind::Radial; + if g.gradient.kind == GradientKind::Freeform { + self.warn(GRADIENTS); + return Paint::solid(average(&g.gradient)); + } + if !writable_gradient(&g.gradient) || !finite || geom.length() < 1e-9 || (radial && geom.aspect <= 1e-9) { + self.warn(GRADIENT_SHAPES); + return Paint::solid(average(&g.gradient)); + } + Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..(**g).clone() })) + } + + /// The fills and strokes of `n` that paint (outline `bounds`), their gradients placed + /// ([`Self::placed`]): a fill's on the shape's bounds, a stroke's on what it paints. A gradient + /// along or across a stroke is its average color (the stroke is written as its outline). + pub(super) fn items(&mut self, n: &vectorcraft_doc::Node, bounds: Rect) -> Vec { + super::visible_items(n) + .into_iter() + .map(|i| match i { + AppearanceItem::Fill(f) => AppearanceItem::Fill(FillLayer { paint: self.placed(&f.paint, bounds), ..f.clone() }), + AppearanceItem::Stroke(s) => { + let paint = match s.path_gradient() { + Some(g) => { + self.warn(GRADIENTS); + Paint::solid(average(&g.gradient)) + } + None => self.placed(&s.paint, s.paint_bounds(bounds)), + }; + AppearanceItem::Stroke(StrokeLayer { paint, ..s.clone() }) + } + }) + .collect() + } + + /// Can paint `p` be written as the paint of a path object: a color, a placed gradient, or a + /// pattern [`Self::pattern_writable`]? + pub(super) fn direct(&self, p: &Paint) -> bool { + match p { + Paint::Solid { .. } => true, + Paint::Gradient(g) => g.geom.is_some() && writable_gradient(&g.gradient), + Paint::Pattern { pattern, .. } => self.pattern_writable(pattern), + Paint::None => false, + } + } + + /// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can + /// write it)? + pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool { + self.direct(&s.paint) && stroke::is_plain(s) + } + + /// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the + /// line over the fill; `None` when it has other paint. + pub(super) fn plain_paint<'i>(&self, items: &'i [AppearanceItem]) -> Option<(Option<&'i FillLayer>, Option<&'i StrokeLayer>)> { + match items { + [] => Some((None, None)), + [AppearanceItem::Fill(f)] if self.direct(&f.paint) => Some((Some(f), None)), + [AppearanceItem::Stroke(s)] if self.direct_stroke(s) => Some((None, Some(s))), + [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] if self.direct(&f.paint) && self.direct_stroke(s) => Some((Some(f), Some(s))), + _ => None, + } + } + + /// The painting operator `op` of a subpath (`closed` or open), with the gradient instances of + /// the fill (`fill`) and the stroke (`stroke`) around it when it is the last subpath of its + /// object: `Bb` … `op` `flag BB`, the stroke's `1 Bb` … after the fill's `BB`; the flag is 0, or + /// with a stroke 2 (closed) or 1 (open). `stroked`: the object has a stroke. A clipping path's + /// instances (`clip`) don't issue a clip of their own. `path`: the path the operator paints (all + /// its subpaths), in the document. + pub(super) fn painted( + &mut self, + op: char, + closed: bool, + gradients: (Option<&GradientPaint>, Option<&GradientPaint>), + stroked: bool, + clip: bool, + path: &BezPath, + ) { + let op = if closed { op } else { op.to_ascii_uppercase() }; + let flag = match (stroked, closed) { + (false, _) => "0 BB", + (true, true) => "2 BB", + (true, false) => "1 BB", + }; + let (fill, stroke) = gradients; + if let Some(f) = fill { + self.instance(f, false, clip, path); + if stroke.is_some() { + self.line(if closed { "2 BB" } else { "1 BB" }); + } + } + if let Some(s) = stroke { + self.instance(s, true, clip, path); + } + self.body.push(op); + self.body.push('\n'); + if fill.is_some() || stroke.is_some() { + self.line(flag); + } + } + + /// A gradient instance's start (placed gradient `g`, on the stroke when `stroke`, on `path` in + /// the document), before its painting operator: `Bb` (`1 Bb` on the stroke); a radial + /// gradient's focal point `x y angle fraction Bh` (its offset from the center in the space of the + /// gradient's matrices, then its angle and fraction as [`placement`] gives them; `0 0 0 0 Bh` at + /// the center); `flag (name) x y angle length a b c d tx ty 1 Bg` (flag 1, or 0 for a clipping + /// path; the rest as [`placement`] gives them); then the gradient's place: a linear one's `a b c d tx ty Xm` (the + /// unit vector onto its whole ramp), its cap before the first stop `… Bc`, a `… Bm` for each pair + /// of stops next to each other (the unit vector onto the part between them) and its cap past the + /// last stop; a radial one's `… Bm` (the unit circle onto its extent ellipse). + fn instance(&mut self, g: &GradientPaint, stroke: bool, clip: bool, path: &BezPath) { + let Some(geom) = g.geom else { return }; + self.line(if stroke { "1 Bb" } else { "Bb" }); + self.instance_head(g, clip, path); + let m = self.grad_space; + let u = geom.end - geom.start; + let radial = g.gradient.kind == GradientKind::Radial; + // The unit vector along the gradient, and across it as long. + let frame = |from: f64, to: f64| { + let p = geom.start + u * from; + m * Affine::new([u.x * (to - from), u.y * (to - from), -u.y, u.x, p.x, p.y]) + }; + let mut matrix = |a: Affine, op: &str| { + ps::push_nums(&mut self.body, &a.as_coeffs()); + self.body.push_str(op); + self.body.push('\n'); + }; + if radial { + matrix(m * geom.unit_frame().unwrap_or(Affine::new([u.x, u.y, -u.y, u.x, geom.start.x, geom.start.y])), "Bm"); + return; + } + matrix(frame(0.0, 1.0), "Xm"); + let offsets: Vec = sorted_stops(&g.gradient).iter().map(|s| f64::from(s.offset)).collect(); + let len = u.hypot().max(1e-9); + let (first, last) = (offsets.first().copied().unwrap_or(0.0), offsets.last().copied().unwrap_or(1.0)); + matrix(frame(first - CAP / len, first), "Bc"); + for pair in offsets.windows(2) { + if let [a, b] = pair { + matrix(frame(*a, *b), "Bm"); + } + } + matrix(frame(last, last + CAP / len), "Bc"); + } + + /// A gradient instance's focal point (`Bh`, radial gradients only) and its `Bg` line, as + /// [`Self::instance`] writes them; also what a fill's art style holds after its `Bb`. + pub(super) fn instance_head(&mut self, g: &GradientPaint, clip: bool, path: &BezPath) { + let Some(geom) = g.geom else { return }; + let name = self.define_gradient(&g.gradient, g.swatch.as_deref()); + let m = self.grad_space; + let radial = g.gradient.kind == GradientKind::Radial; + let place = placement(&geom, radial, &(self.canvas * path.clone()), self.canvas); + if radial { + let c = m * geom.start; + let off = geom.focal.map_or(Vec2::ZERO, |f| m * f - c); + let (angle, fraction) = if off.hypot() > 1e-9 { place.focal } else { (0.0, 0.0) }; + let off = if fraction > 0.0 { off } else { Vec2::ZERO }; + ps::push_nums(&mut self.body, &[off.x, off.y, angle, fraction]); + self.line("Bh"); + } + let _ = write!(self.body, "{} {} ", u8::from(!clip), ps::bytes(name.as_bytes())); + ps::push_nums(&mut self.body, &place.bg); + ps::push_nums(&mut self.body, &place.transform.as_coeffs()); + self.line("1 Bg"); + } + + /// A gradient definition: `%AI5_BeginGradient: (name)`, `(name) type stops Bd` (type 0 linear, + /// 1 radial), `[`, each stop on a `%_` line (`color style opacity 6 midpoint rampPoint Bs`), a + /// linear gradient's from the last to the first and a radial one's from the first to the last, + /// `BD`, `%AI5_EndGradient`. + fn gradient_def(&mut self, s: &mut String, d: &GradientDef) { + if d.gradient.dither || !d.gradient.method.is_classic() { + self.warn(GRADIENT_MIX); + } + let name = ps::bytes(d.name.as_bytes()); + let radial = d.gradient.kind == GradientKind::Radial; + let _ = writeln!(s, "%AI5_BeginGradient: {name}\n{name} {} {} Bd\n[", u8::from(radial), d.gradient.stops.len()); + let mut stops = sorted_stops(&d.gradient); + if !radial { + stops.reverse(); + } + for stop in stops { + s.push_str("%_"); + self.stop_color(s, stop); + ps::push_nums(s, &[f64::from(unit(stop.opacity)), 6.0, f64::from(stop.midpoint) * 100.0, f64::from(stop.offset) * 100.0]); + s.push_str("Bs\n"); + } + s.push_str("BD\n%AI5_EndGradient\n"); + } + + /// A stop's color and its style: gray `lightness 0`, CMYK `c m y k 1`, RGB (and Lab, as RGB) + /// `c m y k r g b 2` with its CMYK equivalent; a spot color its full color's CMYK equivalent, + /// then its RGB values when it isn't CMYK, its name and how much lighter than the full color, + /// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB). + fn stop_color(&mut self, s: &mut String, stop: &GradientStop) { + let doc = self.doc; + let intent = self.cms.settings().intent; + if let Some(name) = stop.swatch.as_deref().filter(|n| *n != REGISTRATION) + && let Some(sw) = doc.swatch(name) + && let Paint::Solid { color: full, swatch: None, .. } = sw.paint + { + if sw.spot { + let cmyk = self.cms.to_cmyk(&doc.linked_color(full, true), intent).map(unit); + ps::push_nums(s, &cmyk.map(f64::from)); + let rgb = !matches!(full, Color::Cmyk { .. }); + if rgb { + ps::push_nums(s, &full.to_rgb().map(|v| f64::from(unit(v)))); + } + s.push_str(&ps::bytes(name.as_bytes())); + s.push(' '); + ps::push_num(s, f64::from(1.0 - unit(stop.tint))); + s.push_str(if rgb { " 1 4 " } else { " 3 " }); + return; + } + if sw.global { + self.warn(STOP_LINKS); + } + } + match stop.color { + Color::Gray { k } => { + ps::push_num(s, f64::from(1.0 - unit(k))); + s.push_str(" 0 "); + } + Color::Cmyk { c, m, y, k } => { + ps::push_nums(s, &[c, m, y, k].map(|v| f64::from(unit(v)))); + s.push_str("1 "); + } + color @ (Color::Rgb { .. } | Color::Lab { .. }) => { + let cmyk = self.cms.to_cmyk(&color, intent).map(unit); + ps::push_nums(s, &cmyk.map(f64::from)); + ps::push_nums(s, &color.to_rgb().map(|v| f64::from(unit(v)))); + s.push_str("2 "); + } + } + } + + // ---------- patterns ---------- + + /// Can pattern `name` be written as a definition and painted with from here: the document has + /// it, its tiles make a grid, its art is within its tile and holds something, and it isn't used + /// in another pattern's tile or a symbol's art (the reader keeps no symbol whose art paints with + /// a pattern) or nested more than [`MAX_NEST`] deep? + pub(super) fn pattern_writable(&self, name: &str) -> bool { + if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol { + return false; + } + if self.patterns.iter().any(|p| p.name == name) { + return true; + } + self.doc.pattern(name).is_some_and(tile_holds_art) + } + + /// Write pattern `name`'s definition, once: `%AI3_BeginPattern: (name)`, `(name) llx lly urx + /// ury` (the tile, y up), the tile's box (an unpainted path whose dictionary marks it, + /// `AIPattern_Editor_Backing_Tile_Rect`) and the art on `%_` lines, `E`, `%AI3_EndPattern`. + /// False when it can't be ([`Self::pattern_writable`]). + fn define_pattern(&mut self, name: &str) -> bool { + if !self.pattern_writable(name) { + return false; + } + let used = !self.in_palette; + if let Some(p) = self.patterns.iter_mut().find(|p| p.name == name) { + p.used |= used; + return true; + } + let doc = self.doc; + let Some(def) = doc.pattern(name) else { return false }; + self.defining.push(name.to_string()); + // The art is written in the pattern's space, y up, from the state a definition starts in. + let saved = ( + std::mem::take(&mut self.body), + (self.to_art, self.grad_space, self.canvas), + self.state.take(), + self.gs.replace(Xy::OPAQUE), + self.clip.take(), + self.block_end, + ); + // `Bg` places a gradient in a pattern's tile as on the canvas, mirrored top to bottom: its + // placement is worked out in the tile's space turned y up. + (self.to_art, self.grad_space, self.canvas, self.block_end) = (Affine::FLIP_Y, self.tile_grad_space, Affine::FLIP_Y, usize::MAX); + // The tile's box first, unpainted and marked as the box: the tile is that box. + self.state(false, false); + self.line("0 XR"); + if let Some(sp) = vectorcraft_geom::shapes::rectangle(def.tile).subpaths.first() { + crate::ai_ops::subpath(&mut self.body, self.to_art, sp); + } + self.line("n\n%_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_"); + self.nest += 1; + self.hidden += 1; + // The tile's effects are its own, not those of a drawn look that first uses it. + let in_look = std::mem::take(&mut self.in_look); + for a in &def.art { + self.node(a); + } + self.in_look = in_look; + self.hidden -= 1; + self.nest -= 1; + let art; + (art, (self.to_art, self.grad_space, self.canvas), self.state, self.gs, self.clip, self.block_end) = saved; + let art = std::mem::replace(&mut self.body, art); + self.defining.pop(); + let tile = Affine::FLIP_Y.transform_rect_bbox(def.tile); + let quoted = ps::bytes(name.as_bytes()); + let mut text = format!("%AI3_BeginPattern: {quoted}\n{quoted} "); + ps::push_nums(&mut text, &[tile.x0, tile.y0, tile.x1, tile.y1]); + text.pop(); + text.push('\n'); + super::hide(&art, &mut text); + text.push_str("E\n%AI3_EndPattern\n"); + self.patterns.push(PatternOut { name: name.to_string(), text, used }); + true + } + + /// Set the fill (or with `stroke`, the stroke) to pattern `name` placed by `xf` (the pattern's + /// space → the document): `(name) 0 0 1 1 0 0 0 0 0 [matrix] p` (`P` for the stroke), the + /// matrix taking the pattern's space (y up, the tile's lower left corner its origin) to the + /// art's. A pattern that can't be defined paints mid gray. + pub(super) fn pattern_paint(&mut self, name: &str, xf: Affine, stroke: bool) { + let height = self.doc.pattern(name).map(|d| d.tile.height()); + let Some(h) = height.filter(|_| self.define_pattern(name)) else { + self.warn(super::PATTERNS); + return self.plain_color(Color::gray(0.5), stroke); + }; + let m = self.to_art * xf * Affine::translate((0.0, h)) * Affine::FLIP_Y; + let _ = writeln!(self.body, "{} 0 0 1 1 0 0 0 0 0 {} {}", ps::bytes(name.as_bytes()), ps::matrix(m), if stroke { 'P' } else { 'p' }); + } + + /// The definitions, in the setup before the palette: the gradients the art uses (`n Bn`, then + /// each), those only the palette uses between `%AI5_Begin_NonPrinting`, `Np` and + /// `%AI5_End_NonPrinting--`, then the patterns in the same way (a pattern after those its art + /// uses). + pub(in crate::ai_editing) fn definitions(&mut self, s: &mut String) { + let defs = std::mem::take(&mut self.gradients); + let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.iter().partition(|d| d.used); + let _ = writeln!(s, "{} Bn", used.len()); + for d in &used { + self.gradient_def(s, d); + } + if !unused.is_empty() { + let _ = writeln!(s, "%AI5_Begin_NonPrinting\nNp\n{} Bn", unused.len()); + for d in &unused { + self.gradient_def(s, d); + } + s.push_str("%AI5_End_NonPrinting--\n"); + } + self.gradients = defs; + for p in self.patterns.iter().filter(|p| p.used) { + s.push_str(&p.text); + } + if self.patterns.iter().any(|p| !p.used) { + s.push_str("%AI5_Begin_NonPrinting\nNp\n"); + for p in self.patterns.iter().filter(|p| !p.used) { + s.push_str(&p.text); + } + s.push_str("%AI5_End_NonPrinting--\n"); + } + } + + /// A gradient swatch's or pattern swatch's paint in the palette: `Bb`, a radial gradient's + /// `0 0 0 0 Bh`, `2 (name) 0 0 0 1 1 0 0 1 0 0 1 Bg`, `0 BB`; a pattern's + /// `(name) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p`. False for other paint, and for paint that can't + /// be written. + pub(super) fn swatch_paint(&mut self, s: &mut String, sw: &vectorcraft_color::swatch::Swatch) -> bool { + match &sw.paint { + Paint::Gradient(g) if writable_gradient(&g.gradient) => { + let swatch = Some(sw.name.as_str()); + let name = self.define_gradient(&g.gradient, swatch); + s.push_str("Bb\n"); + if g.gradient.kind == GradientKind::Radial { + s.push_str("0 0 0 0 Bh\n"); + } + let _ = writeln!(s, "2 {} 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB", ps::bytes(name.as_bytes())); + true + } + Paint::Pattern { pattern, xf } if self.define_pattern(pattern) => { + if *xf != Affine::IDENTITY { + self.warn(SWATCH_PLACEMENT); + } + let _ = writeln!(s, "{} 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p", ps::bytes(pattern.as_bytes())); + true + } + _ => false, + } + } +} + +/// Where `Bg` places a gradient: its `x y angle length` operands, its matrix, and a radial +/// gradient's focal point as `Bh`'s angle and fraction ([`placement`]). +struct Placement { + bg: [f64; 4], + transform: Affine, + focal: (f64, f64), +} + +impl Placement { + /// The gradient's place on the path before it is moved: `0 0 0 1`, the identity. + const UNMOVED: Placement = Placement { bg: [0.0, 0.0, 0.0, 1.0], transform: Affine::IDENTITY, focal: (0.0, 0.0) }; +} + +/// The `Bg` operands that place gradient `geom` (`radial` or linear) on `path`, both in the canvas's +/// space (y down; `canvas` takes the document there; in a pattern's tile, the tile's space turned y +/// up). `Bg` places a gradient in the space its matrix takes to the canvas's, on the path as it lies +/// there: +/// +/// - a linear one's ramp runs at `angle` degrees (counterclockwise, y up) from `x` times the path's +/// extent along that angle past where the path starts along it, `length` times that extent long +/// (`y` doesn't move it); +/// - a radial one's center lies `x` times the width and `y` times the height (y down) of the path's +/// bounds from their center, and its radius is `length` times √((dx² + dy²) / 2), `dx` and `dy` the +/// center's distances to the right side and to the bottom of the bounds, whether or not those are +/// the nearer sides; its focal point lies at `Bh`'s angle (y up), its distance from the center a +/// fraction of the radius. +/// +/// A linear gradient is written with the identity, a radial one with the matrix that takes the +/// unit circle onto its extent ellipse at the origin (so that its circle there is the unit circle). +/// [`Placement::UNMOVED`] when the path has no extent along the gradient or the gradient has none. +fn placement(geom: &GradientGeom, radial: bool, path: &BezPath, canvas: Affine) -> Placement { + let s = canvas * geom.start; + let u = canvas * geom.end - s; + if !radial { + let turn = Affine::rotate(-u.atan2()); + let along = (turn * path.clone()).bounding_box(); + let extent = along.width(); + if !(extent > 1e-9 && extent.is_finite() && u.hypot() > 1e-9) { + return Placement::UNMOVED; + } + let bg = [((turn * s).x - along.x0) / extent, 0.0, (-u.y).atan2(u.x).to_degrees(), u.hypot() / extent]; + return Placement { bg, ..Placement::UNMOVED }; + } + // The unit circle's image: `u` along the vector, `v` across it (the aspect ratio), turning the same way. + let across = geom.end - geom.start; + let mut v = canvas * (geom.start + Vec2::new(-across.y, across.x) * geom.aspect) - s; + if u.cross(v) < 0.0 { + v = -v; + } + let m = Affine::new([u.x, u.y, v.x, v.y, 0.0, 0.0]); + let det = m.determinant().abs(); + if det.is_nan() || det <= 1e-12 { + return Placement::UNMOVED; + } + let back = m.inverse(); + let b = (back * path.clone()).bounding_box(); + let c = back * s; + let (dx, dy) = (b.x1 - c.x, b.y1 - c.y); + let unit = ((dx * dx + dy * dy) / 2.0).sqrt(); + if !(b.width() > 1e-9 && b.height() > 1e-9 && unit > 1e-9 && unit.is_finite()) { + return Placement::UNMOVED; + } + let off = geom.focal.map_or(Vec2::ZERO, |f| back * (canvas * f) - c); + let focal = if off.hypot() > 1e-9 { ((-off.y).atan2(off.x).to_degrees(), off.hypot()) } else { (0.0, 0.0) }; + let bg = [(c.x - b.center().x) / b.width(), (c.y - b.center().y) / b.height(), 0.0, 1.0 / unit]; + Placement { bg, transform: m, focal } +} + +/// Do `def`'s tiles make a grid, with its art (something) within the tile? Art past the tile would +/// be cut off at the tile's edge. +fn tile_holds_art(def: &PatternDef) -> bool { + let t = def.tile; + let tile_ok = [t.x0, t.y0, t.x1, t.y1].iter().all(|v| v.is_finite()) && t.width() > 0.0 && t.height() > 0.0; + tile_ok + && def.tile_type == TileType::Grid + && def.art_bounds().is_some_and(|b| { + let room = t.inflate(1e-6, 1e-6); + b.x0 >= room.x0 && b.y0 >= room.y0 && b.x1 <= room.x1 && b.y1 <= room.y1 + }) +} diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs new file mode 100644 index 0000000000..1f10bb4c86 --- /dev/null +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -0,0 +1,905 @@ +//! Art styles: objects whose appearance a plain path can't hold, written as their drawn look, the +//! object itself on `%_` lines and `1 (style) XW`; the styles they name and the Graphic Styles +//! panel's styles in `%AI9_BeginArtStyles`, and the panel's order in `%AI9_BeginArtStyleList` (see +//! [`crate::ai_editing`] for the form). Each style is read back before it is written +//! ([`crate::import::read_art_style`]: the `.ai` reader's style parser and its reading of a graphic +//! style, with the object's own gradient): one that reads back differently is not written, and the +//! object is written as its drawn look alone. + +use std::collections::{HashMap, HashSet}; +use std::fmt::Write; +use std::sync::Arc; + +use serde_json::Value; +use vectorcraft_color::{BlendMode, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, GraphicStyle, Knockout, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_geom::{BezPath, FillRule, Rect, Shape}; + +use super::{Writer, Xy, blend_code, compound_path, hide}; +use crate::ai_ops; +use crate::ps; + +pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str = "on a large canvas, no art styles or graphic styles are written: objects with live effects are written with their geometry effects applied to the artwork, where they can no longer be edited, and their other effects are left out of the editing data for other apps"; +pub(in crate::ai_editing) const PANEL_STYLES: &str = "graphic styles with gradient or pattern fills, with fills, strokes or effects the editing data can't hold as a graphic style, with a name another style has, with names over 1,024 bytes, or past 4,096 styles, are left out of the editing data for other apps"; +pub(in crate::ai_editing) const PANEL_EMPTY: &str = + "a Graphic Styles panel with no style written opens from the editing data with a new document's styles"; +pub(in crate::ai_editing) const STYLE_LINKS: &str = "links to graphic styles are left out of the editing data for other apps on type, images, symbol instances, knockout shapes and other objects that aren't written with their graphic style"; + +/// How many objects of `doc`'s layers, opacity masks and symbols are linked to a graphic style. +pub(in crate::ai_editing) fn style_links(doc: &Document) -> usize { + fn count(n: &Node) -> usize { + let own = usize::from(n.extras().graphic_style.is_some()); + let mask = n.extras().mask.as_ref().map_or(0, |m| count(&m.art)); + own + mask + n.children().map_or(0, |c| c.iter().map(|m| count(m)).sum()) + } + doc.layers.iter().map(|l| count(l)).sum::() + doc.symbols.iter().map(|s| count(&s.art)).sum::() +} + +/// The objects of `doc`'s layers that may be written with an art style ([`Writer::styled_object`]), +/// by id: paths and compound paths with points and groups, with live effects or linked to a graphic +/// style, without Opacity & Mask Define Knockout Shape (the reader takes an object's transparency +/// from its look, which doesn't carry it). A group's members are paths, compound paths or such +/// groups, none with effects or anything baking changes. +pub(in crate::ai_editing) fn styled_objects(doc: &Document) -> HashMap> { + fn walk(nodes: &[Arc], out: &mut HashMap>) { + for n in nodes { + if candidate(n) { + out.insert(n.id, n.clone()); + } + // A group's members are written with a style of their own only when the group is written + // without one. Baking a container with effects of its own changes its members, which + // keep their ids: they are written as baking left them. + if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &n.kind + && !bakes_members(n) + { + walk(children, out); + } + } + } + let mut out = HashMap::new(); + walk(&doc.layers, &mut out); + out +} + +/// Does container `n` need baking for what it has itself, whatever its members hold? +fn bakes_members(n: &Node) -> bool { + let mut own = n.clone(); + if let Some(children) = own.children_mut() { + children.clear(); + } + vectorcraft_effects::needs_bake(&own) +} + +/// Whether `n` may be written with an art style ([`styled_objects`]). +fn candidate(n: &Node) -> bool { + let styled = !n.appearance.effects.is_empty() || n.extras().graphic_style.is_some(); + if !styled || n.knockout_shape { + return false; + } + match &n.kind { + NodeKind::Path { path, guide: false, clipping: false, .. } => has_points(path), + NodeKind::Compound { .. } => has_points(&compound_path(n)), + NodeKind::Group { children, clip: false } => !n.is_compound_shape() && children.iter().all(|c| plain_member(c)), + _ => false, + } +} + +/// Does `path` write anything ([`Writer::plain_object`] skips subpaths without points)? +fn has_points(path: &vectorcraft_geom::PathData) -> bool { + path.subpaths.iter().any(|sp| !sp.anchors.is_empty()) +} + +/// A member of a group written with an art style: written as it is, and read back as it is. +fn plain_member(n: &Node) -> bool { + let quiet = n.appearance.effects.is_empty() && n.appearance.items.iter().all(|i| i.effects().is_empty()) && !vectorcraft_effects::needs_bake(n); + quiet + && match &n.kind { + NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => true, + NodeKind::Group { children, .. } => children.iter().all(|c| plain_member(c)), + _ => false, + } +} + +/// The art styles written: the Graphic Styles panel's (listed, in its order) and those objects +/// name, each with its text after its name (`/ActiveStyle :` to `/Def ;`). +#[derive(Default)] +pub(in crate::ai_editing) struct Styles { + /// Every style, in the order written: its name and text. + known: Vec<(String, String)>, + /// The panel's styles written, by the graphic style's id. + panel: HashMap, + /// The panel's styles written, in its order. + listed: Vec, + /// The names styles have, and the name of each object style by its text. + names: HashSet, + by_text: HashMap, + next_anon: u64, + /// How many objects were written with the graphic style they are linked to. + pub(super) links_written: usize, +} + +impl Styles { + /// The name of an object style of `text`: a style with the same text already written, else a + /// new one named `Anon` and a number no other style has. + fn object_style(&mut self, text: String) -> String { + if let Some(name) = self.by_text.get(&text) { + return name.clone(); + } + let name = loop { + self.next_anon += 1; + let name = format!("Anon {}", self.next_anon); + if !self.names.contains(&name) { + break name; + } + }; + self.names.insert(name.clone()); + self.by_text.insert(text.clone(), name.clone()); + self.known.push((name.clone(), text)); + name + } +} + +/// One style as the reader's section holds it: `/KnownStyle :`, `(name) /Name ,`, its text. +fn known_style(name: &str, text: &str) -> String { + format!("/KnownStyle :\n{} /Name ,\n{text}", ps::bytes(name.as_bytes())) +} + +/// The number transparency's `Xy` gives the blending mode a live effect's `mode` names (any case, +/// spaces and dashes ignored). +fn mode_code(mode: &str) -> Option { + let key: String = mode.chars().filter(char::is_ascii_alphanumeric).collect::().to_ascii_lowercase(); + BlendMode::ALL.iter().find(|m| format!("{m:?}").to_ascii_lowercase() == key).map(|m| blend_code(*m)) +} + +/// A filter's `Xy` line: `mode opacity isolate knockout shape Xy`. +fn xy_line(s: &mut String, xy: Xy) { + let knockout = match xy.knockout { + Knockout::Off => 0, + Knockout::On => 1, + Knockout::Neutral => 2, + }; + let _ = write!(s, "{} ", blend_code(xy.blend)); + ps::push_num(s, f64::from(xy.opacity)); + let _ = writeln!(s, " {} {knockout} {} Xy", u8::from(xy.isolate), u8::from(xy.shape)); +} + +/// The line style of a paint style that isn't a stroke's. +const NO_LINE: &str = "0 J 0 j 1 w 10 M []0 d\n"; + +/// A basic filter's start: its name and kind numbers (`1 0` for an effect, `0 0` for the +/// style's own filters), `/Visible` and the dictionary's start. +fn basic(s: &mut String, name: &str, effect: bool, visible: bool) { + let _ = write!(s, "/BasicFilter :\n{} {} 0 /Filter ,\n{} /Visible ,\n", ps::bytes(name.as_bytes()), u8::from(effect), u8::from(visible)); +} + +/// The filter that stands for the object's contents in its stack. +const CONDUIT: &str = "/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n"; + +/// A basic filter's end. +const END_BASIC: &str = "; /Dict ;\n /Part ,\n"; + +/// The blend filter of transparency `xy`. +fn blend_filter(s: &mut String, xy: Xy) { + basic(s, "Blend Style Filter", false, true); + s.push_str("/Dictionary : /NotRecorded ,\n/BlendStyle : "); + xy_line(s, xy); + s.push_str(NO_LINE); + s.push_str("0 XR\n/Def ; \n (BlendStyle) ,\n"); + s.push_str(END_BASIC); +} + +/// A live effect's dictionary entries. +#[derive(Default)] +struct Entries(String); + +impl Entries { + fn real(&mut self, key: &str, v: f64) { + ps::push_num(&mut self.0, v); + let _ = writeln!(self.0, " /Real {} ,", ps::bytes(key.as_bytes())); + } + + fn int(&mut self, key: &str, v: i64) { + let _ = writeln!(self.0, "{v} /Int {} ,", ps::bytes(key.as_bytes())); + } + + fn bool(&mut self, key: &str, v: bool) { + let _ = writeln!(self.0, "{} /Bool {} ,", u8::from(v), ps::bytes(key.as_bytes())); + } +} + +/// `p`'s entry `key` as a number. +fn num(p: &Value, key: &str) -> Option { + p.get(key)?.as_f64().filter(|v| v.is_finite()) +} + +/// `p`'s entry `key` as text, for comparing: lower case, letters and digits only. +fn word(p: &Value, key: &str) -> Option { + Some(p.get(key)?.as_str()?.chars().filter(char::is_ascii_alphanumeric).collect::().to_ascii_lowercase()) +} + +/// `p`'s entry `key` as a switch. +fn flag(p: &Value, key: &str) -> Option { + p.get(key)?.as_bool() +} + +impl Writer<'_> { + /// What `paint` writes with [`Self::color`] (a color, a spot or global color), as a string. + fn color_ops(&mut self, paint: &Paint, stroke: bool) -> String { + let saved = std::mem::take(&mut self.body); + self.color(paint, stroke); + std::mem::replace(&mut self.body, saved) + } + + /// A fill style holding a color, as an effect's entry `key` or a fill's own. + fn fill_style(&mut self, s: &mut String, color: vectorcraft_color::Color, key: &str) { + let ops = self.color_ops(&Paint::solid(color), false); + let _ = write!(s, "/FillStyle : 0 O\n{ops}0 1 0 0 0 Xy\n{NO_LINE}0 XR\n0 1 Xd\n/Def ; \n {} ,\n", ps::bytes(key.as_bytes())); + } + + /// A fill's basic filter: a color, or a gradient placed on the object's outline (`on`: the + /// object's own outline and rule), filling by the non-zero rule. `None` for other paint. + fn fill_filter(&mut self, s: &mut String, f: &FillLayer, visible: bool, on: Option<(&BezPath, FillRule)>) -> Option<()> { + if f.overprint { + return None; + } + // A color comes before the paint state, a gradient's instance after it. + let (color, gradient) = match &f.paint { + Paint::Solid { .. } => (self.color_ops(&f.paint, false), String::new()), + Paint::Gradient(_) => { + let (path, _) = on?; + let Paint::Gradient(placed) = self.placed(&f.paint, path.bounding_box()) else { return None }; + (String::new(), format!("Bb\n{}0 BB\n", self.gradient_bg(&placed, path)?)) + } + Paint::Pattern { .. } | Paint::None => return None, + }; + basic(s, "Fill Style Filter", false, visible); + let _ = write!( + s, + "/Dictionary : /NotRecorded ,\n0 /Bool (UseEvenOdd) ,\n/FillStyle : 0 O\n{color}0 1 0 0 0 Xy\n{NO_LINE}0 XR\n0 1 Xd\n{gradient}" + ); + s.push_str("/Def ; \n (FillStyle) ,\n"); + s.push_str(END_BASIC); + Some(()) + } + + /// A stroke's basic filter: a color, its line style, and its width profile as the arrays + /// `BSVariableWidthTValuesArray`, `BSLeftWidthsArray` and `BSRightWidthsArray`. `None` for + /// other paint. + fn stroke_filter(&mut self, s: &mut String, st: &StrokeLayer, visible: bool) -> Option<()> { + if !matches!(st.paint, Paint::Solid { .. }) || st.overprint { + return None; + } + let ops = self.color_ops(&st.paint, true); + basic(s, "Stroke Style Filter", false, visible); + s.push_str("2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 R\n"); + s.push_str(&ops); + s.push_str("0 1 0 0 0 Xy\n"); + ai_ops::line_style(s, st); + s.push_str("0 XR\n1 0 Xd\n/Def ; \n (StrokeStyle) ,\n"); + if let Some(p) = &st.profile { + let array = |s: &mut String, key: &str, values: &mut dyn Iterator| { + s.push_str("/Array :"); + for v in values { + s.push(' '); + ps::push_num(s, v); + s.push_str(" /Real ,"); + } + let _ = writeln!(s, " ; {} ,", ps::bytes(key.as_bytes())); + }; + array(s, "BSVariableWidthTValuesArray", &mut p.points.iter().map(|q| q.0)); + array(s, "BSLeftWidthsArray", &mut p.points.iter().map(|q| q.1)); + array(s, "BSRightWidthsArray", &mut p.points.iter().map(|q| q.2)); + } + s.push_str(END_BASIC); + Some(()) + } + + /// A gradient instance's focal point (`Bh`, radial gradients only) and its `flag (name) x y + /// angle length a b c d tx ty 1 Bg` line for placed gradient `g` on `path`, as a fill's style + /// holds them ([`Self::instance_head`]). + fn gradient_bg(&mut self, g: &vectorcraft_color::GradientPaint, path: &BezPath) -> Option { + let saved = std::mem::take(&mut self.body); + self.instance_head(g, false, path); + let line = std::mem::replace(&mut self.body, saved); + (!line.is_empty()).then_some(line) + } + + /// An appearance item's filter: its basic filter, or a chain of it, its effects and its + /// transparency. + fn item_filter(&mut self, s: &mut String, item: &AppearanceItem, on: Option<(&BezPath, FillRule)>) -> Option<()> { + let plain = item.opacity() >= 1.0 && item.blend() == BlendMode::Normal && item.effects().is_empty(); + let mut basic_text = String::new(); + // In a chain, the chain holds the item's visibility. + let visible = item.visible() || !plain; + match item { + AppearanceItem::Fill(f) => self.fill_filter(&mut basic_text, f, visible, on)?, + AppearanceItem::Stroke(st) => self.stroke_filter(&mut basic_text, st, visible)?, + } + if plain { + s.push_str(&basic_text); + return Some(()); + } + let _ = write!(s, "/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n{} /Visible ,\n", u8::from(item.visible())); + s.push_str(&basic_text); + for e in item.effects() { + s.push_str(&self.effect_filter(e)?); + } + let opacity = if item.opacity().is_finite() { item.opacity().clamp(0.0, 1.0) } else { 1.0 }; + blend_filter(s, Xy { blend: item.blend(), opacity, ..Xy::OPAQUE }); + s.push_str(";\n /Part ,\n"); + Some(()) + } + + /// The text of a style of appearance `ap` and transparency `xy` (after its name): the chain + /// of its stack (the fills and strokes that paint, the top one first, the contents among them + /// where the appearance puts them), its effects and its blend filter. A gradient fill is + /// placed on the outline of `on`, and a fill fills by its rule (`None`: the non-zero rule, on no + /// object). `None` when a fill, stroke or effect isn't one written here. + pub(super) fn style_text(&mut self, ap: &Appearance, xy: Xy, on: Option<(&BezPath, FillRule)>) -> Option { + let mut s = String::from( + "/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n", + ); + let ci = ap.contents_index.unwrap_or(0).min(ap.items.len()); + let painting: Vec<(usize, &AppearanceItem)> = ap.items.iter().enumerate().filter(|(_, i)| !i.paint().is_none()).collect(); + let below = painting.iter().filter(|(at, _)| *at < ci).count(); + // Listed top first: the contents go above the `below` fills and strokes under them. + for (written, (_, item)) in painting.iter().rev().enumerate() { + if painting.len() - written == below { + s.push_str(CONDUIT); + } + self.item_filter(&mut s, item, on)?; + } + if below == 0 { + s.push_str(CONDUIT); + } + s.push_str(";\n /Part ,\n"); + for e in &ap.effects { + s.push_str(&self.effect_filter(e)?); + } + blend_filter(&mut s, xy); + s.push_str(";\n\n/Execution ;\n /Def ;\n"); + Some(s) + } + + /// A live effect's basic filter, with the settings the reader reads + /// ([`crate::import`]'s `.ai` reader, `style.rs`), in the units it reads them in. `None` for an + /// effect, or a setting, that isn't written here. + fn effect_filter(&mut self, e: &Effect) -> Option { + let p = vectorcraft_effects::merged_params(&e.id, &e.params); + let mut d = Entries::default(); + let id = e.id.as_str(); + let name = if id.starts_with("stylize.") { + self.stylize_entries(id, &p, &mut d)? + } else if id.starts_with("warp.") || id.starts_with("distort.") || id.starts_with("blur.") { + Self::distort_entries(id, &p, &mut d)? + } else { + Self::path_entries(id, &p, &mut d)? + }; + let mut s = String::new(); + basic(&mut s, name, true, e.visible); + s.push_str("/Dictionary : /NotRecorded ,\n"); + s.push_str(&d.0); + s.push_str(END_BASIC); + Some(s) + } + + /// A Stylize effect's entries ([`Self::effect_filter`]) and its filter's name. + fn stylize_entries(&mut self, id: &str, p: &Value, d: &mut Entries) -> Option<&'static str> { + Some(match id { + "stylize.dropShadow" => { + d.int("blnd", i64::from(mode_code(p.get("mode")?.as_str()?)?)); + d.real("opac", num(p, "opacity")? / 100.0); + let darkness = word(p, "shade").as_deref() == Some("darkness"); + if darkness { + d.real("dark", num(p, "darkness")?); + } + d.real("vert", num(p, "y")?); + d.real("horz", num(p, "x")?); + d.real("blur", num(p, "blur")? / 2.0); + let color = vectorcraft_effects::color_param(p, vectorcraft_color::Color::BLACK); + self.fill_style(&mut d.0, color, "sclr"); + d.int("csrc", i64::from(darkness)); + "Adobe Drop Shadow" // brand-ok: the filter's name in the files + } + "stylize.innerGlow" => { + d.int("blnd", i64::from(mode_code(p.get("mode")?.as_str()?)?)); + d.real("opac", num(p, "opacity")? / 100.0); + d.real("blur", num(p, "blur")?); + let color = vectorcraft_effects::color_param(p, vectorcraft_color::Color::WHITE); + self.fill_style(&mut d.0, color, "gclr"); + d.int("gtyp", i64::from(word(p, "source").as_deref() == Some("edge"))); + "Adobe Inner Glow" // brand-ok: the filter's name in the files + } + "stylize.outerGlow" => { + d.int("blnd", i64::from(mode_code(p.get("mode")?.as_str()?)?)); + d.real("opac", num(p, "opacity")? / 100.0); + d.real("blur", num(p, "blur")? / 2.0); + let color = vectorcraft_effects::color_param(p, vectorcraft_color::Color::BLACK); + self.fill_style(&mut d.0, color, "sclr"); + "Adobe Outer Glow" // brand-ok: the filter's name in the files + } + "stylize.feather" => { + d.real("Radius", num(p, "radius")?); + "Adobe Fuzzy Mask" // brand-ok: the filter's name in the files + } + "stylize.roundCorners" => { + d.real("radius", num(p, "radius")?); + "Adobe Round Corners" // brand-ok: the filter's name in the files + } + "stylize.scribble" => { + d.real("Angle", num(p, "angle")?); + d.real("EdgeOverlap", num(p, "overlap")?); + d.real("EdgeOverlapVariation", num(p, "overlapVariation")?); + d.real("StrokeWidth", num(p, "strokeWidth")?); + d.real("Scribbliness", num(p, "curviness")? / 100.0); + d.real("ScribbleVariation", num(p, "curvinessVariation")? / 100.0); + d.real("Spacing", num(p, "spacing")?); + d.real("SpacingVariation", num(p, "spacingVariation")?); + "Adobe Scribble Fill" // brand-ok: the filter's name in the files + } + _ => return None, + }) + } + + /// Convert to Shape's, a Path effect's or Pathfinder › Add's entries ([`Self::effect_filter`]) + /// and its filter's name. + fn path_entries(id: &str, p: &Value, d: &mut Entries) -> Option<&'static str> { + Some(match id { + "convertToShape.rectangle" | "convertToShape.roundedRectangle" | "convertToShape.ellipse" => { + let shape = match id { + "convertToShape.rectangle" => 0, + "convertToShape.roundedRectangle" => 1, + _ => 2, + }; + let relative = flag(p, "relative")?; + d.int("Shape", shape); + d.real("Absolute", if relative { 0.0 } else { 1.0 }); + d.real("AbsWidth", num(p, "width")?); + d.real("AbsHeight", num(p, "height")?); + d.real("RelWidth", num(p, "extraW")? / 2.0); + d.real("RelHeight", num(p, "extraH")? / 2.0); + if shape == 1 { + d.real("CornerRadius", num(p, "radius")?); + } + "Adobe Shape Effects" // brand-ok: the filter's name in the files + } + "path.offsetPath" => { + d.real("ofst", num(p, "offset")?); + let joins = match word(p, "joins")?.as_str() { + "round" => 0, + "bevel" => 1, + "miter" => 2, + _ => return None, + }; + d.int("jntp", joins); + d.real("mlim", num(p, "miterLimit")?); + "Adobe Offset Path" // brand-ok: the filter's name in the files + } + "path.outlineObject" => "Adobe Outline Type", // brand-ok: the filter's name in the files + "path.outlineStroke" => "Adobe Outline Stroke", // brand-ok: the filter's name in the files + "pathfinder.add" => { + d.int("Command", 0); + d.bool("ConvertCustom", true); + d.bool("ExtractUnpainted", true); + d.real("Mix", 0.5); + d.real("Precision", 10.0); + d.bool("RemovePoints", false); + d.real("TrapAspect", 1.0); + d.bool("TrapConvertCustom", false); + d.real("TrapMaxTint", 1.0); + d.bool("TrapReverse", false); + d.real("TrapThickness", 0.25); + d.real("TrapTint", 0.4); + d.real("TrapTintTolerance", 0.05); + "Adobe Pathfinder" // brand-ok: the filter's name in the files + } + _ => return None, + }) + } + + /// A Warp, Distort & Transform or Gaussian Blur effect's entries ([`Self::effect_filter`]) and + /// its filter's name. + fn distort_entries(id: &str, p: &Value, d: &mut Entries) -> Option<&'static str> { + Some(match id { + id if id.starts_with("warp.") => { + let style = crate::import::warp_number(id.strip_prefix("warp.")?)?; + d.int("DeformStyle", style); + d.real("DeformValue", num(p, "bend")? / 100.0); + d.real("DeformHoriz", num(p, "horizontal")? / 100.0); + d.real("DeformVert", num(p, "vertical")? / 100.0); + d.bool("Rotate", word(p, "orientation").as_deref() == Some("vertical")); + "Adobe Deform" // brand-ok: the filter's name in the files + } + "distort.transform" => { + d.real("scaleH_Factor", num(p, "scaleH")? / 100.0); + d.real("scaleV_Factor", num(p, "scaleV")? / 100.0); + d.real("moveH_Pts", num(p, "moveH")?); + // Art space has y up. + d.real("moveV_Pts", 0.0 - num(p, "moveV")?); + d.real("rotate_Radians", num(p, "rotate")?.to_radians()); + d.int("numCopies", num(p, "copies")? as i64); + d.int("pinPoint", num(p, "reference")? as i64); + d.bool("reflectX", flag(p, "reflectX")?); + d.bool("reflectY", flag(p, "reflectY")?); + d.bool("transformObjects", flag(p, "objects")?); + d.bool("scaleLines", flag(p, "strokes")?); + d.bool("transformPatterns", flag(p, "patterns")?); + d.bool("randomize", false); + "Adobe Transform" // brand-ok: the filter's name in the files + } + "distort.freeDistort" => { + let corners = p.get("corners")?.as_array()?; + let corner = |i: usize| -> Option<(f64, f64)> { + let c = corners.get(i)?.as_array()?; + Some((c.first()?.as_f64()?, c.get(1)?.as_f64()?)) + }; + // The source frame is the unit square (y up); destination corners 0, 1, 3, 2 are + // the catalog's top left, top right, bottom right, bottom left (y down). + for (i, (h, v)) in [(0.0, 1.0), (1.0, 1.0), (0.0, 0.0), (1.0, 0.0)].into_iter().enumerate() { + d.real(&format!("src{i}h"), h); + d.real(&format!("src{i}v"), v); + } + for (i, from) in [0, 1, 3, 2].into_iter().enumerate() { + let (x, y) = corner(from)?; + d.real(&format!("dst{i}h"), x); + d.real(&format!("dst{i}v"), 1.0 - y); + } + "Adobe Free Distort" // brand-ok: the filter's name in the files + } + "distort.puckerBloat" => { + d.real("d_factor", num(p, "amount")?); + "Adobe Punk and Bloat" // brand-ok: the filter's name in the files + } + "distort.twist" => { + d.real("angle", num(p, "angle")?); + "Adobe Twirl" // brand-ok: the filter's name in the files + } + "distort.zigZag" => { + let relative = flag(p, "relative")?; + d.real("absoluteness", if relative { 0.0 } else { 1.0 }); + d.real(if relative { "relAmount" } else { "amount" }, num(p, "size")?); + d.real("ridges", num(p, "ridges")?); + d.real("roundness", if word(p, "points").as_deref() == Some("smooth") { 1.0 } else { 0.0 }); + "Adobe Zigzag" // brand-ok: the filter's name in the files + } + "blur.gaussian" => { + d.real("blur", num(p, "radius")?); + "Adobe PSL Gaussian Blur" // brand-ok: the filter's name in the files + } + _ => return None, + }) + } + + /// The Graphic Styles panel's styles that the reader reads as they are: each checked, and + /// the others left out with a warning. Their names are taken before the art's styles are. + pub(in crate::ai_editing) fn panel_styles(&mut self) { + let doc = self.doc; + // A new document's styles are what the reader gives a file without a style list; they are + // still written when an object is linked to one of them, so that it keeps its link. + let linked = self.styled.values().any(|n| n.extras().graphic_style.is_some()); + if !linked && doc.graphic_styles == Document::new(1.0, 1.0).graphic_styles { + return; + } + for g in doc.graphic_styles.iter() { + self.styles.names.insert(g.name.clone()); + } + let mut readable: Vec<(&GraphicStyle, String)> = vec![]; + let mut seen: HashSet<&str> = HashSet::new(); + for g in doc.graphic_styles.iter() { + if readable.len() >= crate::import::MAX_LISTED || g.name.len() > crate::import::MAX_LISTED_NAME || seen.contains(g.name.as_str()) { + self.warn(PANEL_STYLES); + continue; + } + let xy = Xy { blend: g.blend, opacity: g.opacity.clamp(0.0, 1.0), isolate: g.isolate, knockout: g.knockout, shape: false }; + let text = self.style_text(&g.appearance, xy, None).filter(|t| panel_reads(g, t)); + let Some(text) = text else { + self.warn(PANEL_STYLES); + continue; + }; + seen.insert(g.name.as_str()); + readable.push((g, text)); + } + // The list as the reader reads it: names too long, and styles past its count, aren't. + let list: String = readable.iter().map(|(g, _)| ps::bytes(g.name.as_bytes()) + "\n").collect(); + let listed: HashSet = crate::import::read_style_list(list.as_bytes()).into_iter().collect(); + for (g, text) in readable { + if !listed.contains(&g.name) { + self.warn(PANEL_STYLES); + continue; + } + if g.id != 0 { + self.styles.panel.insert(g.id, g.name.clone()); + } + self.styles.listed.push(g.name.clone()); + self.styles.known.push((g.name.clone(), text)); + } + // The reader gives a file without a style list a new document's styles. + if self.styles.listed.is_empty() { + self.warn(PANEL_EMPTY); + } + } + + /// Warn when fewer objects were written with their graphic style than `links` are linked to one. + pub(in crate::ai_editing) fn lost_links(&mut self, links: usize) { + if self.styles.links_written < links { + self.warn(STYLE_LINKS); + } + } + + /// The style object `orig` (`n` before baking) is written with: the graphic style it is linked + /// to when it has that style's appearance and transparency and the panel's style is written, + /// else a style of its own; `None` when the reader wouldn't read the object as it is with + /// either. A gradient fill is placed on `n`'s outline, as the object draws it. A style of its own + /// that isn't written leaves no gradient definition or warning behind. + pub(super) fn object_style(&mut self, n: &Node, orig: &Node) -> Option { + if let NodeKind::Group { children, .. } = &orig.kind + && bakes_members(orig) + && !children.iter().all(|c| self.member_keeps_outline(c)) + { + return None; + } + let doc = self.doc; + if let Some(id) = orig.extras().graphic_style + && let Some(name) = self.styles.panel.get(&id).cloned() + && let Some(g) = doc.graphic_style_by_id(id) + && g.transparency_matches(orig) + && g.appearance_on(orig).approx_eq(&orig.appearance) + && let Some(text) = self.styles.known.iter().find(|(n, _)| *n == name).map(|(_, t)| t.clone()) + && object_reads(orig, &text) + { + self.styles.links_written += 1; + return Some(name); + } + if orig.appearance.effects.is_empty() || !own_style_holds(&orig.appearance) { + return None; + } + let graded = orig.appearance.items.iter().any(|i| matches!(i.paint(), Paint::Gradient(_))); + let saved = (graded.then(|| self.gradient_mark()), self.warnings.len()); + let path = drawn_outline(n, orig); + let rule = object_rule(orig); + let text = self.style_text(&orig.appearance, Xy::of(orig), path.as_ref().map(|p| (p, rule))).filter(|t| object_reads(orig, t)); + let Some(text) = text else { + if let Some(mark) = saved.0 { + self.gradient_rollback(mark); + } + self.warnings.truncate(saved.1); + return None; + }; + Some(self.styles.object_style(text)) + } + + /// Is member `m` of a styled group whose effects change its members' outlines (and each of its + /// own members) written on the outline those effects draw on: every fill and stroke as the + /// object paints it ([`Self::direct`], [`Self::direct_stroke`]), not as filled outlines, brush + /// art or pattern tiles, and no gradient that fits its object, which the effects would fit to + /// the new outline? + fn member_keeps_outline(&self, m: &Node) -> bool { + let items_keep = m.appearance.items.iter().all(|i| match i { + AppearanceItem::Fill(f) => f.paint.is_none() || self.direct(&f.paint), + AppearanceItem::Stroke(s) => s.paint.is_none() || self.direct_stroke(s), + }); + items_keep && m.children().is_none_or(|c| c.iter().all(|c| self.member_keeps_outline(c))) + } + + /// Object `n` (as baking left it; `orig` before baking) with the style `name`: its lock and + /// hidden state; its drawn look (a group of its vector art as baking left it, without shadows, + /// glows or feathers, the object's transparency + /// after the group's end, `0 0 Xd`, `6 () XW`); the object itself on `%_` lines (a path's or + /// compound path's points painted with nothing, or with its gradient fill when its style has + /// one; a group with its members), its name and opacity mask; then `1 (name) XW`. + pub(super) fn styled_object(&mut self, n: &Node, orig: &Node, name: &str) { + self.state(orig.locked, !orig.visible); + let xy = Xy::of(orig); + let was = self.in_look; + self.in_look = true; + self.line("u"); + let mut look = n.clone(); + (look.name, look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = + (None, 1.0, BlendMode::Normal, false, Knockout::Neutral, false); + if look.extras().mask.is_some() { + look.extras_mut().mask = None; + } + match &look.kind { + NodeKind::Group { children, clip: false } => { + for c in children.clone() { + self.node(&c); + } + } + _ => self.node(&look), + } + self.line("U"); + self.write_xy(xy); + self.line("0 0 Xd\n6 () XW"); + self.in_look = was; + // The object, on `%_` lines, in its own state (the look's members may have changed it). + self.state(orig.locked, !orig.visible); + let saved = std::mem::take(&mut self.body); + self.hidden += 1; + let fit = drawn_outline(n, orig).map(|p| p.bounding_box()); + match &orig.kind { + NodeKind::Path { path, rule, .. } => self.styled_outline(orig, path, *rule, fit, xy), + NodeKind::Compound { rule, .. } => self.styled_outline(orig, &compound_path(orig), *rule, fit, xy), + NodeKind::Group { children, .. } => { + self.line("u"); + for c in children { + self.node(c); + } + self.line("U"); + } + _ => {} + } + self.dictionary(orig); + self.hidden -= 1; + let part = std::mem::replace(&mut self.body, saved); + hide(&part, &mut self.body); + self.block_end = usize::MAX; + let _ = writeln!(self.body, "1 {} XW", ps::bytes(name.as_bytes())); + } + + /// A styled path's or compound path's points: painted with nothing, or with its gradient fill + /// (which its style's gradient fill is), placed on `fit` (the outline's bounds when `None`). + fn styled_outline(&mut self, orig: &Node, path: &vectorcraft_geom::PathData, rule: vectorcraft_geom::FillRule, fit: Option, xy: Xy) { + let bounds = fit.unwrap_or_else(|| path.to_bezpath().bounding_box()); + let gradient = orig.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) if matches!(f.paint, Paint::Gradient(_)) => Some(f), + _ => None, + }); + match gradient { + Some(f) => { + let fill = FillLayer { paint: self.placed(&f.paint, bounds), ..f.clone() }; + self.plain_object(path, rule, Some(&fill), None, xy.object()); + } + None => self.plain_object(path, rule, None, None, xy.object()), + } + } + + /// The art styles written, in a non-printing block: `%AI9_BeginArtStyles`, each style, + /// `%AI9_EndArtStyles`. + pub(in crate::ai_editing) fn art_styles(&self, s: &mut String) { + if self.styles.known.is_empty() { + return; + } + s.push_str("%AI5_Begin_NonPrinting\nNp\n%AI9_BeginArtStyles\n"); + for (name, text) in &self.styles.known { + s.push_str(&known_style(name, text)); + } + s.push_str("%AI9_EndArtStyles\n%AI5_End_NonPrinting--\n"); + } + + /// The panel's styles written, in its order, in a non-printing block: + /// `%AI9_BeginArtStyleList`, a name on each line, `%AI9_EndArtStyleList`. + pub(in crate::ai_editing) fn art_style_list(&self, s: &mut String) { + if self.styles.listed.is_empty() { + return; + } + s.push_str("%AI5_Begin_NonPrinting\nNp\n%AI9_BeginArtStyleList\n"); + for name in &self.styles.listed { + s.push_str(&ps::bytes(name.as_bytes())); + s.push('\n'); + } + s.push_str("%AI9_EndArtStyleList\n%AI5_End_NonPrinting--\n"); + } +} + +/// The outline a path's or compound path's style places a gradient fill on. +fn object_outline(n: &Node) -> Option { + match &n.kind { + NodeKind::Path { path, .. } => Some(path.to_bezpath()), + NodeKind::Compound { .. } => Some(compound_path(n).to_bezpath()), + _ => None, + } +} + +/// The outline a styled path or compound path draws: `n`'s, as baking left it, when it is still a +/// path or compound path, else `orig`'s. +fn drawn_outline(n: &Node, orig: &Node) -> Option { + object_outline(orig)?; + object_outline(n).or_else(|| object_outline(orig)) +} + +/// The fill rule of a path or compound path (a group's is the default). +fn object_rule(n: &Node) -> FillRule { + match &n.kind { + NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. } => *rule, + _ => FillRule::NonZero, + } +} + +/// Can appearance `ap` be written as a style of an object's own: fills and strokes that paint without +/// transparency or effects of their own, and no Warp, Distort & Transform or Blur effect? Those +/// are written only in the Graphic Styles panel's styles. +fn own_style_holds(ap: &Appearance) -> bool { + let plain = |i: &AppearanceItem| i.opacity() >= 1.0 && i.blend() == BlendMode::Normal && i.effects().is_empty(); + let panel_only = |e: &Effect| ["warp.", "distort.", "blur."].iter().any(|p| e.id.starts_with(p)); + ap.items.iter().filter(|i| !i.paint().is_none()).all(plain) && !ap.effects.iter().any(panel_only) +} + +/// Does the reader read graphic style `g` from style text `text` as it is? +fn panel_reads(g: &GraphicStyle, text: &str) -> bool { + let section = known_style("x", text); + let Some(read) = crate::import::read_art_style(section.as_bytes(), "x", None) else { return false }; + // The opacity within the written number's precision. + read.transparency.is_some_and(|t| (t.0 - g.opacity).abs() <= 1e-4 && (t.1, t.2, t.3) == (g.blend, g.isolate, g.knockout)) + && same_appearance(&read.appearance, &g.appearance) +} + +/// Does the reader read object `n` written with style text `text` as it is: a path or compound +/// path with a style it reads on any object, filled by the non-zero rule when the style fills it, +/// or a group with no fills or strokes of its own, with effects that move the outline only where the +/// reader reads them ([`crate::import::style_moves_with`])? +fn object_reads(n: &Node, text: &str) -> bool { + let section = known_style("x", text); + let own = n.appearance.fill().map(|f| &f.paint).filter(|p| matches!(p, Paint::Gradient(_))); + let Some(mut read) = crate::import::read_art_style(section.as_bytes(), "x", own) else { return false }; + let group = matches!(n.kind, NodeKind::Group { .. }); + if !read.simple + || (group && !read.appearance.items.is_empty()) + || (!group && read.pathfinder) + || !crate::import::style_moves_with(section.as_bytes(), "x", n) + { + return false; + } + if !group { + let filled = n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)) && !i.paint().is_none()); + if filled && object_rule(n) == FillRule::EvenOdd { + return false; + } + // A path's contents are nothing: the reader keeps the object's own. + read.appearance.contents_index = n.appearance.contents_index; + } + same_appearance(&read.appearance, &n.appearance) +} + +/// Do appearances `a` and `b` draw the same, as the reader reads one written from the other: the +/// fills and strokes that paint, within the written numbers' precision, and the effects with +/// their settings filled in from their defaults (blending modes in any case, colors as colors). +pub(in crate::ai_editing) fn same_appearance(a: &Appearance, b: &Appearance) -> bool { + let norm = |ap: &Appearance| -> Value { + let mut ap = ap.clone(); + let ci = ap.contents_index.unwrap_or(0).min(ap.items.len()); + let below = ap.items.iter().take(ci).filter(|i| !i.paint().is_none()).count(); + ap.items.retain(|i| !i.paint().is_none()); + ap.contents_index = (below > 0).then_some(below); + for e in ap.effects.iter_mut().chain(ap.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) { + e.params = normalized_params(e); + } + serde_json::to_value(&ap).unwrap_or(Value::Null) + }; + near(&norm(a), &norm(b)) +} + +/// Effect `e`'s settings with its defaults filled in, its blending mode in lower case and its color as +/// `#rrggbb`. +fn normalized_params(e: &Effect) -> Value { + let mut p = vectorcraft_effects::merged_params(&e.id, &e.params); + if let Some(m) = word(&p, "mode") { + p["mode"] = Value::String(m); + } + if p.get("color").is_some() { + p["color"] = Value::String(vectorcraft_effects::color_param(&p, vectorcraft_color::Color::BLACK).to_hex()); + } + for key in ["shade", "source", "joins", "points", "orientation"] { + if let Some(w) = word(&p, key) { + p[key] = Value::String(w); + } + } + p +} + +/// How far apart two numbers may read in [`near`]: a number written to 4 decimals, then converted +/// from a fraction to a percentage (`5e-3`) or from radians to degrees (`3e-3`). +const NEAR: f64 = 6e-3; + +/// JSON values equal but for numbers within the written numbers' precision. +fn near(a: &Value, b: &Value) -> bool { + match (a, b) { + (Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) { + (Some(x), Some(y)) => (x - y).abs() <= NEAR, + _ => x == y, + }, + (Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(x, y)| near(x, y)), + (Value::Object(x), Value::Object(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| near(v, w))), + _ => a == b, + } +} diff --git a/crates/eps/src/ai_editing/writer/symbols.rs b/crates/eps/src/ai_editing/writer/symbols.rs new file mode 100644 index 0000000000..bfc1ccc3ca --- /dev/null +++ b/crates/eps/src/ai_editing/writer/symbols.rs @@ -0,0 +1,343 @@ +//! Symbols: their definitions, the symbol list and their instances (see [`crate::ai_editing`] for +//! the form). + +use std::collections::HashSet; +use std::fmt::Write; + +use vectorcraft_color::Paint; +use vectorcraft_doc::{Knockout, Node, NodeKind, SymbolExportType}; +use vectorcraft_geom::Affine; + +use super::{MAX_NEST, Writer, Xy}; +use crate::import::MAX_SYMBOLS; +use crate::ps; + +pub(in crate::ai_editing) const SYMBOL_ART: &str = "symbol instances with a fill, appearance changes, isolation, knockout or knockout shape of their own, instances of symbols with 9-slice guides or pattern paint, instances in pattern tiles or in art cut to a clipping object, instances scaled almost flat, instances that turn, mirror or scale symbols holding type, live objects, instances written as their art, shapes with rounded live corners or strokes written as outlines or brush art, instances that scale their symbol more than 100 times, instances on the layers of a large canvas and instances of symbols past 4,096 are written as their art in the editing data for other apps"; +pub(in crate::ai_editing) const SYMBOL_OPTIONS: &str = + "the 9-slice guides, export types and dynamic type of symbols are left out of the editing data for other apps"; +pub(in crate::ai_editing) const MISSING_SYMBOL: &str = + "symbol instances of symbols the document doesn't have are written as empty groups in the editing data for other apps"; +/// The most an instance may scale its symbol's art, nested instances' scales included: the art's +/// numbers are written to four decimals, so a scale of 100 places them within 0.005 pt. +const MAX_SCALE: f64 = 100.0; +pub(in crate::ai_editing) const SYMBOL_COUNT: &str = "symbols past 4,096 are left out of the editing data for other apps"; + +/// Whether the canvas works `n` itself (not its children) out again after placing an instance: +/// type, live objects and shapes with rounded live corners, whose strokes, steps and corners depend +/// on where the instance puts them. +pub(super) fn redrawn(n: &Node) -> bool { + let rounded = |l: &vectorcraft_doc::LiveShape| match l { + vectorcraft_doc::LiveShape::Rectangle { radii, .. } => radii.iter().any(|r| *r > 0.0), + vectorcraft_doc::LiveShape::Polygon { radii, .. } | vectorcraft_doc::LiveShape::Path { radii, .. } => radii.iter().any(|r| *r > 0.0), + vectorcraft_doc::LiveShape::Ellipse { .. } | vectorcraft_doc::LiveShape::Line { .. } => false, + }; + match &n.kind { + NodeKind::Path { live: Some(l), .. } => rounded(l), + NodeKind::Text(_) + | NodeKind::Blend { .. } + | NodeKind::Envelope { .. } + | NodeKind::Mesh(_) + | NodeKind::Repeat(_) + | NodeKind::PlacedDocument(_) + | NodeKind::Intertwine { .. } => true, + _ => false, + } +} + +impl Writer<'_> { + /// Whether instance `n` of symbol `symbol`, placed by `xf`, is written as an instance: not on the + /// layers of a large canvas, in a pattern's tile or in art cut to a clipping object, without a + /// fill or appearance changes of its own (which stain or change the art it draws) and without + /// isolation, knockout or knockout shape of its own (which an instance's transparency doesn't + /// hold), of a symbol without 9-slice guides and without pattern paint in its art (the canvas + /// keeps an instance's pattern tiles where the document puts them, and a definition's art moves + /// with each instance) whose definition can be written ([`Self::define_symbol`]), by a matrix + /// that keeps the art's area as it is written and scales it as the definition allows + /// ([`Self::keeps_scale`]). + pub(super) fn live_instance(&mut self, n: &Node, symbol: &str, xf: Affine) -> bool { + let own = vectorcraft_brush::stain(n).is_some() || !n.extras().symbol_overrides.is_empty(); + let group_state = n.isolate || n.knockout != Knockout::Neutral || n.knockout_shape; + // The matrix as written (to ten decimals) must still keep the art's area. + let m = Affine::new((self.instance_space * xf).as_coeffs().map(|v| (v * 1e10).round() / 1e10)); + (self.symbols_live || self.in_symbol) + && self.defining.is_empty() + && self.clip.is_none() + && !own + && !group_state + && self.doc.symbol_nine_slice(symbol).is_none() + && m.as_coeffs().iter().all(|v| v.is_finite()) + && m.determinant().abs() >= 1e-12 + && self.define_symbol(symbol) + && !self.symbol_paints_pattern(symbol) + && self.keeps_scale(symbol, xf) + } + + /// Whether instance matrix `xf` places symbol `symbol`'s definition as the canvas draws the + /// instance. A definition holding art the canvas works out again after placing an instance + /// ([`redrawn`], strokes written as outlines or brush art, and instances written as their art) + /// takes only matrices that move it; + /// any other takes a scale up to [`MAX_SCALE`], nested instances' scales included. A live + /// instance in a symbol's art passes both to that symbol. + fn keeps_scale(&mut self, symbol: &str, xf: Affine) -> bool { + let [a, b, c, d, ..] = xf.as_coeffs(); + let fixed = self.fixed_symbols.contains(symbol); + let scale = a.hypot(b).max(c.hypot(d)) * self.symbol_scales.get(symbol).copied().unwrap_or(1.0); + let keeps = if fixed { (a - 1.0).abs() < 1e-9 && b.abs() < 1e-9 && c.abs() < 1e-9 && (d - 1.0).abs() < 1e-9 } else { scale <= MAX_SCALE }; + if keeps && self.in_symbol { + self.wrote_fixed |= fixed; + self.inner_scale = self.inner_scale.max(scale); + } + keeps + } + + /// Whether the art of symbol `name`, an opacity mask in it or the art of a symbol it holds an + /// instance of, at any depth, fills or strokes something (type included) with a pattern, or its + /// definition holds pattern tiles. Worked out once a symbol, after it is defined. + fn symbol_paints_pattern(&mut self, name: &str) -> bool { + if self.pattern_written.contains(name) { + return true; + } + if let Some(known) = self.patterned_symbols.get(name) { + return *known; + } + let mut seen = HashSet::from([name.to_string()]); + let mut todo = vec![name.to_string()]; + let mut found = false; + while let Some(next) = todo.pop() { + let (own, used) = self.symbol_own_patterns(&next); + if own { + found = true; + break; + } + for u in used { + if seen.insert(u.clone()) { + todo.push(u); + } + } + } + self.patterned_symbols.insert(name.to_string(), found); + found + } + + /// Whether the art of symbol `name` or an opacity mask in it fills or strokes something (type + /// included) with a pattern, and the symbols its instances and inline graphics there use; looked + /// at once a symbol. + fn symbol_own_patterns(&mut self, name: &str) -> (bool, Vec) { + if let Some(known) = self.pattern_symbols.get(name) { + return known.clone(); + } + let doc = self.symbol_doc; + let mut own = false; + let mut used = vec![]; + if let Some(sym) = doc.symbols.iter().find(|s| s.name == name) { + let pattern = |p: &Paint| matches!(p, Paint::Pattern { .. }); + vectorcraft_doc::swatches::walk_with_masks(&sym.art, &mut |m| { + own |= vectorcraft_doc::pattern::uses_pattern(m, None); + match &m.kind { + NodeKind::Text(t) => { + own |= t.runs.iter().any(|r| pattern(&r.style.fill) || pattern(&r.style.stroke)); + // Inline graphics are written as their symbols' art. + used.extend(t.runs.iter().filter_map(|r| r.inline.as_ref()).map(|art| art.symbol.clone())); + } + NodeKind::SymbolInstance { symbol, .. } => used.push(symbol.clone()), + _ => {} + } + }); + } + self.pattern_symbols.insert(name.to_string(), (own, used.clone())); + (own, used) + } + + /// An instance of `symbol` placed by `xf`, of transparency `xy`: `/SymbolInstance :`, `(name) + /// /SymbolRef ,`, the matrix taking the symbol's art to art space (in a symbol's art, to the + /// canvas's space turned y up about art space's origin there) as `a b c d tx ty + /// /RTransformMatrix` (to ten decimals), `;`, then its state block as a group's: `Xy`, `0 0 Xd` + /// and `6 () XW` when it has transparency, else `9 () XW`. Its dictionary goes between the two. + pub(super) fn symbol_instance(&mut self, symbol: &str, xf: Affine, xy: Xy) { + let m = self.instance_space * xf; + let _ = write!(self.body, "/SymbolInstance :\n{} /SymbolRef ,\n", ps::bytes(symbol.as_bytes())); + for v in m.as_coeffs() { + self.body.push_str(&super::images::precise(v)); + self.body.push(' '); + } + self.body.push_str("/RTransformMatrix\n;\n"); + // An instance with isolation, knockout or knockout shape of its own is written as its art + // ([`Self::live_instance`]); these are the values of the others. + let xy = Xy { isolate: false, knockout: Knockout::Neutral, shape: false, ..xy }; + self.block_start = self.body.len(); + if xy == Xy::PLAIN { + self.line("9 () XW"); + } else { + self.write_xy(xy); + self.line("0 0 Xd\n6 () XW"); + } + self.block_end = self.body.len(); + } + + /// Write symbol `name`'s definition, once: `%AI14_BeginSymbol`, `(name)`, `0 A`, `0 Xw`, `0 Ae`, + /// the art in the symbol's space (y down: its numbers are the symbol's own) as a group (`u` … + /// `U`; art that isn't a group, or is a plain group of one object, in a group of its own), the + /// symbol's registration point (`AI13PatternRegistrationType`, 1 to 9 from the top left, row by + /// row) in that group's dictionary, `9 () XW`, `%AI10_EndSymbol`. Linked images in the + /// art are embedded. The symbols its art's instances use are defined first, and the art is + /// written from the top of the nesting whatever the instance that asks for it, so a definition + /// is the same wherever its first instance lies. False when it can't be: the document doesn't + /// have the symbol, it is being written (its art holds an instance of itself), it is reached + /// through more than [`MAX_NEST`] definitions being written, or the definitions written and + /// being written leave no place under [`MAX_SYMBOLS`]. + pub(super) fn define_symbol(&mut self, name: &str) -> bool { + if self.defined_symbols.contains(name) { + return true; + } + let doc = self.symbol_doc; + let Some(sym) = doc.symbols.iter().find(|s| s.name == name) else { return false }; + if self.defining_symbols.iter().any(|d| d == name) || self.defining_symbols.len() >= MAX_NEST as usize { + return false; + } + // The reader keeps no more definitions than this, and each definition being written takes + // one when it ends. + if self.symbol_defs.len() + self.defining_symbols.len() >= MAX_SYMBOLS { + self.warn(SYMBOL_COUNT); + return false; + } + if sym.dynamic || doc.symbol_export_type(name) != SymbolExportType::default() || doc.symbol_nine_slice(name).is_some() { + self.warn(SYMBOL_OPTIONS); + } + // The art's effects are its own, not those of a drawn look that first places it. + let in_look = std::mem::take(&mut self.in_look); + self.defining_symbols.push(name.to_string()); + let mut used = vec![]; + vectorcraft_doc::swatches::walk_with_masks(&sym.art, &mut |m| { + if let NodeKind::SymbolInstance { symbol, .. } = &m.kind { + used.push(symbol.as_str()); + } + }); + for u in used { + self.define_symbol(u); + } + if self.symbol_defs.len() + self.defining_symbols.len() > MAX_SYMBOLS { + self.defining_symbols.pop(); + self.warn(SYMBOL_COUNT); + self.in_look = in_look; + return false; + } + // The art is written in the symbol's space, from the state `0 A` and `0 Xw` set, from the + // document at its own size. + let origin = self.canvas_origin; + let about_origin = Affine::new([1.0, 0.0, 0.0, -1.0, -origin.0, origin.1]); + let page_doc = std::mem::replace(&mut self.doc, doc); + let saved = ( + std::mem::take(&mut self.body), + (self.to_art, self.grad_space, self.canvas, self.instance_space), + self.state.replace((false, false)), + self.gs.replace(Xy::OPAQUE), + self.clip.take(), + (self.block_start, self.block_end), + (std::mem::replace(&mut self.in_symbol, true), std::mem::take(&mut self.hidden)), + self.root_entries.take(), + std::mem::take(&mut self.wrote_pattern), + (std::mem::take(&mut self.wrote_fixed), std::mem::replace(&mut self.inner_scale, 1.0)), + ); + // Gradients' matrices and instances' matrices are written about the canvas point of art + // space's origin, y up; `Bg` places a gradient on the art as it lies in the symbol's space. + (self.to_art, self.grad_space, self.canvas, self.instance_space) = (Affine::IDENTITY, about_origin, Affine::IDENTITY, about_origin); + self.block_end = usize::MAX; + let registration = u16::from(doc.symbol_registration(name).0.min(8)) + 1; + let entries = format!("%_{registration} /Int (AI13PatternRegistrationType) ,\n"); + // The canvas draws a symbol's art even when its root is hidden, so the root is written shown. + let shown; + let root: &Node = if sym.art.visible { + &sym.art + } else { + let mut a = (*sym.art).clone(); + a.visible = true; + shown = a; + &shown + }; + // A definition holds a group: art of another kind, and a plain group of one object (which + // the reader takes for that group), are written in one. + let wrap = !matches!(root.kind, NodeKind::Group { clip: false, .. }) || crate::import::symbol_art_member(root).is_some(); + let nest = std::mem::replace(&mut self.nest, 1); + if wrap { + self.line("u"); + self.node(root); + let _ = write!(self.body, "U\n%_/ArtDictionary :\n{entries}%_;\n%_\n9 () XW\n"); + } else { + // A group always writes its dictionary ([`Self::dictionary`]), which takes the entries. + self.root_entries = Some((root.id, entries)); + self.node(root); + } + self.nest = nest; + // Objects the writing doesn't pass through one by one (clipping paths, a clipping group's + // own path) count as well. + vectorcraft_doc::swatches::walk_with_masks(&sym.art, &mut |m| self.wrote_fixed |= redrawn(m)); + if self.wrote_pattern { + self.pattern_written.insert(name.to_string()); + } + if self.wrote_fixed { + self.fixed_symbols.insert(name.to_string()); + } + if self.inner_scale > 1.0 { + self.symbol_scales.insert(name.to_string(), self.inner_scale); + } + let art; + ( + art, + (self.to_art, self.grad_space, self.canvas, self.instance_space), + self.state, + self.gs, + self.clip, + (self.block_start, self.block_end), + (self.in_symbol, self.hidden), + self.root_entries, + self.wrote_pattern, + (self.wrote_fixed, self.inner_scale), + ) = saved; + self.doc = page_doc; + self.in_look = in_look; + let art = std::mem::replace(&mut self.body, art); + self.defining_symbols.pop(); + let text = format!("%AI14_BeginSymbol\n{}\n0 A\n0 Xw\n0 Ae\n{art}%AI10_EndSymbol\n", ps::bytes(name.as_bytes())); + self.defined_symbols.insert(name.to_string()); + self.symbol_defs.push(text); + true + } + + /// Every symbol of the document defined, in its order (those its art uses before it): the + /// Symbols panel keeps the ones no instance uses too, and on a large canvas all of them. + pub(in crate::ai_editing) fn symbols(&mut self) { + let doc = self.symbol_doc; + for s in &doc.symbols { + self.define_symbol(&s.name); + } + } + + /// The symbol definitions, in the setup after the patterns: `%AI5_Begin_NonPrinting`, `Np`, each + /// definition, `%AI5_End_NonPrinting--`. + pub(in crate::ai_editing) fn symbol_definitions(&self, s: &mut String) { + if self.symbol_defs.is_empty() { + return; + } + s.push_str("%AI5_Begin_NonPrinting\nNp\n"); + for d in &self.symbol_defs { + s.push_str(d); + } + s.push_str("%AI5_End_NonPrinting--\n"); + } + + /// The symbol list, after the palette: the names of the symbols defined in the document's order + /// (the Symbols panel's), between `%AI24_BeginSymbolList` and `%AI24_EndSymbolList` in a + /// non-printing block. + pub(in crate::ai_editing) fn symbol_list(&self, s: &mut String) { + if self.symbol_defs.is_empty() { + return; + } + s.push_str("%AI5_Begin_NonPrinting\nNp\n%AI24_BeginSymbolList\n"); + for sym in &self.symbol_doc.symbols { + if self.defined_symbols.contains(&sym.name) { + let _ = writeln!(s, "{}", ps::bytes(sym.name.as_bytes())); + } + } + s.push_str("%AI24_EndSymbolList\n%AI5_End_NonPrinting--\n"); + } +} diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs new file mode 100644 index 0000000000..f494e859a7 --- /dev/null +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -0,0 +1,1034 @@ +//! Type as the text document of the editing data (`%AI11_BeginTextDocument`): the characters of each +//! text object, their character and paragraph attributes and where they sit, as the text document +//! reader reads them ([`crate::import`]'s `ate.rs`), and a text object stub (`/AI11Text`) in the +//! layers naming its story. +//! +//! The document is ASCII85 on comment lines of nested dictionaries with numbers for keys. Its root +//! holds the version (`/98`), the resources (`/0`: fonts, character and paragraph style sheets, the +//! frames, and empty sets of the resources the writer has none of) and the objects (`/1`: the +//! document's text settings, the stories, and the attributes stories start from). A story holds its +//! characters (paragraphs end in `\r`, a forced line break is `\x03`), its paragraph and character +//! runs (each a length in characters and its attributes) and the frames it flows through: point type +//! (a point on the canvas and, when it is turned, a matrix), area type (the frame's cubic segments, +//! rows, columns, gutters, first baseline) or type on a path (the path's cubic segments and where +//! the type starts and ends on it). Coordinates are the canvas's (y down, 16383 points a side, its +//! center the center of `%AI3_TemplateBox`). The stories carry no composed lines: the app that +//! opens the file lays them out. + +use std::collections::{HashMap, HashSet}; +use std::fmt::Write; + +use kurbo::{ParamCurveArclen, PathSeg}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{ + AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, Mojikumi, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, + PathEffect, TextKind, TextObject, VerticalAlign, +}; +use vectorcraft_geom::{Affine, PathData, Point}; + +use crate::ps; + +/// What the text document holds of type, and what it leaves out. +pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and stroke weight, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps"; + +/// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it. +const STREAM_VERSION: u32 = 14; +/// The font that shows hidden characters, as the files users sent name it, last in the font set. +const HIDDEN_GLYPH_FONT: &str = "AdobeInvisFont"; +/// The hidden characters that font shows: each whitespace character and the glyph it shows as. +const HIDDEN_GLYPHS: [(&str, &str); 7] = + [(" ", "1"), ("\r", "6"), ("\t", "0"), ("\u{2029}", "5"), ("\u{3}", "5"), ("\u{3000}", "1"), ("\u{ad}", "3")]; +/// Most characters a line of ASCII85 holds. +const LINE: usize = 100; + +/// A value of the text document. +enum V { + Int(i64), + Real(f64), + /// A real to ten decimals (the turn and scale of a matrix, which the reader divides by). + Fine(f64), + /// A real to eight decimals (the type's lengths and factors, which may be small; a size the reader + /// multiplies by a matrix's scale comes back within these). + Small(f64), + Bool(bool), + Str(String), + Name(&'static str), + List(Vec), + Dict(Vec<(u32, V)>), +} + +impl V { + /// How many values the reader counts in `self` (each value, list and dictionary one). + fn count(&self) -> usize { + match self { + V::List(l) => 1 + l.iter().map(V::count).sum::(), + V::Dict(d) => 1 + d.iter().map(|(_, v)| v.count()).sum::(), + _ => 1, + } + } + + fn write(&self, out: &mut Vec) { + match self { + V::Int(n) => out.extend_from_slice(n.to_string().as_bytes()), + V::Real(r) => { + let mut s = String::new(); + ps::push_num(&mut s, if r.is_finite() { *r } else { 0.0 }); + let s = s.trim_end(); + out.extend_from_slice(s.as_bytes()); + // A real is written with a point, as the files users sent write them. + if !s.contains(['.', 'e', 'E']) { + out.extend_from_slice(b".0"); + } + } + V::Fine(r) => decimals(*r, 10, out), + V::Small(r) => decimals(*r, 8, out), + V::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }), + V::Str(s) => { + out.push(b'('); + let mut bytes = vec![0xfe, 0xff]; + for u in s.encode_utf16() { + bytes.extend_from_slice(&u.to_be_bytes()); + } + for b in bytes { + if matches!(b, b'(' | b')' | b'\\') { + out.push(b'\\'); + } + out.push(b); + } + out.push(b')'); + } + V::Name(n) => { + out.push(b'/'); + out.extend_from_slice(n.as_bytes()); + } + V::List(l) => { + out.push(b'['); + for v in l { + out.push(b' '); + v.write(out); + } + out.extend_from_slice(b" ]"); + } + V::Dict(d) => { + out.extend_from_slice(b"<<"); + for (k, v) in d { + let _ = write!(Bytes(out), " /{k} "); + v.write(out); + } + out.extend_from_slice(b" >>"); + } + } + } +} + +/// `r` to `n` decimals (trailing zeros left out, a point always), into `out`. +fn decimals(r: f64, n: i32, out: &mut Vec) { + let k = 10f64.powi(n); + let r = if r.is_finite() && (r * k).is_finite() { (r * k).round() / k } else { 0.0 }; + let s = format!("{:.*}", n as usize, r + 0.0); + let s = s.trim_end_matches('0'); + out.extend_from_slice(s.as_bytes()); + if s.ends_with('.') { + out.push(b'0'); + } +} + +/// `fmt::Write` into bytes. +struct Bytes<'a>(&'a mut Vec); + +impl std::fmt::Write for Bytes<'_> { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + self.0.extend_from_slice(s.as_bytes()); + Ok(()) + } +} + +/// A length or a factor of the type's attributes, to eight decimals. +fn real(v: f64) -> V { + V::Small(v) +} + +fn reals(v: &[f64]) -> V { + V::List(v.iter().map(|x| V::Real(*x)).collect()) +} + +fn fines(v: &[f64]) -> V { + V::List(v.iter().map(|x| V::Fine(*x)).collect()) +} + +fn dict(pairs: Vec<(u32, V)>) -> V { + V::Dict(pairs) +} + +/// A resource set: its resources, each `<< /0 resource >>`, and its display list. +fn set(resources: Vec, display: bool) -> V { + let mut d = vec![(0, V::List(resources.into_iter().map(|r| dict(vec![(0, r)])).collect()))]; + if display { + d.push((1, V::List(vec![dict(vec![(0, V::Int(0))])]))); + } + dict(d) +} + +/// A paint: kind 0 gray (`[alpha, lightness]`), 1 RGB, 2 CMYK, as the reader's `paint` reads them. +fn paint(c: &Color) -> V { + let (kind, values) = match *c { + Color::Gray { k } => (0, vec![1.0 - f64::from(k.clamp(0.0, 1.0))]), + Color::Cmyk { c, m, y, k } => (2, [c, m, y, k].iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()), + Color::Rgb { .. } | Color::Lab { .. } => (1, c.to_rgb().iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()), + }; + let values: Vec = std::iter::once(1.0).chain(values).collect(); + dict(vec![(99, V::Name("SimplePaint")), (0, dict(vec![(0, V::Int(kind)), (1, reals(&values))]))]) +} + +/// The color of paint `p` when the text document can hold it (a solid color or none). +fn solid(p: &Paint) -> Option> { + match p { + Paint::Solid { color, .. } => Some(Some(*color)), + Paint::None => Some(None), + Paint::Gradient(_) | Paint::Pattern { .. } => None, + } +} + +/// Can the text document hold type `t` of object `n` as it is: point type that isn't mirrored, or +/// area type or type on a path that is only moved ([`shape`]); characters other than inline graphics +/// and ruby; solid fills and strokes; no fills, strokes, effects or opacity mask of the object's +/// own; some text. +pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject) -> bool { + let xf = t.xf.as_coeffs(); + let shape_ok = match &t.kind { + TextKind::Point => xf.iter().all(|v| v.is_finite()) && t.xf.determinant() > 1e-12, + TextKind::Area { .. } => closed_frame(t), + // An open path whose ends meet would be read back closed. + TextKind::OnPath { path, .. } => { + let open = path.subpaths.iter().any(|sp| !sp.anchors.is_empty() && !sp.closed); + shape(t).as_ref().and_then(segments).is_some_and(|s| !(open && closed(&s))) + } + }; + // Area type that flows around wrap objects: the data doesn't hold their wrap settings. + shape_ok + && t.wrap.is_empty() + && t.ruby.is_empty() + && t.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace())) + && runs_held(t) + && plain(n) + && within_reader(t, story_scale(t)) +} + +/// Is the frame of area type `t` one closed part? An open frame whose ends meet would be read back +/// closed. +fn closed_frame(t: &TextObject) -> bool { + shape(t).filter(|p| p.subpaths.iter().all(|sp| sp.anchors.is_empty() || sp.closed)).as_ref().and_then(segments).is_some_and(|s| closed(&s)) +} + +/// Document points to a unit of the story of type `t`: its scale is put into its lengths. +fn story_scale(t: &TextObject) -> f64 { + 1.0 / t.xf.determinant().abs().sqrt() +} + +/// Are the lengths and scales of type `t`, written at `scale`, within what the reader's +/// `Texts::style`, `Texts::para` and `AreaFrame::read` read (it reads others as their defaults)? +fn within_reader(t: &TextObject, scale: f64) -> bool { + const MAX_LENGTH: f64 = 1e5; + let length = |v: f64| (v / scale).is_finite() && (v / scale).abs() < MAX_LENGTH; + // Scales are written as fractions to eight decimals. + let factor = |v: f64| v.is_finite() && v / 100.0 >= 1e-7 && v / 100.0 < 100.0; + let char_ok = |s: &CharStyle| { + // Sizes are written to eight decimals. + length(s.size) + && s.size / scale >= 1e-7 + && s.leading.is_none_or(|l| length(l) && l / scale >= 1e-7) + // Tracking is written rounded to a whole number. + && s.tracking.is_finite() + && s.tracking.round().abs() < MAX_LENGTH + && length(s.baseline_shift) + && factor(s.h_scale) + && factor(s.v_scale) + && (s.stroke.is_none() || (s.stroke_width.is_finite() && s.stroke_width >= 0.0 && s.stroke_width / scale < 1e4)) + }; + let para_ok = |p: &ParaStyle| [p.left_indent, p.right_indent, p.first_line_indent, p.space_before, p.space_after].into_iter().all(length); + let max = vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS; + let area_ok = |o: &AreaOptions| { + [o.gutter, o.row_gutter.unwrap_or(o.gutter), o.first_baseline_min].iter().all(|g| g.is_finite() && *g >= 0.0 && *g / scale <= 10_000.0) + && o.rows <= max + && o.columns <= max + }; + t.runs.iter().all(|r| char_ok(&r.style)) + && t.paragraph_styles().iter().all(para_ok) + && (!matches!(t.kind, TextKind::Area { .. }) || area_ok(&t.area)) +} + +/// Are the runs of `t` characters (no inline graphics, and none of the characters a story ends its +/// paragraphs and lines with, `\r` and `\x03`) filled and stroked with solid colors or nothing? +fn runs_held(t: &TextObject) -> bool { + t.runs + .iter() + .all(|r| r.inline.is_none() && !r.text.contains(['\r', '\u{3}']) && solid(&r.style.fill).is_some() && solid(&r.style.stroke).is_some()) +} + +/// The story of a thread whose frames `texts` (in order) each hold a slice of it: their runs one +/// after another, and their paragraphs' attributes, a paragraph split between two frames once (a +/// frame whose text before it doesn't end with a paragraph break continues that paragraph), and +/// whether a paragraph split between two frames has other attributes in the second (left out: +/// the story keeps the first's). +fn joined(texts: &[&TextObject]) -> Option<(TextObject, bool)> { + let mut whole = (*texts.first()?).clone(); + whole.runs.clear(); + let mut last: Option = None; + let mut differs = false; + // Whether the story so far has text, and ends with a paragraph break. + let (mut started, mut ended) = (false, false); + for t in texts.iter().filter(|t| t.runs.iter().any(|r| !r.text.is_empty())) { + let continues = started && !ended; + (started, ended) = (true, t.plain_text().ends_with('\n')); + let own = t.paragraph_styles(); + if continues && own.first() != last.as_ref() { + differs = true; + } + last = own.last().cloned(); + whole.runs.extend(t.runs.iter().filter(|r| !r.text.is_empty()).cloned()); + } + if whole.runs.is_empty() { + whole.runs = texts.first()?.runs.clone(); + } + whole.set_paragraph_styles(vectorcraft_text::thread::story_paras(texts, &[])); + Some((whole, differs)) +} + +/// The frame of area type or the path of type on a path, in document coordinates: when the matrix +/// of type `t` only moves it and scales it by one factor (as a large canvas does), its frame or +/// path through that matrix ([`story_scale`] puts the factor into its lengths). `None` for point +/// type and for type that is turned, mirrored, skewed or scaled by two factors. +fn shape(t: &TextObject) -> Option { + let [a, b, c, d, e, f] = t.xf.as_coeffs(); + let even = a > 0.0 && (a - d).abs() <= a * 1e-9 && b == 0.0 && c == 0.0 && e.is_finite() && f.is_finite(); + match &t.kind { + TextKind::Area { frame } if even => Some(frame.transformed(t.xf)), + TextKind::OnPath { path, .. } if even => Some(path.transformed(t.xf)), + _ => None, + } +} + +/// Has text object `n` no fills, strokes or effects of its own that paint or show, and no opacity +/// mask (the reader doesn't keep a text object's mask)? +fn plain(n: &Node) -> bool { + n.appearance.items.iter().all(|i| !i.visible() || (i.paint().is_none() && !i.effects().iter().any(|e| e.visible))) + && !n.appearance.effects.iter().any(|e| e.visible) + && n.extras().mask.is_none() +} + +/// Is the end bracket of type on an open path so near the path's end that the reader reads it as +/// no bracket (`Story::node`: within 0.02 of a segment)? +fn end_read_as_none(t: &TextObject) -> bool { + let (Some((_, end)), Some(segs)) = (t.kind.path_span(), shape(t).as_ref().and_then(segments)) else { return false }; + !closed(&segs) && end < 1.0 - 1e-9 && place_on(&segs, end) >= segs.len() as f64 - 0.02 +} + +/// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? +pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { + // Small capitals are read back at Document Setup's default size. + let default_small_caps = vectorcraft_doc::DocSetup::default().small_caps_size; + // A run's style as the text document holds it: every other attribute at its default. A color + // is held without its swatch link. + let held_char = |s: &CharStyle| { + let unlinked = |p: &Paint| match p { + Paint::Solid { color, .. } => Paint::solid(*color), + other => other.clone(), + }; + let stroked = !s.stroke.is_none(); + CharStyle { + font_family: s.font_family.clone(), + font_style: s.font_style.clone(), + size: s.size, + leading: s.leading, + tracking: s.tracking.round(), + baseline_shift: s.baseline_shift, + h_scale: s.h_scale, + v_scale: s.v_scale, + fill: unlinked(&s.fill), + stroke: unlinked(&s.stroke), + stroke_width: if stroked { s.stroke_width } else { CharStyle::default().stroke_width }, + all_caps: s.all_caps, + small_caps: s.small_caps.filter(|v| *v == default_small_caps), + tate_chu_yoko: s.tate_chu_yoko, + // Key 35 holds one of the two: a Tate-chu-yoko run is read back without the other. + standard_vertical_roman: s.standard_vertical_roman && !s.tate_chu_yoko, + ..CharStyle::default() + } + }; + let run_lost = |s: &CharStyle| { + let stroked = !s.stroke.is_none(); + let s = CharStyle { stroke_width: if stroked { s.stroke_width } else { CharStyle::default().stroke_width }, ..s.clone() }; + // A Lab color is written as RGB. + let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. }); + s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !font_kept(&s) + }; + // A paragraph's style as the text document holds it, and its text: aligned to the start of + // its direction (Auto) without a direction of its own, it comes back aligned left, which + // differs when its first strong letter is right-to-left. + let para_lost = |(p, text): (&ParaStyle, &str)| { + let rtl_letter = text.chars().find_map(strong_direction) == Some(true); + if p.justify == Justify::Auto && p.direction.is_none() && rtl_letter { + return true; + } + let held = ParaStyle { + justify: p.justify, + left_indent: p.left_indent, + right_indent: p.right_indent, + first_line_indent: p.first_line_indent, + space_before: p.space_before, + space_after: p.space_after, + hyphenate: p.hyphenate, + direction: p.direction.filter(|d| *d == ParaDirection::RightToLeft), + // The composition of Japanese punctuation new type gets (Line-end Punctuation Half + // Width, Standard burasagari) isn't reported: it changes no other script's lines. + mojikumi: if p.mojikumi == Mojikumi::LineEndHalf { p.mojikumi } else { ParaStyle::default().mojikumi }, + burasagari: if p.burasagari == Burasagari::Standard { p.burasagari } else { ParaStyle::default().burasagari }, + ..ParaStyle::default() + }; + *p != held + }; + let area = AreaOptions::default(); + let text = t.plain_text(); + t.runs.iter().any(|r| run_lost(&r.style)) + || t.paragraph_styles().iter().zip(text.split('\n')).any(para_lost) + || t.optical_margin + || t.system_layout + || !t.fractional_widths + || (matches!(t.kind, TextKind::Area { .. }) + && (t.area.inset != area.inset + || t.area.vertical_align != VerticalAlign::default() + || t.area.flow != area.flow + || t.area.fit != area.fit + // The text document holds the Ascent first baseline by leaving it out, without a minimum. + || (t.area.first_baseline == FirstBaseline::Ascent && t.area.first_baseline_min != 0.0))) + || (matches!(t.kind, TextKind::OnPath { .. }) + && (t.path_effect != PathEffect::default() || t.path_align != PathAlign::default() || t.path_spacing != 0.0 || end_read_as_none(t))) +} + +/// Key 35 of a run in style `st`, as the reader's `Texts::style` reads it: 3 for Tate-chu-yoko, 1 +/// (Standard) for Standard Vertical Roman Alignment, else 2 (rotated). +fn baseline_direction(st: &CharStyle) -> i64 { + if st.tate_chu_yoko { + 3 + } else if st.standard_vertical_roman { + 1 + } else { + 2 + } +} + +/// The name the font of style `st` is written under, and whether it's TrueType: an installed +/// face's PostScript name; else its family and style as `family-style` (the family alone for +/// Regular), the form the reader's `family_style` splits. +fn font_name(st: &CharStyle) -> (String, bool) { + let db = vectorcraft_text::FontDb::global(); + // The face of that family and style (the font database gives a fallback face for others). + match db + .face_version(&st.font_family, &st.font_style, st.font_version.as_deref()) + .filter(|f| f.family == st.font_family && f.style == st.font_style) + { + Some(face) => (face.postscript_name(), face.is_truetype()), + None if st.font_style.is_empty() || st.font_style == "Regular" => (st.font_family.clone(), false), + None => (format!("{}-{}", st.font_family, st.font_style.replace(' ', "")), false), + } +} + +/// Does the font of style `st` come back as itself: the family and style the reader makes of the +/// name it is written under (as its `char_style` does)? +fn font_kept(st: &CharStyle) -> bool { + let (family, style) = crate::family_style(&font_name(st).0); + let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); + family == st.font_family && style == st.font_style +} + +/// Whether `c` is a strong right-to-left letter (`Some(true)`: Hebrew, Arabic, Syriac, Thaana, NKo +/// and their presentation forms) or a strong left-to-right one (`Some(false)`: any other letter). +fn strong_direction(c: char) -> Option { + let rtl = matches!(c, '\u{0590}'..='\u{08FF}' | '\u{FB1D}'..='\u{FDFF}' | '\u{FE70}'..='\u{FEFF}'); + if rtl { + Some(true) + } else if c.is_alphabetic() { + Some(false) + } else { + None + } +} + +/// The cubic segments of `path`, eight numbers each (start, two handles, end) in document +/// coordinates; `None` unless it has one subpath with points and no other (a frame of the text +/// document is one path), of no more segments than the reader reads. +fn segments(path: &PathData) -> Option> { + let mut drawn = path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()); + let sp = drawn.next().filter(|sp| sp.anchors.len() > 1 && sp.segment_count() <= crate::import::MAX_SEGMENTS)?; + if drawn.next().is_some() { + return None; + } + let bp = PathData::new(vec![sp.clone()]).to_bezpath(); + let out: Vec<[f64; 8]> = bp + .segments() + .map(|s| { + let c = match s { + PathSeg::Line(l) => kurbo::CubicBez::new(l.p0, l.p0, l.p1, l.p1), + PathSeg::Quad(q) => q.raise(), + PathSeg::Cubic(c) => c, + }; + [c.p0.x, c.p0.y, c.p1.x, c.p1.y, c.p2.x, c.p2.y, c.p3.x, c.p3.y] + }) + .collect(); + (!out.is_empty() && out.len() <= crate::import::MAX_SEGMENTS && out.iter().flatten().all(|v| v.is_finite())).then_some(out) +} + +/// Do `segments` end where they start? +fn closed(segments: &[[f64; 8]]) -> bool { + matches!((segments.first(), segments.last()), (Some(f), Some(l)) if (f[0] - l[6]).abs() < 1e-3 && (f[1] - l[7]).abs() < 1e-3) +} + +/// Where the fraction `f` of the length of `segments` lies, as the reader's `length_fraction` +/// reads it back: a segment's index plus the place in that segment. +fn place_on(segments: &[[f64; 8]], f: f64) -> f64 { + const ACCURACY: f64 = 1e-4; + let cubic = |s: &[f64; 8]| kurbo::CubicBez::new((s[0], s[1]), (s[2], s[3]), (s[4], s[5]), (s[6], s[7])); + let lengths: Vec = segments.iter().map(|s| cubic(s).arclen(ACCURACY)).collect(); + let total: f64 = lengths.iter().sum(); + if !(total.is_finite() && total > 0.0) { + return 0.0; + } + let mut left = f.clamp(0.0, 1.0) * total; + for (i, (s, len)) in segments.iter().zip(&lengths).enumerate() { + if left <= *len || i + 1 == segments.len() { + let t = if *len > 0.0 { cubic(s).inv_arclen(left.min(*len), ACCURACY) } else { 0.0 }; + return i as f64 + t.clamp(0.0, 1.0); + } + left -= len; + } + segments.len() as f64 +} + +/// The text document being written. +#[derive(Default)] +pub(in crate::ai_editing) struct TextDoc { + /// Each font's PostScript name and whether it's TrueType. + fonts: Vec<(String, bool)>, + frames: Vec, + stories: Vec, + /// The story and frame each text object of a thread is written as. + threaded: HashMap, + /// The threads (by their first frame) already planned. + planned: HashSet, + /// A thread written since the last [`Self::take_lost`] has attributes the text document leaves + /// out ([`loses`], in any of its frames). + lost: bool, + /// The bytes of the stories written, each counted once for each text object that names it. + text_bytes: usize, + /// The bytes of the frames and stories as written in the text document, and the values the + /// reader counts in them. + doc_bytes: usize, + doc_values: usize, +} + +impl TextDoc { + pub(in crate::ai_editing) fn is_empty(&self) -> bool { + self.stories.is_empty() + } + + /// The index of the font of `st` in the font set. + fn font(&mut self, st: &CharStyle) -> i64 { + let (name, truetype) = font_name(st); + let i = match self.fonts.iter().position(|(n, _)| *n == name) { + Some(i) => i, + None => { + self.fonts.push((name, truetype)); + self.fonts.len() - 1 + } + }; + i as i64 + } + + /// The character attributes of a run in style `st`, at `scale` (document points to a unit of + /// the text document), as the reader's `Texts::style` reads them. + fn char_features(&mut self, st: &CharStyle, scale: f64) -> V { + let font = self.font(st); + let num = |v: f64, d: f64| if v.is_finite() { v } else { d }; + // Sizes to eight decimals: the reader reads a size of 0 as none. + let mut d = vec![(0, V::Int(font)), (1, V::Small(num(st.size, 12.0) / scale))]; + match st.leading { + Some(l) if l.is_finite() && l > 0.0 => d.extend([(4, V::Bool(false)), (5, V::Small(l / scale))]), + _ => d.push((4, V::Bool(true))), + } + d.extend([ + (6, V::Small(num(st.h_scale, 100.0) / 100.0)), + (7, V::Small(num(st.v_scale, 100.0) / 100.0)), + // Tracking is a whole number of thousandths of an em. + (8, V::Int(num(st.tracking, 0.0).round() as i64)), + (9, real(num(st.baseline_shift, 0.0) / scale)), + ]); + let caps = if st.all_caps { + 2 + } else if st.small_caps.is_some() { + 1 + } else { + 0 + }; + d.push((12, V::Int(caps))); + d.push((35, V::Int(baseline_direction(st)))); + let fill = solid(&st.fill).flatten(); + // A stroke of no width keeps its paint. + let stroke = solid(&st.stroke).flatten(); + if let Some(c) = &fill { + d.push((53, paint(c))); + } + if let Some(c) = &stroke { + d.push((54, paint(c))); + } + d.extend([(56, V::Bool(fill.is_some())), (57, V::Bool(stroke.is_some()))]); + if stroke.is_some() { + d.push((63, V::Small(st.stroke_width / scale))); + } + dict(d) + } + + /// The paragraph attributes of `p` at `scale`, as the reader's `Texts::para` reads them. + fn para_features(p: &ParaStyle, scale: f64) -> V { + let rtl = p.direction == Some(ParaDirection::RightToLeft); + // A right-to-left paragraph's left and right alignments are each other's. + let justify = match p.justify { + // Auto: the start of the paragraph's direction. + Justify::Auto => 0, + Justify::Left if rtl => 1, + Justify::Right if rtl => 0, + Justify::Left => 0, + Justify::Right => 1, + Justify::Center => 2, + Justify::JustifyLeft => 3, + Justify::JustifyRight => 4, + Justify::JustifyCenter => 5, + Justify::JustifyAll => 6, + }; + let len = |v: f64| real(if v.is_finite() { v / scale } else { 0.0 }); + let mut d = vec![ + (0, V::Int(justify)), + (1, len(p.first_line_indent)), + (2, len(p.left_indent)), + (3, len(p.right_indent)), + (4, len(p.space_before)), + (5, len(p.space_after)), + (9, V::Bool(p.hyphenate)), + ]; + if rtl { + d.push((33, V::Int(1))); + } + dict(d) + } + + /// The story of type `t`: its characters, runs and the frames `frames` (indices into the + /// frame set). `scale`: document points to a unit of the text document. + fn story(&mut self, t: &TextObject, frames: &[usize], scale: f64) -> usize { + let mut text = String::new(); + let mut char_runs = vec![]; + for r in &t.runs { + let piece: String = r + .text + .chars() + .map(|c| match c { + '\n' => '\r', + '\u{2028}' => '\u{3}', + c => c, + }) + .collect(); + let n = piece.chars().count(); + if n == 0 { + continue; + } + text.push_str(&piece); + let features = self.char_features(&r.style, scale); + char_runs.push((features, n)); + } + // Every paragraph ends in `\r`, the last one too; the last run takes it. + text.push('\r'); + match char_runs.last_mut() { + Some(last) => last.1 += 1, + None => { + let features = self.char_features(&CharStyle::default(), scale); + char_runs.push((features, 1)); + } + } + let paras: Vec<(V, usize)> = + text.split_inclusive('\r').enumerate().map(|(i, p)| (Self::para_features(t.para_at(i), scale), p.chars().count())).collect(); + let run = |features: V, n: usize, para: bool| { + let sheet = if para { + dict(vec![(0, V::Str(String::new())), (5, features), (6, V::Int(0))]) + } else { + dict(vec![(0, V::Str(String::new())), (5, V::Int(0)), (6, features)]) + }; + dict(vec![(0, dict(vec![(0, sheet)])), (1, V::Int(n as i64))]) + }; + let para_runs: Vec = paras.into_iter().map(|(f, n)| run(f, n, true)).collect(); + let char_runs: Vec = char_runs.into_iter().map(|(f, n)| run(f, n, false)).collect(); + let model = dict(vec![ + (0, V::Str(text)), + (5, dict(vec![(0, V::List(para_runs))])), + (6, dict(vec![(0, V::List(char_runs))])), + (10, dict(vec![(0, V::Int(4)), (2, V::Bool(true))])), + ]); + let view = dict(vec![(0, V::List(frames.iter().map(|f| dict(vec![(0, V::Int(*f as i64))])).collect()))]); + self.stories.push(dict(vec![(0, model), (1, view)])); + self.stories.len() - 1 + } + + /// The frame of type `t`, `canvas` taking the document onto the canvas (y down) and `scale` + /// being document points to a unit there. Point type's frame is its point and, unless it is + /// neither turned nor scaled, the matrix of its type round that point (scale taken out). + fn frame(&mut self, t: &TextObject, canvas: Affine, scale: f64) -> usize { + let mut data = vec![]; + let mut f = vec![]; + let vertical = t.vertical.then_some((1, V::Int(2))); + let segs = |path: &PathData| -> Vec { + segments(path) + .unwrap_or_default() + .iter() + .flat_map(|s| { + let p = |x: f64, y: f64| canvas * Point::new(x, y); + let (a, b, c, d) = (p(s[0], s[1]), p(s[2], s[3]), p(s[4], s[5]), p(s[6], s[7])); + [a.x, a.y, b.x, b.y, c.x, c.y, d.x, d.y] + }) + .collect() + }; + match &t.kind { + TextKind::Point => { + let at = canvas * Point::new(t.xf.as_coeffs()[4], t.xf.as_coeffs()[5]); + f.push((0, reals(&[at.x, at.y]))); + data.extend(vertical); + let [a, b, c, d, ..] = t.xf.as_coeffs(); + let s = (a * d - b * c).abs().sqrt(); + let (a, b, c, d) = (a / s, b / s, c / s, d / s); + if [a - 1.0, b, c, d - 1.0].iter().any(|v| v.abs() > 1e-9) { + // Round the point: it stays where it is. + let (e, g) = (at.x - (a * at.x + c * at.y), at.y - (b * at.x + d * at.y)); + let mut m = fines(&[a, b, c, d]); + if let V::List(l) = &mut m { + l.extend([V::Real(e), V::Real(g)]); + } + data.push((2, m)); + } + } + TextKind::Area { .. } => { + f.push((1, dict(vec![(0, reals(&shape(t).map(|p| segs(&p)).unwrap_or_default()))]))); + data.push((0, V::Int(1))); + data.extend(vertical); + let o = &t.area; + data.extend([(3, V::Int(o.rows.max(1) as i64)), (4, V::Int(o.columns.max(1) as i64))]); + data.extend([(7, real(o.row_gutter.unwrap_or(o.gutter) / scale)), (8, real(o.gutter / scale))]); + let kind = match o.first_baseline { + FirstBaseline::Ascent => None, + FirstBaseline::Fixed => Some(0), + FirstBaseline::CapHeight => Some(2), + FirstBaseline::Leading => Some(3), + FirstBaseline::XHeight => Some(4), + }; + if let Some(k) = kind { + data.push((10, dict(vec![(0, V::Int(k)), (1, real(o.first_baseline_min / scale))]))); + } + } + TextKind::OnPath { .. } => { + let path = shape(t).unwrap_or_else(|| PathData::new(vec![])); + let doc_segs = segments(&path).unwrap_or_default(); + f.push((1, dict(vec![(0, reals(&segs(&path)))]))); + data.push((0, V::Int(2))); + data.extend(vertical); + let (start, end) = t.kind.path_span().unwrap_or((0.0, 1.0)); + let n = doc_segs.len() as f64; + let s = place_on(&doc_segs, start); + // Round a closed path the end is the start plus the run, past the last segment when + // the run passes the path's start. + let e = if closed(&doc_segs) { + let run = (end - start).clamp(0.0, 1.0); + if run >= 1.0 - 1e-9 { s + n } else { place_on(&doc_segs, end.rem_euclid(1.0)) } + } else { + place_on(&doc_segs, end) + }; + data.push((6, reals(&[s, e]))); + } + } + f.push((2, dict(data))); + self.frames.push(dict(f)); + self.frames.len() - 1 + } + + /// Room for a story of type `t` named by `frames` text objects, within what the reader reads + /// of a story and of all the text objects' stories together: taken when there is. + fn room(&mut self, t: &TextObject, frames: usize) -> bool { + // The story as written: `\x03` (one byte) for a forced line break, and its last `\r`. + let len: usize = t.runs.iter().flat_map(|r| r.text.chars()).map(|c| if c == '\u{2028}' { 1 } else { c.len_utf8() }).sum::() + 1; + let total = self.text_bytes.saturating_add(len.saturating_mul(frames)); + let fits = len <= crate::import::MAX_STORY && frames <= crate::import::MAX_FRAMES && total <= crate::import::MAX_TEXT; + if fits { + self.text_bytes = total; + } + fits + } + + /// Type `t` as a story of one frame, `canvas` taking the document onto the canvas; its story + /// index, `None` past what the reader reads ([`Self::room`]). Lengths are written in document + /// points: a large canvas document is written at its scale already, and the reader scales the + /// text document's lengths with the art. Type that is scaled has its scale taken out of its + /// frame's matrix, or put into its frame or path, and put into its lengths. + pub(in crate::ai_editing) fn add(&mut self, t: &TextObject, canvas: Affine) -> Option { + let mark = self.mark(); + if !self.room(t, 1) { + return None; + } + let scale = story_scale(t); + let frame = self.frame(t, canvas, scale); + let story = self.story(t, &[frame], scale); + self.fits(mark).then_some(story) + } + + /// Where the frames, stories and fonts written so far end, and the bytes of the document they + /// make. + fn mark(&self) -> (usize, usize, usize, usize, usize) { + (self.frames.len(), self.stories.len(), self.doc_bytes, self.text_bytes, self.fonts.len()) + } + + /// Whether the frames and stories written since `mark` keep the text document within what the + /// reader reads of it (its ASCII85, a quarter of the bytes it decodes, with room for the + /// resources and settings); when they don't, they are taken out again. + fn fits(&mut self, (frames, stories, bytes, text, fonts_before): (usize, usize, usize, usize, usize)) -> bool { + // Room for the fonts, sheets and settings: bytes, and values. + const RESERVE: usize = 1 << 20; + const RESERVE_VALUES: usize = 1 << 16; + let (mut added, mut values) = (0, 0); + for v in self.frames.iter().skip(frames).chain(self.stories.iter().skip(stories)) { + let mut out = vec![]; + v.write(&mut out); + added += out.len() + 1; + values += v.count(); + } + let total = bytes.saturating_add(added); + let total_values = self.doc_values.saturating_add(values); + // The font set: each name in UTF-16 with its dictionary round it. + let fonts: usize = self.fonts.iter().map(|(n, _)| n.encode_utf16().count() * 2 + 64).sum(); + // ASCII85 writes five characters for every four bytes. + if total.saturating_add(RESERVE).saturating_add(fonts).saturating_mul(5) / 4 <= crate::import::MAX_TEXT_DOCUMENT / 4 + && total_values.saturating_add(RESERVE_VALUES) <= crate::import::MAX_TEXT_VALUES + { + (self.doc_bytes, self.doc_values) = (total, total_values); + return true; + } + self.frames.truncate(frames); + self.stories.truncate(stories); + // The fonts only the stories taken out named. + self.fonts.truncate(fonts_before); + self.text_bytes = text; + false + } + + /// The story and frame text object `id` of a thread is written as, planning the thread + /// `thread` (its frames in order, all area type the document holds, the first holding the + /// story) the first time one of its frames is written. `None` when the thread can't be written + /// as one story: `writable` says which frames are written where type can be text (every frame + /// of the thread must be). + pub(in crate::ai_editing) fn thread( + &mut self, + doc: &Document, + thread: &[NodeId], + id: NodeId, + canvas: Affine, + writable: &dyn Fn(NodeId) -> bool, + ) -> Option<(usize, usize)> { + let first = *thread.first()?; + if self.planned.insert(first) { + let members: Option> = thread.iter().map(|i| doc.node(*i)).collect(); + // The first frame holds the story; the others hold no text of their own. + // The frames of a story share one orientation (the reader reads no other). + let vertical = members.as_ref().and_then(|m| m.first()).is_some_and(|n| matches!(&n.kind, NodeKind::Text(t) if t.vertical)); + // The story has one scale for its lengths, so its frames share it. + let scale = match members.as_ref().and_then(|m| m.first()).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => story_scale(t), + _ => 1.0, + }; + let area = |n: &&Node| match &n.kind { + NodeKind::Text(t) => { + matches!(t.kind, TextKind::Area { .. }) + && t.vertical == vertical + && writable(n.id) + && t.wrap.is_empty() + && plain(n) + && t.ruby.is_empty() + && runs_held(t) + && (story_scale(t) / scale - 1.0).abs() <= 1e-9 + && within_reader(t, scale) + && closed_frame(t) + } + _ => false, + }; + let ok = members.as_ref().is_some_and(|m| m.len() > 1 && m.iter().all(area)); + if let (true, Some(members)) = (ok, members) { + let texts: Vec<&TextObject> = + members.iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(t.as_ref()) } else { None }).collect(); + let (whole, split_differs) = joined(&texts)?; + let mark = self.mark(); + if !whole.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace())) || !self.room(&whole, texts.len()) { + return None; + } + let lost = split_differs || texts.iter().any(|t| loses(t)); + let frames: Vec = texts.iter().map(|t| self.frame(t, canvas, scale)).collect(); + let story = self.story(&whole, &frames, scale); + if !self.fits(mark) { + return None; + } + self.lost |= lost; + for (k, i) in thread.iter().enumerate() { + self.threaded.insert(*i, (story, k)); + } + } + } + self.threaded.get(&id).copied() + } + + /// Whether a thread written since the last call has attributes the text document leaves out. + pub(in crate::ai_editing) fn take_lost(&mut self) -> bool { + std::mem::take(&mut self.lost) + } + + /// The text document as its section of the program: `%AI11_BeginTextDocument`, the ASCII85 of + /// the document on comment lines, `%AI11_EndTextDocument`. `doc` gives the text settings. + pub(in crate::ai_editing) fn section(&self, doc: &Document) -> String { + let mut bytes = vec![]; + let root: Vec<(u32, V)> = vec![(98, dict(vec![(0, V::Int(i64::from(STREAM_VERSION)))])), (0, self.resources()), (1, self.objects(doc))]; + for (i, (k, v)) in root.iter().enumerate() { + if i > 0 { + bytes.push(b' '); + } + let _ = write!(Bytes(&mut bytes), "/{k} "); + v.write(&mut bytes); + } + let packed: String = ps::ascii85(&bytes).chars().filter(|c| !c.is_whitespace()).collect(); + let mut s = String::from("%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n"); + // Each line starts with `%`, no line's data starts with `_` (a `%_` line is content), and the + // end marker `~>` stays on one line (the reader looks for it before it joins the lines). + let mut col = 0; + s.push('%'); + for ch in packed.chars() { + if col >= LINE && ch != '_' && !(ch == '>' && s.ends_with('~')) { + s.push_str("\n%"); + col = 0; + } + s.push(ch); + col += 1; + } + s.push_str("\n;\n%AI11_EndTextDocument\n"); + s + } + + fn resources(&self) -> V { + let mut fonts: Vec = self + .fonts + .iter() + .map(|(name, truetype)| { + dict(vec![(99, V::Name("CoolTypeFont")), (0, dict(vec![(0, V::Str(name.clone())), (2, V::Int(i64::from(*truetype)))]))]) + }) + .collect(); + fonts.push(dict(vec![(99, V::Name("CoolTypeFont")), (0, dict(vec![(0, V::Str(HIDDEN_GLYPH_FONT.into())), (2, V::Int(0))]))])); + let normal_char = dict(vec![(0, V::Str("[Normal Character Style]".into())), (6, Self::normal_char())]); + let normal_para = dict(vec![(0, V::Str("[Normal Paragraph Style]".into())), (5, Self::normal_para())]); + let empty = || set(vec![], false); + dict(vec![ + (1, set(fonts, true)), + (2, empty()), + (3, empty()), + (4, empty()), + (5, set(vec![normal_char], true)), + (6, set(vec![normal_para], true)), + (8, set(self.frames.iter().map(clone_v).collect(), false)), + (9, empty()), + ]) + } + + /// The character attributes stories start from. + fn normal_char() -> V { + dict(vec![ + (0, V::Int(0)), + (1, real(12.0)), + (4, V::Bool(true)), + (6, real(1.0)), + (7, real(1.0)), + (8, real(0.0)), + (9, real(0.0)), + (12, V::Int(0)), + // Every run writes its own key 35, so this only sets where new type starts: Standard (1). + (35, V::Int(1)), + (53, paint(&Color::gray(1.0))), + (56, V::Bool(true)), + (57, V::Bool(false)), + (63, real(1.0)), + ]) + } + + /// The paragraph attributes stories start from. + fn normal_para() -> V { + Self::para_features(&ParaStyle::default(), 1.0) + } + + fn objects(&self, doc: &Document) -> V { + let s = &doc.setup; + let hidden = (self.fonts.len()) as i64; + let mapping = V::List(HIDDEN_GLYPHS.iter().map(|(c, g)| dict(vec![(0, V::Str((*c).into())), (1, V::Str((*g).into()))])).collect()); + let q = &s.quotes; + let quotes = dict(vec![ + (0, V::Int(0)), + (1, V::Str(q.double[0].to_string())), + (2, V::Str(q.double[1].to_string())), + (3, V::Str(q.single[0].to_string())), + (4, V::Str(q.single[1].to_string())), + ]); + let pct = |v: f64| real(if v.is_finite() { v / 100.0 } else { 0.0 }); + let settings = dict(vec![ + (0, dict(vec![(0, V::Int(hidden)), (1, mapping)])), + (1, V::Int(0)), + (2, V::Int(0)), + (3, pct(s.superscript.size)), + (4, pct(s.superscript.position)), + (5, pct(s.subscript.size)), + (6, pct(s.subscript.position)), + (7, pct(s.small_caps_size)), + (8, V::Bool(s.typographers_quotes)), + (9, V::List(vec![quotes])), + (11, V::Int(6)), + (16, V::Bool(true)), + (17, V::Int(0)), + ]); + dict(vec![(0, settings), (1, V::List(self.stories.iter().map(clone_v).collect())), (2, Self::normal_char()), (3, Self::normal_para())]) + } +} + +/// A copy of `v`. +fn clone_v(v: &V) -> V { + match v { + V::Int(n) => V::Int(*n), + V::Real(r) => V::Real(*r), + V::Fine(r) => V::Fine(*r), + V::Small(r) => V::Small(*r), + V::Bool(b) => V::Bool(*b), + V::Str(s) => V::Str(s.clone()), + V::Name(n) => V::Name(n), + V::List(l) => V::List(l.iter().map(clone_v).collect()), + V::Dict(d) => V::Dict(d.iter().map(|(k, v)| (*k, clone_v(v))).collect()), + } +} + +/// The text object stub of story `story`, frame `frame`: `/AI11Text :`, `/FreeUndo`, `/FrameIndex`, +/// `/StoryIndex`, for area type and type on a path the frame's path (`/Art :`, `X=`, the path in +/// art space through `to_art`, `X+`, `; /ConfiningPath ,`), `/TextAntialiasing`, `;`. +pub(in crate::ai_editing) fn stub(s: &mut String, story: usize, frame: usize, t: &TextObject, to_art: Affine) { + let _ = writeln!(s, "/AI11Text :\n0 /FreeUndo ,\n{frame} /FrameIndex ,\n{story} /StoryIndex ,"); + let area = matches!(t.kind, TextKind::Area { .. }); + if let Some(path) = shape(t) { + s.push_str("/Art :\nX=\n"); + for sp in path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()) { + crate::ai_ops::subpath(s, to_art, sp); + s.push_str(if sp.closed || area { "n\n" } else { "N\n" }); + } + s.push_str("X+\n; /ConfiningPath ,\n"); + } + s.push_str("2 /TextAntialiasing ,\n;\n"); +} diff --git a/crates/eps/src/ai_editing/writer/variables.rs b/crates/eps/src/ai_editing/writer/variables.rs new file mode 100644 index 0000000000..b714b7ecd2 --- /dev/null +++ b/crates/eps/src/ai_editing/writer/variables.rs @@ -0,0 +1,372 @@ +//! The variable library: the document's variables, data sets and the objects bound to them, as XML +//! nodes of the `/Document` dictionary (see [`crate::ai_editing`] for the form). + +use std::collections::HashSet; +use std::fmt::Write; + +use vectorcraft_doc::{DataValue, Node, NodeId, NodeKind, VariableKind}; + +use super::Writer; +use crate::ps; + +pub(in crate::ai_editing) const BINDINGS: &str = "variable bindings to layers, to type written as outlines, to graphs, and to linked images written as other objects are left out of the editing data for other apps"; +pub(in crate::ai_editing) const VALUES: &str = "data set values of graphs, values that don't fit their variable, linked files that aren't absolute paths or that would read back as other paths, and values of variables whose names have a colon are left out of the editing data for other apps"; +pub(in crate::ai_editing) const ACTIVE: &str = + "the data set shown is left out of the editing data for other apps when it isn't one of the data sets written"; + +pub(in crate::ai_editing) const LIMITS: &str = "variables and data sets whose names are empty, repeated, longer than 255 characters or start or end with white space, variables past 256, data sets past 1,000, bindings past 100,000, bindings to objects whose XML ids are longer than 255 characters, values past 200,000 text lines and values in all, and names and values past 8,388,608 bytes in all are left out of the editing data for other apps"; + +/// The most bytes of a string literal on one line; a longer string is written across lines. +const LITERAL: usize = 64; +/// The reader's caps on a variable library: the variables, bindings and data sets it keeps, the +/// characters of a name and of an object's XML id, and the bytes of the names (a binding's variable name and +/// object id) and values it keeps. +const MAX_VARIABLES: usize = 256; +const MAX_BINDINGS: usize = 100_000; +const MAX_DATASETS: usize = 1_000; +const MAX_ID: usize = 255; +const MAX_BYTES: usize = 8 << 20; +/// The most XML nodes the data sets' values are written with: a value's element, and a text value's +/// `p` element and text for each line. +const MAX_VALUE_NODES: usize = 200_000; + +/// The bytes of names and values written so far, as the reader counts them, the XML nodes of the +/// values, and whether anything was left out past the caps. +#[derive(Default)] +struct Budget { + bytes: usize, + nodes: usize, + past: bool, +} + +impl Budget { + /// Whether `len` more bytes fit in [`MAX_BYTES`] (they are then counted). + fn keep(&mut self, len: usize) -> bool { + self.keep_value(len, 0) + } + + /// Whether a value of `len` bytes written with `nodes` XML nodes fits in [`MAX_BYTES`] and + /// [`MAX_VALUE_NODES`] (it is then counted). + fn keep_value(&mut self, len: usize, nodes: usize) -> bool { + let fits = self.bytes.saturating_add(len) <= MAX_BYTES && self.nodes.saturating_add(nodes) <= MAX_VALUE_NODES; + if fits { + self.bytes += len; + self.nodes += nodes; + } + fits + } +} + +/// The value of an XML node's entry, with the type it is written with. +#[derive(Clone, Copy)] +enum Value<'a> { + /// A `/String`. + Str(&'a str), + /// A `/UnicodeString`. + Unicode(&'a str), + /// A `/Bool`. + Bool(bool), + /// An object's XML id, `/XMLUIDREF`. + Uid(&'a str), +} + +/// `s` as string literals on `%_` lines, at most [`LITERAL`] bytes each, the first line's `%_` +/// included and the last line left open for what follows it. +fn literals(s: &str) -> String { + let mut parts = vec![]; + let mut start = 0; + for (at, c) in s.char_indices() { + if at + c.len_utf8() - start > LITERAL { + parts.push(&s[start..at]); + start = at; + } + } + parts.push(&s[start..]); + parts.iter().map(|p| format!("%_{}", ps::bytes(p.as_bytes()))).collect::>().join("\n") +} + +/// `v` written before an entry's key, from the start of its line. +fn value(v: Value) -> String { + match v { + Value::Str(s) => format!("{} /String", literals(s)), + Value::Unicode(s) => format!("{} /UnicodeString", literals(s)), + Value::Bool(b) => format!("%_{} /Bool", u8::from(b)), + Value::Uid(id) => format!("%_/XMLUIDREF : {} ;", ps::bytes(id.as_bytes())), + } +} + +/// An XML node (`/XMLNode`) up to the `;` that closes it: its name, its value, its type `kind` (1 an +/// element, 2 an attribute, 3 text, 9 the document), its children (an array, each closed as an item) +/// and its attribute nodes (a dictionary, each under its name). +fn node(kind: u8, name: &str, v: Value, attributes: &[(&str, Value)], children: &[String]) -> String { + let mut s = format!( + "%_/XMLNode :\n{} (xmlnode-nodename) ,\n{} (xmlnode-nodevalue) ,\n%_{kind} /Int (xmlnode-nodetype) ,\n%_/Array :\n", + value(Value::Str(name)), + value(v) + ); + for c in children { + s.push_str(c); + s.push_str("%_; ,\n"); + } + s.push_str("%_; (xmlnode-children) ,\n%_/Dictionary :\n"); + for (k, v) in attributes { + s.push_str(&node(2, k, *v, &[], &[])); + let _ = writeln!(s, "%_; {} ,", ps::bytes(k.as_bytes())); + } + s.push_str("%_; (xmlnode-attributes) ,\n"); + s +} + +/// An element `name` with `attributes` and `children`, up to the `;` that closes it. +fn element(name: &str, attributes: &[(&str, Value)], children: &[String]) -> String { + node(1, name, Value::Str(""), attributes, children) +} + +/// A text node (`#text`) holding `v`, up to the `;` that closes it. +fn text(v: Value) -> String { + node(3, "#text", v, &[], &[]) +} + +/// A linked file's path as a data set holds it: a path from the root (`/…`) as a `file://` URL +/// (`file:///` and the path, with `%`, `#`, `?`, white space, control characters and bytes outside ASCII +/// escaped as `%XX`), another absolute path (a drive's, or a network path) as it is. `None` for a +/// path that isn't absolute, for the root alone (`/`), for a path from the root whose first part +/// starts like a drive (`/C:…`, which the reader reads as the drive's path), and for one written as +/// it is with white space at either end. +fn file_value(path: &str) -> Option { + // A drive's path from its root (`C:\…`, `C:/…`); `C:name` is relative to the drive's folder. + let drive = matches!(path.as_bytes(), [l, b':', b'\\' | b'/', ..] if l.is_ascii_alphabetic()); + if path.starts_with('/') && !path.starts_with("//") { + let rest = &path.as_bytes()[1..]; + if rest.is_empty() || matches!(rest, [l, b':', ..] if l.is_ascii_alphabetic()) { + return None; + } + let mut url = String::from("file:///"); + for &b in path.as_bytes() { + if matches!(b, b'%' | b'#' | b'?') || !(0x21..=0x7e).contains(&b) { + let _ = write!(url, "%{b:02X}"); + } else { + url.push(char::from(b)); + } + } + return Some(url); + } + // The reader takes white space off both ends of a path written as it is. + let trimmed = path.trim_matches([' ', '\t', '\n', '\r']) == path; + (trimmed && path.len() > 1 && (path.starts_with('/') || path.starts_with("\\\\") || drive)).then(|| path.to_string()) +} + +/// Whether the reader reads `name` as a variable's or a data set's name as it is: not empty, at most +/// [`MAX_ID`] characters, and without white space at either end. +fn readable_name(name: &str) -> bool { + !name.is_empty() && name.trim() == name && name.chars().count() <= MAX_ID +} + +impl Writer<'_> { + /// The variables `n` is bound to that its XML id is written for: visibility variables, image + /// variables when `n` was written as a placed file (`placed`, see [`Self::placed`]), and text + /// variables when `n` was written as type (`typed`, see [`Self::typed`]). Only objects of the + /// document's own tree are bound, not copies of them (symbol art, live objects' art, opacity + /// masks' art, pattern tiles). + /// The bindings left out are reported by [`Self::variable_library`]. + pub(super) fn bound_variables(&self, n: &Node, placed: bool, typed: bool) -> Vec { + let doc = self.doc; + let Some(names) = doc.variables.bindings.get(&n.id) else { return vec![] }; + if self.nest > 0 || self.hidden > 0 || !doc.node(n.id).is_some_and(|d| std::ptr::eq(d, n)) { + return vec![]; + } + let fits = |name: &&String| match doc.variables.variable(name).map(|v| v.kind) { + Some(VariableKind::Visibility) => true, + Some(VariableKind::Image) => placed && matches!(n.kind, NodeKind::Image(_)), + Some(VariableKind::Text) => typed && matches!(n.kind, NodeKind::Text(_)), + _ => false, + }; + names.iter().filter(fits).cloned().collect() + } + + /// The `#document` entry of the `/Document` dictionary's `/Recorded` part that holds the + /// variable library, on `%_` lines: nothing when the document has no variables or data sets. + pub(in crate::ai_editing) fn variable_library(&mut self) -> String { + let doc = self.doc; + let vars = &doc.variables; + if vars.variables.is_empty() && vars.datasets.is_empty() && !vars.locked { + return String::new(); + } + // Bindings not written: to layers, to type written as outlines, to graphs, and to objects + // not written as themselves. Bindings to objects no longer in the document have nothing to + // write. + let pairs: HashSet<(NodeId, &str)> = self.bound.iter().flat_map(|(n, _, names)| names.iter().map(|name| (*n, name.as_str()))).collect(); + let written = |id: &NodeId, name: &String| pairs.contains(&(*id, name.as_str())); + let kind = |name: &str| vars.variable(name).map(|v| v.kind); + let missing = vars.bindings.iter().any(|(id, names)| { + doc.node(*id).is_some() && names.iter().any(|name| kind(name).is_some_and(|k| k != VariableKind::Unknown) && !written(id, name)) + }); + if missing { + self.warn(BINDINGS); + } + // What the reader keeps: names it doesn't read, and names, bindings and values past its + // caps, are left out. + let mut budget = Budget::default(); + let mut kept: Vec<&vectorcraft_doc::Variable> = vec![]; + for v in &vars.variables { + let new = readable_name(&v.name) && !kept.iter().any(|k| k.name == v.name); + if new && kept.len() < MAX_VARIABLES && budget.keep(v.name.len()) { + kept.push(v); + } else { + budget.past = true; + } + } + let mut declared = vec![]; + let mut bindings = 0usize; + for v in &kept { + let mut attributes = vec![]; + let kind = match v.kind { + VariableKind::Text => Some(("textcontent", "&ns_flows;")), + VariableKind::Visibility => Some(("visibility", "&ns_vars;")), + VariableKind::Image => Some(("fileref", "&ns_vars;")), + VariableKind::Graph => Some(("graphdata", "&ns_vars;")), + VariableKind::Unknown => None, + }; + if let Some((t, category)) = kind { + attributes.push(("trait", Value::Str(t))); + attributes.push(("category", Value::Str(category))); + } + attributes.push(("varName", Value::Unicode(&v.name))); + // A variable bound to several objects is declared once for each. + let objects = self.bound.iter().filter(|(_, _, names)| names.contains(&v.name)).map(|(_, id, _)| id.as_str()); + let mut written = 0; + for id in objects { + if bindings >= MAX_BINDINGS || id.chars().count() > MAX_ID || !budget.keep(v.name.len().saturating_add(id.len())) { + budget.past = true; + continue; + } + bindings += 1; + written += 1; + let mut with = attributes.clone(); + with.push(("docRef", Value::Uid(id))); + declared.push(element("variable", &with, &[])); + } + if written == 0 { + declared.push(element("variable", &attributes, &[])); + } + } + let mut left_out = false; + let mut rows = vec![]; + let mut row_names: Vec<&str> = vec![]; + for ds in &vars.datasets { + let new = readable_name(&ds.name) && !row_names.contains(&ds.name.as_str()); + if !new || rows.len() >= MAX_DATASETS || !budget.keep(ds.name.len()) { + budget.past = true; + continue; + } + let mut values = vec![]; + for (name, v) in &ds.values { + let Some(kind) = kept.iter().find(|k| &k.name == name).map(|k| k.kind) else { + // A value of a variable left out, or of none. + left_out |= vars.variable(name).is_none(); + continue; + }; + // The value's bytes as the reader counts them, and the nodes it is written with. + let (len, nodes) = match (v, kind) { + _ if name.contains(':') => { + left_out = true; + continue; + } + (DataValue::Text(t), VariableKind::Text) => { + let lines = t.bytes().filter(|b| *b == b'\n').count() + 1; + (t.len(), 1 + 2 * lines) + } + (DataValue::Visible(_), VariableKind::Visibility) => (1, 2), + (DataValue::Image(path), VariableKind::Image) if file_value(path).is_some() => (path.len(), 2), + _ => { + left_out = true; + continue; + } + }; + if !budget.keep_value(len, nodes) { + budget.past = true; + continue; + } + let children = match v { + DataValue::Text(t) => t + .split('\n') + .map(|line| { + let words = if line.is_empty() { vec![] } else { vec![text(Value::Unicode(line))] }; + element("p", &[], &words) + }) + .collect(), + DataValue::Visible(show) => vec![text(Value::Bool(*show))], + DataValue::Image(path) => file_value(path).map(|f| vec![text(Value::Unicode(&f))]).unwrap_or_default(), + DataValue::Graph(_) => vec![], + }; + values.push(element(name, &[], &children)); + } + rows.push(element("v:sampleDataSet", &[("dataSetName", Value::Unicode(&ds.name))], &values)); + row_names.push(&ds.name); + } + if left_out { + self.warn(VALUES); + } + if budget.past { + self.warn(LIMITS); + } + let mut attributes = vec![]; + // The data set shown, when a data set of that exact name is written. + if let Some(active) = &vars.active_dataset { + if row_names.contains(&active.as_str()) { + attributes.push(("i:activeDataSet", Value::Unicode(active))); + } else { + self.warn(ACTIVE); + } + } + attributes.push(("xmlns", Value::Str("&ns_custom;"))); + attributes.push(("xmlns:v", Value::Str("&ns_vars;"))); + let data_sets = element("v:sampleDataSets", &attributes, &rows); + let locked = if vars.locked { "variableAndTypes" } else { "none" }; + let set = element( + "variableSet", + &[("locked", Value::Str(locked)), ("varSetName", Value::Str("binding1"))], + &[element("variables", &[], &declared), data_sets], + ); + let sets = element("variableSets", &[("xmlns", Value::Str("&ns_vars;"))], &[set]); + let document = node(9, "#document", Value::Str(""), &[], &[element("metadata", &[], &[sets])]); + format!("{document}%_; (#document) ,\n") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paths_from_the_root_are_file_urls() { + assert_eq!(file_value("/Users/a b/100%.png").as_deref(), Some("file:////Users/a%20b/100%25.png")); + assert_eq!(file_value("/tmp/é.png").as_deref(), Some("file:////tmp/%C3%A9.png")); + assert_eq!(file_value("C:\\Art\\pic.png").as_deref(), Some("C:\\Art\\pic.png")); + assert_eq!(file_value("\\\\server\\share\\pic.png").as_deref(), Some("\\\\server\\share\\pic.png")); + assert_eq!(file_value("//server/share/pic.png").as_deref(), Some("//server/share/pic.png")); + assert_eq!(file_value("/a/#1?.png").as_deref(), Some("file:////a/%231%3F.png")); + assert_eq!(file_value("pic.png"), None); + assert_eq!(file_value("C:pic.png"), None); + assert_eq!(file_value("C:\\Art\\pic.png "), None); + assert_eq!(file_value("/tmp/pic.png ").as_deref(), Some("file:////tmp/pic.png%20")); + } + + #[test] + fn paths_the_reader_reads_as_other_paths_are_left_out() { + assert_eq!(file_value("/"), None); + assert_eq!(file_value("/a:b/x.png"), None); + assert_eq!(file_value("/C:/x.png"), None); + assert_eq!(file_value("/1:b/x.png").as_deref(), Some("file:////1:b/x.png")); + assert_eq!(file_value("/ab:c/x.png").as_deref(), Some("file:////ab:c/x.png")); + } + + #[test] + fn long_strings_are_written_across_lines() { + // 140 bytes: two lines of 64 bytes and one of 12. + let s = "é".repeat(70); + let lines = literals(&s); + assert_eq!(lines.lines().count(), 3); + assert!(lines.lines().all(|l| l.starts_with("%_("))); + } +} diff --git a/crates/eps/src/ai_ops.rs b/crates/eps/src/ai_ops.rs new file mode 100644 index 0000000000..a22c94de53 --- /dev/null +++ b/crates/eps/src/ai_ops.rs @@ -0,0 +1,100 @@ +//! Operators the legacy `.ai` writer ([`crate::legacy_ai`]) and the editing data writer +//! ([`crate::ai_editing`]) both write: path points, guides and line style (Adobe Illustrator File +//! Format Specification, version 7.0, §5.3, §5.4 and §6), and the colors they write in place of +//! the paint they can't hold. + +use std::fmt::Write; + +use vectorcraft_color::{Color, Gradient}; +use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer}; +use vectorcraft_geom::{Affine, Anchor, AnchorKind, PathData, Point, SubPath}; + +use crate::ps; + +/// One subpath's points, taken into art space by `xf`: `m`, then a line or curve to each point +/// (lower case: the point is smooth, upper case: a corner, §5.3.2), and for a closed one the +/// segment back to the start, which says whether the start is smooth or a corner (as the +/// specification's examples close paths: the start point again, then the painting operator). +pub(crate) fn subpath(s: &mut String, xf: Affine, sp: &SubPath) { + let Some(first) = sp.anchors.first() else { return }; + let pt = |s: &mut String, p: Point| { + let p = xf * p; + ps::push_nums(s, &[p.x, p.y]); + }; + pt(s, first.p); + s.push_str("m\n"); + let segment = |s: &mut String, a: &Anchor, b: &Anchor| { + let straight = a.h_out == a.p && b.h_in == b.p; + let smooth = b.kind == AnchorKind::Smooth; + if straight { + pt(s, b.p); + s.push_str(if smooth { "l\n" } else { "L\n" }); + } else { + pt(s, a.h_out); + pt(s, b.h_in); + pt(s, b.p); + s.push_str(if smooth { "c\n" } else { "C\n" }); + } + }; + for pair in sp.anchors.windows(2) { + if let [a, b] = pair { + segment(s, a, b); + } + } + if sp.closed + && sp.anchors.len() > 1 + && let Some(last) = sp.anchors.last() + { + segment(s, last, first); + } +} + +/// A guide (§6): for each subpath, `(N) *`, its points, `(N) *`. In `editing` data (see +/// [`crate::ai_editing`]) a subpath is its points and `(N) *` alone, `(n) *` when closed (the +/// painting operator that closes it first). +pub(crate) fn guide(s: &mut String, xf: Affine, path: &PathData, editing: bool) { + for sp in path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()) { + if !editing { + s.push_str("(N) *\n"); + } + subpath(s, xf, sp); + s.push_str(if editing && sp.closed { "(n) *\n" } else { "(N) *\n" }); + } +} + +pub(crate) fn unit(v: f32) -> f32 { + if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } +} + +/// The average colour of a gradient's stops (in RGB). +pub(crate) fn average(g: &Gradient) -> Color { + let n = g.stops.len().max(1) as f32; + let sum = g.stops.iter().map(|s| s.color.to_rgb()).fold([0.0f32; 3], |a, c| [a[0] + c[0], a[1] + c[1], a[2] + c[2]]); + Color::rgb(unit(sum[0] / n), unit(sum[1] / n), unit(sum[2] / n)) +} + +/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`. +pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) { + let cap = match st.cap { + LineCap::Butt => 0, + LineCap::Round => 1, + LineCap::Square => 2, + }; + let join = match st.join { + LineJoin::Miter => 0, + LineJoin::Round => 1, + LineJoin::Bevel => 2, + }; + ps::push_num(s, st.width); + let _ = write!(s, " w {cap} J {join} j "); + ps::push_num(s, if st.miter_limit.is_finite() { st.miter_limit.max(1.0) } else { 10.0 }); + s.push_str(" M ["); + let dash = st.dash.as_ref().filter(|d| d.is_dashed()); + if let Some(d) = dash { + ps::push_nums(s, &d.pattern); + s.pop(); + } + s.push_str("] "); + ps::push_num(s, dash.map_or(0.0, |d| d.offset)); + s.push_str(" d\n"); +} diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 5a7a9b4911..1e0fd01c3f 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -18,7 +18,8 @@ //! `%%Creator`) and these operators: Adobe Illustrator File Format Specification, version 7.0 //! (1998), listed by PRONOM at https://www.nationalarchives.gov.uk/PRONOM/fmt/423. A file in that //! format whose program has its layers (`%AI5_BeginLayer`) comes in through them, as `native` reads -//! an Illustrator EPS's editing copy (#1027). One VectorCraft wrote (its prolog the procedure set +//! an Illustrator EPS's editing copy (#1027), and one without layers (Illustrator 3) comes in +//! through its art put on one layer, as its page when that can't be read. One VectorCraft wrote (its prolog the procedure set //! [`crate::legacy_ai::PROCSET`], which prints its gradients flat and leaves its type out) comes in //! from those layers alone, without its page. //! @@ -43,10 +44,13 @@ mod obj; mod preview; mod shading; mod text; +mod type42; #[cfg(test)] mod tests; #[cfg(test)] +mod tests_composite; +#[cfg(test)] mod tests_fontnames; #[cfg(test)] mod tests_generators; @@ -69,7 +73,12 @@ use graphics::{GState, Out}; use interp::{Fault, Interp}; use obj::PsError; -pub use native::{ai_alone, is_loss, layered_ai}; +pub(crate) use ai::{ + MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, read_art_style, read_style_list, style_moves_with, symbol_art_member, warp_number, +}; +pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES}; +pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; +pub(crate) use native::{MAX_TEXT, scale_document}; pub use text::family_style; /// The page of a PostScript file without a bounding box (US Letter). @@ -266,7 +275,7 @@ pub fn import_trusting(bytes: &[u8], editing_data: bool, trust: bool) -> Result< } let drew = !out.drawn.is_empty(); let why = match (&result, drew) { - (Ok(()), true) if editing_data => return Ok(native::layered(ps, finish(out), trust)), + (Ok(()), true) if editing_data => return Ok(native::layered(ps, finish(out), trust, dsc.illustrator)), (Ok(()), true) => return Ok(finish(out)), (Ok(()), false) => "it draws nothing VectorCraft's PostScript reader can show".to_string(), (Err(e), _) => reason(e, fault.as_ref()), @@ -299,7 +308,8 @@ pub fn import_trusting(bytes: &[u8], editing_data: bool, trust: bool) -> Result< /// The document of what `out` drew: one layer, clipped art in clipping groups (grouped art in /// groups), the spot inks as spot swatches, in CMYK when most process colours were. fn finish(mut out: Out) -> Imported { - let drawn = std::mem::take(&mut out.drawn); + let mut drawn = std::mem::take(&mut out.drawn); + graphics::merge_strips(&mut drawn, &mut out.shadings); let mut children = vectorcraft_doc::clipnest::nest(&mut out.doc, drawn); if !out.shadings.is_empty() { graphics::collapse(&mut children, &out.shadings); diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index b1a2112495..c84f3b4066 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -13,11 +13,13 @@ //! groups, paths, colours, gradients, images) with newer ones (transparency, hidden objects) and //! dictionaries (names, artboards, type). `lex` scans it, `read` builds the document. //! -//! Reading is bounded: the data decompresses to at most [`MAX_DATA`], and the reader caps nesting, +//! Reading is bounded: the data decompresses to at most [`max_data`], and the reader caps nesting, //! objects and points. Anything it doesn't read is an error: the caller opens the file the way it //! did before (the printed page, or the PDF), with a warning saying why. mod blend; +mod brush; +mod envelope; mod frames; mod lex; mod mesh; @@ -32,22 +34,67 @@ use std::io::Read as _; use super::lex::find; use crate::ps; +pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; +#[cfg(test)] +pub(crate) use envelope::MAX_CHECKED; +pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType}; pub(crate) use frames::text_frames; -pub use read::{IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, palette, read, variables}; -pub(crate) use read::{slot_frame, slot_of}; +pub(crate) use paint::MAX_STOPS as MAX_GRADIENT_STOPS; +#[cfg(test)] +pub(crate) use read::with_image_limits; +pub use read::{ + BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles, + palette, read, read_beside, symbols, variables, +}; +pub(crate) use read::{ + MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_style_list, slot_frame, slot_of, style_moves_with, symbol_art_member, +}; + +pub(crate) use read::is_look_slot; +pub(crate) use style::{MAX_LISTED, MAX_LISTED_NAME, warp_number}; #[cfg(test)] mod tests; -/// Largest editing data read, decompressed (bytes). Files with embedded rasters reach 340 MB (a -/// 30 MB poker box template unpacks to 322 MiB), so 64-bit builds read twice the old 256 MiB; a -/// 32-bit address space (wasm) keeps it. -pub const MAX_DATA: u64 = if cfg!(target_pointer_width = "64") { 512 << 20 } else { 256 << 20 }; +/// Least editing data read, decompressed (bytes), whatever the machine: 512 MiB on 64-bit builds (a +/// 30 MB poker box template with embedded rasters unpacks to 322 MiB), 256 MiB in a 32-bit address +/// space (wasm). +pub const MIN_DATA: u64 = if cfg!(target_pointer_width = "64") { 512 << 20 } else { 256 << 20 }; +/// Most editing data read on any machine (bytes). Reading takes about as much memory again as the +/// data (1.1 GB of data with 24 embedded 4096 x 4096 images peaked 1.1 GB above the start). +pub const MAX_DATA: u64 = if cfg!(target_pointer_width = "64") { 2 << 30 } else { 256 << 20 }; + +/// Largest editing data read, decompressed (bytes): an eighth of installed memory, from +/// [`MIN_DATA`] to [`MAX_DATA`], so a file whose embedded rasters unpack past 512 MiB keeps its +/// layers on a machine with room for it (#3510), while a small file that unpacks without end +/// still stops early. +pub fn max_data() -> u64 { + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + *LIMIT.get_or_init(|| data_limit(vectorcraft_render::installed_memory())) +} + +/// [`max_data`] on a machine with `memory` bytes installed (`None`: not known). +fn data_limit(memory: Option) -> u64 { + memory.map_or(MIN_DATA, |m| (m / 8).clamp(MIN_DATA, MAX_DATA)) +} /// Largest Zstandard window accepted (a frame asking for more is damaged data). const MAX_ZSTD_WINDOW: u64 = 64 << 20; /// Most Zstandard frames read (the app writes one). const MAX_FRAMES: usize = 4096; +#[cfg(test)] +thread_local! { + /// How many bytes [`Codec::decode`] has looked at on this thread to find whether another + /// Zstandard frame follows or only zero padding is left. + static PADDING_LOOKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// [`PADDING_LOOKS`] of this thread. +#[cfg(test)] +fn padding_looks() -> u64 { + PADDING_LOOKS.get() +} + const EPS_BEGIN: &[u8] = b"%AI9_PrivateDataBegin"; const EPS_END: &[u8] = b"%AI9_PrivateDataEnd"; @@ -81,13 +128,13 @@ fn eps_section(section: &[u8]) -> Result, String> { } header.extend_from_slice(line); header.extend_from_slice(b"\n"); - if header.len() as u64 > MAX_DATA { + if header.len() as u64 > max_data() { return Err(too_large()); } } let Some(codec) = codec else { // Not compressed: the section is the data, as it is (images' samples are binary). - if section.len() as u64 > MAX_DATA { + if section.len() as u64 > max_data() { return Err(too_large()); } return Ok(section.to_vec()); @@ -96,7 +143,7 @@ fn eps_section(section: &[u8]) -> Result, String> { for line in lines { let body = line.strip_prefix(b"%").unwrap_or(line); text.push_str(std::str::from_utf8(body).map_err(|_| damaged("its ASCII85 encoding"))?); - if text.len() as u64 > MAX_DATA { + if text.len() as u64 > max_data() { return Err(too_large()); } } @@ -105,21 +152,21 @@ fn eps_section(section: &[u8]) -> Result, String> { } let packed = ps::ascii85_decode(&text).ok_or_else(|| damaged("its ASCII85 encoding"))?; let mut data = header; - data.extend(codec.decode(&packed, MAX_DATA.saturating_sub(data.len() as u64))?); + data.extend(codec.decode(&packed, max_data().saturating_sub(data.len() as u64))?); Ok(data) } /// The editing data of a `.ai` file: its `AIPrivateData` streams joined (`raw`), decompressed. The /// compressed data may follow header comments that aren't. pub fn decode_private(raw: &[u8]) -> Result, String> { - if raw.len() as u64 > MAX_DATA { + if raw.len() as u64 > max_data() { return Err(too_large()); } for (marker, codec) in [(&b"%AI24_ZStandard_Data"[..], Codec::Zstd), (b"%AI12_CompressedData", Codec::Zlib)] { if let Some(at) = find(raw, marker) { let (header, body) = raw.split_at(at); let mut data = header.to_vec(); - data.extend(codec.decode(body.get(marker.len()..).unwrap_or_default(), MAX_DATA.saturating_sub(header.len() as u64))?); + data.extend(codec.decode(body.get(marker.len()..).unwrap_or_default(), max_data().saturating_sub(header.len() as u64))?); return Ok(data); } } @@ -141,11 +188,15 @@ impl Codec { flate2::read::ZlibDecoder::new(data).take(max + 1).read_to_end(&mut out).map_err(|_| damaged("its zlib compression"))?; } Codec::Zstd => { - // The data may be several frames one after the other, padded with zeros. - let end = data.iter().rposition(|b| *b != 0).map_or(0, |i| i + 1); - let mut src = data.get(..end).unwrap_or_default(); + // The data may be several frames one after the other, padded with zeros. A frame + // can itself end in a zero byte, so the padding is what is left after the last frame. + let mut src = data; let mut frames = 0usize; - while !src.is_empty() { + while src.iter().any(|b| { + #[cfg(test)] + PADDING_LOOKS.set(PADDING_LOOKS.get().saturating_add(1)); + *b != 0 + }) { frames += 1; if frames > MAX_FRAMES { return Err(damaged("its Zstandard compression")); @@ -172,5 +223,5 @@ fn damaged(what: &str) -> String { } fn too_large() -> String { - format!("it decompresses to more than {} MB", MAX_DATA >> 20) + format!("it decompresses to more than {} MB", max_data() >> 20) } diff --git a/crates/eps/src/import/ai/blend.rs b/crates/eps/src/import/ai/blend.rs index 553ab64b8c..6124c9eeea 100644 --- a/crates/eps/src/import/ai/blend.rs +++ b/crates/eps/src/import/ai/blend.rs @@ -3,27 +3,32 @@ //! What a blend is and does is Illustrator's public documentation: key objects, the spine the //! steps follow, Blend Options' Spacing (Smooth Color, Specified Steps, Specified Distance) and //! Orientation (Align to Page, Align to Path), Replace Spine and Reverse Spine -//! (). +//! (, +//! ). //! //! How the editing data writes one isn't documented. As written in files users sent (used //! locally, never committed): the blend's own art on `%_` lines, a group holding the key objects //! and the spine, each object's `/ArtDictionary` naming its part (`ShapeBlendPathType`: `K` a key, //! `S` the spine) and a key's id (`ShapeBlendPathID`); then the steps drawn, a group on plain //! lines; then `(Adobe Path Blends) 1 0 n XP` and `n` bytes as hex on `%` lines. Those bytes -//! start `DCBA`, version 1; word 10 (little endian) is the number of keys, and the words after it -//! a record per key that starts with the key's id. What the other words mean isn't known, so the -//! spacing and orientation are taken from the steps drawn instead: as many steps as they have -//! between two keys, and whichever orientation lays the blend out as they are drawn. A blend whose -//! parts don't agree, or that doesn't come out as drawn, keeps its drawn steps. +//! start `DCBA`. A blend whose spine was never edited has no spine part: only its keys. +//! +//! The reader reads the words after `DCBA` (little endian) this way. Word 1 is the spacing: 0 is +//! Smooth Color, 1 is Specified Steps and 2 is Specified Distance. For Specified Distance, word 2 +//! is the distance in points, as a 32-bit float. Word 10 is the number of keys, and the words after +//! it are a record of six words per key that starts with the key's id. For Specified Steps, the +//! steps between two keys are counted from the steps drawn. The orientation is taken from the steps +//! drawn: whichever one lays the blend out as they are drawn. A blend whose parts don't agree, +//! whose spacing isn't one of these, or that doesn't come out as drawn, keeps its drawn steps. use std::collections::HashMap; use std::sync::Arc; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::blend::blend_expand; +use vectorcraft_doc::blend::{blend_expand, blend_steps}; use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec}; use vectorcraft_doc::{AppearanceItem, Node, NodeId, NodeKind}; -use vectorcraft_geom::{PathData, Point}; +use vectorcraft_geom::{PathData, Point, SubPath}; /// The plugin that writes blends. pub(super) const PLUGIN: &str = "Adobe Path Blends"; // brand-ok: the plugin name the files use @@ -55,15 +60,40 @@ pub(super) fn hex_bytes(hex: &[u8]) -> Option> { hex.as_chunks::<2>().0.iter().map(|&[a, b]| Some(digit(a)? << 4 | digit(b)?)).collect() } -/// The keys' ids in a blend's record, in its order; `None` for a record that isn't one. -pub(super) fn record_ids(bytes: &[u8]) -> Option> { +/// What a blend's record says: its keys' ids, in its order, and its spacing. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Record { + pub(super) ids: Vec, + /// `None`: Specified Steps, whose steps the reader counts from the drawn ones. + pub(super) spacing: Option, +} + +/// A blend's record, or `None` for a record that isn't one or whose spacing isn't read: an +/// unknown spacing, or a distance that isn't a positive number. +pub(super) fn record(bytes: &[u8]) -> Option { if bytes.get(..4)? != b"DCBA" || bytes.len() > MAX_RECORD { return None; } let words: Vec = bytes.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c)).collect(); - if words.get(1) != Some(&1) { - return None; - } + let spacing = match *words.get(1)? { + 0 => Some(BlendSpacing::SmoothColor), + 1 => None, + 2 => Some(BlendSpacing::Distance(distance(*words.get(2)?)?)), + _ => return None, + }; + let ids = record_ids(&words)?; + Some(Record { ids, spacing }) +} + +/// The distance in a record's word `bits` (a 32-bit float), as the shortest decimal that reads +/// back as that float (2.3 for the float nearest 2.3), or `None` when it isn't a positive number. +fn distance(bits: u32) -> Option { + let d: f64 = f32::from_bits(bits).to_string().parse().ok()?; + (d.is_finite() && d > 0.0).then_some(d) +} + +/// The keys' ids in a blend's record `words`, in its order; `None` when they aren't there. +fn record_ids(words: &[u32]) -> Option> { let count = usize::try_from(*words.get(10)?).ok().filter(|c| (2..=MAX_KEYS).contains(c))?; let rest = words.len().checked_sub(11)?; if rest == 0 || !rest.is_multiple_of(count) { @@ -80,14 +110,15 @@ pub(super) fn record_ids(bytes: &[u8]) -> Option> { } /// The blend `edit` (its key objects and spine, as their dictionaries name them in `roles`) and -/// `drawn` (its steps as the file draws them) make, with the keys of the record `ids`: one live -/// blend, or `None` when they don't agree or it doesn't come out as drawn. +/// `drawn` (its steps as the file draws them) make, with the keys and spacing of `record`: one +/// live blend, or `None` when they don't agree or it doesn't come out as drawn. /// /// `budget`: how many more objects blends may lay out in this import; a blend that would lay out /// more isn't made live (each blend is laid out twice, once per orientation, and checked against /// its drawn steps, so a file of huge blends mustn't stall the import). What it lays out is taken /// from it. -pub(super) fn live_blend(edit: &Node, drawn: &Node, ids: &[String], roles: &Roles, budget: &mut usize) -> Option { +pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Roles, budget: &mut usize) -> Option { + let ids = &record.ids; let parts = edit.children()?; let role = |n: &Arc| roles.get(&n.id); let keys: Vec> = parts.iter().filter(|n| role(n).is_some_and(|(t, _)| t == "K")).cloned().collect(); @@ -106,20 +137,10 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, ids: &[String], roles: &Role if named != listed || named.windows(2).any(|w| w.first() == w.get(1)) { return None; } - // The steps between two keys: the drawn objects that aren't keys, shared out. let drawn: Vec<&Arc> = drawn.children()?.iter().collect(); - let between = (drawn.len().checked_sub(keys.len())?).checked_div(keys.len() - 1)?; - if between == 0 || between > MAX_STEPS || drawn.len() != keys.len() + between * (keys.len() - 1) || drawn.len() > MAX_BLEND_OBJECTS { + if drawn.len() < keys.len() || drawn.len() > MAX_BLEND_OBJECTS { return None; } - // Both orientations are laid out. - let cost = drawn.len().saturating_mul(2); - if cost > *budget { - return None; - } - *budget -= cost; - // The drawn steps' centres and paints, once. - let drawn: Vec<(Point, Fill)> = drawn.iter().map(|d| Some((centre(d)?, fill(d)))).collect::>()?; let keys: Vec> = keys .into_iter() .map(|k| { @@ -128,14 +149,41 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, ids: &[String], roles: &Role Arc::new(k) }) .collect(); - let spine = spine?; + // A blend whose spine was never edited has none written: its spine is the straight lines + // between the keys' centres, in the record's order. + let spine = match spine { + Some(spine) => spine, + None => straight_spine(&keys, ids, roles)?, + }; let key_anchors = on_spine(&keys, &spine)?; - let spacing = BlendSpacing::Steps(u32::try_from(between).ok()?); + let spacing = match record.spacing { + // Specified Steps: the steps between two keys are the drawn objects that aren't keys, + // shared out. + None => { + let between = (drawn.len() - keys.len()).checked_div(keys.len() - 1)?; + BlendSpacing::Steps(u32::try_from(between).ok().filter(|n| (1..=MAX_STEPS as u32).contains(n))?) + } + Some(spacing) => spacing, + }; + // Both orientations are laid out, as many objects as are drawn each. + let cost = drawn.len().saturating_mul(2); + if cost > *budget { + return None; + } + let spec = BlendSpec { spacing, spine: Some(spine), key_anchors, ..BlendSpec::default() }; + // As many objects as the spacing lays out between each pair of keys (the orientation doesn't + // change how many), counted before anything is laid out: as many as are drawn. + if blend_steps(&keys, &spec).into_iter().fold(keys.len(), usize::saturating_add) != drawn.len() { + return None; + } + *budget -= cost; + // The drawn steps' centres and paints, once. + let drawn: Vec<(Point, Fill)> = drawn.iter().map(|d| Some((centre(d)?, fill(d)))).collect::>()?; // The orientation that lays the steps out as drawn, the closest when both do. [BlendOrientation::AlignToPage, BlendOrientation::AlignToPath] .into_iter() .filter_map(|orientation| { - let spec = BlendSpec { spacing, orientation, spine: Some(spine.clone()), key_anchors: key_anchors.clone(), ..BlendSpec::default() }; + let spec = BlendSpec { orientation, ..spec.clone() }; let laid = blend_expand(&keys, &spec); let off = how_far(&laid, &drawn)?; Some((off, spec)) @@ -161,6 +209,20 @@ fn on_spine(keys: &[Arc], spine: &PathData) -> Option> { Some(out) } +/// The straight lines between the centres of `keys`, taken in the order of the record's `ids`: a +/// blend's spine until it is edited or replaced, as [`vectorcraft_doc::blend::blend_spine`] lays +/// out a blend with no spine of its own. +fn straight_spine(keys: &[Arc], ids: &[String], roles: &Roles) -> Option { + let centres = ids + .iter() + .map(|id| { + let key = keys.iter().find(|k| roles.get(&k.id).and_then(|(_, named)| named.as_ref()) == Some(id))?; + centre(key) + }) + .collect::>>()?; + Some(PathData::single(SubPath::polyline(¢res, false))) +} + fn centre(n: &Node) -> Option { n.geometric_bounds().map(|b| b.center()).filter(|p| p.x.is_finite() && p.y.is_finite()) } @@ -242,7 +304,7 @@ fn how_far(laid: &[Node], drawn: &[(Point, Fill)]) -> Option { mod tests { use super::*; - /// Records that aren't one: too short, another magic, another version, key counts out of + /// Records that aren't one: too short, another magic, an unknown spacing, key counts out of /// range or not dividing the rest, ids that aren't letters or digits, and hex digits that /// don't pair up. None of them panics. #[test] @@ -250,7 +312,7 @@ mod tests { let words = |w: &[u32]| w.iter().flat_map(|x| x.to_le_bytes()).collect::>(); let magic = u32::from_le_bytes(*b"DCBA"); let good = words(&[magic, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 'A' as u32, 0, 0, 0, 0, 0, 'B' as u32, 0, 0, 0, 0, 0]); - assert_eq!(record_ids(&good), Some(vec!["A".to_string(), "B".to_string()])); + assert_eq!(record(&good).map(|r| r.ids), Some(vec!["A".to_string(), "B".to_string()])); for bad in [ vec![], b"DCB".to_vec(), @@ -262,7 +324,33 @@ mod tests { words(&[magic, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0x20, 0, 66, 0]), words(&[magic, 1, 0, 0, 0, 0, 0, 0, 0, 0, u32::MAX]), ] { - assert_eq!(record_ids(&bad), None, "{bad:?}"); + assert_eq!(record(&bad), None, "{bad:?}"); + } + } + + /// The spacing at word 1 (0 Smooth Color, 1 Specified Steps, 2 Specified Distance) and, for + /// Specified Distance, the distance at word 2 as a 32-bit float, read as the decimal it was + /// typed as. Specified Steps leaves the steps to be counted from the drawn ones, whatever word + /// 4 holds. An unknown spacing, or a distance that isn't a positive number, isn't read. + #[test] + fn records_say_their_spacing() { + let words = |spacing: u32, distance: f32, steps: u32| { + let magic = u32::from_le_bytes(*b"DCBA"); + [magic, spacing, distance.to_bits(), 0, steps, 0, 0, 0, 0, 0, 2, 'A' as u32, 0, 0, 0, 0, 0, 'B' as u32, 0, 0, 0, 0, 0] + .iter() + .flat_map(|x| x.to_le_bytes()) + .collect::>() + }; + let spacing = |b: Vec| record(&b).map(|r| r.spacing); + assert_eq!(spacing(words(0, 4.0, 254)), Some(Some(BlendSpacing::SmoothColor))); + assert_eq!(spacing(words(1, 50.0, 3)), Some(None)); + assert_eq!(spacing(words(1, 0.0, 0)), Some(None)); + assert_eq!(spacing(words(2, 12.5, 7)), Some(Some(BlendSpacing::Distance(12.5)))); + assert_eq!(spacing(words(2, 2.3, 0)), Some(Some(BlendSpacing::Distance(2.3)))); + assert_eq!(spacing(words(2, 0.1, 0)), Some(Some(BlendSpacing::Distance(0.1)))); + assert_eq!(spacing(words(2, 12345.67, 0)), Some(Some(BlendSpacing::Distance(12345.67)))); + for (kind, distance) in [(2, 0.0), (2, -10.0), (2, f32::NAN), (2, f32::INFINITY), (3, 10.0), (u32::MAX, 10.0)] { + assert_eq!(spacing(words(kind, distance, 7)), None, "spacing {kind}, distance {distance}"); } assert_eq!(hex_bytes(b"4A4"), None); assert_eq!(hex_bytes(b"4G"), None); @@ -276,10 +364,69 @@ mod tests { let edit = Node::new(NodeId(1), NodeKind::Group { children: vec![], clip: false }); let drawn = Node::new(NodeId(2), NodeKind::Group { children: vec![], clip: false }); let mut budget = 1; - assert!(live_blend(&edit, &drawn, &["A".into(), "B".into()], &Roles::new(), &mut budget).is_none()); + let record = Record { ids: vec!["A".into(), "B".into()], spacing: None }; + assert!(live_blend(&edit, &drawn, &record, &Roles::new(), &mut budget).is_none()); assert_eq!(budget, 1); } + /// Two 20 pt keys (`A` at x 0 and `B` at x 100) on a straight spine through their centers, + /// with three 20 pt steps drawn evenly between them: the blend's edit group, its drawn steps + /// and the roles naming its parts. + fn two_keys() -> (Node, Node, Roles) { + let square = |id: u64, x: f64| { + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 40.0, x + 20.0, 60.0)); + Arc::new(Node::path(NodeId(id), path, Default::default())) + }; + let spine = vectorcraft_geom::shapes::line(Point::new(10.0, 50.0), Point::new(110.0, 50.0)); + let spine = Arc::new(Node::path(NodeId(3), spine, Default::default())); + let edit = Node::new(NodeId(10), NodeKind::Group { children: vec![square(1, 0.0), square(2, 100.0), spine], clip: false }); + let steps = (0..5u32).map(|i| square(20 + u64::from(i), f64::from(i) * 25.0)).collect(); + let drawn = Node::new(NodeId(11), NodeKind::Group { children: steps, clip: false }); + let roles = Roles::from([ + (NodeId(1), ("K".to_string(), Some("A".to_string()))), + (NodeId(2), ("K".to_string(), Some("B".to_string()))), + (NodeId(3), ("S".to_string(), None)), + ]); + (edit, drawn, roles) + } + + /// The budget: a blend whose two layouts (one per orientation, five objects each) fit in what + /// is left is made live and takes ten; one that doesn't fit, or whose spacing lays out another + /// number of steps than are drawn, isn't made live and takes nothing. + #[test] + fn a_blend_takes_from_the_budget_only_when_it_is_laid_out() { + let (edit, drawn, roles) = two_keys(); + let steps = Record { ids: vec!["A".into(), "B".into()], spacing: None }; + let mut budget = 10; + assert!(matches!(live_blend(&edit, &drawn, &steps, &roles, &mut budget), Some(NodeKind::Blend { .. }))); + assert_eq!(budget, 0); + let mut budget = 9; + assert!(live_blend(&edit, &drawn, &steps, &roles, &mut budget).is_none()); + assert_eq!(budget, 9, "a blend past the budget takes nothing"); + let nine = Record { spacing: Some(BlendSpacing::Distance(10.0)), ..steps }; + let mut budget = 10; + assert!(live_blend(&edit, &drawn, &nine, &roles, &mut budget).is_none()); + assert_eq!(budget, 10, "a spacing that lays out nine steps where three are drawn takes nothing"); + } + + /// A distance longer than the keys are apart lays out no steps: a blend drawn as its two keys + /// alone comes in live with that distance, and one of Specified Steps drawn that way doesn't. + #[test] + fn a_distance_past_the_keys_lays_out_no_steps() { + let (edit, drawn, roles) = two_keys(); + let NodeKind::Group { children, .. } = &drawn.kind else { panic!("a group") }; + let keys_alone = [children[0].clone(), children[4].clone()]; + let drawn = Node::new(NodeId(11), NodeKind::Group { children: keys_alone.to_vec(), clip: false }); + let far = Record { ids: vec!["A".into(), "B".into()], spacing: Some(BlendSpacing::Distance(150.0)) }; + let mut budget = 10; + let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &far, &roles, &mut budget) else { panic!("a live blend") }; + assert_eq!(spec.spacing, BlendSpacing::Distance(150.0)); + assert_eq!(budget, 6); + let steps = Record { spacing: None, ..far }; + assert!(live_blend(&edit, &drawn, &steps, &roles, &mut budget).is_none()); + assert_eq!(budget, 6); + } + /// Two drawn steps on one laid object don't both match it: each laid object matches one drawn /// one, so a drawing the blend doesn't lay out isn't taken for it. #[test] diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs new file mode 100644 index 0000000000..47fdc34fe2 --- /dev/null +++ b/crates/eps/src/import/ai/brush.rs @@ -0,0 +1,551 @@ +//! Brush definitions (not publicly documented): plug-in objects in the setup, as written in files +//! that users own and sent us, brush library files among them (not presets installed with any +//! other app). +//! +//! - Each object is a `%AI8_BeginPluginObject` section of strings: the plug-in's name, the brush's +//! name, then its parameters, split into strings that `-` continues and `.` ends. +//! - One object, the brush manager's order, has the order of the Brushes panel: its parameters +//! are the plug-in name and brush name of each brush, each one after a `/` and a space. +//! - A Calligraphic brush's parameters are 11 numbers: the first is 1; the diameter, roundness and +//! angle as (low, high) pairs; how the diameter, roundness and angle vary; a last number. The +//! codes follow the order of the Brush Options menu: 0 Fixed, 1 Random, 2 Pressure, 3 Stylus +//! Wheel, 4 Tilt, 5 Bearing, 6 Rotation. A user's 6D Art Pen brushes (#372) vary the diameter +//! with 2, the roundness with 5 and the angle with 6, the angle over a whole turn, as the barrel +//! rotation turns the nib. VectorCraft reads no stylus wheel: 3 is read as Random when the value +//! varies, as an unknown code is. +//! - A path with a Calligraphic brush is a stroke in its art style ([`super::style`]): the filter +//! `(Adobe Calligraphic Brush Tool)`, its stroke's paint and weight (the weight scales the brush: +//! 1 pt draws it at its own size), the brush by name (`/GObjRef : (name) (plug-in) +//! /PluginObject`), and the brush's settings for this path as entries: `Diameter`, `Roundness`, +//! `Angle`, their `…Variation` either side and `…DependsOn` codes, and `AngleRelativeTo` (0 the +//! page). +//! - A path with an Art brush is a stroke in its art style too: the filter +//! `(Adobe ArtOnPath Brush Tool)`, its stroke's paint and weight (the weight scales the art across +//! the path), the brush by name, and its settings for this path as entries: `Scaling`, +//! `MinScaling` and `MaxScaling` (the width as a factor), `Colorization`, `Proportional`, +//! `Segmented` with `StartSegmentLength` and `EndSegmentLength`, `UpsideDown`, `Counterclockwise`, +//! `ScaleYDependsOn`, `Spacing`, `Adjustment` and `FoldAdjustment` (1 is +//! [`vectorcraft_brush::ArtBrush`]'s `overlap: false`). +//! - A Scatter, Art or Pattern brush's parameters are fields split by `/`: a number, the art's +//! section names (one for Scatter, five for Art and Pattern, empty where there is none, each +//! after a space for Art and Pattern), more fields, and last 15 numbers. +//! - Scatter: the size (2, 3), spacing (5, 6) and scatter (8, 9) as (low, high) factors of the +//! art, the rotation in degrees (11, 12), how each varies (4, 7, 10, 13) and whether the +//! rotation follows the path (14), and 1 Tints (1). +//! - Art: 1 Tints (2). +//! - Pattern: its scale as a factor (3). +//! - A Bristle brush's parameters start with 8 numbers: two codes, then the stiffness, bristle +//! thickness, density, paint opacity and bristle length as fractions and the size in +//! millimeters. +//! - The art is a `%AI8_BeginBrushPattern` section: its name as a string, then the art (read by +//! [`super::read`]), usually in a group after its frame, an unpainted rectangle around it. A frame +//! at the art's bounds isn't kept ([`without_frame`]); a wider one is. +//! +//! What isn't read keeps its default: the Art brush's other options, the pattern brush's tiles +//! (which slot is which tile isn't known) and the colorization of the other brushes, which is left +//! at None so the art keeps its own colors. + +use std::collections::{HashMap, HashSet}; + +use kurbo::Affine; +use vectorcraft_brush::{ArtBrush, Bristle, Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation}; +use vectorcraft_color::Paint; +use vectorcraft_doc::{AppearanceItem, Node, NodeKind}; + +use super::lex::{Lexer, Tok}; +use super::obj; + +/// The brush manager's order: the plug-in name of its object. +pub(super) const MANAGER: &str = "Adobe Brush Manager Order"; // brand-ok: the plug-in name the files use + +/// The plug-in names of the brush kinds. +const TOOLS: [(&str, Tool); 5] = [ + ("Adobe Calligraphic Brush Tool", Tool::Calligraphic), // brand-ok: the plug-in name the files use + ("Adobe Scatter Brush Tool", Tool::Scatter), // brand-ok: the plug-in name the files use + ("Adobe ArtOnPath Brush Tool", Tool::Art), // brand-ok: the plug-in name the files use + ("Adobe PatternOnPath Brush Tool", Tool::Pattern), // brand-ok: the plug-in name the files use + ("Adobe dBrush Brush Tool", Tool::Bristle), // brand-ok: the plug-in name the files use +]; + +/// Most brushes read from one file. +pub(super) const MAX_BRUSHES: usize = 4096; +/// Most brush art sections read from one file (a pattern brush has up to five). +pub(super) const MAX_BRUSH_ART: usize = 5 * MAX_BRUSHES; +/// Most named colors kept from one brush art section, and brought in from the art of one file's +/// brushes, each name once per section: the rest are left out. +pub(super) const MAX_BRUSH_ART_COLORS: usize = 20_000; +/// Most [`art_weight`] copied into the brushes of one file, each brush counting its own copy. +const MAX_BRUSH_ART_NODES: usize = 250_000; + +/// Most bytes of a plug-in object's parameters read (the brush manager's order of [`MAX_BRUSHES`] +/// brushes with long names fits): the rest is left out. +const MAX_PARAMS: usize = 1 << 20; + +/// Millimeters → points. +const MM: f64 = 72.0 / 25.4; + +/// A brush's kind, as its plug-in name gives it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Tool { + Calligraphic, + Scatter, + Art, + Pattern, + Bristle, +} + +/// The kind of a brush whose object's plug-in name is `name`. +pub(super) fn tool(name: &str) -> Option { + TOOLS.iter().find(|(n, _)| *n == name).map(|(_, t)| *t) +} + +/// A brush as its object gives it: its definition, and the names of the art sections it needs. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct BrushDraft { + pub name: String, + pub kind: DraftKind, +} + +#[derive(Clone, Debug, PartialEq)] +pub(super) enum DraftKind { + Calligraphic(Calligraphic), + /// The art is the section named `art`. + Scatter { + brush: Scatter, + art: String, + }, + /// The art is the section named `art`. `plain`: the brush stretches its art along the path, + /// unflipped, at 100% in Tints (see [`art_is_plain`]), so [`Self::Art`]'s `brush` draws as the + /// file's brush does. + Art { + brush: ArtBrush, + art: String, + plain: bool, + }, + /// The five art sections the brush names, in its order (which is which tile isn't known), and + /// its scale (%). + Pattern { + tiles: [Option; 5], + scale: f64, + }, + Bristle(Bristle), +} + +impl DraftKind { + pub(super) fn tool(&self) -> Tool { + match self { + DraftKind::Calligraphic(_) => Tool::Calligraphic, + DraftKind::Scatter { .. } => Tool::Scatter, + DraftKind::Art { .. } => Tool::Art, + DraftKind::Pattern { .. } => Tool::Pattern, + DraftKind::Bristle(_) => Tool::Bristle, + } + } +} + +/// Why a brush's object isn't read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) enum BrushError { + /// Fewer values than the kind has, or one that isn't a finite number. + Values, + /// No art section named. + NoArt, +} + +/// The strings of a plug-in object's section (`section`: what follows `%AI8_BeginPluginObject`): +/// its plug-in name, its name and its parameters, joined. The name is `None` with one string, and +/// the whole is `None` with none. +pub(super) fn plugin_strings(section: &[u8]) -> Option<(String, Option, String)> { + let mut lex = Lexer::new(section); + let mut strings = vec![]; + let mut params = vec![]; + while let Some(t) = lex.next_token() { + if let Tok::Str(s) | Tok::Hex(s) = t.tok { + if strings.len() < 2 { + strings.push(obj::text(&s)); + } else { + // Joined before they are text: a string may end inside a character. + let room = MAX_PARAMS.saturating_sub(params.len()); + params.extend_from_slice(s.get(..room.min(s.len())).unwrap_or_default()); + } + } + } + let mut strings = strings.into_iter(); + let kind = strings.next()?; + Some((kind, strings.next(), obj::text(¶ms))) +} + +/// The brush manager's order (`params`: its parameters): the kind and name of each brush. Pairs +/// whose plug-in name isn't a brush kind's are left out; `None` when there are none. +pub(super) fn parse_brush_manager(params: &str) -> Option> { + let fields: Vec<&str> = params.split('/').take(2 * MAX_BRUSHES).map(|f| f.strip_prefix(' ').unwrap_or(f)).collect(); + let mut out = vec![]; + for [kind, name] in fields.as_chunks::<2>().0 { + if let Some(t) = tool(kind) + && out.len() < MAX_BRUSHES + { + out.push((t, (*name).to_string())); + } + } + (!out.is_empty()).then_some(out) +} + +/// The numbers of `s` (split by white space): `None` when one isn't a finite number. +fn numbers(s: &str) -> Option> { + s.split_whitespace().map(|w| w.parse::().ok().filter(|v| v.is_finite())).collect() +} + +/// How a value varies, by its code: `None` for the stylus wheel and codes that aren't known. +fn variation(code: f64) -> Option { + match code { + 0.0 => Some(Variation::Fixed), + 1.0 => Some(Variation::Random), + 2.0 => Some(Variation::Pressure), + 4.0 => Some(Variation::Tilt), + 5.0 => Some(Variation::Bearing), + 6.0 => Some(Variation::Rotation), + _ => None, + } +} + +/// [`variation`], or for another code, Random when the value varies and Fixed when it doesn't. +fn mode(code: f64, varies: bool) -> Variation { + variation(code).unwrap_or(if varies { Variation::Random } else { Variation::Fixed }) +} + +/// A Calligraphic brush of angle, roundness and size `values`, each varying `variation` either side +/// as its code in `codes` says. +pub(super) fn calligraphic(values: [f64; 3], variation: [f64; 3], codes: [f64; 3]) -> Calligraphic { + let [angle, roundness, size] = values; + let modes = [0, 1, 2].map(|i| mode(codes[i], variation[i] != 0.0)); + Calligraphic { angle, roundness, size, variation, modes: Some(modes) } +} + +/// The settings a path's art style gives its stroke's brush. +#[derive(Clone, Debug, PartialEq)] +pub(super) enum PathBrush { + Calligraphic(Calligraphic), + /// An Art brush whose art stretches along the path, at the brush's own width, in Tints. + Art, +} + +/// Does an Art brush draw `art` as the file does? It bends paths in solid colors: other objects +/// are left out of the pieces, a gradient or pattern stays where it was and takes no color from the +/// stroke, an effect isn't bent with its path, a stroke's outline isn't stretched along it, and art +/// with no length along the path draws nothing. +pub(super) fn art_bends(art: &Node) -> bool { + let mut bends = art.geometric_bounds().is_some_and(|b| b.width() > 1e-9); + art.walk(&mut |n| { + bends &= matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Group { .. }) + && n.extras().mask.is_none() + && n.appearance.effects.is_empty() + && n.appearance.items.iter().all(|i| i.effects().is_empty() && !matches!(i, AppearanceItem::Stroke(s) if !s.paint.is_none())) + && vectorcraft_doc::swatches::node_paints(n).all(|p| matches!(p, Paint::Solid { .. } | Paint::None)); + }); + bends +} + +/// The art sections of `drafts`' Art brushes that an Art brush draws as the file does. +pub(super) fn bending_art(drafts: &[BrushDraft], art: &HashMap) -> HashSet { + let names: HashSet<&String> = drafts + .iter() + .filter_map(|d| match &d.kind { + DraftKind::Art { art, .. } => Some(art), + _ => None, + }) + .collect(); + names.into_iter().filter(|n| art.get(*n).is_some_and(art_bends)).cloned().collect() +} + +/// Does the brush `draft` draw as `settings`, the settings a path's art style gives it? A path whose +/// settings differ (Options of Selected Object) keeps its drawn look: a stroke names a brush, and +/// has no settings of its own. `bending`: [`bending_art`]. +pub(super) fn draws_as(draft: &BrushDraft, settings: &PathBrush, bending: &HashSet) -> bool { + let close = |a: f64, b: f64| (a - b).abs() <= 1e-3 * a.abs().max(b.abs()).max(1.0); + match (&draft.kind, settings) { + (DraftKind::Calligraphic(d), PathBrush::Calligraphic(c)) => { + close(d.angle, c.angle) + && close(d.roundness, c.roundness) + && close(d.size, c.size) + && d.variation.iter().zip(&c.variation).all(|(a, b)| close(*a, *b)) + && d.modes() == c.modes() + } + (DraftKind::Art { plain: true, art: name, .. }, PathBrush::Art) => bending.contains(name), + _ => false, + } +} + +/// Are an Art brush's last 15 numbers those of a brush that stretches its art along the path, +/// unflipped, at 100% in Tints? The numbers aren't read otherwise: any other value keeps its paths' +/// drawn look. +fn art_is_plain(numbers: &[f64; 15]) -> bool { + *numbers == [1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0] +} + +/// The brush named `name` of kind `kind` from its parameters `params`. +pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result { + let kind = match kind { + Tool::Calligraphic => { + let n = numbers(params).ok_or(BrushError::Values)?; + let [_, d0, d1, r0, r1, a0, a1, dm, rm, am, ..] = n.as_slice() else { return Err(BrushError::Values) }; + let mid = |a: f64, b: f64| (a + b) / 2.0; + let half = |a: f64, b: f64| (b - a).abs() / 2.0; + DraftKind::Calligraphic(calligraphic( + [mid(*a0, *a1), mid(*r0, *r1), mid(*d0, *d1)], + [half(*a0, *a1), half(*r0, *r1), half(*d0, *d1)], + [*am, *rm, *dm], + )) + } + Tool::Scatter | Tool::Art | Tool::Pattern => { + let fields: Vec<&str> = params.split('/').collect(); + let slots = if kind == Tool::Scatter { 1 } else { 5 }; + if fields.len() < slots + 2 { + return Err(BrushError::Values); + } + let tiles: Vec> = fields + .iter() + .skip(1) + .take(slots) + .map(|f| { + let f = f.strip_prefix(' ').unwrap_or(f); + (!f.is_empty()).then(|| f.to_string()) + }) + .collect(); + let n = fields.last().and_then(|f| numbers(f)).ok_or(BrushError::Values)?; + let n: &[f64; 15] = n.as_slice().try_into().map_err(|_| BrushError::Values)?; + let [_, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, _] = n; + let art = || tiles.first().cloned().flatten().ok_or(BrushError::NoArt); + match kind { + Tool::Scatter => { + let pct = |a: f64, b: f64| (a * 100.0, b * 100.0); + let values = [pct(*p2, *p3), pct(*p5, *p6), pct(*p8, *p9), (*p11, *p12)]; + let codes = [*p4, *p7, *p10, *p13]; + let modes = [0, 1, 2, 3].map(|i| mode(codes[i], values[i].0 != values[i].1)); + let [size, spacing, scatter, rotation] = values; + let brush = Scatter { + size, + spacing, + scatter, + rotation, + rotation_relative_to_path: *p14 == 1.0, + // The first of the 15 numbers: 1 is Tints. + colorization: if n.first() == Some(&1.0) { Colorization::Tints } else { Colorization::None }, + modes: Some(modes), + ..Scatter::default() + }; + DraftKind::Scatter { brush, art: art()? } + } + Tool::Art => { + let colorization = if *p2 == 1.0 { Colorization::Tints } else { Colorization::None }; + DraftKind::Art { brush: ArtBrush { colorization, ..ArtBrush::default() }, art: art()?, plain: art_is_plain(n) } + } + _ => { + let tiles: [Option; 5] = tiles.try_into().map_err(|_| BrushError::Values)?; + DraftKind::Pattern { tiles, scale: p3 * 100.0 } + } + } + } + Tool::Bristle => { + let words: Vec<&str> = params.split_whitespace().take(8).collect(); + let n = numbers(&words.join(" ")).ok_or(BrushError::Values)?; + let [_, _, stiffness, thickness, density, opacity, length, size] = n.as_slice() else { return Err(BrushError::Values) }; + DraftKind::Bristle(Bristle { + stiffness: stiffness * 100.0, + thickness: thickness * 100.0, + density: density * 100.0, + opacity: opacity * 100.0, + length: length * 100.0, + size: size * MM, + ..Bristle::default() + }) + } + }; + Ok(BrushDraft { name: name.to_string(), kind }) +} + +/// The brushes of `drafts`, their art from the sections `art` (by name), in the brush manager's +/// `order` (brushes it doesn't list after those it does, in the order of their objects), each +/// kept within its ranges → the brushes and how many were left out: those whose art isn't read, +/// pattern brushes (which slot holds which tile isn't known), a second brush of the same name, and +/// brushes whose copies of art go past [`MAX_BRUSH_ART_NODES`]. +pub(super) fn finish_brushes(drafts: Vec, art: &HashMap, order: Option<&[(Tool, String)]>) -> (Vec, usize) { + finish_brushes_within(drafts, art, order, MAX_BRUSH_ART_NODES) +} + +/// What copying `art` costs: its nodes, the art of their opacity masks, and the anchors of their paths. +pub(super) fn art_weight(art: &Node) -> usize { + let mut weight = 0usize; + art.walk(&mut |n| { + weight = weight.saturating_add(1 + n.path_data().map_or(0, |p| p.anchor_count())); + if let Some(m) = &n.extras().mask { + weight = weight.saturating_add(art_weight(&m.art)); + } + }); + weight +} + +/// Which of `drafts` [`finish_brushes`] makes into brushes, with [`MAX_BRUSH_ART_NODES`] of art. +pub(super) fn kept(drafts: &[BrushDraft], art: &HashMap) -> Vec { + kept_brushes(drafts, art, MAX_BRUSH_ART_NODES) +} + +/// Which of `drafts` become brushes, with at most `budget` of [`art_weight`] copied into them: not +/// a pattern brush, a brush whose art isn't read, a brush whose art would go past `budget`, or a +/// brush named as one kept before it. +pub(super) fn kept_brushes(drafts: &[BrushDraft], art: &HashMap, budget: usize) -> Vec { + let mut copied = 0usize; + let mut weights: HashMap<&str, usize> = HashMap::new(); + let mut names: HashSet<&str> = HashSet::new(); + drafts + .iter() + .map(|d| { + let fits = match &d.kind { + _ if names.contains(d.name.as_str()) => false, + DraftKind::Calligraphic(_) | DraftKind::Bristle(_) => true, + DraftKind::Pattern { .. } => false, + DraftKind::Scatter { art: name, .. } | DraftKind::Art { art: name, .. } => art.get_key_value(name).is_some_and(|(key, a)| { + let weight = *weights.entry(key.as_str()).or_insert_with(|| art_weight(a)); + let total = copied.saturating_add(weight); + let fits = total <= budget; + if fits { + copied = total; + } + fits + }), + }; + if fits { + names.insert(&d.name); + } + fits + }) + .collect() +} + +/// [`finish_brushes`] with at most `budget` of [`art_weight`] copied into the brushes (each brush +/// that uses a section holds its own copy): a brush whose art would go past it is left out. +pub(super) fn finish_brushes_within( + drafts: Vec, + art: &HashMap, + order: Option<&[(Tool, String)]>, + budget: usize, +) -> (Vec, usize) { + let kept = kept_brushes(&drafts, art, budget); + let copy = |name: &str| art.get(name).cloned(); + let mut left_out = 0; + let mut made: Vec> = vec![]; + for (d, kept) in drafts.into_iter().zip(kept) { + let tool = d.kind.tool(); + let kind = match d.kind { + _ if !kept => None, + DraftKind::Calligraphic(c) => Some(BrushKind::Calligraphic(c)), + DraftKind::Scatter { brush, art: name } => copy(&name).map(|a| BrushKind::Scatter(Scatter { art: a, ..brush })), + DraftKind::Art { brush, art: name, .. } => copy(&name).map(|mut a| { + // The side of the section with y up draws on the right of the path, and a brush + // draws art's y (down here) on the left of the path. + a.transform(Affine::scale_non_uniform(1.0, -1.0), false); + BrushKind::Art(ArtBrush { art: a, ..brush }) + }), + DraftKind::Pattern { .. } => None, + DraftKind::Bristle(b) => Some(BrushKind::Bristle(b)), + }; + match kind { + Some(kind) => { + let mut b = Brush { name: d.name, kind }; + b.sanitize(); + made.push(Some((tool, b))); + } + _ => left_out += 1, + } + } + let mut out = Vec::with_capacity(made.len()); + for (tool, name) in order.unwrap_or_default() { + if let Some(slot) = made.iter_mut().find(|m| m.as_ref().is_some_and(|(t, b)| t == tool && &b.name == name)) + && let Some((_, b)) = slot.take() + { + out.push(b); + } + } + out.extend(made.into_iter().flatten().map(|(_, b)| b)); + (out, left_out) +} + +/// The note for brushes [`finish_brushes`] left out. +pub(super) fn left_out_note(n: usize) -> String { + format!("brushes VectorCraft can't read yet were left out of the Brushes panel ({n})") +} + +/// Is `n` a frame: an unnamed, unpainted rectangle with nothing of its own (shown, unlocked, at full +/// opacity in Normal, with no effects, note, mask or other settings), a path of one subpath whose +/// anchors, without handles, are its four corners in order around it: closed, with the first again +/// at the end or not, or open with the first again at the end? +fn unpainted_rectangle(n: &Node) -> bool { + let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return false }; + let ([sp], Some(b)) = (path.subpaths.as_slice(), n.geometric_bounds()) else { return false }; + let corner = |p: kurbo::Point| (p.x == b.x0 || p.x == b.x1) && (p.y == b.y0 || p.y == b.y1); + let mut corners: Vec = vec![]; + for a in &sp.anchors { + if !corners.contains(&a.p) { + corners.push(a.p); + } + } + let last_repeats = sp.anchors.len() == 5 && sp.anchors.first().map(|a| a.p) == sp.anchors.last().map(|a| a.p); + // Each corner to the next goes along a side, not across: one coordinate stays. + let sides = corners.len() == 4 + && (0..4).all(|i| match (corners.get(i), corners.get((i + 1) % 4)) { + (Some(a), Some(b)) => (a.x == b.x) != (a.y == b.y), + _ => false, + }); + n.name.is_none() + && *n.extras() == vectorcraft_doc::NodeExtras::default() + && n.visible + && !n.locked + && n.opacity >= 1.0 + && n.blend == vectorcraft_color::BlendMode::Normal + && !n.isolate + && n.knockout == vectorcraft_doc::Knockout::Neutral + && !n.knockout_shape + && n.appearance.effects.is_empty() + && n.appearance.items.iter().all(|i| i.paint().is_none()) + && ((sp.closed && sp.anchors.len() == 4) || last_repeats) + && sides + && b.width() > 0.0 + && b.height() > 0.0 + && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p && corner(a.p)) +} + +/// Brush art `art` without its frame: a group whose first object is an unpainted rectangle around +/// the rest, exactly (within 1/1000 pt), loses that rectangle, and a group without a look or state +/// of its own (hidden, locked, isolation, knockout, opacity, blend mode, name, appearance, or a mask, +/// note or other setting) that is left with one object is that object. A frame wider than the art +/// is kept. +pub(super) fn without_frame(art: Node) -> Node { + let NodeKind::Group { children, clip: false } = &art.kind else { return art }; + let Some((first, rest)) = children.split_first() else { return art }; + let around = rest.iter().filter_map(|n| n.geometric_bounds()).reduce(|a, b| a.union(b)); + let exact = match (around, first.geometric_bounds()) { + (Some(a), Some(f)) => [a.x0 - f.x0, a.y0 - f.y0, a.x1 - f.x1, a.y1 - f.y1].iter().all(|d| d.abs() <= 1e-3), + _ => false, + }; + if !exact || !unpainted_rectangle(first) { + return art; + } + let plain = art.opacity >= 1.0 + && art.visible + && !art.locked + && !art.isolate + && art.knockout == vectorcraft_doc::Knockout::Neutral + && !art.knockout_shape + && art.blend == vectorcraft_color::BlendMode::Normal + && art.name.is_none() + && *art.extras() == vectorcraft_doc::NodeExtras::default() + && art.appearance.effects.is_empty() + && art.appearance.items.is_empty(); + if let ([only], true) = (rest, plain) { + return Node::clone(only); + } + let mut out = art.clone(); + if let Some(c) = out.children_mut() { + c.remove(0); + } + out +} diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs new file mode 100644 index 0000000000..a421bbd6a3 --- /dev/null +++ b/crates/eps/src/import/ai/envelope.rs @@ -0,0 +1,500 @@ +//! Envelopes from the editing data (`(Adobe Deform Plugin) 1 0 0 XP`), read as live envelopes. +//! +//! What an envelope is and does is Illustrator's public documentation: Make with Warp, Make with +//! Mesh (rows and columns) and Make with Top Object +//! (), +//! Edit Contents +//! (), +//! Envelope Options +//! () +//! and the warp styles with their bend and distortions +//! (). +//! +//! An envelope is written in three parts. On `%_` lines, a group holding the mesh that shapes it, +//! then its `/ArtDictionary`: Envelope Options as a bit word (`AIDeformOptionsKey`), Fidelity +//! (`AIDeformFidelityKey`), Edit Contents (`AIDeformEditModeKey`), a warp's style (`DeformStyle`, +//! numbered as Effect › Warp lists them), bend and distortions (`DeformValue`, `DeformHoriz`, +//! `DeformVert`, fractions) and orientation (`Rotate`), the size of the contents, read as the size +//! of the box they map from with Distort Appearance on when it matches their bounds with strokes +//! (`AIDeformArtWidthKey`, `AIDeformArtHeightKey`), the contents (`X=` … `X+`, then +//! `(AIDeformArtKey)`) and the kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object). Then the +//! distorted art on plain lines, and the plugin's `XP`. While the contents are edited, the group +//! holds the contents and the dictionary the mesh. A top object's outline is the edge of its +//! one-patch mesh. An envelope whose parts don't read, or that doesn't come out as drawn, keeps its +//! drawn art. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +use kurbo::{Affine, BezPath, Point, Rect, Vec2}; +use vectorcraft_doc::live::{ + EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, default_fidelity, envelope_content_boxes, + envelope_stroke_margin, +}; +use vectorcraft_doc::{Appearance, Document, Effect, ImageBlob, LayerColor, Node, NodeId, NodeKind, PatternDef}; +use vectorcraft_geom::PathData; + +use super::obj::Obj; +use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, compare_scale, differ, differ_in_colour}; + +/// The plugin that writes envelopes. +pub(super) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use +/// The note for an envelope that keeps its drawn art. +pub(crate) const DRAWN: &str = "an envelope VectorCraft couldn't read as a live envelope comes in as its drawn art"; +/// The note for warped type that keeps its drawn art, before how many. +pub(crate) const WARPED_TYPE_DRAWN: &str = "warped text objects that came in as drawn art, not as editable type"; +/// The most envelopes waiting for their drawn art at once. +pub(super) const MAX_PENDING: usize = 64; +/// The most envelopes and warped text objects one import draws to check; more keep their drawn art. +pub(crate) const MAX_CHECKED: usize = 256; +/// The most rows or columns of a mesh read (Make with Mesh's own limit). +const MAX_GRID: u32 = 50; +/// How far, in points over width and height together, a saved size may lie from the contents' +/// bounds with their strokes and still count as that box. +const SAVED_SIZE_SLACK: f64 = 0.5; +/// The bits of the options word that are read: Distort Appearance, Distort Pattern Fills, Distort +/// Linear Gradients, Anti-Alias (set: off) and Preserve Shape Using (set: Clipping Mask). +const KNOWN_BITS: i64 = 0b111 | 1 << 16 | 1 << 17; +/// More of the inked pixels than this differing, each with all its neighbours, and the envelope +/// doesn't come out as drawn. +const MAX_SOLID: f64 = 0.03; +/// More of the inked pixels than this differing at all, and the envelope doesn't come out as drawn. +const MAX_ANY: f64 = 0.1; + +/// The whole number of entry `key`: `None` when it is missing, `Some(None)` when it isn't one. +fn whole(o: &Obj, key: &str) -> Option> { + o.get(key)?; + let n = o.nums(key); + Some(match n.as_slice() { + [v] if v.is_finite() && v.fract() == 0.0 && v.abs() < 1e12 => Some(*v as i64), + _ => None, + }) +} + +/// A switch (`0` or `1`), off when missing. +fn switch(o: &Obj, key: &str) -> Option { + match whole(o, key) { + None | Some(Some(0)) => Some(false), + Some(Some(1)) => Some(true), + _ => None, + } +} + +/// Envelope Options and Fidelity. +pub(super) fn options(o: &Obj) -> Option<(EnvelopeOptions, f64)> { + let word = whole(o, "AIDeformOptionsKey")??; + if word < 0 || word & !KNOWN_BITS != 0 { + return None; + } + let fidelity = match whole(o, "AIDeformFidelityKey") { + None => default_fidelity(), + Some(Some(f)) if (0..=100).contains(&f) => f as f64, + Some(_) => return None, + }; + let bit = |n: u32| word & (1 << n) != 0; + let options = EnvelopeOptions { + anti_alias: !bit(16), + preserve_shape: if bit(17) { PreserveShape::ClippingMask } else { PreserveShape::Transparency }, + distort_appearance: bit(0), + distort_pattern_fills: bit(1), + distort_linear_gradients: bit(2), + bounds_margin: [0.0; 4], + }; + Some((options, fidelity)) +} + +/// The margins of `content` when the size the file saves for it (`AIDeformArtWidthKey`, +/// `AIDeformArtHeightKey`) matches its bounds with its strokes within [`SAVED_SIZE_SLACK`] and lies +/// nearer them than its geometric bounds. None without that size, or for contents with no width or +/// no height. +fn saved_margin(o: &Obj, content: &[Arc]) -> Option<[f32; 4]> { + let saved = |key: &str| match o.nums(key).as_slice() { + [v] if v.is_finite() => Some(*v), + _ => None, + }; + let (w, h) = (saved("AIDeformArtWidthKey")?, saved("AIDeformArtHeightKey")?); + let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY)?; + let off = |r: Rect| (r.width() - w).abs() + (r.height() - h).abs(); + if off(stroked) > SAVED_SIZE_SLACK || off(stroked) >= off(plain) { + return None; + } + envelope_stroke_margin(stroked, plain) +} + +/// A warp: its style, bend, distortions and orientation. +fn warp(o: &Obj) -> Option { + let style = whole(o, "DeformStyle")??; + let id = super::style::warp_style(style)?; + let percent = |key: &str| -> Option { + if o.get(key).is_none() { + return Some(0.0); + } + match o.nums(key).as_slice() { + [v] if v.is_finite() && (-1.0..=1.0).contains(v) => Some(v * 100.0), + _ => None, + } + }; + o.get("DeformValue")?; + let vertical = switch(o, "Rotate")?; + Some(EnvelopeKind::Warp { + style: id.into(), + bend: percent("DeformValue")?, + h: percent("DeformHoriz")?, + v: percent("DeformVert")?, + horizontal: !vertical, + }) +} + +/// The gradient mesh `n` is, or the one its plain groups hold alone. +fn only_mesh(n: &Node) -> Option<&GradientMesh> { + match &n.kind { + NodeKind::Mesh(m) => Some(m), + NodeKind::Group { children, clip: false } => match children.as_slice() { + [c] => only_mesh(c), + _ => None, + }, + _ => None, + } +} + +/// A grid point and its handles. +type GridPoint = (Point, [Vec2; 4]); + +/// The points of mesh `m` as a `rows`×`cols` grid with its first row at the top and its first +/// column at the left (y down), as an envelope's mesh lays them out; `None` for a grid out of range +/// or with points that aren't finite. +fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec)> { + let (mut rows, mut cols) = (m.rows, m.cols); + if rows == 0 || cols == 0 || rows > MAX_GRID || cols > MAX_GRID { + return None; + } + let len = (rows as usize + 1) * (cols as usize + 1); + if m.points.len() != len { + return None; + } + let finite = |v: Vec2| v.x.is_finite() && v.y.is_finite(); + if !m.points.iter().all(|q| finite(q.p.to_vec2()) && q.handles.iter().all(|h| finite(*h))) { + return None; + } + let mut pts: Vec = m.points.iter().map(|q| (q.p, q.handles)).collect(); + let at = |pts: &[GridPoint], cols: u32, r: u32, c: u32| pts.get((r * (cols + 1) + c) as usize).map_or(Point::ZERO, |q| q.0); + let remap = |h: [Vec2; 4], slots: [usize; 4]| slots.map(|s| h.get(s).copied().unwrap_or(Vec2::ZERO)); + // Columns that run down the page: the grid goes the other way round. + let along = at(&pts, cols, 0, cols) - at(&pts, cols, 0, 0); + if along.y.abs() > along.x.abs() { + let mut t = Vec::with_capacity(len); + for r in 0..=cols { + for c in 0..=rows { + let (p, h) = pts.get((c * (cols + 1) + r) as usize).copied()?; + // The new next column is the old next row. + let mut slots = [0; 4]; + (slots[H_RIGHT], slots[H_LEFT], slots[H_DOWN], slots[H_UP]) = (H_DOWN, H_UP, H_RIGHT, H_LEFT); + t.push((p, remap(h, slots))); + } + } + (rows, cols) = (cols, rows); + pts = t; + } + if (at(&pts, cols, 0, cols) - at(&pts, cols, 0, 0)).x < 0.0 { + for row in pts.chunks_mut(cols as usize + 1) { + row.reverse(); + for (_, h) in row.iter_mut() { + h.swap(H_RIGHT, H_LEFT); + } + } + } + if (at(&pts, cols, rows, 0) - at(&pts, cols, 0, 0)).y < 0.0 { + let mut flipped: Vec = pts.chunks(cols as usize + 1).rev().flatten().copied().collect(); + for (_, h) in &mut flipped { + h.swap(H_DOWN, H_UP); + } + pts = flipped; + } + Some((rows, cols, pts)) +} + +/// The outline of an upright grid: its edge, clockwise from the top left corner. +fn outline(rows: u32, cols: u32, pts: &[GridPoint]) -> Option { + let at = |r: u32, c: u32| pts.get((r * (cols + 1) + c) as usize).copied(); + // Each edge: from a point by one of its handles to the next point by one of its handles. + type Edge = ((u32, u32), usize, (u32, u32), usize); + let mut ring: Vec = vec![]; + ring.extend((0..cols).map(|c| ((0, c), H_RIGHT, (0, c + 1), H_LEFT))); + ring.extend((0..rows).map(|r| ((r, cols), H_DOWN, (r + 1, cols), H_UP))); + ring.extend((1..=cols).rev().map(|c| ((rows, c), H_LEFT, (rows, c - 1), H_RIGHT))); + ring.extend((1..=rows).rev().map(|r| ((r, 0), H_UP, (r - 1, 0), H_DOWN))); + let mut bp = BezPath::new(); + bp.move_to(at(0, 0)?.0); + for ((ar, ac), out, (br, bc), into) in ring { + let ((a, ha), (b, hb)) = (at(ar, ac)?, at(br, bc)?); + bp.curve_to(a + *ha.get(out)?, b + *hb.get(into)?, b); + } + bp.close_path(); + Some(PathData::from_bezpath(&bp)) +} + +/// Has group `n` nothing of its own: no name, lock, transparency, appearance or other properties, +/// shown? +fn plain_group(n: &Node) -> bool { + let plain = Node::new(n.id, NodeKind::Group { children: vec![], clip: false }); + matches!(n.kind, NodeKind::Group { clip: false, .. }) + && (&n.name, n.visible, n.locked, n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) + == (&plain.name, plain.visible, plain.locked, plain.opacity, plain.blend, plain.isolate, plain.knockout, plain.knockout_shape) + && n.appearance == plain.appearance + && n.extras() == plain.extras() +} + +/// `nodes` without the plain group the editing data puts round an envelope's contents. +fn unwrapped(mut nodes: Vec) -> Vec> { + if nodes.len() == 1 + && let Some(n) = nodes.first() + && plain_group(n) + && let Some(n) = nodes.pop() + && let NodeKind::Group { children, .. } = n.kind + { + return children; + } + nodes.into_iter().map(Arc::new).collect() +} + +/// The live envelope of dictionary `o`, the group on `%_` lines before it (`before`) and the art +/// in its `AIDeformArtKey` block (`inner`); `None` where they don't make one. +pub(super) fn live(o: &Obj, before: Option, inner: Vec) -> Option { + let editing = switch(o, "AIDeformEditModeKey")?; + let (mut options, fidelity) = options(o)?; + let before = before?; + // While the contents are edited, they are the group before the dictionary and the mesh is in it. + let (content, shape): (Vec>, Option<&GradientMesh>) = if editing { + let NodeKind::Group { children, clip: false } = &before.kind else { return None }; + let shape = match inner.as_slice() { + [n] => only_mesh(n), + _ => None, + }; + (children.clone(), shape) + } else { + let shape = only_mesh(&before); + (unwrapped(inner), shape) + }; + if content.is_empty() { + return None; + } + if options.distort_appearance { + options.bounds_margin = saved_margin(o, &content).unwrap_or_default(); + } + let kind = match whole(o, "AIDeformStyle")?? { + 1 => warp(o)?, + 2 => { + let (rows, cols, pts) = upright(shape?)?; + let (points, handles) = pts.into_iter().unzip(); + EnvelopeKind::Mesh { rows, cols, points, handles } + } + 3 => { + let (rows, cols, pts) = upright(shape?)?; + // The outline runs clockwise from the top left corner, one segment per grid edge. + let corners = [0, cols, cols.checked_add(rows)?, cols.checked_mul(2)?.checked_add(rows)?]; + EnvelopeKind::TopObject { path: outline(rows, cols, &pts)?, corners: Some(corners) } + } + _ => return None, + }; + Some(NodeKind::Envelope { content, kind: Box::new(kind), fidelity, editing, options, frame: Box::default() }) +} + +/// What the import's documents hold that art refers to: the patterns and image blobs. +pub(super) struct Shared<'a> { + pub(super) patterns: &'a [PatternDef], + pub(super) images: &'a BTreeMap, +} + +/// A document of `node` alone, on a layer with id `layer`, with the patterns and images it shows. +fn alone(node: &Node, layer: NodeId, shared: &Shared<'_>) -> Document { + let mut doc = Document::new(1.0, 1.0); + let mut l = Node::layer(layer, "", LayerColor::Preset(0)); + if let Some(c) = l.children_mut() { + c.push(Arc::new(node.clone())); + } + doc.layers = vec![Arc::new(l)]; + doc.patterns = shared.patterns.to_vec(); + let mut keys = vec![]; + doc.visit_images(|_, im| keys.push(im.key.clone())); + for k in keys { + if let Some(blob) = shared.images.get(&k) { + doc.images.insert(k, blob.clone()); + } + } + doc +} + +/// How `live` and `drawn`, drawn over `region` at `scale`, differ: the pixels that differ in +/// lightness or colour, those whose neighbours all differ too (where one draws something the other +/// doesn't, not an edge drawn a little apart), and the pixels either inks. `None` when they can't +/// be drawn. +fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Option<(usize, usize, usize)> { + let x = vectorcraft_render::Renderer::new().render_region(live, region, scale, false); + let y = vectorcraft_render::Renderer::new().render_region(drawn, region, scale, false); + if x.width == 0 || x.height == 0 || x.width != y.width || x.height != y.height { + return None; + } + let (w, h) = (x.width as usize, x.height as usize); + let (xs, ys) = (x.pixels.as_chunks::<4>().0, y.pixels.as_chunks::<4>().0); + let differs: Vec = xs.iter().zip(ys).map(|(p, q)| differ(p, q) || differ_in_colour(p, q)).collect(); + let inked = xs.iter().zip(ys).filter(|(p, q)| p[3] > 8 || q[3] > 8).count(); + let at = |i: usize, j: usize| differs.get(j * w + i).copied().unwrap_or(false); + let any = differs.iter().filter(|d| **d).count(); + let solid = (1..h.saturating_sub(1)) + .flat_map(|j| (1..w.saturating_sub(1)).map(move |i| (i, j))) + .filter(|&(i, j)| (j - 1..=j + 1).all(|n| (i - 1..=i + 1).all(|m| at(m, n)))) + .count(); + Some((any, solid, inked)) +} + +/// The differences from their drawn art that the live envelopes and warped type of one import may +/// add up to, as shares of the page drawn as the page check draws it: half of what that check allows +/// ([`MAX_DIFFERENCE`], [`MAX_SOLID_DIFFERENCE`]), so they never make the file open from its PDF part +/// instead. +#[derive(Debug, Default)] +pub(crate) struct Spent { + pub(super) any: f64, + pub(super) solid: f64, +} + +/// A text object read with a Warp. +#[derive(Debug)] +pub(super) struct WarpedLook { + /// The id of its slot. + pub(super) slot: NodeId, + /// The drawn art its style's look saved. + pub(super) look: Node, + /// That art's box, when the comparisons with the page leave it out ([`super::Structure::restyled`]). + pub(super) left_out: Option, +} + +/// The text objects read with a Warp, and what the import has left of the budget for checks +/// ([`drawn_alike`]). Type is laid out after the layers are read, so these wait for that +/// ([`Self::settle`]). +#[derive(Debug, Default)] +pub struct WarpedType { + pub(super) looks: Vec, + pub(super) checks: usize, + pub(super) spent: Spent, + pub(super) page: Option, +} + +impl WarpedType { + /// Replace each warped text object of `doc` that doesn't draw as its saved look (or that the + /// budget has no check left for) with that look: `made` gives the text object a slot became. A + /// frame in `threaded` stays type, since the frames of a thread share one story. A replaced + /// object's box goes back into the comparisons with the page (out of `restyled`), and only what + /// `doc` shows counts against the page's share of the budget. Returns how many were replaced. + pub(crate) fn settle( + self, + doc: &mut Document, + made: impl Fn(NodeId) -> Option, + threaded: &BTreeSet, + restyled: &mut Vec, + ) -> usize { + let Self { looks, mut checks, mut spent, page } = self; + let mut shown_ids = BTreeSet::new(); + doc.layers.iter().for_each(|l| collect_shown(l, &mut shown_ids)); + let mut replaced = 0; + for WarpedLook { slot, mut look, left_out } in looks { + let Some(id) = made(slot).filter(|id| !threaded.contains(id)) else { continue }; + let Some(text) = doc.node(id).filter(|n| matches!(n.kind, NodeKind::Text(_)) && warps(&n.appearance)).cloned() else { continue }; + let mut alike = false; + if checks > 0 { + checks -= 1; + let layer = doc.alloc_id(); + let shared = Shared { patterns: &doc.patterns, images: &doc.images }; + let (mut shown, mut plain) = (text.clone(), look.clone()); + (shown.visible, shown.opacity) = (true, 1.0); + (plain.visible, plain.opacity) = (true, 1.0); + alike = warped_alike(&shown, &plain, layer, &shared, page.filter(|_| shown_ids.contains(&id)), &mut spent); + } + if alike { + continue; + } + (look.id, look.name, look.visible, look.locked) = (id, text.name.clone(), text.visible, text.locked); + if let Some(wrap) = text.extras().wrap { + look.extras_mut().wrap = Some(wrap); + } + if let Some(n) = doc.node_mut(id) { + *n = look; + replaced += 1; + if let Some(at) = left_out.and_then(|b| restyled.iter().position(|r| *r == b)) { + restyled.remove(at); + } + } + } + replaced + } +} + +#[cfg(test)] +impl WarpedType { + /// The text objects of `looks` (slot and saved look) with no check left. + pub(crate) fn unchecked(looks: Vec<(NodeId, Node)>) -> Self { + Self { looks: looks.into_iter().map(|(slot, look)| WarpedLook { slot, look, left_out: None }).collect(), ..Default::default() } + } +} + +/// Add to `out` the ids of `n` and what is in it, unless hidden. +fn collect_shown(n: &Node, out: &mut BTreeSet) { + if n.visible { + out.insert(n.id); + n.children().into_iter().flatten().for_each(|c| collect_shown(c, out)); + } +} + +/// Does `appearance` have a Warp that shows, on the object or on one of its fills or strokes? +pub(super) fn warps(appearance: &Appearance) -> bool { + let warp = |e: &Effect| e.visible && e.id.starts_with("warp."); + appearance.effects.iter().any(warp) || appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(warp)) +} + +/// Do `live` and `drawn` draw alike: few of the pixels either inks differ, and fewer still where a +/// whole patch differs; and, on `page` (when the file has one), do they differ little enough that +/// with the differences in `spent` the page check still takes the layers' art (it is added to +/// `spent` when they do)? Both are drawn on `layer`, a layer id no other node has. +pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { + alike_within(live, drawn, live.visual_bounds(), layer, shared, page, spent) +} + +/// [`drawn_alike`] for type under a Warp, compared over all that its effects draw, which can reach +/// past its own box. +pub(super) fn warped_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { + let reach = vectorcraft_render::effect_bounds(&alone(live, layer, shared).symbol_boxes(), live); + alike_within(live, drawn, vectorcraft_geom::union_opt(live.visual_bounds(), reach), layer, shared, page, spent) +} + +/// [`drawn_alike`], with `live` measured as `reach`. +fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { + let (Some(a), Some(b)) = (reach, drawn.visual_bounds()) else { return false }; + let region = a.union(b).inflate(2.0, 2.0); + if !(region.is_finite() && region.width() > 0.0 && region.height() > 0.0) || region.width().max(region.height()) > 1e6 { + return false; + } + let (x, y) = (alone(live, layer, shared), alone(drawn, layer, shared)); + let Some((any, solid, inked)) = differing(&x, &y, region, compare_scale(region)) else { return false }; + if inked == 0 { + return false; + } + let share = |n: usize| n as f64 / inked as f64; + if share(solid) > MAX_SOLID || share(any) > MAX_ANY { + return false; + } + let Some(page) = page.filter(|p| p.is_finite() && p.width() > 0.0 && p.height() > 0.0) else { return true }; + // Only what is on the page counts, drawn as the page check draws it (about 400 pixels along the + // page's longer side). + let on_page = region.intersect(page); + let scale = compare_scale(page); + if on_page.width() * scale < 1.0 || on_page.height() * scale < 1.0 { + return true; + } + let Some((any, solid, _)) = differing(&x, &y, on_page, scale) else { return false }; + let pixels = (page.width() * scale * page.height() * scale).max(1.0); + let (any, solid) = (spent.any + any as f64 / pixels, spent.solid + solid as f64 / pixels); + if any > MAX_DIFFERENCE / 2.0 || solid > MAX_SOLID_DIFFERENCE / 2.0 { + return false; + } + *spent = Spent { any, solid }; + true +} diff --git a/crates/eps/src/import/ai/frames.rs b/crates/eps/src/import/ai/frames.rs index 24f0b8b835..f6b00c44c5 100644 --- a/crates/eps/src/import/ai/frames.rs +++ b/crates/eps/src/import/ai/frames.rs @@ -66,8 +66,8 @@ fn number_before(head: &[u8], key: &[u8]) -> Option { number(words(head.get(..k)?).last()?) } -/// A path in the format's path operators (`m`, `l`/`L`, `c`/`C`, `v`/`V`, `y`/`Y`; any other -/// operator ends the numbers before it). +/// A path in the format's path operators (`m`, `l`/`L`, `c`/`C`, `v`/`V`, `y`/`Y`, closed by `n`, +/// `f`, `s`, `b` or `h`; any other operator ends the numbers before it). fn path(text: &[u8]) -> Option { let mut bp = BezPath::new(); let mut nums: Vec = vec![]; @@ -106,6 +106,12 @@ fn path(text: &[u8]) -> Option { bp.curve_to(p(n - 4)?, q, q); cur = Some(q); } + // The painting operators that close the path first (lower case), and `h`: an area's frame + // is closed, its last point the first again. + b"n" | b"f" | b"s" | b"b" | b"h" if cur.is_some() => { + bp.close_path(); + cur = None; + } _ => {} } nums.clear(); @@ -135,4 +141,17 @@ mod tests { assert_eq!(f[&(49, 0)].bounding_box(), kurbo::Rect::new(1.0, 2.0, 3.0, 4.0)); assert!(text_frames(b"/AI11Text : garbage").is_empty()); } + + /// An area's frame painted with `n` (as the format writes it, the last point the first again) + /// is a closed path of its corners; one painted with `N` stays open. + #[test] + fn a_frame_painted_closed_is_closed() { + let doc = b"/AI11Text :\r0 /FreeUndo ,\r0 /FrameIndex ,\r3 /StoryIndex ,\r/Art :\rX=\r40 130 m\r40 250 L\r240 250 L\r240 130 L\r40 130 L\rn\rX+\r; /ConfiningPath ,\r;\r\ + /AI11Text :\r0 /FreeUndo ,\r0 /FrameIndex ,\r4 /StoryIndex ,\r/Art :\rX=\r40 130 m\r40 250 L\r240 250 L\rN\rX+\r; /ConfiningPath ,\r;\r"; + let f = text_frames(doc); + let closed = vectorcraft_geom::PathData::from_bezpath(&f[&(3, 0)]); + assert!(closed.subpaths[0].closed); + assert_eq!(closed.subpaths[0].anchors.len(), 4, "the last point merges with the first"); + assert!(!vectorcraft_geom::PathData::from_bezpath(&f[&(4, 0)]).subpaths[0].closed); + } } diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index 126619c13e..a1b24662ec 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -1,67 +1,247 @@ //! Type in the legacy format (version 7 specification §15): text objects `type To` … `TO`, their -//! text path (`a b c d tx ty startPt Tp`, an area's frame or the path type runs along, `TP`), the -//! modal character and paragraph attributes (`Tr Tf Ts Tz Tt TA Tl Ta Ti`), the paint style, and -//! the characters (`Tx`, `Tj`, overflow `TX`; `\r` ends a paragraph). Final-form operators (the +//! text paths (`a b c d tx ty startPt Tp`, an area's frame, one for each linked area, or the path +//! type runs along, `TP`), the modal character and paragraph attributes +//! (`Tr Tf Ts Tz Tt TA Tl Ta Ti`, and §15.4.7 and §22's letter and word spacing `TC TW`, hanging +//! punctuation `Tq`, hyphenation `Th` and tab stops `Xb Xe XB`, and §15.3.4's writing direction `TV`, +//! Roman character rotation `Tv`, Kumi blocks `Ty TY` and binding punctuation `Tg`), the paint +//! style, and the characters (`Tx`, `Tj`, overflow `TX`; `\r` ends a paragraph). Type set in rendering modes 4 to 7 is a mask (§5.7): the +//! text object clips the objects of its clipping group. Final-form operators (the //! computed positions, §15.1) are skipped: the type is laid out again. Strings are decoded by the -//! file's `TE` encoding, else as Windows-1252; a re-encoded font `/_name` is the font its -//! `%AI3_BeginEncoding` names (else `name`). +//! encoding pairs of the current font's `TZ`, then by the file's `TE` encoding unless that `TZ`'s +//! `useDefault` is 0, else as Windows-1252; a re-encoded font `/_name` is the font its `%AI3_BeginEncoding` or `TZ` names +//! (else `name`). Strings in a composite font named `base-CMap` (CJK type) whose `TZ` gives no +//! encoding pairs are decoded by that predefined CMap instead, and the font is `base`. +use std::sync::Arc; + +use craft_pdf::interpret::hayro_cmap::{BfString, CMap, CMapName, load_embedded}; use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen}; use vectorcraft_color::Paint; -use vectorcraft_doc::{CharStyle, Justify, NodeKind, ParaStyle, TextKind, TextObject, TextRun}; -use vectorcraft_geom::PathData; +use vectorcraft_doc::{Burasagari, CharStyle, Justify, NodeKind, ParaStyle, TabAlign, TabStop, TextKind, TextObject, TextRun}; +use vectorcraft_geom::AnchorKind; use super::super::obj::V; -use super::{FLIP, GState, Reader}; +use super::art::path_data; +use super::{FLIP, GState, HashSet, Kind, Node, NodeId, Reader}; use crate::latin; /// Most characters of type read in one file. const MAX_CHARS: usize = 1 << 22; /// Largest type size and indent read (points). const MAX_SIZE: f64 = 1e4; +/// Most re-encoded fonts read in one file, for their names and for their encodings each. +const MAX_FONTS: usize = 4096; +/// Most tab stops read in one tab definition. +const MAX_TABS: usize = 1024; +/// Largest tab stop position read (points), as `text.tabs.set` takes it. +const MAX_TAB_POSITION: f64 = 100_000.0; +/// Most tab stops copied in one text object into its runs of paragraphs with the same attributes +/// while it is read, and again, counted apart, into each of its paragraphs when it has more than one +/// run and into the frames of its linked areas after the first. The runs, paragraphs and frames past +/// it take the default stops, with a warning. +const MAX_STORY_TABS: usize = 1 << 20; +/// The warning when [`MAX_STORY_TABS`] leaves tab stops out. +const TABS_LEFT_OUT: &str = "tab stops past VectorCraft's limits were left out"; +/// Most values read before one operator in a re-encoding section. +const MAX_ENCODING_VALUES: usize = 1024; +/// Most text paths read in one text object (its linked areas); the frames of others are left out, +/// with a warning. +const MAX_TEXT_PATHS: usize = 4096; +/// Most frames of linked areas times characters of their story: the story is laid out again +/// through its frames when the file opens. The frames of the areas past it are left out, with a +/// warning. +const MAX_THREAD_WORK: usize = MAX_CHARS; +/// The warning when [`MAX_TEXT_PATHS`] or [`MAX_THREAD_WORK`] leaves frames of linked areas out. +const LINKED_AREAS_LEFT_OUT: &str = "linked type areas past VectorCraft's limits were left out"; +/// The warning when type set in a mask rendering mode can't be a clipping path: type in linked +/// areas (several frames), in wraparound text or in a compound path doesn't clip. +const MASK_NOT_CLIPPED: &str = "type used as a mask in linked areas, wraparound text or a compound path doesn't clip"; +/// The warning when `TV` changes after a text object's first character: the object keeps the +/// direction of that character. +const DIRECTION_CHANGE_LEFT_OUT: &str = "type that changes writing direction inside a text object opens in the direction of its first character"; + +/// A text path (`Tp` … `TP`). +#[derive(Debug, Default)] +struct TextPath { + /// `Tp`'s matrix: text space (y up) → art space. + matrix: Option, + /// Where type on a path starts: a segment's index plus how far along it. + start: f64, + /// The frame or path, in art space, and the kind of the anchor each of its segments ends on. + path: Option<(BezPath, Vec)>, +} + +/// Paragraphs in a row that start with the same attributes. +#[derive(Debug)] +struct ParaRun { + /// The attributes, as they were at the first character of each paragraph. + style: ParaStyle, + /// How many paragraphs. + count: usize, + /// [`TypeState::tabs_version`] when the last of them started. + tabs_version: u64, +} + +/// An overflow paragraph break (`(\r) TX`) read before any more type, with the state in force +/// where it was read. +#[derive(Debug)] +struct PendingBreak { + /// `TV` at the break. + vertical: bool, + /// The attributes and [`TypeState::tabs_version`] of the empty paragraph the break ends, when + /// it ends one that no character started. + para: Option<(ParaStyle, u64)>, +} /// A text object being read. #[derive(Debug, Default)] pub(super) struct LegacyText { /// `To`'s type: 0 point type, 1 area type, 2 type on a path. kind: i64, - /// `Tp`'s matrix: text space (y up) → art space. - matrix: Option, - /// Where type on a path starts: a segment's index plus how far along it. - start: f64, + /// Its text paths in file order: area type has one for each linked area (§15.5.3). + paths: Vec, /// Between `Tp` and `TP`: the path read is the text path. in_path: bool, - /// The frame or path, in art space. - path: Option, + /// It has more than [`MAX_TEXT_PATHS`] text paths: the paths read past them are left out. + past_limit: bool, + /// The story: the characters after every text path, in file order. runs: Vec, - /// Each paragraph's attributes, as they were at its first character. - paras: Vec, + /// The paragraphs' attributes, as they were at the first character of each, by runs of + /// paragraphs with the same attributes. + paras: Vec, + /// The tab stops that the runs in `paras` hold. + tab_stops: usize, + /// [`MAX_STORY_TABS`] left tab stops out. + tabs_left_out: bool, /// The current paragraph's attributes are in `paras`. para_taken: bool, /// An overflow paragraph break (`(\r) TX`) not yet followed by type: the story's end. - pending_break: bool, + pending_break: Option, + /// Characters were set in a mask rendering mode (`Tr` 4 to 7): the text object is a clipping + /// path (§5.7). + clips: bool, + /// `TV` at its first character: VectorCraft keeps one writing direction for each text object. + vertical: bool, + /// A later character was set in the other direction. + direction_changed: bool, /// The state when it began (lock, visibility), and whether it began on a `%_` line. gs: GState, hidden: bool, } +impl LegacyText { + /// A paragraph starts, with the attributes `para` at [`TypeState::tabs_version`] + /// `tabs_version`. When they are those of the paragraph before it, it joins that paragraph's + /// run; else a new run starts, with the tab stops that [`MAX_STORY_TABS`] leaves room for. + fn begin_para(&mut self, para: &mut ParaStyle, tabs_version: u64) { + if let Some(run) = self.paras.last_mut() { + // No tab definition since the run's last paragraph started: the stops are the same. + let same = if run.tabs_version == tabs_version { same_but_tabs(&mut run.style, para) } else { run.style == *para }; + if same { + run.count += 1; + run.tabs_version = tabs_version; + return; + } + } + let style = within_tabs(para, &mut self.tab_stops, &mut self.tabs_left_out); + self.paras.push(ParaRun { style, count: 1, tabs_version }); + } +} + +/// Are `a` and `b` the same, leaving their tab stops out? +fn same_but_tabs(a: &mut ParaStyle, b: &mut ParaStyle) -> bool { + let (a_tabs, b_tabs) = (std::mem::take(&mut a.tabs), std::mem::take(&mut b.tabs)); + let same = a == b; + (a.tabs, b.tabs) = (a_tabs, b_tabs); + same +} + +/// A copy of `para`, with its tab stops when `copied` (the tab stops copied so far) has room for +/// them within [`MAX_STORY_TABS`], else with the default stops and `left_out` set. +fn within_tabs(para: &ParaStyle, copied: &mut usize, left_out: &mut bool) -> ParaStyle { + let mut style = para.clone(); + if MAX_STORY_TABS.saturating_sub(*copied) >= style.tabs.len() { + *copied += style.tabs.len(); + } else { + *left_out = true; + style.tabs = Vec::new(); + } + style +} + +/// The attributes of each paragraph of the runs `runs`, in order. A paragraph keeps its tab stops +/// while `copied` (the tab stops copied so far) has room for them within [`MAX_STORY_TABS`]; the +/// paragraphs past it take the default stops, and `left_out` is set. +fn each_paragraph(runs: Vec, copied: &mut usize, left_out: &mut bool) -> Vec { + let mut each = Vec::with_capacity(runs.iter().map(|r| r.count).sum()); + for run in runs { + let stops = run.style.tabs.len(); + let room = MAX_STORY_TABS.saturating_sub(*copied); + let kept = room.checked_div(stops).map_or(run.count, |n| run.count.min(n)); + *copied += kept * stops; + let bare = (kept < run.count).then(|| ParaStyle { tabs: Vec::new(), ..run.style.clone() }); + each.extend(std::iter::repeat_n(run.style, kept)); + if let Some(bare) = bare { + *left_out = true; + each.extend(std::iter::repeat_n(bare, run.count - kept)); + } + } + each +} + /// The modal type attributes of the legacy format, which last from one text object to the next. #[derive(Debug)] pub(super) struct TypeState { style: CharStyle, para: ParaStyle, + /// How many tab definitions set `para`'s tab stops: paragraphs that start at the same count + /// start with the same stops. + tabs_version: u64, /// `Tr`. render: i64, + /// `TV`: vertical writing. + vertical: bool, + /// `TY`: a Kumi block recorded for later use, which horizontal type keeps as its mark. + kumi_recorded: bool, /// The encoding strings are in, by code (`TE`); None where it says nothing. encoding: Vec>, - /// Re-encoded fonts' original names (`%AI3_BeginEncoding: _new old`). + /// Re-encoded fonts' original names (`%AI3_BeginEncoding: _new old`, or `TZ`'s). fonts: Vec<(String, String)>, + /// Re-encoded fonts' own encodings (`TZ`), by the new font's name: what its encoding pairs + /// change, by code (None where they say nothing), and whether `TE`'s encoding applies to it. + font_encodings: Vec<(String, Vec>, bool)>, + /// The new fonts' names whose `TZ` gives encoding pairs, which no composite font has. + paired_fonts: Vec, + /// The font `Tf` set last, as the file names it. + font: Option, + /// How strings in that font decode, when it is a composite font ([`composite_font`]). + cmap: Option>, + /// The predefined CMaps read so far, by name (`None` when one couldn't be read). + cmaps: Vec<(String, Option>)>, + /// Between `Xb` and `XB`: the tab stops of the tab definition read so far. + tabs: Option>, chars: usize, } impl Default for TypeState { fn default() -> Self { - Self { style: CharStyle::default(), para: ParaStyle::default(), render: 0, encoding: vec![None; 256], fonts: vec![], chars: 0 } + Self { + style: CharStyle::default(), + para: ParaStyle::default(), + tabs_version: 0, + render: 0, + vertical: false, + kumi_recorded: false, + encoding: vec![None; 256], + fonts: vec![], + font_encodings: vec![], + paired_fonts: vec![], + font: None, + cmap: None, + cmaps: vec![], + tabs: None, + chars: 0, + } } } @@ -70,34 +250,447 @@ impl TypeState { pub(super) fn encoding_comment(&mut self, line: &str) { let Some((_, names)) = line.split_once(':') else { return }; let mut words = names.split_whitespace(); - if let (Some(new), Some(old)) = (words.next(), words.next()) - && self.fonts.len() < 4096 - { - self.fonts.push((new.trim_start_matches('/').to_string(), old.trim_start_matches('/').to_string())); + if let (Some(new), Some(old)) = (words.next(), words.next()) { + self.font_names(new.trim_start_matches('/'), old.trim_start_matches('/')); + } + } + + /// Re-encoded font `new` is font `old`. The first statement for a name is used. + fn font_names(&mut self, new: &str, old: &str) { + if self.fonts.len() < MAX_FONTS && !self.fonts.iter().any(|(n, _)| n == new) { + self.fonts.push((new.to_string(), old.to_string())); + } + } + + /// A string's bytes, in the current font. + fn decode(&self, bytes: &[u8]) -> String { + if let Some(cmap) = &self.cmap { + return cmap.decode(bytes); + } + let own = self.font.as_ref().and_then(|f| self.font_encodings.iter().find(|(n, _, _)| n == f)); + let (own, te) = own.map_or((None, true), |(_, e, te)| (Some(e.as_slice()), *te)); + bytes + .iter() + .map(|&b| { + if b == b'\r' { + return '\n'; + } + own.and_then(|e| e.get(usize::from(b)).copied().flatten()) + .or_else(|| if te { self.encoding.get(usize::from(b)).copied().flatten() } else { None }) + .unwrap_or_else(|| latin::decode(b)) + }) + .collect() + } + + /// How strings in a font with predefined CMap `cmap` decode; `None` when the CMap can't be read. + fn cmap_codes(&mut self, cmap: &str) -> Option> { + if let Some(form) = unicode_cmap(cmap) { + return Some(Arc::new(CMapCodes::Unicode(form))); + } + if let Some((_, codes)) = self.cmaps.iter().find(|(n, _)| n == cmap) { + return codes.clone(); + } + let codes = cid_codes(cmap).map(Arc::new); + self.cmaps.push((cmap.to_string(), codes.clone())); + codes + } +} + +/// How a composite font's strings decode. +#[derive(Debug)] +enum CMapCodes { + /// By a predefined CMap's codes to CIDs, then by its character collection's CID → Unicode CMap; + /// with `high_bit`, each byte 0x21 to 0x7E gets its high bit set first. `space` is the CMap's + /// code space ([`code_space`]). + Cids { codes: Box, unicode: Box, high_bit: bool, space: Option }, + /// A predefined Unicode CMap: the codes are the characters. + Unicode(Unicode), +} + +/// A CMap's code space: ranges of codes, each given by its lowest and highest code, both with the +/// code's length in bytes. +type CodeSpace = &'static [(&'static [u8], &'static [u8])]; + +/// What control byte `b` is in a composite font's string: `\r` a paragraph break, `\t` a tab. +fn control(b: u8) -> Option { + match b { + b'\r' => Some('\n'), + b'\t' => Some('\t'), + _ => None, + } +} + +impl CMapCodes { + /// The characters of string `bytes`, leaving out codes the CMaps don't map; a `\r` is a + /// paragraph break and a `\t` a tab (also as a byte left over after the last whole code of a + /// UTF-16 or UTF-32 string). + fn decode(&self, bytes: &[u8]) -> String { + let (codes, unicode, high_bit, space) = match self { + Self::Unicode(form) => { + let unit = match form { + Unicode::Utf16 => 2, + Unicode::Utf8 => 1, + Unicode::Utf32 => 4, + }; + let (whole, rest) = bytes.split_at_checked(bytes.len() - bytes.len() % unit).unwrap_or((bytes, &[])); + let mut text = unicode_text(whole, *form).replace('\r', "\n"); + text.extend(rest.last().copied().and_then(control)); + return text; + } + Self::Cids { codes, unicode, high_bit, space } => (codes, unicode, *high_bit, space), + }; + let euc: Vec; + let bytes = if high_bit { + euc = bytes.iter().map(|&b| if (0x21..0x7f).contains(&b) { b | 0x80 } else { b }).collect(); + euc.as_slice() + } else { + bytes + }; + let mut out = String::new(); + let mut at = 0; + while let Some(&first) = bytes.get(at) { + // VectorCraft reads a 0x0D byte as a paragraph break and a 0x09 byte as a tab in every + // CMap, as in other fonts' strings, including the row-and-cell CMaps, whose code space + // has no one-byte codes. + if let Some(control) = control(first) { + out.push(control); + at += 1; + continue; + } + let rest = bytes.get(at..).unwrap_or_default(); + let code = |len: u8| rest.get(..usize::from(len)).map(|b| b.iter().fold(0u32, |c, &b| c << 8 | u32::from(b))); + let found = match space { + // The code is as long as the code space range it falls in; a byte that starts no + // code in the code space is skipped. + Some(space) => { + let Some(len) = code_len(space, rest) else { + at += 1; + continue; + }; + code(len).map(|c| (len, codes.lookup_cid_code(c, len))) + } + None => (1..=4u8).find_map(|len| Some((len, Some(codes.lookup_cid_code(code(len)?, len)?)))), + }; + let Some((len, cid)) = found else { + at += 1; + continue; + }; + at += usize::from(len); + // A code the CMap leaves out is dropped. + let Some(cid) = cid else { continue }; + match unicode.lookup_bf_string(cid) { + // A one-byte Roman code whose CID the table gives as a combining mark alone (0x7E in + // the Mac Shift-JIS CMaps, U+0303): the ASCII character, as Adobe's cid2code.txt lists first. + Some(BfString::Char('\u{300}'..='\u{36f}')) if len == 1 && (0x20..0x7f).contains(&first) => out.push(char::from(first)), + Some(BfString::Char(c)) if c != char::REPLACEMENT_CHARACTER => out.push(c), + Some(BfString::String(s)) => out.extend(s.chars().filter(|c| *c != char::REPLACEMENT_CHARACTER)), + _ => {} + } + } + out + } +} + +/// How a predefined Unicode CMap's codes encode their characters. +#[derive(Clone, Copy, PartialEq, Debug)] +enum Unicode { + /// Two bytes a character (`UCS2`) or a UTF-16 surrogate pair, the high byte first. + Utf16, + Utf8, + /// Four bytes, the high byte first. + Utf32, +} + +/// The encoding of predefined Unicode CMap `name`: `Uni` and a character collection, then `-UCS2`, +/// `-UTF8`, `-UTF16` or `-UTF32` (and `-HW` for half-width forms), then `-H` or `-V` +/// (`UniJIS-UCS2-H`, `UniGB-UTF16-V`: ). +fn unicode_cmap(name: &str) -> Option { + let rest = name.strip_suffix("-H").or_else(|| name.strip_suffix("-V"))?; + let rest = rest.strip_suffix("-HW").unwrap_or(rest); + let (collection, form) = rest.rsplit_once('-')?; + let collections = ["UniJIS", "UniJISPro", "UniJIS2004", "UniJISX0213", "UniJISX02132004", "UniHojo", "UniGB", "UniCNS", "UniKS", "UniAKR"]; + if !collections.contains(&collection) { + return None; + } + match form { + "UCS2" | "UTF16" => Some(Unicode::Utf16), + "UTF8" => Some(Unicode::Utf8), + "UTF32" => Some(Unicode::Utf32), + _ => None, + } +} + +/// The characters string `s` encodes in Unicode form `form` (invalid codes left out). +fn unicode_text(s: &[u8], form: Unicode) -> String { + match form { + Unicode::Utf16 => { + let units = s.as_chunks::<2>().0.iter().map(|b| u16::from_be_bytes(*b)); + char::decode_utf16(units).filter_map(Result::ok).collect() + } + Unicode::Utf8 => s.utf8_chunks().map(|chunk| chunk.valid()).collect(), + Unicode::Utf32 => s.as_chunks::<4>().0.iter().filter_map(|b| char::from_u32(u32::from_be_bytes(*b))).collect(), + } +} + +/// Predefined CMap `name` among those VectorCraft carries, leaving out the Identity CMaps, whose +/// codes are CIDs of no known character collection. +fn predefined(name: &str) -> Option> { + match CMapName::from_bytes(name.as_bytes()) { + CMapName::Custom(_) | CMapName::IdentityH | CMapName::IdentityV => None, + name => Some(name), + } +} + +/// Adobe's predefined CMaps that VectorCraft doesn't carry, by name without `-H` or `-V` +/// (): the nearest carried CMap with the same +/// code space, and whether each byte of a row-and-cell code gets its high bit set first (the EUC +/// form of the same code; `GB-H`, `CNS1-H` and `KSC-H` have no one-byte codes, their code space +/// is `<2121>` to `<7E7E>`); `None` for those no carried CMap reads. +fn stand_in(stem: &str) -> Option> { + Some(match stem { + "RKSJ" | "78-RKSJ" | "78ms-RKSJ" => Some(("90ms-RKSJ-H", false)), + "78-EUC" => Some(("EUC-H", false)), + "78" | "Add" | "Ext" | "NWP" => Some(("H", false)), + "GB" => Some(("GB-EUC-H", true)), + "CNS1" => Some(("CNS-EUC-H", true)), + "KSC" => Some(("KSC-EUC-H", true)), + "B5" => Some(("ETen-B5-H", false)), + "ETHK-B5" | "HKdla-B5" | "HKdlb-B5" | "HKgccs-B5" | "HKm314-B5" | "HKm471-B5" => Some(("HKscs-B5-H", false)), + "GBT" | "GBT-EUC" | "GBTpc-EUC" | "CNS2" | "KSC-Johab" => None, + _ => return None, + }) +} + +/// Predefined CMap `cmap`'s codes to CIDs, and its character collection's CID → Unicode CMap. A +/// vertical CMap's codes are read with its horizontal CMap when VectorCraft carries that: the two +/// differ only in the CIDs of vertical glyph forms. A CMap VectorCraft doesn't carry is read with +/// its [`stand_in`]. +fn cid_codes(cmap: &str) -> Option { + let read = |name: &str| CMap::parse(load_embedded(predefined(name)?)?, load_embedded); + let horizontal = cmap.strip_suffix('V').map(|stem| format!("{stem}H")); + let stem = cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V")); + let (codes, high_bit) = horizontal.iter().map(String::as_str).chain([cmap]).find_map(|n| Some((read(n)?, false))).or_else(|| { + let (name, high_bit) = stand_in(stem?).flatten()?; + Some((read(name)?, high_bit)) + })?; + let table = codes.metadata().character_collection.as_ref()?.family.ucs2_cmap()?; + let unicode = CMap::parse(load_embedded(table)?, load_embedded)?; + // A row-and-cell code read in its EUC form falls in the EUC CMap's code space. + let space = if high_bit { stand_in(stem?).flatten().and_then(|(name, _)| code_space(name)) } else { code_space(cmap) }; + Some(CMapCodes::Cids { codes: Box::new(codes), unicode: Box::new(unicode), high_bit, space }) +} + +/// The code space of predefined CMap `cmap`, as Adobe's CMap files give it +/// (); a CMap's vertical form has its +/// horizontal form's. `None` for a CMap not listed here. +fn code_space(cmap: &str) -> Option { + const RKSJ: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa0", b"\xdf"), (b"\x81\x40", b"\x9f\xfc"), (b"\xe0\x40", b"\xfc\xfc")]; + const RKSJ_MAC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa0", b"\xdf"), (b"\xfd", b"\xff"), (b"\x81\x40", b"\x9f\xfc"), (b"\xe0\x40", b"\xfc\xfc")]; + const EUC_JP: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8e\xa0", b"\x8e\xdf"), (b"\xa1\xa1", b"\xfe\xfe")]; + const ROW_CELL: CodeSpace = &[(b"\x21\x21", b"\x7e\x7e")]; + const EUC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\xa1", b"\xfe\xfe")]; + const GB_PC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xfd", b"\xff"), (b"\xa1\xa1", b"\xfc\xfe")]; + const GBK: CodeSpace = &[(b"\x00", b"\x80"), (b"\x81\x40", b"\xfe\xfe")]; + const GBK2K: CodeSpace = &[(b"\x00", b"\x7f"), (b"\x81\x40", b"\xfe\xfe"), (b"\x81\x30\x81\x30", b"\xfe\x39\xfe\x39")]; + const B5_PC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xfd", b"\xff"), (b"\xa1\x40", b"\xfc\xfe")]; + const B5: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\x40", b"\xfe\xfe")]; + const HKSCS: CodeSpace = &[(b"\x00", b"\x80"), (b"\x87\x40", b"\xfe\xfe")]; + const HKDLB: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8e\x40", b"\xfe\xfe")]; + const HKGCCS: CodeSpace = &[(b"\x00", b"\x80"), (b"\x8a\x40", b"\xfe\xfe")]; + const CNS_EUC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\xa1", b"\xfe\xfe"), (b"\x8e\xa1\xa1\xa1", b"\x8e\xa3\xfe\xfe")]; + const KSC_PC: CodeSpace = &[(b"\x00", b"\x84"), (b"\xfe", b"\xff"), (b"\xa1\x41", b"\xfd\xfe")]; + const UHC: CodeSpace = &[(b"\x00", b"\x80"), (b"\x81\x41", b"\xfe\xfe")]; + let stem = match cmap { + "H" | "V" => "", + _ => cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V"))?, + }; + let stem = stem.strip_suffix("-HW").unwrap_or(stem); + Some(match stem { + "83pv-RKSJ" | "90pv-RKSJ" => RKSJ_MAC, + _ if stem.ends_with("RKSJ") => RKSJ, + "EUC" | "78-EUC" => EUC_JP, + "" | "78" | "Add" | "Ext" | "NWP" => ROW_CELL, + "GB-EUC" | "GBT-EUC" | "KSC-EUC" => EUC, + "GBpc-EUC" | "GBTpc-EUC" => GB_PC, + "GBK-EUC" | "GBKp-EUC" => GBK, + "GBK2K" => GBK2K, + "B5pc" => B5_PC, + "B5" | "ETen-B5" | "ETenms-B5" | "HKdla-B5" | "HKm314-B5" | "HKm471-B5" => B5, + "HKscs-B5" | "ETHK-B5" => HKSCS, + "HKdlb-B5" => HKDLB, + "HKgccs-B5" => HKGCCS, + "CNS-EUC" => CNS_EUC, + "KSCpc-EUC" => KSC_PC, + "KSCms-UHC" => UHC, + _ => return None, + }) +} + +/// The length of the code string `bytes` starts with: the length of the code space range whose +/// lowest and highest codes hold each of its bytes between them. `None` when no range does. +fn code_len(space: CodeSpace, bytes: &[u8]) -> Option { + space + .iter() + .filter(|(lo, hi)| bytes.get(..lo.len()).is_some_and(|b| b.iter().zip(lo.iter().zip(hi.iter())).all(|(b, (lo, hi))| (lo..=hi).contains(&b)))) + .map(|(lo, _)| lo.len()) + .min() + .and_then(|len| u8::try_from(len).ok()) +} + +/// Encoding pairs (§3.3.1): codes, each followed by the glyph names from it on, into `table`. +fn encoding_pairs(table: &mut [Option], vals: &[V]) { + let mut code: Option = None; + for v in vals { + match v { + V::Num(n) if n.is_finite() && (0.0..256.0).contains(n) => code = Some(*n as usize), + V::Name(name) => { + if let Some(c) = code { + if let (Some(slot), Ok(b)) = (table.get_mut(c), u8::try_from(c)) { + *slot = latin::glyph(b, name); + } + code = Some(c + 1); + } + } + _ => {} } } } -fn num(vals: &[V], i: usize) -> Option { - vals.iter().filter_map(V::num).nth(i).filter(|v| v.is_finite()) +/// A composite font's name `base-CMap`: the base font's name and its CMap's name, when that is a +/// predefined Unicode CMap ([`unicode_cmap`]), one of the predefined CMaps VectorCraft carries +/// ([`predefined`]) or one of the others ([`stand_in`]), in its horizontal (`-H`) or vertical +/// (`-V`) form. A name ending in an Identity CMap is not read as one, nor is one that ends in an +/// unknown CMap name with an encoding part (`UniFoo-UTF8-H`), which would otherwise end in `H`. +fn composite_font(name: &str) -> Option<(&str, &str)> { + if !(name.ends_with("-H") || name.ends_with("-V")) { + return None; + } + // The longest CMap name first: `83pv-RKSJ-H` before `H`. + // No predefined CMap name is longer than 32 bytes. + for (at, _) in name.match_indices('-').filter(|(at, _)| name.len() - at <= 33) { + let (Some(base), Some(cmap)) = (name.get(..at).filter(|b| !b.is_empty()), name.get(at + 1..)) else { continue }; + if matches!(cmap, "Identity-H" | "Identity-V") { + return None; + } + let encoding_part = + base.rsplit('-').next().is_some_and(|part| ["UCS2", "UTF8", "UTF16", "UTF32", "HW", "EUC", "RKSJ", "B5", "UHC", "Johab"].contains(&part)); + if matches!(cmap, "H" | "V") && encoding_part { + return None; + } + let vertical_of_predefined = || cmap.strip_suffix('V').is_some_and(|stem| predefined(&format!("{stem}H")).is_some()); + let other = || cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V")).is_some_and(|stem| stand_in(stem).is_some()); + if unicode_cmap(cmap).is_some() || predefined(cmap).is_some() || vertical_of_predefined() || other() { + return Some((base, cmap)); + } + } + None +} + +/// An operator's `N` operands, the last `N` values before it, when each is a finite number. +fn nums(vals: &[V]) -> Option<[f64; N]> { + let operands = vals.get(vals.len().checked_sub(N)?..)?; + let mut out = [0.0; N]; + for (o, v) in out.iter_mut().zip(operands) { + *o = v.num().filter(|n| n.is_finite())?; + } + Some(out) +} + +/// A flag operand: 0 or 1. +fn flag(v: f64) -> Option { + match v { + 0.0 => Some(false), + 1.0 => Some(true), + _ => None, + } } impl Reader<'_> { /// `[encodingPairs TE`: codes, each followed by the glyph names from it on (§3.3.1). pub(super) fn te(&mut self, vals: &[V]) { - let mut code: Option = None; - for v in vals { - match v { - V::Num(n) if n.is_finite() && (0.0..256.0).contains(n) => code = Some(*n as usize), - V::Name(name) => { - if let Some(c) = code { - if let (Some(slot), Ok(b)) = (self.type_state.encoding.get_mut(c), u8::try_from(c)) { - *slot = latin::glyph(b, name); - } - code = Some(c + 1); + encoding_pairs(&mut self.type_state.encoding, vals); + } + + /// `[encodingPairs newFontName oldFontName direction fontScript useDefault TZ`, with a Multiple + /// Master weight vector `[w0 … wn]` after it, and without the encoding pairs or the direction + /// in some versions (§3.3.1): the new font's own encoding pairs, which strings in it are + /// decoded by first. `useDefault` 1 (or no number after the names) decodes the codes the pairs + /// leave out by `TE`'s encoding, and 0 leaves `TE`'s encoding out for the font. The font names + /// are the last two names; only numbers and the weight vector follow them. The first `TZ` for + /// a font is used. + pub(super) fn tz(&mut self, vals: &[V]) { + let mut names = vals.iter().enumerate().filter_map(|(i, v)| if let V::Name(n) = v { Some((i, n)) } else { None }).rev(); + let (Some((old_at, old)), Some((new_at, new))) = (names.next(), names.next()) else { return }; + if new_at + 1 != old_at { + return; + } + let tail = vals.get(old_at + 1..).unwrap_or_default(); + let weights = matches!(tail.last(), Some(V::Arr(_))); + let numbers = tail.get(..tail.len() - usize::from(weights)).unwrap_or_default(); + if !numbers.iter().all(|v| matches!(v, V::Num(_))) { + return; + } + let te = !matches!(numbers.last(), Some(V::Num(n)) if *n == 0.0); + let st = &mut self.type_state; + st.font_names(new, old); + if st.font_encodings.iter().any(|(n, _, _)| n == new) || st.font_encodings.len() >= MAX_FONTS { + return; + } + // The pairs start after the `[` that opens them. + let pairs = vals.get(..new_at).unwrap_or_default(); + let pairs = pairs.iter().rposition(|v| matches!(v, V::Mark)).map_or(pairs, |m| pairs.get(m + 1..).unwrap_or_default()); + let mut table = vec![None; 256]; + encoding_pairs(&mut table, pairs); + if pairs.iter().any(|v| matches!(v, V::Name(_))) { + st.paired_fonts.push(new.clone()); + } + st.font_encodings.push((new.clone(), table, te)); + } + + /// What is between `%AI3_BeginEncoding` and `%AI3_EndEncoding` (§3.3): its `TZ` is read, and + /// every other operator is skipped with its operands. + pub(super) fn encoding_section(&mut self, section: &[u8]) { + let mut lex = super::Lexer::new(section); + let mut vals: Vec = Vec::new(); + let mut marks: Vec = Vec::new(); + // `[`s past the value limit, which are not kept: as many `]`s after them are skipped. + let mut dropped: usize = 0; + while let Some(t) = lex.next_token() { + let v = match t.tok { + super::Tok::Num(n) => V::Num(n), + super::Tok::Name(n) => V::Name(super::obj::text(n)), + super::Tok::Str(s) | super::Tok::Hex(s) => V::Str(s), + super::Tok::Word(b"[") => { + // Each `[` kept is a value, so the open arrays are no more than the values. + if vals.len() >= MAX_ENCODING_VALUES { + dropped = dropped.saturating_add(1); + continue; } + marks.push(vals.len()); + V::Mark } - _ => {} + super::Tok::Word(b"]") => { + if dropped > 0 { + dropped -= 1; + continue; + } + let Some(m) = marks.pop() else { continue }; + let items: Vec = vals.split_off(m.min(vals.len())).into_iter().skip(1).collect(); + V::Arr(items) + } + super::Tok::Word(w) => { + if w == b"TZ" { + self.tz(&vals); + } + vals.clear(); + marks.clear(); + dropped = 0; + continue; + } + _ => continue, + }; + if vals.len() < MAX_ENCODING_VALUES { + vals.push(v); } } } @@ -110,35 +703,47 @@ impl Reader<'_> { /// `type To`: a text object begins. pub(super) fn begin_text(&mut self, vals: &[V], hidden: bool) { self.end_path_quietly(); - let kind = num(vals, 0).map_or(0, |k| k as i64); + if self.pattern.is_some() { + self.unreadable("type in a pattern", false); + } + let kind = nums::<1>(vals).map_or(0, |[k]| k as i64); + // A tab definition left open by an earlier text object (an `Xb` with no `XB`) ends here. + self.type_state.tabs = None; self.text = Some(LegacyText { kind, gs: self.gs.clone(), hidden, ..LegacyText::default() }); } /// `a b c d tx ty startPt Tp`: the text path begins. pub(super) fn begin_text_path(&mut self, vals: &[V]) { self.end_path_quietly(); - let n: Vec = vals.iter().filter_map(V::num).collect(); let Some(t) = self.text.as_mut() else { return }; - if let Some(m) = n.get(..6).and_then(|m| <[f64; 6]>::try_from(m).ok()) { - let m = Affine::new(m); + // Seven operands, or the matrix alone. + let (m, start) = match vals.len() { + 7 => (vals.get(..6).and_then(nums::<6>), vals.get(6).and_then(V::num)), + 6 => (nums::<6>(vals), None), + _ => (None, None), + }; + let matrix = m.map(Affine::new).filter(|m| { let det = m.determinant(); - if m.as_coeffs().iter().all(|v| v.is_finite()) && det.is_finite() && det.abs() > 1e-12 { - t.matrix = Some(m); - } + det.is_finite() && det.abs() > 1e-12 + }); + let start = start.filter(|s| s.is_finite() && *s >= 0.0).unwrap_or(0.0); + t.past_limit |= t.paths.len() >= MAX_TEXT_PATHS; + if !t.past_limit { + t.paths.push(TextPath { matrix, start, path: None }); } - t.start = n.get(6).copied().filter(|s| s.is_finite() && *s >= 0.0).unwrap_or(0.0); t.in_path = true; } - /// The path painted (or `TP`, ending the text path): the text object's frame or path. + /// The path painted (or `TP`, ending the text path): the text path's frame or path. pub(super) fn text_path(&mut self) { let path = std::mem::take(&mut self.path); + let kinds = std::mem::take(&mut self.path_kinds); self.end_path_quietly(); - if let Some(t) = self.text.as_mut() - && t.path.is_none() + if let Some(p) = self.text.as_mut().filter(|t| !t.past_limit).and_then(|t| t.paths.last_mut()) + && p.path.is_none() && !path.elements().is_empty() { - t.path = Some(path); + p.path = Some((path, kinds)); } } @@ -150,56 +755,202 @@ impl Reader<'_> { } } - /// A character or paragraph attribute. + /// A character or paragraph attribute. An attribute whose operands are missing, are not + /// numbers, or are flags other than 0 and 1 stays as it was. pub(super) fn text_attr(&mut self, w: &str, vals: &[V]) { let st = &mut self.type_state; - let n0 = num(vals, 0); + let n0 = nums::<1>(vals).map(|[v]| v); match w { - "Tr" => st.render = n0.map_or(0, |v| v as i64), + // `render Tr`: a mode from 0 to 9 (§15.4.5.1). + "Tr" => { + if let Some(v) = n0.filter(|v| v.fract() == 0.0 && (0.0..=9.0).contains(v)) { + st.render = v as i64; + } + } "Tf" => { - if let Some(name) = vals.iter().find_map(|v| if let V::Name(n) = v { Some(n.clone()) } else { None }) { - let name = st - .fonts - .iter() - .find(|(new, _)| *new == name) - .map_or_else(|| name.trim_start_matches('_').to_string(), |(_, old)| old.clone()); - let (family, style) = super::super::super::text::family_style(&name); + // `/name size Tf`, or `/name size ascent descent Tf`. + let Some(at) = vals.iter().position(|v| matches!(v, V::Name(_))) else { return }; + if let Some(V::Name(name)) = vals.get(at) { + st.font = Some(name.clone()); + let full = + st.fonts.iter().find(|(new, _)| new == name).map_or_else(|| name.trim_start_matches('_').to_string(), |(_, old)| old.clone()); + // A font whose `TZ` gives encoding pairs is re-encoded, which a composite font + // can't be; a `TZ` without pairs only names the font. + let reencoded = st.paired_fonts.contains(name); + let (name, cmap) = match composite_font(&full).filter(|_| !reencoded) { + Some((base, cmap)) => (base, st.cmap_codes(cmap)), + None => (full.as_str(), None), + }; + st.cmap = cmap; + let (family, style) = super::super::super::text::family_style(name); st.style.font_family = family; st.style.font_style = style; st.style.font_version = None; } - if let Some(size) = num(vals, 0).filter(|s| *s > 0.0) { + if let Some(size) = vals.get(at + 1).and_then(V::num).filter(|s| s.is_finite() && *s > 0.0) { st.style.size = size.min(MAX_SIZE); } } - "Ts" => st.style.baseline_shift = n0.unwrap_or(0.0).clamp(-MAX_SIZE, MAX_SIZE), + "Ts" => { + if let Some(v) = n0 { + st.style.baseline_shift = v.clamp(-MAX_SIZE, MAX_SIZE); + } + } "Tz" => { + // `parallelScale perpendicularScale Tz`; before version 7, `scale Tz`. let scale = |v: f64| v.clamp(1.0, 10_000.0); - st.style.h_scale = n0.map_or(100.0, scale); - st.style.v_scale = num(vals, 1).map_or(100.0, scale); + let scales = match vals.len() { + 2 => nums::<2>(vals), + 1 => n0.map(|h| [h, 100.0]), + _ => None, + }; + if let Some([h, v]) = scales { + (st.style.h_scale, st.style.v_scale) = (scale(h), scale(v)); + } + } + "Tt" => { + if let Some(v) = n0 { + st.style.tracking = v.clamp(-10_000.0, 10_000.0); + } + } + "TA" => { + if let Some(auto) = n0.and_then(flag) { + st.style.kerning = if auto { None } else { Some(0.0) }; + } } - "Tt" => st.style.tracking = n0.unwrap_or(0.0).clamp(-10_000.0, 10_000.0), - "TA" => st.style.kerning = if n0 == Some(0.0) { Some(0.0) } else { None }, "Tl" => { - if let Some(l) = n0 { + // `leading paragraphLeading Tl`; before version 7, `leading Tl`. + let leading = match vals.len() { + 2 => nums::<2>(vals), + 1 => n0.map(|l| [l, 0.0]), + _ => None, + }; + if let Some([l, before]) = leading { let l = l.clamp(0.0, MAX_SIZE); // The automatic leading, 120% of the size, stays automatic. st.style.leading = if (l - st.style.size * 1.2).abs() < 1e-3 { None } else { Some(l) }; + st.para.space_before = before.clamp(-MAX_SIZE, MAX_SIZE); } - st.para.space_before = num(vals, 1).unwrap_or(0.0).clamp(-MAX_SIZE, MAX_SIZE); } "Ta" => { - st.para.justify = match n0.map(|v| v as i64) { - Some(1) => Justify::Center, - Some(2) => Justify::Right, - Some(3) => Justify::JustifyLeft, - Some(4) => Justify::JustifyAll, - _ => Justify::Left, + let justify = match n0 { + Some(0.0) => Some(Justify::Left), + Some(1.0) => Some(Justify::Center), + Some(2.0) => Some(Justify::Right), + Some(3.0) => Some(Justify::JustifyLeft), + Some(4.0) => Some(Justify::JustifyAll), + _ => None, + }; + if let Some(j) = justify { + st.para.justify = j; } } "Ti" => { - let indent = |i: usize| num(vals, i).unwrap_or(0.0).clamp(-MAX_SIZE, MAX_SIZE); - (st.para.first_line_indent, st.para.left_indent, st.para.right_indent) = (indent(0), indent(1), indent(2)); + if let Some(i) = nums::<3>(vals) { + let [first, left, right] = i.map(|v| v.clamp(-MAX_SIZE, MAX_SIZE)); + (st.para.first_line_indent, st.para.left_indent, st.para.right_indent) = (first, left, right); + } + } + // `min opt max TC` (letter spacing) and `min opt max TW` (word spacing), in percent of + // a space's width, as the paragraph's Justification options take them. + "TC" | "TW" => { + if let Some(v) = nums::<3>(vals) { + let j = &mut st.para.justification; + if w == "TC" { + j.letter_spacing = v; + } else { + j.word_spacing = v; + } + j.keep_in_range(); + } + } + // `hangingQuotes Tq`. + "Tq" => { + if let Some(on) = n0.and_then(flag) { + st.para.roman_hanging = on; + } + } + // `bindrepeat Tg` (§15.3.4): 1 and 3 turn binding punctuation on, and 0 and 2 turn it + // off. VectorCraft's own mapping opens it on as Burasagari's Force setting and off as no + // Burasagari. The repeat character (2 and 3) is not kept. + "Tg" => { + let burasagari = match n0 { + Some(1.0 | 3.0) => Some(Burasagari::Forced), + Some(0.0 | 2.0) => Some(Burasagari::None), + _ => None, + }; + if let Some(b) = burasagari { + st.para.burasagari = b; + } + } + // `hyphenate limitHyphLines minLeadHyphen minTailHyphen maxHyphLines Th`, kept to the + // ranges `text.setFormat` takes. + "Th" => { + let Some([on, limit, lead, tail, max]) = nums::<5>(vals) else { return }; + let (Some(on), Some(limit)) = (flag(on), flag(limit)) else { return }; + let letters = |v: f64, lo: f64, hi: f64| v.round().clamp(lo, hi) as u32; + st.para.hyphenate = on; + let h = &mut st.para.hyphenation; + h.after_first = letters(lead, 1.0, 15.0); + h.before_last = letters(tail, 1.0, 15.0); + h.hyphen_limit = if limit { letters(max, 0.0, 25.0) } else { 0 }; + } + // `direction TV` (§15.3.4): 0 horizontal, 1 vertical. + "TV" => { + if let Some(on) = n0.and_then(flag) { + st.vertical = on; + } + } + // `rotation Tv`: in vertical writing, 0 rotates Roman characters 90 degrees clockwise and + // 1 keeps them upright. + "Tv" => { + if let Some(on) = n0.and_then(flag) { + st.style.standard_vertical_roman = on; + } + } + // `kumi Ty`: 1 begins a Kumi block and 0 ends it. + "Ty" => { + if let Some(on) = n0.and_then(flag) { + st.style.tate_chu_yoko = on; + } + } + // `kumi TY`: as `Ty`, for a block that does not appear in the set text. + "TY" => { + if let Some(on) = n0.and_then(flag) { + st.kumi_recorded = on; + } + } + // A tab definition (§22.6): `numDots numTabs Xb` begins it, each + // `leader decimal tabType tabPosition Xe` describes one tab stop, and `XB` ends it. The + // stops it describes replace the paragraph's tab stops, sorted by position, one stop at + // each position; a definition with none (or whose descriptions were all skipped) leaves + // the default stops. The dot-leader distance, the count and the two reserved operands are + // not read. A description whose type is not 1 to 4 (left, center, right, decimal) or + // whose position is not a number from 0 to [`MAX_TAB_POSITION`] is skipped, and so is one + // outside a tab definition or past the first [`MAX_TABS`] of one. A text object's `To` + // ends a definition that an earlier object left open. + "Xb" => st.tabs = Some(vec![]), + "Xe" => { + let Some(tabs) = st.tabs.as_mut().filter(|t| t.len() < MAX_TABS) else { return }; + let Some([kind, position]) = nums::<2>(vals) else { return }; + let align = match kind { + 1.0 => TabAlign::Left, + 2.0 => TabAlign::Center, + 3.0 => TabAlign::Right, + 4.0 => TabAlign::Decimal, + _ => return, + }; + if (0.0..=MAX_TAB_POSITION).contains(&position) { + tabs.push(TabStop { position, align, leader: String::new(), align_on: '.' }); + } + } + "XB" => { + if let Some(mut tabs) = st.tabs.take() { + tabs.sort_by(|a, b| a.position.total_cmp(&b.position)); + tabs.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6); + st.para.tabs = tabs; + st.tabs_version = st.tabs_version.wrapping_add(1); + } } _ => {} } @@ -210,24 +961,38 @@ impl Reader<'_> { let Some(bytes) = vals.iter().rev().find_map(|v| if let V::Str(s) = v { Some(s.clone()) } else { None }) else { return }; let st = &mut self.type_state; let Some(t) = self.text.as_mut() else { return }; - let decoded: String = bytes - .iter() - .map(|&b| if b == b'\r' { '\n' } else { st.encoding.get(usize::from(b)).copied().flatten().unwrap_or_else(|| latin::decode(b)) }) - .collect(); + let decoded = st.decode(&bytes); if decoded.is_empty() { return; } // Overflow text ending the story with a paragraph break (`(\r) TX`) adds no paragraph. if w == "TX" && decoded == "\n" { - t.pending_break = true; + if t.pending_break.is_none() { + let para = (!t.para_taken).then(|| (st.para.clone(), st.tabs_version)); + t.pending_break = Some(PendingBreak { vertical: st.vertical, para }); + } return; } - if st.chars >= MAX_CHARS { + // As many characters as the file's allowance has left. + let room = MAX_CHARS.saturating_sub(st.chars); + if room == 0 { return; } + let decoded: String = decoded.chars().take(room).collect(); st.chars += decoded.chars().count(); + // A break read before these characters keeps the direction and paragraph attributes it was + // read with, and is the story's first character when nothing came before it. + let brk = t.pending_break.take(); + if t.runs.is_empty() { + t.vertical = brk.as_ref().map_or(st.vertical, |b| b.vertical); + } + t.direction_changed |= st.vertical != t.vertical || brk.as_ref().is_some_and(|b| b.vertical != t.vertical); let gs = &self.gs; let mut style = st.style.clone(); + style.tate_chu_yoko |= st.kumi_recorded && !t.vertical; + // Characters in modes 4 to 7 make the whole text object the mask, not each run (§5.7); 7 + // paints nothing, nor does 3 (invisible). + t.clips |= (4..=7).contains(&st.render); let (fill, stroke) = match st.render { 0 | 4 => (true, false), 1 | 5 => (false, true), @@ -236,23 +1001,26 @@ impl Reader<'_> { }; style.fill = if fill { gs.fill.clone() } else { Paint::None }; style.stroke = if stroke { gs.stroke.clone() } else { Paint::None }; - style.stroke_width = if stroke { gs.width } else { 0.0 }; + style.stroke_width = if stroke { gs.line_width() } else { 0.0 }; (style.stroke_cap, style.stroke_join, style.stroke_miter_limit, style.stroke_dash) = (gs.cap, gs.join, gs.miter, gs.dash.clone()); (style.overprint_fill, style.overprint_stroke) = (gs.overprint_fill, gs.overprint_stroke); let mut text = String::new(); - if std::mem::take(&mut t.pending_break) { + if let Some(brk) = brk { + if let Some((mut para, tabs_version)) = brk.para { + t.begin_para(&mut para, tabs_version); + } text.push('\n'); t.para_taken = false; } for c in decoded.chars() { if c != '\n' && !t.para_taken { - t.paras.push(st.para.clone()); + t.begin_para(&mut st.para, st.tabs_version); t.para_taken = true; } text.push(c); if c == '\n' { if !t.para_taken { - t.paras.push(st.para.clone()); + t.begin_para(&mut st.para, st.tabs_version); } t.para_taken = false; } @@ -263,33 +1031,128 @@ impl Reader<'_> { } } - /// `TO`: the text object ends. + /// `TO`: the text object ends. Area type with several linked areas becomes one frame for each + /// area, threaded in file order: the first frame holds the story, and the flow from area to + /// area (final-form, §15.1) is laid out again. The frames are added last to first, so the + /// object's dictionary that follows names the first one ([`Reader::each_linked_frame`]). + /// Point type is read at its first text path; area type and type on a path at the first one + /// that has a frame or path (else at the first one, as point type). pub(super) fn end_text(&mut self, hidden: bool) -> Result<(), String> { - let Some(t) = self.text.take() else { return Ok(()) }; + let Some(mut t) = self.text.take() else { return Ok(()) }; if t.runs.is_empty() { return Ok(()); } - let m = t.matrix.unwrap_or(Affine::IDENTITY); let to_doc = self.space(); - // Art space → text space (y down). - let to_text = FLIP * m.inverse(); - let kind = match (t.kind, &t.path) { - (1, Some(p)) => TextKind::Area { frame: PathData::from_bezpath(&(to_text * p.clone())) }, - (2, Some(p)) => TextKind::OnPath { path: PathData::from_bezpath(&(to_text * p.clone())), start: start_fraction(p, t.start), end: None }, - _ => TextKind::Point, + let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum(); + let most = (MAX_THREAD_WORK / chars.max(1)).max(1); + let all_areas = t.paths.iter().filter(|p| p.path.is_some()).count(); + // Area type with linked areas, also when the limits leave one frame of it. + let linked = t.kind == 1 && (all_areas > 1 || t.past_limit); + let areas: Vec<&TextPath> = t.paths.iter().filter(|p| p.path.is_some()).take(most).collect(); + let placed: Vec<(Affine, TextKind)> = match t.kind { + 1 if areas.len() > 1 => areas.into_iter().map(|p| placed(1, Some(p))).collect(), + 0 => vec![placed(0, t.paths.first())], + kind => vec![placed(kind, areas.first().copied().or(t.paths.first()))], }; - let mut obj = TextObject::point(kurbo::Point::ZERO, "", CharStyle::default()); - obj.kind = kind; - obj.xf = to_doc * m * FLIP; - obj.runs = t.runs; - let mut paras = t.paras; - if paras.is_empty() { - paras.push(self.type_state.para.clone()); + if t.kind == 1 && (t.past_limit || all_areas > placed.len()) { + self.warn(LINKED_AREAS_LEFT_OUT); } - obj.set_paragraph_styles(paras); - let node = self.new_node(NodeKind::Text(Box::new(obj)), &t.gs); - self.add(node, t.hidden || hidden) + if t.direction_changed { + self.warn(DIRECTION_CHANGE_LEFT_OUT); + } + let mut paras = std::mem::take(&mut t.paras); + if paras.is_empty() { + paras.push(ParaRun { style: self.type_state.para.clone(), count: 1, tabs_version: 0 }); + } + let last_para = paras.last().map(|r| r.style.clone()).unwrap_or_default(); + let last_style = t.runs.last().map(|r| r.style.clone()).unwrap_or_default(); + let mut story = Some((std::mem::take(&mut t.runs), paras)); + // The tab stops copied into the paragraphs and frames. + let mut copied = 0; + let mut nodes = Vec::with_capacity(placed.len()); + for (m, kind) in placed { + let mut obj = TextObject::point(kurbo::Point::ZERO, "", last_style.clone()); + obj.kind = kind; + obj.vertical = t.vertical; + obj.xf = to_doc * m * FLIP; + match story.take() { + Some((runs, paras)) => { + obj.runs = runs; + // Paragraphs that all have the same attributes share one copy of them. + match <[ParaRun; 1]>::try_from(paras) { + Ok([one]) => obj.set_all_paras(one.style), + Err(paras) => obj.set_paragraph_styles(each_paragraph(paras, &mut copied, &mut t.tabs_left_out)), + } + } + None => obj.set_all_paras(within_tabs(&last_para, &mut copied, &mut t.tabs_left_out)), + } + nodes.push(self.new_node(NodeKind::Text(Box::new(obj)), &t.gs)); + } + if t.tabs_left_out { + self.warn(TABS_LEFT_OUT); + } + let frames: Vec = nodes.iter().map(|n| n.id).collect(); + // Type used as a mask clips the objects of its clipping group, as a `W` path does. A + // clipping path is one object, and wraparound text and compound paths don't clip their + // objects with type, so the frames of linked areas and type in those don't clip, with a + // warning. The frames up to the clipping group or opacity mask's art are checked, a group in + // either included. + let in_wrap_or_compound = self + .frames + .iter() + .rev() + .take_while(|f| !matches!(f.kind, Kind::Clip | Kind::Mask | Kind::Layer(_))) + .any(|f| matches!(f.kind, Kind::Wrap | Kind::Compound)); + let can_clip = !linked && nodes.len() == 1 && !in_wrap_or_compound; + if t.clips && !can_clip { + self.warn(MASK_NOT_CLIPPED); + } + for node in nodes.into_iter().rev() { + if t.clips + && can_clip + && let Some(f) = self.frames.last_mut() + { + f.clips.push(f.children.len()); + } + self.add(node, t.hidden || hidden)?; + } + if frames.len() > 1 { + self.doc.text_threads.push(frames); + } + Ok(()) } + + /// Call `f` on the other frames of the threaded text object just read, whose first frame is + /// the last object ([`Reader::end_text`]): the opacity mask and text wrap of the object's + /// dictionary apply to every frame. + pub(super) fn each_linked_frame(&mut self, mut f: impl FnMut(&mut Node)) { + if !self.after_object { + return; + } + let Some(first) = self.frames.last().and_then(|fr| fr.children.last()).map(|n| n.id) else { return }; + let Some(thread) = self.doc.text_threads.last().filter(|t| t.first() == Some(&first)) else { return }; + let rest: HashSet = thread.iter().skip(1).copied().collect(); + let Some(fr) = self.frames.last_mut() else { return }; + for n in fr.children.iter_mut().rev().skip(1).take(rest.len()).filter(|n| rest.contains(&n.id)) { + f(n); + } + } +} + +/// A text object of type `kind` on text path `p` (none: at the origin): the matrix from text space +/// (y up) to art space, and the kind of type with its frame or path in text space (y down). +fn placed(kind: i64, p: Option<&TextPath>) -> (Affine, TextKind) { + let m = p.and_then(|p| p.matrix).unwrap_or(Affine::IDENTITY); + // Art space → text space (y down). + let to_text = FLIP * m.inverse(); + let kind = match (kind, p.and_then(|p| p.path.as_ref().map(|path| (path, p.start)))) { + (1, Some(((path, kinds), _))) => TextKind::Area { frame: path_data(&(to_text * path.clone()), kinds) }, + (2, Some(((path, kinds), start))) => { + TextKind::OnPath { path: path_data(&(to_text * path.clone()), kinds), start: start_fraction(path, start), end: None } + } + _ => TextKind::Point, + }; + (m, kind) } /// Where type on `path` starts (`index.fraction`: a segment and how far along it, §15.5.2), as a diff --git a/crates/eps/src/import/ai/lex.rs b/crates/eps/src/import/ai/lex.rs index 071176bb4a..810a01c3f2 100644 --- a/crates/eps/src/import/ai/lex.rs +++ b/crates/eps/src/import/ai/lex.rs @@ -8,6 +8,9 @@ //! line starts a comment that is skipped. //! - The binary image data after `%%BeginData:` is one [`Tok::Data`]; the binary preview of a placed //! file is one [`Tok::Preview`]. +//! - A document included whole (`%%BeginDocument:` … `%%EndDocument` lines, DSC 3.0 p. 68, nested +//! ones counted, the counted payloads of `%%BeginData:` and `%%BeginBinary:` inside skipped) is +//! one [`Tok::Document`]. use super::super::lex::{find, hex_decode}; @@ -29,6 +32,9 @@ pub(super) enum Tok<'a> { Data(&'a [u8]), /// A placed file's preview: what is between `%AI26_BeginPlacedObjectPreview` and its end. Preview(&'a [u8]), + /// A document included whole: what is between `%%BeginDocument:`'s line and the line of the + /// `%%EndDocument` that ends it, or `None` when none does (the rest of the data is skipped). + Document(Option<&'a [u8]>), } #[derive(Clone, Debug, PartialEq)] @@ -40,9 +46,65 @@ pub(super) struct Token<'a> { /// A placed file's preview (binary): (begin, end) markers. const PREVIEW: (&[u8], &[u8]) = (b"%AI26_BeginPlacedObjectPreview", b"%AI26_EndPlacedObjectPreview"); -/// A binary section skipped whole: (begin, end) markers. +/// A placed file's markers, which a hidden one has on `%_` lines. +const PLACE: [&[u8]; 2] = [b"%AI5_BeginPlace", b"%AI5_EndPlace"]; +/// A path's note comments, also read on `%_` lines. +const NOTES: [&[u8]; 3] = [b"%AI3_Note:", b"%%Note:", b"%AI5_NoteMore:"]; +/// The markers around a placed file's relative folder, which a hidden one has on `%_` lines too. +const RELATIVE: [&[u8]; 2] = [b"%AI28_BeginPlacedRelativePath", b"%AI28_EndPlacedRelativePath"]; +/// A document included whole: (begin, end) markers. const DOCUMENT: (&[u8], &[u8]) = (b"%%BeginDocument", b"%%EndDocument"); +/// The line of `src` before the one that starts at `at`, without its line end, when it ends within +/// [`OPERAND_LINE`] bytes of `at` and is no longer than that. +fn previous_line(src: &[u8], at: usize) -> Option<&[u8]> { + let before = src.get(at.saturating_sub(OPERAND_LINE)..at)?; + let end = before.iter().rposition(|b| !is_eol(*b))? + 1; + let start = before.get(..end)?.iter().rposition(|b| is_eol(*b))? + 1; + before.get(start..end) +} + +/// The longest line of an image's `XI` operands looked at. +const OPERAND_LINE: usize = 1024; + +/// How many bytes the alpha channel of an image whose `XI` operands are on `line` takes (`[matrix] +/// llx lly urx ury w h bits type alpha …`, `%_` before them in a hidden object): a byte a pixel when +/// the alpha count isn't 0, else none (or when the operands aren't of that shape). +fn alpha_bytes(line: &[u8]) -> usize { + let line = line.strip_prefix(b"%_").unwrap_or(line); + let Some(after) = line.iter().rposition(|b| *b == b']').and_then(|i| line.get(i + 1..)) else { return 0 }; + let nums: Vec = std::str::from_utf8(after).unwrap_or_default().split_whitespace().take(9).map_while(|w| w.parse().ok()).collect(); + match (nums.get(4), nums.get(5), nums.get(8)) { + // At most the pixels the reader reads an image with. + (Some(&w), Some(&h), Some(&a)) if a > 0.0 && w >= 1.0 && h >= 1.0 && w * h <= (1u64 << 25) as f64 => (w * h) as usize, + _ => 0, + } +} + +/// Where in `w` the `%%EndData` that ends an image's samples starts: the first one on a line whose +/// next line is `XH` (`%_XH` in a hidden object), as an image's is; else the first one that a line +/// end, or the end of `w`, follows. +fn end_data(w: &[u8]) -> Option { + const MARK: &[u8] = b"%%EndData"; + let mut first = None; + let mut at = 0; + while let Some(i) = w.get(at..).and_then(|r| find(r, MARK)) { + let i = at + i; + let rest = w.get(i + MARK.len()..).unwrap_or_default(); + if rest.first().is_none_or(|b| matches!(b, b'\r' | b'\n')) { + let next = rest.strip_prefix(b"\r").unwrap_or(rest); + let next = next.strip_prefix(b"\n").unwrap_or(next); + let next = next.strip_prefix(b"%_").unwrap_or(next); + if next.starts_with(b"XH") { + return Some(i); + } + first = first.or(Some(i)); + } + at = i + 1; + } + first +} + fn is_space(b: u8) -> bool { matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b'\x0c' | b'\0') } @@ -71,7 +133,8 @@ impl<'a> Lexer<'a> { self.src.get(self.pos).copied() } - fn rest(&self) -> &'a [u8] { + /// The data from where the next token is looked for. + pub fn rest(&self) -> &'a [u8] { self.src.get(self.pos..).unwrap_or_default() } @@ -87,11 +150,28 @@ impl<'a> Lexer<'a> { rest.get(..n).unwrap_or_default() } + /// [`Self::line`], the position moved past its end too (`\r`, `\n` or `\r\n`). + fn whole_line(&mut self) -> &'a [u8] { + let line = self.line(); + if self.peek() == Some(b'\r') { + self.pos += 1; + } + if self.peek() == Some(b'\n') { + self.pos += 1; + } + line + } + /// Where the next token is looked for. pub fn offset(&self) -> usize { self.pos } + /// Look for the next token at `pos` again (the end of the data at most). + pub fn seek(&mut self, pos: usize) { + self.pos = pos.min(self.src.len()); + } + /// The data from `from` to `to` (empty where that isn't in it). pub fn slice(&self, from: usize, to: usize) -> &'a [u8] { self.src.get(from..to).unwrap_or_default() @@ -137,6 +217,11 @@ impl<'a> Lexer<'a> { if start { return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: false }); } + // So does a hidden placed file: its `~` ends what `%_%AI5_BeginPlace` begins. And a + // hidden path's note. + if prefixed && PLACE.iter().chain(&NOTES).chain(&RELATIVE).any(|m| line.starts_with(m)) { + return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: true }); + } // A comment later in a line. continue; } @@ -169,13 +254,15 @@ impl<'a> Lexer<'a> { /// The token a comment line stands for when it starts a section read differently: image data /// (`%%BeginData:` followed by `XI`), a placed file's preview and skipped binary sections. fn special(&mut self, line: &'a [u8]) -> Option> { - if let Some((_, end)) = [PREVIEW, DOCUMENT].iter().find(|(b, _)| line.starts_with(b)) { + if line.starts_with(PREVIEW.0) { let from = self.pos; - let after = find(self.rest(), end).map_or(self.src.len(), |i| self.pos + i); + let after = find(self.rest(), PREVIEW.1).map_or(self.src.len(), |i| self.pos + i); self.pos = after; self.line(); - let tok = if *end == PREVIEW.1 { Tok::Preview(self.slice(from, after)) } else { Tok::Comment(line.get(1..).unwrap_or_default()) }; - return Some(Token { tok, hidden: false }); + return Some(Token { tok: Tok::Preview(self.slice(from, after)), hidden: false }); + } + if line.starts_with(DOCUMENT.0) { + return Some(Token { tok: Tok::Document(self.document()), hidden: false }); } let n = line.strip_prefix(b"%%BeginData:")?; let n: usize = std::str::from_utf8(n).ok()?.split_whitespace().next()?.parse().ok()?; @@ -196,12 +283,18 @@ impl<'a> Lexer<'a> { (Some(b'\r' | b'\n'), _) => data += 1, _ => {} } - // The count leaves out an alpha channel: the data ends where `%%EndData` starts. + // The count leaves out an alpha channel: the data ends where `%%EndData` starts, the first one + // that a line end or the end of the data follows (samples can hold the marker's bytes). let declared = from.saturating_add(n).min(self.src.len()).max(data); - let window = - self.src.get(declared.saturating_sub(4).max(data)..declared.saturating_add(n.saturating_mul(2)).saturating_add(64).min(self.src.len())); - let end = match window.and_then(|w| find(w, b"%%EndData")) { - Some(i) => declared.saturating_sub(4).max(data) + i, + // The alpha channel the line before gives the image (its `XI` operands) follows the counted + // samples: the marker is looked for after it. + let line_start = self.pos.saturating_sub(line.len()); + let line_start = if line_start >= 2 && self.src.get(line_start - 2..line_start) == Some(b"%_") { line_start - 2 } else { line_start }; + let alpha = previous_line(self.src, line_start).map_or(0, alpha_bytes); + let start = if alpha > 0 { declared.saturating_add(alpha).saturating_sub(2) } else { declared.saturating_sub(4) }.max(data); + let stop = declared.saturating_add(n.saturating_mul(2)).saturating_add(64).max(start.saturating_add(64)).min(self.src.len()); + let end = match self.src.get(start..stop).and_then(end_data) { + Some(i) => start + i, None => declared, }; self.pos = end; @@ -210,6 +303,55 @@ impl<'a> Lexer<'a> { Some(Token { tok: Tok::Data(samples), hidden: false }) } + /// After a `%%BeginDocument:` line: the document up to the start of the `%%EndDocument` line + /// that ends it, the position moved past that line. A `%%BeginDocument:` line inside starts a + /// nested document, and the bytes a `%%BeginData:` or `%%BeginBinary:` line inside counts are + /// skipped (DSC 3.0 pp. 68 and 72): a marker in them ends nothing. `None` when no line ends it: + /// the position moves to the end of the data. + fn document(&mut self) -> Option<&'a [u8]> { + // The rest of the `%%BeginDocument:` line is its end; the line after the document starts + // tokens afresh (not hidden unless it starts with `%_`). + self.whole_line(); + self.hidden = false; + let from = self.pos; + let mut depth = 0usize; + while self.pos < self.src.len() { + let start = self.pos; + // A hidden object's document is on `%_` lines. + let line = self.whole_line(); + let line = line.strip_prefix(b"%_").unwrap_or(line); + if line.starts_with(DOCUMENT.1) { + if depth == 0 { + return Some(self.slice(from, start)); + } + depth -= 1; + } else if line.starts_with(DOCUMENT.0) { + depth = depth.saturating_add(1); + } else if let Some(n) = line.strip_prefix(b"%%BeginData:").or_else(|| line.strip_prefix(b"%%BeginBinary:")) { + self.skip_counted(n); + } + } + None + } + + /// Skip what a `%%BeginData:` or `%%BeginBinary:` comment counts (`n`, its text after the + /// colon): `count [type [Bytes|Lines]]`, bytes unless it says `Lines`. + fn skip_counted(&mut self, n: &[u8]) { + let mut words = std::str::from_utf8(n).unwrap_or_default().split_whitespace(); + let Some(count) = words.next().and_then(|c| c.parse::().ok()) else { return }; + if words.nth(1).is_some_and(|unit| unit.eq_ignore_ascii_case("lines")) { + for _ in 0..count { + if self.pos >= self.src.len() { + break; + } + self.whole_line(); + } + } else { + // The count starts after the comment's line end, which `document` has passed. + self.pos = self.pos.saturating_add(count).min(self.src.len()); + } + } + /// A regular token's characters. fn word(&mut self) -> &'a [u8] { let start = self.pos; @@ -356,11 +498,38 @@ mod tests { let toks = all(b"%AI26_BeginPlacedObjectPreview\r\n2 1 (\x00\xff\r\n%AI26_EndPlacedObjectPreview\r\nN\r\n"); assert_eq!(toks, vec![t(Tok::Preview(b"\r\n2 1 (\x00\xff\r\n"), false), t(Tok::Word(b"N"), false)]); let toks = all(b"%%BeginDocument: a.eps\n(\x00 frobnicate\n%%EndDocument\nN\n"); - assert_eq!(toks, vec![t(Tok::Comment(b"%BeginDocument: a.eps"), false), t(Tok::Word(b"N"), false)]); + assert_eq!(toks, vec![t(Tok::Document(Some(b"(\x00 frobnicate\n")), false), t(Tok::Word(b"N"), false)]); // One that doesn't end takes the rest. assert_eq!(all(b"%AI26_BeginPlacedObjectPreview\r1 (").len(), 1); } + #[test] + fn an_included_document_ends_at_its_own_end_line() { + // A nested document, `%%EndDocument` later in a line and in counted data end nothing; `\r\n`, + // `\r` and `\n` lines alike. + let body = b"1 0 0 setrgbcolor\r\n%%BeginDocument: inner.eps\r(%%EndDocument) pop\r%%EndDocument\r\n\ + %%BeginData: 14 Binary Bytes\n%%EndDocument\n%%BeginBinary: 14\n%%EndDocument\n\ + %%BeginData: 1 Hex Lines\n%%EndDocument\n"; + let mut src = b"%%BeginDocument: outer.eps\r\n".to_vec(); + src.extend_from_slice(body); + src.extend_from_slice(b"%%EndDocument\r\n~\r\n"); + assert_eq!(all(&src), vec![t(Tok::Document(Some(body)), false), t(Tok::Word(b"~"), false)]); + // On a hidden object's `%_` lines. + let toks = all(b"%_%%BeginDocument: a.eps\r%_1 0 0 setrgbcolor\r%_%%EndDocument\r%_~\r"); + assert_eq!(toks, vec![t(Tok::Document(Some(b"%_1 0 0 setrgbcolor\r")), true), t(Tok::Word(b"~"), true)]); + // The line after it is hidden only when it starts with `%_`. + let toks = all(b"%_%%BeginDocument: a.eps\r%_%%EndDocument\rN\r"); + assert_eq!(toks, vec![t(Tok::Document(Some(b"")), true), t(Tok::Word(b"N"), false)]); + } + + #[test] + fn an_included_document_that_doesnt_end_takes_the_rest() { + for src in [&b"%%BeginDocument: a.eps\n%%BeginDocument: b.eps\n%%EndDocument\n~\n"[..], b"%%BeginDocument: a.eps\n%%BeginData: 99999999999\n"] + { + assert_eq!(all(src), vec![t(Tok::Document(None), false)]); + } + } + #[test] fn skip_past_data() { let mut l = Lexer::new(b"/Binary : /ASCII85Decode ,\r\n%_(abc[%\r\n%x~>\r\n%_; 1"); diff --git a/crates/eps/src/import/ai/mesh.rs b/crates/eps/src/import/ai/mesh.rs index b5a3ee574a..3937045dbe 100644 --- a/crates/eps/src/import/ai/mesh.rs +++ b/crates/eps/src/import/ai/mesh.rs @@ -1,5 +1,5 @@ //! Gradient meshes: `/Mesh X!`, then on `%_` lines `value /key X#` entries — the colour space -//! (`/CS`), and per patch its place (`/P [row col]`) and four corners (`/N`, from the corner nearest +//! (`/CS`, see [`Space`]), and per patch its place (`/P [row col]`) and four corners (`/N`, from the corner nearest //! the origin round to the one beside it), ended by `/E` — and `/End X!`. //! //! A corner is `[colour… opacity x y` then the handle towards the next corner, a weight, the handle @@ -18,14 +18,16 @@ use vectorcraft_doc::live::{GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, MeshPoi use super::obj::V; -/// The most patches read from one mesh. -const MAX_PATCHES: usize = 4096; +/// The most patches read from one mesh (files users sent have up to 97 × 72). +const MAX_PATCHES: usize = 16_384; /// The most points kept from one mesh: a patch with anchors on its edges is cut into cells, up to /// 34 × 34 points, so the patch cap alone doesn't bound them. const MAX_POINTS: usize = MAX_PATCHES * 16; /// The largest grid `/Size` read as one mesh, a side. -const MAX_SIDE: usize = 64; +const MAX_SIDE: usize = 128; +/// The most inks of an `/NChannel` colour space read. +const MAX_INKS: usize = 32; /// The most rows or columns a mesh stitched from its patches may have once the lines through the /// anchors on its patches' edges are added. const MAX_LINES: usize = 256; @@ -49,9 +51,109 @@ pub(super) enum NotOne { Unjoined, } +/// A mesh's colour space (`/CS`). The files write one only where it changes, before the corner +/// it applies to, even within a patch; a mesh starts grey. Besides the device spaces it may be a +/// named colour, `[c m y k /DeviceCMYK (name) /Process]` (or `/Spot`), or several process or spot +/// inks, `[[ink] [ink] … n /NChannel]` (each ink `[c m y k /DeviceCMYK (name) /Separation]`). A +/// corner gives a named colour's tint (1 is the full colour), or each ink's in order. +#[derive(Debug, Clone, Default, PartialEq)] +enum Space { + #[default] + Gray, + Rgb, + Cmyk, + /// The inks' full colours. + Inks(Vec), + /// One this doesn't read: its corners are unread. + Other, +} + +impl Space { + fn read(value: Option<&V>) -> Space { + match value { + Some(v @ (V::Name(_) | V::Str(_))) => match v.text().as_deref() { + Some("DeviceGray") => Space::Gray, + Some("DeviceRGB") => Space::Rgb, + Some("DeviceCMYK") => Space::Cmyk, + _ => Space::Other, + }, + Some(V::Arr(a)) => match a.last().and_then(V::text).as_deref() { + Some("Process" | "Spot") => ink(a).map_or(Space::Other, |c| Space::Inks(vec![c])), + Some("NChannel") => { + let inks: Vec<&Vec> = a.iter().filter_map(|v| if let V::Arr(i) = v { Some(i) } else { None }).collect(); + let count = a.len().checked_sub(2).and_then(|i| a.get(i)).and_then(V::num); + let read: Option> = inks.iter().map(|i| ink(i)).collect(); + match read { + Some(read) if !read.is_empty() && read.len() <= MAX_INKS && count == Some(read.len() as f64) => Space::Inks(read), + _ => Space::Other, + } + } + _ => Space::Other, + }, + _ => Space::Other, + } + } + + /// The colour components a corner gives. + fn components(&self) -> Option { + match self { + Space::Gray => Some(1), + Space::Rgb => Some(3), + Space::Cmyk => Some(4), + Space::Inks(inks) => Some(inks.len()), + Space::Other => None, + } + } + + fn color(&self, c: &[f64]) -> Option { + let u = |i: usize| c.get(i).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1.0) as f32); + Some(match self { + Space::Gray => Color::gray(1.0 - u(0)?), + Space::Rgb => Color::rgb(u(0)?, u(1)?, u(2)?), + Space::Cmyk => Color::cmyk(u(0)?, u(1)?, u(2)?, u(3)?), + Space::Inks(inks) => match inks.as_slice() { + [one] => one.tinted(u(0)?), + // Several inks overprint: their CMYK at their tints, added up. + many => { + let mut sum = [0.0f32; 4]; + for (i, ink) in many.iter().enumerate() { + let Color::Cmyk { c, m, y, k } = *ink else { return None }; + let t = u(i)?; + for (s, v) in sum.iter_mut().zip([c, m, y, k]) { + *s += v * t; + } + } + let [c, m, y, k] = sum.map(|v| v.min(1.0)); + Color::cmyk(c, m, y, k) + } + }, + Space::Other => return None, + }) + } +} + +/// A named colour or ink's full colour: `[c m y k /DeviceCMYK (name) /kind]` or `[r g b /DeviceRGB …]`. +fn ink(a: &[V]) -> Option { + let at = a.iter().position(|v| matches!(v, V::Name(_)))?; + let nums: Vec = a.get(..at)?.iter().map(|v| v.num().filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1.0) as f32)).collect::>()?; + match (a.get(at).and_then(V::text).as_deref(), nums.as_slice()) { + (Some("DeviceCMYK"), &[c, m, y, k]) => Some(Color::cmyk(c, m, y, k)), + (Some("DeviceRGB"), &[r, g, b]) => Some(Color::rgb(r, g, b)), + _ => None, + } +} + +/// A corner as read: its colour in the colour space it was given in, and the numbers after it +/// (opacity, unless the file is older, then the point and its handles). +#[derive(Debug, Clone)] +struct RawCorner { + color: Option, + rest: Vec, +} + #[derive(Debug, Default)] pub(super) struct MeshReader { - space: String, + space: Space, /// `/Type` (`Cartesian` in the files read). kind: Option, /// `/Size [a b]`: the grid's patches along the first and the second index of `/P`. @@ -60,7 +162,7 @@ pub(super) struct MeshReader { at: Option<(i64, i64)>, /// The patches read, in order, for [`Self::one_mesh`]. cells: Vec, - corners: Vec>, + corners: Vec, /// The patch's anchors between its corners (`/A`, `/S`): the edge, and a point and its two handles. anchors: Vec<(usize, [f64; 6])>, pub patches: Vec, @@ -77,14 +179,20 @@ impl MeshReader { let key = vals.get(at).and_then(V::text).unwrap_or_default(); let value = at.checked_sub(1).and_then(|i| vals.get(i)); match key.as_str() { - "CS" => self.space = value.and_then(V::text).unwrap_or_default(), + "CS" => self.space = Space::read(value), "Type" => self.kind = value.and_then(V::text), "Size" => self.size = pair(value), "P" => self.at = pair(value), "N" => { if let Some(V::Arr(a)) = value { if self.corners.len() < 4 { - self.corners.push(a.iter().filter_map(V::num).take(64).collect()); + // A corner holding anything but numbers is unread: skipping it would shift + // the numbers after it into the colour or the opacity. + let n: Vec = a.iter().take(64).map(V::num).collect::>().unwrap_or_default(); + let comps = self.space.components(); + let color = comps.and_then(|k| self.space.color(n.get(..k)?)); + let rest = comps.and_then(|k| n.get(k..)).map(<[f64]>::to_vec).unwrap_or_default(); + self.corners.push(RawCorner { color, rest }); } else { self.unread = true; } @@ -124,50 +232,35 @@ impl MeshReader { } } - fn color(&self, c: &[f64]) -> Option { - let u = |i: usize| c.get(i).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1.0) as f32); - Some(match (self.space.as_str(), c.len()) { - ("DeviceRGB", 3) => Color::rgb(u(0)?, u(1)?, u(2)?), - ("DeviceCMYK", 4) => Color::cmyk(u(0)?, u(1)?, u(2)?, u(3)?), - ("DeviceGray", 1) => Color::gray(1.0 - u(0)?), - _ => return None, - }) - } - /// The four corners of a patch, in the document. - fn read_corners(&self, corners: &[Vec], to_doc: Affine) -> Option<[Corner; 4]> { + fn read_corners(&self, corners: &[RawCorner], to_doc: Affine) -> Option<[Corner; 4]> { let [n0, n1, n2, n3] = corners else { return None }; // (anchor, towards the next corner, towards the previous one, colour, opacity) - let read = |n: &Vec| -> Option<(Point, Vec2, Vec2, Color, f32)> { + let read = |n: &RawCorner| -> Option<(Point, Vec2, Vec2, Color, f32)> { // Older editing streams omit opacity; the colour space determines the number // of colour components, so a coordinate must never be mistaken for opacity. - let comps = match self.space.as_str() { - "DeviceRGB" => 3, - "DeviceCMYK" => 4, - "DeviceGray" => 1, - _ => return None, - }; - let (opacity, geometry) = match n.get(comps..)? { + let (opacity, geometry) = match n.rest.as_slice() { geometry if geometry.len() == 8 => (1.0, geometry), [opacity, geometry @ ..] if geometry.len() == 8 => (*opacity, geometry), _ => return None, }; let &[x, y, nx, ny, nw, px, py, pw] = geometry else { return None }; - // Non-unit rational weights need a different surface representation. - if nw != 1.0 || pw != 1.0 { + // Weights are 1, or 0 on some corners, which draw as the same cubic edges (checked + // against the files' pages). Others would need a rational surface. + if ![nw, pw].iter().all(|w| *w == 1.0 || *w == 0.0) { return None; } if ![opacity, x, y, nx, ny, px, py].iter().all(|v| v.is_finite()) { return None; } let at = to_doc * Point::new(x, y); - let color = self.color(n.get(..comps)?)?; + let color = n.color?; Some((at, to_doc * Point::new(nx, ny) - at, to_doc * Point::new(px, py) - at, color, opacity.clamp(0.0, 1.0) as f32)) }; Some([read(n0)?, read(n1)?, read(n2)?, read(n3)?]) } - fn patch(&self, corners: &[Vec], anchors: &[(usize, [f64; 6])], to_doc: Affine) -> Option { + fn patch(&self, corners: &[RawCorner], anchors: &[(usize, [f64; 6])], to_doc: Affine) -> Option { let [a, b, c, d] = self.read_corners(corners, to_doc)?; if !anchors.is_empty() { return Some(coons([a, b, c, d], anchors, None)); @@ -490,7 +583,7 @@ mod tests { /// anchor, with the anchor's handles along the edge. #[test] fn an_edge_anchor_cuts_its_patch_there() { - let mut reader = MeshReader { space: "DeviceGray".into(), ..MeshReader::default() }; + let mut reader = MeshReader::default(); let corner = |x: f64, y: f64, next: (f64, f64), prev: (f64, f64)| { vec![V::Arr([0.0, 1.0, x, y, next.0, next.1, 1.0, prev.0, prev.1, 1.0].map(V::Num).to_vec()), V::Name("N".into())] }; @@ -515,7 +608,7 @@ mod tests { /// first corner run along its edge, as the patch above a shared edge lists them. #[test] fn anchors_keyed_s_on_a_first_edge_run_along_it() { - let mut reader = MeshReader { space: "DeviceGray".into(), ..MeshReader::default() }; + let mut reader = MeshReader::default(); let corner = |x: f64, y: f64, next: (f64, f64), prev: (f64, f64)| { vec![V::Arr([0.0, 1.0, x, y, next.0, next.1, 1.0, prev.0, prev.1, 1.0].map(V::Num).to_vec()), V::Name("N".into())] }; @@ -539,25 +632,44 @@ mod tests { assert!((first.handles[H_DOWN] - Vec2::new(0.0, 1.0)).hypot() < 1e-9, "{:?}", first.handles); } + /// A corner's handle weights are 1, or 0 on some corners, which draw as the same patch; any + /// other weight leaves the patch unread. + #[test] + fn corners_with_handle_weights_of_zero_are_read() { + let read = |nw: f64, pw: f64| { + let mut reader = MeshReader::default(); + patch(&mut reader, &[0.5, 1.0, 0.0, 0.0, 0.0, 0.3, nw, 0.3, 0.0, pw]); + reader + }; + for (nw, pw) in [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0)] { + let reader = read(nw, pw); + assert!(!reader.unread, "{nw} {pw}"); + let p = &reader.patches[0].points[0]; + assert_eq!((p.handles[H_DOWN], p.handles[H_RIGHT]), (Vec2::new(0.0, 0.3), Vec2::new(0.3, 0.0))); + } + let reader = read(0.5, 1.0); + assert!(reader.unread && reader.patches.is_empty()); + } + #[test] fn hostile_meshes_are_capped_and_checked() { - let mut reader = MeshReader { space: "DeviceGray".into(), ..MeshReader::default() }; + let mut reader = MeshReader::default(); for _ in 0..=MAX_PATCHES { patch(&mut reader, &[0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0]); } assert!(reader.unread && reader.patches.len() == MAX_PATCHES); // Patches cut into cells count by their points. - let mut reader = MeshReader { space: "DeviceGray".into(), points: MAX_POINTS - 3, ..MeshReader::default() }; + let mut reader = MeshReader { points: MAX_POINTS - 3, ..MeshReader::default() }; patch(&mut reader, &[0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0]); assert!(reader.unread && reader.patches.is_empty()); // NaN passes `clamp`: a non-finite opacity or colour leaves the patch unread. for bad in [[0.5, f64::NAN], [f64::INFINITY, 1.0]] { - let mut reader = MeshReader { space: "DeviceGray".into(), ..MeshReader::default() }; + let mut reader = MeshReader::default(); patch(&mut reader, &[bad[0], bad[1], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0]); assert!(reader.unread && reader.patches.is_empty(), "{bad:?}"); } // More corners than a patch has. - let mut reader = MeshReader { space: "DeviceGray".into(), ..MeshReader::default() }; + let mut reader = MeshReader::default(); for _ in 0..1000 { reader.entry(&corner(&[0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0]), Affine::IDENTITY); } @@ -726,4 +838,120 @@ mod tests { } assert_eq!(r.one_mesh().unwrap_err(), NotOne::Unjoined); } + + fn nums(v: &[f64]) -> V { + V::Arr(v.iter().map(|x| V::Num(*x)).collect()) + } + + /// One unit-square patch: each corner's colour components, then (as version 1 meshes write, + /// without opacity) its point and handles at the point; `before[i]`: entries before corner `i`. + fn square(reader: &mut MeshReader, colors: [&[f64]; 4], before: [Vec<(V, &str)>; 4]) { + let at = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)]; + for ((color, (x, y)), entries) in colors.into_iter().zip(at).zip(before) { + for (value, key) in entries { + reader.entry(&[value, V::Name(key.into())], Affine::IDENTITY); + } + let corner: Vec = color.iter().copied().chain([x, y, x, y, 1.0, x, y, 1.0]).collect(); + reader.entry(&[nums(&corner), V::Name("N".into())], Affine::IDENTITY); + } + reader.entry(&[V::Num(0.0), V::Name("E".into())], Affine::IDENTITY); + } + + fn assert_color(got: Color, want: Color) { + let (Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) = (got, want) else { + return assert_eq!(got, want); + }; + assert!([c - c2, m - m2, y - y2, k - k2].iter().all(|d| d.abs() < 1e-6), "{got:?} != {want:?}"); + } + + /// The files write `/CS` only where the colour space changes, before the corner it applies to, + /// even within a patch, and a mesh starts grey: a corner before any `/CS` is one grey + /// component, and one after a `/CS` takes that space. (Patch points: first corner, fourth, + /// second, third.) + #[test] + fn corners_take_the_colour_space_last_set_before_them() { + let cs = |n: &str| vec![(V::Name(n.into()), "CS")]; + let mut reader = MeshReader::default(); + square(&mut reader, [&[0.25], &[1.0, 0.0, 0.0], &[0.75], &[0.0, 0.0, 1.0]], [vec![], cs("DeviceRGB"), cs("DeviceGray"), cs("DeviceRGB")]); + assert!(!reader.unread); + let colors: Vec = reader.patches[0].points.iter().map(|p| p.color).collect(); + assert_eq!(colors, [Color::gray(0.75), Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 0.0, 0.0), Color::gray(0.25)]); + // A mesh with no `/CS` at all is grey. + let mut reader = MeshReader::default(); + square(&mut reader, [&[0.0], &[1.0], &[1.0], &[0.0]], Default::default()); + assert!(!reader.unread && reader.patches[0].points[0].color == Color::gray(1.0)); + } + + /// A named colour (`[c m y k /DeviceCMYK (name) /Process]`) paints at each corner's tint, 1 its + /// full colour; `/NChannel` inks overprint at their tints. Ones that don't add up stay unread. + #[test] + fn named_colours_and_inks_paint_at_their_tints() { + let ink = |c: [f64; 4], name: &str, kind: &str| { + let mut v: Vec = c.iter().map(|x| V::Num(*x)).collect(); + v.extend([V::Name("DeviceCMYK".into()), V::Str(name.as_bytes().to_vec()), V::Name(kind.into())]); + V::Arr(v) + }; + let rose = ink([0.1, 0.6, 0.4, 0.2], "Rose", "Process"); + let mut reader = MeshReader::default(); + // Version 2 corners: tint, then opacity. + square(&mut reader, [&[1.0, 1.0], &[0.5, 1.0], &[1.0, 1.0], &[1.0, 1.0]], [vec![(rose, "CS")], vec![], vec![], vec![]]); + assert!(!reader.unread); + let points = &reader.patches[0].points; + assert_color(points[0].color, Color::cmyk(0.1, 0.6, 0.4, 0.2)); + assert_color(points[2].color, Color::cmyk(0.05, 0.3, 0.2, 0.1)); + + let channels = |n: f64| { + V::Arr(vec![ + ink([0.0, 0.0, 1.0, 0.0], "Yellow", "Separation"), + ink([0.0, 1.0, 0.0, 0.0], "Magenta", "Separation"), + V::Num(n), + V::Name("NChannel".into()), + ]) + }; + let mut reader = MeshReader::default(); + square(&mut reader, [&[0.25, 1.0], &[0.0, 0.0], &[1.0, 1.0], &[0.0, 0.0]], [vec![(channels(2.0), "CS")], vec![], vec![], vec![]]); + assert!(!reader.unread); + assert_color(reader.patches[0].points[0].color, Color::cmyk(0.0, 1.0, 0.25, 0.0)); + assert_color(reader.patches[0].points[3].color, Color::cmyk(0.0, 1.0, 1.0, 0.0)); + + // An ink count that doesn't match its inks, or an ink in a space not read. + let lab = V::Arr(vec![V::Num(50.0), V::Num(0.0), V::Num(0.0), V::Name("Lab".into()), V::Str(b"Grey".to_vec()), V::Name("Spot".into())]); + for space in [channels(3.0), lab] { + let mut reader = MeshReader::default(); + square(&mut reader, [&[1.0, 1.0]; 4], [vec![(space, "CS")], vec![], vec![], vec![]]); + assert!(reader.unread && reader.patches.is_empty()); + } + } + + /// A corner holding anything but numbers is unread: skipping it would shift the numbers after + /// it into its colour and opacity (two inks' tints `0.25 /bad 0.5`, read as `0.25 0.5` and no + /// opacity). + #[test] + fn a_corner_with_something_other_than_numbers_is_unread() { + let ink = |c: [f64; 4], name: &str| { + let mut v: Vec = c.iter().map(|x| V::Num(*x)).collect(); + v.extend([V::Name("DeviceCMYK".into()), V::Str(name.as_bytes().to_vec()), V::Name("Separation".into())]); + V::Arr(v) + }; + let channels = + V::Arr(vec![ink([0.0, 0.0, 1.0, 0.0], "Yellow"), ink([0.0, 1.0, 0.0, 0.0], "Magenta"), V::Num(2.0), V::Name("NChannel".into())]); + let mut reader = MeshReader::default(); + reader.entry(&[channels, V::Name("CS".into())], Affine::IDENTITY); + for (x, y) in [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)] { + let mut corner = vec![V::Num(0.25), V::Name("bad".into()), V::Num(0.5)]; + corner.extend([x, y, x, y, 1.0, x, y, 1.0].map(V::Num)); + reader.entry(&[V::Arr(corner), V::Name("N".into())], Affine::IDENTITY); + } + reader.entry(&[V::Num(0.0), V::Name("E".into())], Affine::IDENTITY); + assert!(reader.unread && reader.patches.is_empty(), "{:?}", reader.patches); + } + + /// Meshes as large as files users sent (97 × 72 patches) are read, as one mesh. + #[test] + fn a_large_grid_is_read_as_one_mesh() { + let r = Grid::new(97, 72).read([97.0, 72.0]); + assert!(!r.unread); + let mesh = r.one_mesh().unwrap(); + assert_eq!((mesh.rows.min(mesh.cols), mesh.rows.max(mesh.cols)), (72, 97)); + } } diff --git a/crates/eps/src/import/ai/obj.rs b/crates/eps/src/import/ai/obj.rs index d91f153a88..10027f0107 100644 --- a/crates/eps/src/import/ai/obj.rs +++ b/crates/eps/src/import/ai/obj.rs @@ -68,6 +68,8 @@ pub(super) struct Obj { pub content: Vec, /// Vector art enclosed by `X=` … `X+` in an opacity-mask dictionary. pub art: Option>, + /// What that art has that isn't read, reported once the mask is known to be enabled. + pub unread: Vec, } impl Obj { diff --git a/crates/eps/src/import/ai/paint.rs b/crates/eps/src/import/ai/paint.rs index b624a22475..8c863ba994 100644 --- a/crates/eps/src/import/ai/paint.rs +++ b/crates/eps/src/import/ai/paint.rs @@ -18,19 +18,24 @@ //! `Bm` for each pair in the order of the ramp (`Bc`, around them, are the caps past the first and //! last stops). Without `Xm`, a radial gradient's one `Bm` takes the unit circle onto it. //! +//! - The name shown for a gradient's or a pattern's name in the file is the part before its first +//! newline (`\n`) ([`ShownNames`]). +//! //! "AI7 spec": Adobe Illustrator File Format Specification, version 7.0 (1998), listed by PRONOM at -//! https://www.nationalarchives.gov.uk/PRONOM/fmt/423; §3.5 documents the gradient operators. +//! https://www.nationalarchives.gov.uk/PRONOM/fmt/423; §3.5 documents the gradient operators and §4 +//! the names of global objects. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use kurbo::{Affine, Point, Vec2}; use vectorcraft_color::gradient::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; use vectorcraft_color::{Color, Paint}; +use super::lex::{Lexer, Tok}; use super::obj::V; /// Largest number of stops read in one gradient. -const MAX_STOPS: usize = 256; +pub(crate) const MAX_STOPS: usize = 256; /// A colour read with the swatch it names (spot and global colours). #[derive(Clone, Debug, PartialEq)] @@ -62,20 +67,29 @@ pub(super) fn color_op(op: &str, vals: &[V]) -> Option<(Paint, Option)> { "x" => named(vals, Some(false)), "xx" => named(vals, None), "xk" => named(vals, None).map(|(p, n)| (p, n.map(|n| Named { spot: false, ..n }))), - "xs" | "xz" => registration(vals), + "xs" | "xz" => registration(op, vals), _ => None, } } +fn is_registration(name: &str) -> bool { + matches!(name, vectorcraft_color::swatch::REGISTRATION | "Registration" | "/All" | "All" | "/[Registration]") +} + /// `c m y k (name) tint x` or `c m y k [r g b | L a b] (name) tint type Xx` (type 1: RGB, 2: Lab); /// `rgb` forces RGB or CMYK. fn named(vals: &[V], rgb: Option) -> Option<(Paint, Option)> { - let at = vals.iter().rposition(|v| matches!(v, V::Str(_)))?; + let at = vals.iter().rposition(|v| matches!(v, V::Str(_) | V::Name(_)))?; let name = vals.get(at)?.text()?; let before: Vec = vals.get(..at)?.iter().filter_map(V::num).map(|v| v as f32).collect(); let after: Vec = vals.get(at + 1..)?.iter().filter_map(V::num).map(|v| v as f32).collect(); let unit = |v: f32| v.clamp(0.0, 1.0); let tint = 1.0 - unit(*after.first()?); + if is_registration(&name) { + let full = Color::cmyk(1.0, 1.0, 1.0, 1.0); + let paint = Paint::Solid { color: full.tinted(tint), swatch: Some(vectorcraft_color::swatch::REGISTRATION.into()), tint }; + return Some((paint, None)); + } let n = before.len(); let kind = after.get(1).copied(); let color = if rgb.unwrap_or(kind == Some(1.0)) { @@ -97,9 +111,20 @@ fn named(vals: &[V], rgb: Option) -> Option<(Paint, Option)> { /// `… (name) tint Xs` / `… (name) tint type Xz`: the built-in Registration swatch at the tint (its /// own colour, whatever values the operands give). -fn registration(vals: &[V]) -> Option<(Paint, Option)> { - let at = vals.iter().rposition(|v| matches!(v, V::Str(_)))?; - let tint = 1.0 - vals.get(at + 1).and_then(V::num).unwrap_or(0.0).clamp(0.0, 1.0) as f32; +fn registration(op: &str, vals: &[V]) -> Option<(Paint, Option)> { + let at = vals.iter().rposition(|v| matches!(v, V::Str(_) | V::Name(_))); + let tint = if let Some(i) = at { + 1.0 - vals.get(i + 1).and_then(V::num).unwrap_or(0.0).clamp(0.0, 1.0) as f32 + } else { + let mut nums = vals.iter().rev().filter_map(V::num); + let t = if op.eq_ignore_ascii_case("xz") { + let _type = nums.next(); + nums.next().unwrap_or(0.0) + } else { + nums.next().unwrap_or(0.0) + }; + 1.0 - t.clamp(0.0, 1.0) as f32 + }; let full = Color::cmyk(1.0, 1.0, 1.0, 1.0); Some((Paint::Solid { color: full.tinted(tint), swatch: Some(vectorcraft_color::swatch::REGISTRATION.into()), tint }, None)) } @@ -172,7 +197,16 @@ impl GradientDef { } // Stops are listed along the ramp from either end: listed downwards they're reversed, so // stops sharing a ramp point keep their order (and each its midpoint, to the next stop). - if self.gradient.stops.first().zip(self.gradient.stops.last()).is_some_and(|(first, last)| first.offset > last.offset) { + // When every stop shares one ramp point, a linear gradient's are taken as listed from the + // last, as newer files list a linear gradient's stops. + let linear = self.gradient.kind == GradientKind::Linear; + if self + .gradient + .stops + .first() + .zip(self.gradient.stops.last()) + .is_some_and(|(first, last)| first.offset > last.offset || (linear && self.gradient.stops.len() > 1 && first.offset == last.offset)) + { self.gradient.stops.reverse(); } self.gradient.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); @@ -180,6 +214,157 @@ impl GradientDef { } } +/// The names of the named colors in the tokens [`Self::token`] is given: those the color operators +/// (`x`, `Xx`, `Xk` and their stroke forms) and gradient stops (`Bs` between `Bd` and `BD`) use, +/// also in the color and tile strings of patterns in the version 7 form (`(…) @`, `(…) &`). It +/// also keeps the names of the gradients `BD` finishes ([`GradientDef::finish`]). +#[derive(Default)] +pub(super) struct ColorNames { + pub names: HashSet, + pub gradients: Vec, + vals: Vec, + def: Option, + spots: Vec, +} + +impl ColorNames { + pub fn token(&mut self, tok: Tok<'_>) { + self.take(tok, true); + } + + /// [`Self::token`], with the names in the strings of a version 7 pattern's layer when `outer`. + fn take(&mut self, tok: Tok<'_>, outer: bool) { + let w = match tok { + Tok::Num(n) => { + if self.vals.len() < MAX_STOPS { + self.vals.push(V::Num(n)); + } + return; + } + Tok::Str(s) | Tok::Hex(s) => { + if self.vals.len() < MAX_STOPS { + self.vals.push(V::Str(s)); + } + return; + } + Tok::Word(w) => w, + _ => return, + }; + let vals = std::mem::take(&mut self.vals); + match w { + b"Bd" => self.def = GradientDef::begin(&vals), + b"BD" => { + if let Some((name, _)) = self.def.take().and_then(GradientDef::finish) { + self.gradients.push(name); + } + } + b"Bs" => { + if let Some(d) = self.def.as_mut() { + d.stop(&vals, &mut self.spots); + } + } + b"x" | b"X" | b"Xx" | b"XX" | b"Xk" | b"XK" => { + if let Some((_, Some(n))) = std::str::from_utf8(w).ok().and_then(|op| color_op(op, &vals)) { + self.spots.push(n); + } + } + b"@" | b"&" if outer => { + for v in &vals { + if let V::Str(s) = v { + let mut inner = ColorNames::default(); + let mut lex = Lexer::new(s); + while let Some(t) = lex.next_token() { + inner.take(t.tok, false); + } + self.names.extend(inner.names); + } + } + } + _ => {} + } + self.names.extend(self.spots.drain(..).map(|n| n.name)); + } +} + +/// A kind of global object. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Global { + Gradient, + Pattern, +} + +/// The names the gradients and patterns get in the document, by their kind and names in the file. +/// The name shown for a name in the file is the part before its first newline (AI7 spec §4): +/// `(Sky\n1)` is shown as "Sky". Gradients and patterns share their swatches' names. A name with a +/// newline is shown as the part before it unless that name is reserved (a custom color's, or a +/// gradient's or pattern's name without a newline) or an object defined earlier (of either kind) +/// got it; then it is the first free "Sky 2", "Sky 3"… A name shown as nothing (`(\n3)`) is shown +/// as "Gradient" or "Pattern", numbered the same way. A name without a newline is kept. An object +/// defined again under the same name in the file keeps the name it got. +#[derive(Debug, Default)] +pub(super) struct ShownNames { + gradients: HashMap, + patterns: HashMap, + taken: HashSet, + /// The number to try first for each shown name already taken. + next: HashMap, +} + +impl ShownNames { + fn by_file(&self, kind: Global) -> &HashMap { + match kind { + Global::Gradient => &self.gradients, + Global::Pattern => &self.patterns, + } + } + + /// The name the object of `kind` defined as `name` in the file got ([`Self::define`]), or + /// `name` for one not defined. + pub fn get<'n>(&'n self, kind: Global, name: &'n str) -> &'n str { + self.by_file(kind).get(name).map_or(name, String::as_str) + } + + /// Keep `name` from the objects defined after. + pub fn reserve(&mut self, name: &str) { + self.taken.insert(name.to_string()); + } + + /// The name the object of `kind` defined as `name` in the file gets. + pub fn define(&mut self, kind: Global, name: &str) -> String { + if let Some(shown) = self.by_file(kind).get(name) { + return shown.clone(); + } + let shown = match name.split_once('\n') { + None => name.to_string(), + Some((base, _)) => { + let base = match (base.is_empty(), kind) { + (false, _) => base, + (true, Global::Gradient) => "Gradient", + (true, Global::Pattern) => "Pattern", + }; + if self.taken.contains(base) { + // The first free number from the one after the last number this base got. Of + // the numbers `from..=tries`, at least one is free. + let from = self.next.get(base).copied().unwrap_or(2); + let tries = from.saturating_add(self.taken.len()); + let i = (from..tries).find(|i| !self.taken.contains(&format!("{base} {i}"))).unwrap_or(tries); + self.next.insert(base.to_string(), i.saturating_add(1)); + format!("{base} {i}") + } else { + base.to_string() + } + } + }; + self.taken.insert(shown.clone()); + let by_file = match kind { + Global::Gradient => &mut self.gradients, + Global::Pattern => &mut self.patterns, + }; + by_file.insert(name.to_string(), shown.clone()); + shown + } +} + /// A gradient instance on an object, between `Bb` and `BB`. #[derive(Clone, Debug, Default)] pub(super) struct Instance { @@ -258,8 +443,9 @@ impl Instance { self.xm.is_some() || self.bm.is_some() } - /// The paint, through `to_doc` (art space → the document), when the gradient is defined. - pub fn paint(&self, defs: &HashMap, to_doc: Affine) -> Option { + /// The paint, through `to_doc` (art space → the document), when the gradient is defined, linked + /// to the gradient's swatch by the name `shown` gave it. + pub fn paint(&self, defs: &HashMap, shown: &ShownNames, to_doc: Affine) -> Option { let name = self.name.as_ref()?; let gradient = defs.get(name)?.clone(); let radial = gradient.kind == GradientKind::Radial; @@ -310,7 +496,8 @@ impl Instance { let focal = (self.hilight.hypot() > 1e-9).then_some(focal).filter(|p| p.is_finite()); let geom = GradientGeom { start, end, aspect, focal: if radial { focal } else { None } }; let angle = -(end - start).atan2().to_degrees(); - Some(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle, swatch: Some(name.clone()), ..GradientPaint::new(gradient) }))) + let swatch = Some(shown.get(Global::Gradient, name).to_string()); + Some(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle, swatch, ..GradientPaint::new(gradient) }))) } } @@ -345,6 +532,29 @@ mod tests { let mut v = nums(&[1.0, 1.0, 1.0, 1.0]); v.extend([V::Str(b"[Registration]".to_vec()), V::Num(0.0)]); assert!(matches!(color_op("Xs", &v), Some((Paint::Solid { tint, .. }, None)) if tint == 1.0)); + let mut v = nums(&[1.0, 1.0, 1.0, 1.0]); + v.extend([V::Str(b"[Registration]".to_vec()), V::Num(1.0)]); + assert!( + matches!(color_op("Xs", &v), Some((Paint::Solid { tint, color, .. }, None)) if tint == 0.0 && color == Color::cmyk(1.0, 1.0, 1.0, 1.0).tinted(0.0)) + ); + let mut v = nums(&[1.0, 1.0, 1.0, 1.0]); + v.extend([V::Name("All".into()), V::Num(1.0)]); + assert!(matches!(color_op("Xs", &v), Some((Paint::Solid { tint, .. }, None)) if tint == 0.0)); + let mut v = nums(&[1.0, 1.0, 1.0, 1.0]); + v.extend([V::Str(b"[Registration]".to_vec()), V::Num(0.2), V::Num(0.0)]); + let (p, named) = color_op("Xx", &v).unwrap(); + assert!(named.is_none()); + assert!(matches!(p, Paint::Solid { swatch: Some(s), tint, .. } if s == "[Registration]" && (tint - 0.8).abs() < 1e-6)); + let mut v = nums(&[1.0, 1.0, 1.0, 1.0]); + v.extend([V::Name("All".into()), V::Num(0.5), V::Num(0.0)]); + let (p, named) = color_op("Xx", &v).unwrap(); + assert!(named.is_none()); + assert!(matches!(p, Paint::Solid { swatch: Some(s), tint, .. } if s == "[Registration]" && (tint - 0.5).abs() < 1e-6)); + // Name-free Xs and Xz operands + let v = nums(&[1.0, 1.0, 1.0, 1.0, 0.3]); + assert!(matches!(color_op("Xs", &v), Some((Paint::Solid { tint, .. }, None)) if (tint - 0.7).abs() < 1e-6)); + let v = nums(&[1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.2, 1.0]); + assert!(matches!(color_op("Xz", &v), Some((Paint::Solid { tint, .. }, None)) if (tint - 0.8).abs() < 1e-6)); } #[test] @@ -361,6 +571,14 @@ mod tests { assert_eq!(named.name, "MySpot"); assert!((named.tint - 0.6).abs() < 1e-6); assert!(matches!(p, Paint::Solid { swatch: Some(_), .. })); + let mut v_name = nums(&[0.0, 0.5, 1.0, 0.0]); + v_name.push(V::Name("MySpot".into())); + v_name.push(V::Num(0.4)); + let (p, named) = color_op("x", &v_name).unwrap(); + let named = named.unwrap(); + assert_eq!(named.name, "MySpot"); + assert!((named.tint - 0.6).abs() < 1e-6); + assert!(matches!(p, Paint::Solid { swatch: Some(_), .. })); assert!(color_op("k", &nums(&[1.0])).is_none()); // A global process colour: CMYK (type 0) or RGB (type 1), not an ink. let mut v = nums(&[0.0, 0.0, 0.0, 1.0]); @@ -406,22 +624,59 @@ mod tests { bg.extend(nums(&[100.0, 100.0, 0.0, 50.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0])); i.bg(&bg); i.bm(&nums(&[50.0, 0.0, 0.0, -50.0, 100.0, 100.0])); - let Some(Paint::Gradient(gp)) = i.paint(&defs, Affine::IDENTITY) else { panic!() }; + let shown = ShownNames::default(); + let Some(Paint::Gradient(gp)) = i.paint(&defs, &shown, Affine::IDENTITY) else { panic!() }; + assert_eq!(gp.swatch.as_deref(), Some("G")); let geom = gp.geom.unwrap(); assert_eq!(geom.start, Point::new(100.0, 100.0)); assert_eq!(geom.end, Point::new(150.0, 100.0)); assert!((geom.aspect - 1.0).abs() < 1e-9); - assert!(i.paint(&HashMap::new(), Affine::IDENTITY).is_none()); + assert!(i.paint(&HashMap::new(), &shown, Affine::IDENTITY).is_none()); // Newer files give the matrix with `Xm`; the `Bm`s after it are bands of a cached ramp. let mut i = Instance::begin(&[]); i.bg(&bg); i.xm(&nums(&[40.0, 0.0, 0.0, -40.0, 10.0, 10.0])); i.bm(&nums(&[5.0, 0.0, 0.0, -40.0, 30.0, 10.0])); - let Some(Paint::Gradient(gp)) = i.paint(&defs, Affine::IDENTITY) else { panic!() }; + let Some(Paint::Gradient(gp)) = i.paint(&defs, &shown, Affine::IDENTITY) else { panic!() }; let geom = gp.geom.unwrap(); assert_eq!((geom.start, geom.end), (Point::new(10.0, 10.0), Point::new(50.0, 10.0))); } + /// A name is shown up to its first newline, numbered when a reserved name or an earlier object + /// of either kind has it; a name defined again keeps the name it got, and a blank one gets its + /// kind's stand-in. A name without a newline is kept. + #[test] + fn global_names_are_shown_up_to_their_newline() { + let mut shown = ShownNames::default(); + // A color's name, and the names without a newline the file defines. + for name in ["Ink", "Sky", "Sky 2", "Sea"] { + shown.reserve(name); + } + let got: Vec = [ + (Global::Gradient, "Sky\n1"), + (Global::Gradient, "Sky\n2"), + (Global::Gradient, "Sky"), + (Global::Gradient, "Sky\n1"), + (Global::Pattern, "Sky\n1"), + (Global::Gradient, "Sea\nA\nB"), + (Global::Gradient, "\n3"), + (Global::Pattern, "\n4"), + (Global::Gradient, "Sky 2"), + (Global::Pattern, "Ink\n1"), + (Global::Gradient, "Ink"), + (Global::Pattern, "Sea"), + (Global::Pattern, "Tide\n1"), + (Global::Pattern, ""), + ] + .iter() + .map(|(kind, n)| shown.define(*kind, n)) + .collect(); + assert_eq!(got, ["Sky 3", "Sky 4", "Sky", "Sky 3", "Sky 5", "Sea 2", "Gradient", "Pattern", "Sky 2", "Ink 2", "Ink", "Sea", "Tide", ""]); + assert_eq!(shown.get(Global::Gradient, "Sky\n2"), "Sky 4"); + assert_eq!(shown.get(Global::Pattern, "Sky\n1"), "Sky 5"); + assert_eq!(shown.get(Global::Pattern, "Sky\n2"), "Sky\n2", "not a pattern's name"); + } + #[test] fn gradient_stops_beyond_the_cap_are_ignored() { let mut d = GradientDef::begin(&[V::Str(b"H".to_vec()), V::Num(0.0)]).unwrap(); @@ -434,6 +689,24 @@ mod tests { assert_eq!(g.stops.len(), MAX_STOPS); } + /// A hard edge: every stop at one ramp point. A linear gradient's are listed from the last, a + /// radial one's from the first. + #[test] + fn stops_at_one_ramp_point_keep_their_sides() { + for (kind, listed) in [(0.0, [0.75, 0.25]), (1.0, [0.25, 0.75])] { + let mut d = GradientDef::begin(&[V::Str(b"E".to_vec()), V::Num(kind), V::Num(2.0)]).unwrap(); + for (gray, mid) in listed.into_iter().zip([40.0, 70.0]) { + d.stop(&nums(&[gray, 0.0, 1.0, 6.0, mid, 30.0]), &mut vec![]); + } + let (_, g) = d.finish().unwrap(); + let lightness: Vec = g.stops.iter().map(|s| (s.color.to_rgb()[0] * 100.0).round() / 100.0).collect(); + let first_mid = if kind == 0.0 { 0.7 } else { 0.4 }; + assert_eq!(lightness, vec![0.25, 0.75], "kind {kind}"); + assert!((g.stops[0].midpoint - first_mid).abs() < 1e-6, "kind {kind}: {:?}", g.stops); + assert!(g.stops.iter().all(|s| (s.offset - 0.3).abs() < 1e-6)); + } + } + /// A linear gradient of three stops as newer files place it: `Bg` with numbers that aren't in /// art space, `Xm` for the whole ramp and a `Bm` for each pair of stops. #[test] @@ -454,7 +727,7 @@ mod tests { // From the stop at 20 to the one at 60, then on to the one at 100. i.bm(&nums(&[0.0, -80.0, -30.0, 0.0, 10.0, 260.0])); i.bm(&nums(&[0.0, -80.0, -30.0, 0.0, 10.0, 180.0])); - let Some(Paint::Gradient(gp)) = i.paint(&defs, Affine::IDENTITY) else { panic!() }; + let Some(Paint::Gradient(gp)) = i.paint(&defs, &ShownNames::default(), Affine::IDENTITY) else { panic!() }; gp.geom.unwrap() }; for xm in [true, false] { diff --git a/crates/eps/src/import/ai/palette.rs b/crates/eps/src/import/ai/palette.rs index bf659cfe94..e816c5d6c0 100644 --- a/crates/eps/src/import/ai/palette.rs +++ b/crates/eps/src/import/ai/palette.rs @@ -2,10 +2,13 @@ //! `%AI5_EndPalette`, as written in files users sent. //! //! - `0 0 Pb` starts the swatches and `PB` ends them. -//! - Each swatch is its paint, then `(name) Pc`. The paint is a colour operator (`g`, `k`, `Xa`: a -//! process colour; `x`, `Xx`: a spot colour; `Xk`: a global process colour), a gradient -//! (`Bb` … `flag (gradient) … Bg` … `BB`) or a pattern (`(pattern) … p`). `Xs` and `Xz` paint -//! with Registration, which every document has. +//! - Each swatch is its paint, then an optional `(name)`, then `Pc`. The paint is a colour operator +//! (`g`, `k`, `Xa`: a process colour; `x`, `Xx`: a spot colour; `Xk`: a global process colour), a +//! gradient (`Bb` … `flag (gradient) … Bg` … `BB`) or a pattern (`(pattern) … p`). `Xs` and `Xz` +//! paint with Registration, which every document has. +//! - A swatch without a name (version 7 files write none) is named by its spot colour, gradient or +//! pattern, or by its values as [`color_name`] gives them. `Pn` (the None swatch) and a `Pc` with +//! no paint before it add nothing: the document has `[None]` already. //! - `flag (name) count Pg` starts a colour group: the swatches up to the next `Pg` or `PB` are //! its own. //! - Newer files write the swatches between `%AI17_Begin_Content_if_version_gt` and @@ -13,9 +16,14 @@ //! the first are read, the others skipped. //! //! Anything else in the section (an operator it doesn't know) is left alone: the swatches around -//! it still come in. +//! it still come in, and a paint before it makes no swatch. +//! +//! "AI7 spec": Adobe Illustrator File Format Specification, version 7.0 (1998), listed by PRONOM at +//! https://www.nationalarchives.gov.uk/PRONOM/fmt/423; §11 documents the palette operators, and its +//! example writes the swatches without names. use vectorcraft_color::Color; +use vectorcraft_doc::swatches::color_name; use super::lex::{Lexer, Tok}; use super::obj::V; @@ -55,8 +63,13 @@ impl Palette { pub fn is_empty(&self) -> bool { self.swatches.is_empty() && self.groups.iter().all(|(_, s)| s.is_empty()) } - fn len(&self) -> usize { - self.swatches.len() + self.groups.iter().map(|(_, s)| s.len()).sum::() + + /// The names the palette gives its color groups and swatches, except the name a swatch takes + /// from its gradient or pattern. + pub fn own_names(&self) -> impl Iterator { + let named = |e: &Entry| !matches!(&e.cell, Cell::Gradient(n) | Cell::Pattern(n) if *n == e.name); + let swatches = self.swatches.iter().chain(self.groups.iter().flat_map(|(_, s)| s)).filter(move |e| named(e)); + self.groups.iter().map(|(name, _)| name.as_str()).chain(swatches.map(|e| e.name.as_str())) } } @@ -65,23 +78,31 @@ pub(super) fn palette(data: &[u8]) -> Palette { let mut lex = Lexer::new(data); let mut out = Palette::default(); let mut vals: Vec = Vec::new(); - // The paint of the swatch being read. - let mut cell: Option = None; + // The paint of the swatch being read, with the name it gets when `Pc` gives none. + let mut cell: Option = None; + // How many swatches have been read. + let mut count = 0usize; // Inside a gradient's `Bb` … `BB`. let mut in_gradient = false; - // Inside versioned content's alternate, which repeats what came before it. - let mut alternate = false; + // How deep in versioned content, and the depth of the block whose later alternatives (which + // repeat its first) are being skipped, nested blocks in them included. + let (mut depth, mut skipping) = (0usize, None::); while let Some(t) = lex.next_token() { if let Tok::Comment(c) = t.tok { let line = String::from_utf8_lossy(c); - if line.contains("_Alternate_Content") { - alternate = true; - } else if line.contains("_End_Versioned_Content") || line.contains("_Begin_Content_if_version") { - alternate = false; + if line.contains("_Begin_Content_if_version") { + depth = depth.saturating_add(1); + } else if line.contains("_Alternate_Content") { + skipping = skipping.or(Some(depth)); + } else if line.contains("_End_Versioned_Content") { + if skipping == Some(depth) { + skipping = None; + } + depth = depth.saturating_sub(1); } continue; } - if alternate { + if skipping.is_some() { continue; } let w = match t.tok { @@ -105,19 +126,20 @@ pub(super) fn palette(data: &[u8]) -> Palette { } "Bg" if in_gradient => { if let Some(name) = last_text(&vals) { - cell = Some(Cell::Gradient(name)); + cell = Some(Entry { cell: Cell::Gradient(name.clone()), name }); } } "BB" => in_gradient = false, - "p" => cell = first_text(&vals).map(Cell::Pattern), + "p" => cell = first_text(&vals).map(|name| Entry { cell: Cell::Pattern(name.clone()), name }), "Xs" | "Xz" | "XS" | "XZ" => cell = None, "g" | "k" | "x" | "Xa" | "Xx" | "Xk" => { cell = paint::color_op(w, &vals).and_then(|(p, named)| match named { - Some(Named { color, spot, .. }) => Some(Cell::Color { color, global: true, spot }), - None => p.color().map(|color| Cell::Color { color, global: false, spot: false }), + Some(Named { name, color, spot, .. }) => Some(Entry { name, cell: Cell::Color { color, global: true, spot } }), + None => p.color().map(|color| Entry { name: color_name(color), cell: Cell::Color { color, global: false, spot: false } }), }); } "Pg" => { + cell = None; // Capped as swatches are: a file of many `Pg` would make as many empty groups. if let Some(name) = first_text(&vals) && out.groups.len() < MAX_SWATCHES @@ -126,19 +148,27 @@ pub(super) fn palette(data: &[u8]) -> Palette { } } "Pc" => { - if let (Some(name), Some(c)) = (last_text(&vals), cell.take()) - && !name.starts_with('[') - && out.len() < MAX_SWATCHES + // The name before `Pc`, or the one the paint gives; `[Registration]` and the other + // built-in swatches every document has are left out. + let name = last_text(&vals); + if let Some(mut e) = cell.take() + && !name.as_ref().is_some_and(|n| n.starts_with('[')) + && count < MAX_SWATCHES { - let e = Entry { name, cell: c }; + if let Some(name) = name { + e.name = name; + } + count += 1; match out.groups.last_mut() { Some((_, g)) => g.push(e), None => out.swatches.push(e), } } - cell = None; } - _ => {} + // A gradient's other operators (its focal point, its matrices) are part of its paint. + _ if in_gradient => {} + // Anything else ends the paint before it, which no `Pc` then makes a swatch of. + _ => cell = None, } vals.clear(); } @@ -211,9 +241,89 @@ mod tests { assert_eq!(p.swatches.len(), 1); } + /// Three alternatives, and versioned content nested in a later one: still one swatch. + #[test] + fn versioned_swatches_with_more_alternatives_are_read_once() { + let p = palette( + b"0 0 Pb\n%AI17_Begin_Content_if_version_gt:24 15\n0 1 1 0 (Red ink) 0 x\n(Red ink)\nPc\n\ + %AI17_Alternate_Content_if_version_gt:24 10\n0 1 1 0 (Red ink) 0 x\n(Red ink)\nPc\n\ + %AI17_Begin_Content_if_version_gt:23 1\n0 0 0 1 k\n(Black)\nPc\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n\ + 0 0 1 0 k\n(Yellow)\nPc\n\ + %AI17_Alternate_Content\n0 1 1 0 (Red ink) 0 x\n(Red ink)\nPc\n%AI17_End_Versioned_Content\n0 0 0 1 k\n(After)\nPc\nPB\n", + ); + assert_eq!(p.swatches.iter().map(|e| e.name.as_str()).collect::>(), ["Red ink", "After"]); + } + #[test] fn what_it_doesnt_know_leaves_the_other_swatches() { let p = palette(b"0 0 Pb\n1 2 3 Zz\n(Odd)\nPc\n(no paint) Pc\n0 0 0 1 k\n(Black)\nPc\nPB\n"); assert_eq!(p.swatches.iter().map(|e| e.name.as_str()).collect::>(), ["Black"]); } + + /// An operator it doesn't know after a paint ends that paint: the `Pc` after it makes no swatch. + #[test] + fn a_paint_before_an_unknown_operator_makes_no_swatch() { + let p = palette(b"0 0 Pb\n0 1 1 0 k\nZz\n(Odd)\nPc\n0.5 g\n1 (Group) 1 Pg\nPc\n0 0 0 1 k\n(Black)\nPc\nPB\n"); + assert_eq!(p.swatches.iter().map(|e| e.name.as_str()).collect::>(), Vec::<&str>::new()); + let groups: Vec<(&str, Vec<&str>)> = p.groups.iter().map(|(n, s)| (n.as_str(), s.iter().map(|e| e.name.as_str()).collect())).collect(); + assert_eq!(groups, [("Group", vec!["Black"])]); + } + + /// The palette of the AI7 spec's example (§11): `Pn`, then each swatch's paint and `Pc` with no + /// name, then a last `Pc`. Each swatch is named by its spot colour or gradient, or by its values; + /// `1 g` is white (§5.4.1). + #[test] + fn swatches_without_names_are_named_by_their_paint() { + let p = palette( + b"0 0 Pb\nPn\nPc\n1 g\nPc\n0 g\nPc\n0 0 0 0 k\nPc\n0.75 g\nPc\n\ + Bb\n2 (B&W) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\nPc\n0.25 0 0 0 k\nPc\n\ + 0 1 1 0 (Spot A) 0 x\nPc\n0.75 g\nPc\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\nPc\nPc\nPB\n", + ); + assert!(p.groups.is_empty()); + assert_eq!( + p.swatches, + vec![ + color("Gray K=0", Color::gray(0.0), false, false), + color("Gray K=100", Color::gray(1.0), false, false), + color("C=0 M=0 Y=0 K=0", Color::cmyk(0.0, 0.0, 0.0, 0.0), false, false), + color("Gray K=25", Color::gray(0.25), false, false), + Entry { name: "B&W".into(), cell: Cell::Gradient("B&W".into()) }, + color("C=25 M=0 Y=0 K=0", Color::cmyk(0.25, 0.0, 0.0, 0.0), false, false), + color("Spot A", Color::cmyk(0.0, 1.0, 1.0, 0.0), true, true), + color("Gray K=25", Color::gray(0.25), false, false), + Entry { name: "Dots".into(), cell: Cell::Pattern("Dots".into()) }, + ] + ); + // RGB and global process colours too. + let p = palette(b"0 0 Pb\n0 0 0 0 1 0.5 0 Xa\nPc\n0 0.5 1 0 1 0.5 0 (Brand) 0 1 Xk\nPc\nPB\n"); + assert_eq!(p.swatches.iter().map(|e| e.name.as_str()).collect::>(), ["R=255 G=128 B=0", "Brand"]); + } + + /// Named and unnamed swatches in one palette: the named ones keep their names, and built-in + /// swatches are still left out. + #[test] + fn named_swatches_keep_their_names_beside_unnamed_ones() { + let p = palette( + b"0 0 Pb\n1 1 1 1 ([Registration]) 0 Xs\n([Registration])\nPc\n0 0 0 1 k\n(Black)\nPc\n0 0 0 0.5 k\nPc\n\ + 1 (Greys) 1 Pg\n0.4 g\n(Mid)\nPc\n0.4 g\nPc\nPB\n", + ); + assert_eq!(p.swatches.iter().map(|e| e.name.as_str()).collect::>(), ["Black", "C=0 M=0 Y=0 K=50"]); + let groups: Vec<(&str, Vec<&str>)> = p.groups.iter().map(|(n, s)| (n.as_str(), s.iter().map(|e| e.name.as_str()).collect())).collect(); + assert_eq!(groups, [("Greys", vec!["Mid", "Gray K=60"])]); + } + + /// No more than `MAX_SWATCHES` swatches, counted across the colour groups. + #[test] + fn swatches_are_capped_across_groups() { + let mut data = b"0 0 Pb\n".to_vec(); + for i in 0..MAX_SWATCHES / 1000 + 1 { + data.extend(format!("1 (G{i}) 1 Pg\n").as_bytes()); + data.extend("0.5 g\nPc\n".repeat(1000).as_bytes()); + } + data.extend(b"PB\n"); + let p = palette(&data); + assert_eq!(p.groups.len(), MAX_SWATCHES / 1000 + 1); + assert_eq!(p.swatches.len() + p.groups.iter().map(|(_, s)| s.len()).sum::(), MAX_SWATCHES); + assert!(p.groups.last().is_some_and(|(_, s)| s.is_empty())); + } } diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index bba345254f..d67d5b83ea 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -1,49 +1,111 @@ //! The reader: runs the editing data's operators into a document. //! //! - Art space has y up; the first artboard's top left corner is the document's origin. -//! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed … colorIndex r g b … -//! dimPercent … Lb` (ten operands in the legacy format, without the one before the colour -//! index), `(name) Ln`, its art, `LB`. +//! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed … colorIndex r g b +//! template dimPercent … Lb` (ten operands in the legacy format, without the one before the +//! colour index; see `Reader::layer_attrs`), `(name) Ln`, its art, `LB`. +//! - Multi-layer masks `Mb` `W n` `Md` … `MB`, whose objects can go on past `LB` into the +//! next layers: a clipping group in each layer, read by [`masks`]. +//! - Ruler guides: a straight `(N) *` guide path, directly on a layer, that runs across the whole +//! canvas (16,383 points around the template box's centre) or from edge to edge of one artboard +//! is a ruler guide on that layer ([`Document::guides`]); other guide paths stay paths. //! - Groups `u` … `U`, compound paths `*u` … `*U`, clipping groups `q` … `Q` (the path painted -//! with `W` clips); a group's transparency and name follow its end. +//! with `W` clips); a group's transparency and name follow its end. A wraparound group `*w` … +//! `*W` (version 7 specification §15.4.2) is a group whose objects other than its type wrap +//! area type, with no offset. //! - Paths: `m`, `l`/`L`, `c`/`C`, `v`/`V`, `y`/`Y`, painted by `N n F f S s B b` (lower case -//! closes), `(op) *` for a guide. Stroke `w J j M d`, fill rule `XR`, overprint `O`/`R`. +//! closes), `(op) *` for a guide. A segment's operator in lower case makes the anchor it ends on +//! smooth, in upper case a corner; a closed path's first anchor takes the kind of the segment +//! back to it. Stroke `w J j M d`, fill rule `XR`, overprint `O`/`R`. //! - State: hidden `Xw`, locked `A`, transparency `mode opacity isolate knockout shape Xy`. //! - Names: an `/ArtDictionary` after an object, its `AI10_ArtUID` the name's XML id. -//! - Artboards: the `ArtboardArray` of the `/Document` dictionary, else `%AI3_Cropmarks`, else -//! the art size around the template box's centre, else (a file in the legacy format another -//! app wrote) the bounding box. -//! - Variables: the variable library, XML nodes of the `/Document` dictionary, isn't read; a note -//! gives how many variables and data sets it has ([`VariableLibrary`]). +//! - Artboards: the `ArtboardArray` of the `/Document` dictionary, with each one's display +//! options, else `%AI3_Cropmarks`, else the art size around the template box's centre +//! (`%AI3_TemplateBox`, `%%TemplateBox` in older files), else (a file in the legacy format +//! another app wrote) the bounding box. +//! - Document settings: Document Raster Effects Settings from the `/Document` dictionary's +//! `AI Auto Rasterize`; the author from the header's `%%For`; swatches for the custom colors of +//! `%%CMYKCustomColor` and `%%RGBCustomColor` that the document has none of. +//! - Variables: the variable library, XML nodes of the `/Document` dictionary: its variables, data +//! sets, active data set and lock, without bindings; a note gives how many entries were left out +//! ([`VariableRead`]). +//! - Objects on Path: a group whose objects' dictionaries carry ids, and a record of the +//! `/Document` dictionary naming them, read by [`on_path`]. //! - Images: `%AI5_BeginRaster`, the colour space `XN`, `[matrix] bounds w h bits type alpha …` //! and the samples after `XI`. 8-bit CMYK samples keep their ink amounts in a CMYK TIFF, and //! an alpha channel that hides part of such an image becomes its opacity mask; other samples -//! become an RGBA PNG. +//! become an RGBA PNG. Images larger than 2^25 pixels keep their samples' channels (1-bit gray as +//! a 1-bit PNG), and are averaged down past a target size ([`raster`]); past the hard limits, one +//! is a box that the page's art replaces when there is a page ([`read_over_page`]). +//! - Linked images in the version 7 form (§8.2, §8.3): `(path) modified XG`, then `XF` with the +//! operands `XI` takes and no samples. Each is a linked image of that file showing a placeholder +//! over the image's place until its file is found. An `XF` without a file name before it, or +//! with operands `XI` couldn't read, is left out with a warning. An `XI` after `XG` (newer files +//! write `() 1 XG` before their embedded images) stays an embedded image. //! - Placed (linked) files, as written in files users sent: `%AI5_BeginPlace`, `[matrix] llx lly urx //! ury … (path)` and the operator `` ` ``, the file's preview between `%AI26_BeginPlacedObjectPreview` //! and its end (`w h rowBytes 32 n `, then rows of premultiplied ARGB, the top one first), `~`. The //! box is as large as the file has pixels; the matrix takes them into art space from the canvas //! (y down, its centre the template box's), where they start at the point of art space's origin, //! the first row the top one. Each is a linked image showing the preview until its file is found. +//! The dictionary after a placed PDF or `.ai` file has the page shown, from 1, in +//! `AI11 PlacedPDFPageIndex` and its box in `AI11 PlacedPDFCropTo` (0 Art, 1 Crop, 2 Trim, 3 Bleed, +//! 4 Media, 5 Bounding Box): each is a placed document of that page and box, showing the preview +//! until its file is found. A value outside those leaves it a linked image. +//! The version 7 form (§16) has no `%AI5_BeginPlace`: `[matrix] llx lly urx ury (path)` and +//! `` ` ``, then `%%IncludeFile:` or the file between `%%BeginDocument:` and `%%EndDocument`, +//! then `~`; its box is the file's `%%BoundingBox`. Newer files have three more numbers before +//! the path. Operands of any other shape, a second `` ` `` before `~` or an included document +//! that doesn't end leave the placed file unread. //! - Art with an appearance the format can't write as plain art (several fills or strokes, //! effects, brushes) comes first as that look, drawn (a group, or an image where an effect //! rasterizes it), then the object itself on `%_` //! lines and `1 (style) XW`: the drawn look is kept, named after the object. //! - Patterns: `%AI3_BeginPattern: (name)`, `(name) llx lly urx ury` (the tile, in the pattern's //! space, y up), the tile's art (on `%_` lines in newer files), `E`, `%AI3_EndPattern`; each is -//! read by a reader of its own and becomes a pattern swatch. A fill or stroke with one: +//! read by a reader of its own and becomes a pattern swatch. An unpainted path whose dictionary +//! marks it as the tile's box (`AIPattern_Editor_Backing_Tile_Rect`) is left out of the art. In +//! the version 7 form (§3.4) a list +//! of layers follows the tile, `[ (colors) @ (tile) & … ] E`, each layer's tile read from its +//! string with the colors' state (`_ &`: the tile's box filled). A fill or stroke with one: //! `(name) x y scaleX scaleY angle reflect axis shear shearAxis [matrix] p` (`P`), the matrix -//! taking the pattern's space to art space (the other operands are what it is made of). +//! taking the pattern's space to art space (the other operands are what it is made of). With a +//! pattern defined in the version 7 form, the other operands are applied in order (§5.4.1) before +//! the initial matrix. //! //! - Type in the legacy format (version 7 specification §15): `type To` … `TO`, read by //! [`legacy_text`]. //! +//! - Graphs (version 7 specification §17): `%_Gs`, the graph's data and settings on `%_` lines, +//! its drawn art as ordinary groups, paths and type (each object followed by `%_… Go`), `%_GS`. +//! The drawn art is read; the data and settings are left out, with a note. +//! //! - Swatches: the palette (`%AI5_BeginPalette`), read by [`super::palette`], replaces the //! default swatches. //! -//! Sections the reader doesn't need (brushes, symbols, styles, filters) are skipped; -//! type, symbols, fills with a pattern it can't read, placed files without a preview and operators -//! it doesn't know are errors. +//! - Brushes: the brush plug-in objects and their art sections (`%AI8_BeginBrushPattern`), read by +//! [`super::brush`], replace the default brushes when the file has any. +//! +//! - Graphic styles: the style list (`%AI9_BeginArtStyleList`), one `(name)` per style in the +//! panel's order, each the name of an art style. The listed styles whose appearance reads +//! ([`appearance_from_art_style`](ops::appearance_from_art_style)) replace the default graphic +//! styles, and an object read as itself with a listed style (`1 (name) XW`) that has the +//! style's appearance and transparency is linked to it. A `1` naming a style the list doesn't +//! have is the object's own appearance, not a link. +//! +//! - Symbols: `%AI14_BeginSymbol` (or `%AI10_`), `(name)`, `0 A 0 Xw 0 Ae`, the art (in the +//! symbol's space, y down), a dictionary whose `AI13PatternRegistrationType` is the registration +//! point (1 to 9, from the top left, row by row), `%AI10_EndSymbol`; each is read by a reader of +//! its own into the document's symbols. `%AI24_BeginSymbolList` (or `%AI10_`) lists their names +//! in the Symbols panel's order. An instance: `/SymbolInstance : (name) /SymbolRef , a b c d tx +//! ty /RTransformMatrix ;`, the matrix taking the symbol's art to art space; in a symbol's art, +//! it takes it to art space about the canvas point of art space's origin, as a pattern's +//! gradients are. Its hide and lock come before it (`Xw`, `A`) and its transparency (`Xy`) after +//! it. +//! +//! Sections the reader doesn't need (styles, filters) are skipped; type, instances of symbols it +//! can't read, fills with a pattern it can't read, placed files without a preview and operators +//! it doesn't know are errors. So is data that ends inside a layer, a group or a compound path. use std::collections::{BTreeSet, HashMap, HashSet}; use std::rc::Rc; @@ -56,35 +118,50 @@ use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::cmyk::Inks; use vectorcraft_doc::{ Appearance, AppearanceItem, Artboard, ColorMode, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin, - LinkInfo, Node, NodeId, NodeKind, OpacityMask, PatternDef, StrokeLayer, Unit, + LinkInfo, Node, NodeId, NodeKind, OpacityMask, PageBox, PatternDef, StrokeLayer, Unit, }; -use vectorcraft_geom::{FillRule, PathData}; +use vectorcraft_geom::{AnchorKind, FillRule, PathData}; use super::super::ate::CANVAS_CENTRE; +use super::super::graphics::HAIRLINE; use super::lex::{Lexer, Tok}; use super::obj::{self, Obj, V}; -use super::paint::{self, GradientDef, Instance, Named}; +use super::paint::{self, Global, GradientDef, Instance, Named, ShownNames}; use crate::ps; mod art; mod containers; mod directives; mod document; +mod masks; +mod on_path; mod ops; +mod raster; mod types; +pub(crate) use art::join_and; use art::preview_png; -pub use document::{PaletteSwatches, VariableLibrary, artboards, palette, variables}; +pub use document::{ + BindingRef, Brushes, PaletteSwatches, Symbols, VariableRead, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette, + symbols, variables, +}; pub(crate) use document::{slot_frame, slot_of}; -pub use types::IMAGE_TOO_LARGE; -use types::{BLEND_BUDGET, FLIP, Frame, GState, Kind, PatternHead, Place, Raster}; +pub(crate) use ops::{read_art_style, read_style_list, style_moves_with}; #[cfg(test)] -pub use types::{NON_NATIVE_ART, NON_NATIVE_ART_UNREAD}; +pub(crate) use raster::with_image_limits; +pub use types::PlacedPage; +use types::{BLEND_BUDGET, BrushArtColors, FLIP, Frame, GState, Graph, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead}; +#[cfg(test)] +pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED}; pub(super) use types::{blend_mode, blend_name}; #[path = "legacy_text.rs"] mod legacy_text; +// The `.ai` writer defines symbols as this reader keeps them. +pub(crate) use directives::symbol_art_member; +pub(crate) use types::MAX_SYMBOLS; + /// What the editing data holds: the document of its art, and where its art space is. #[derive(Debug)] pub struct Structure { @@ -101,24 +178,242 @@ pub struct Structure { pub template: Option<[f64; 4]>, /// What layers that don't show have that isn't read (operators, objects): left out of them. pub hidden_unread: BTreeSet, + /// Top-level object ids and the unread kinds within them. + pub unread: Vec<(NodeId, Vec)>, + /// Other bounds for previewless placed files whose page art uses the file box's corner. + pub unread_elsewhere: Vec<(NodeId, Rect)>, /// The names of text objects, by their slot's id. pub slot_names: HashMap, /// Where the drawn looks lay that objects read with their art style took the place of (the /// document's coordinates): the page draws Illustrator's rendering of those styles there. pub restyled: Vec, + /// Where linked images whose pixels the data doesn't keep (`XF`) show a placeholder (the + /// document's coordinates). A PostScript page doesn't draw them there; a PDF part draws the + /// image's pixels. + pub placeholders: Vec, + /// Placed files whose pixels the file puts at another point too: their image's id and the + /// move, in its pixels, that places them there (the corner of the box they are written with, + /// in place of the canvas point of art space's origin). + pub placed_elsewhere: Vec<(NodeId, Affine)>, + /// The placed files that are pages of PDF or `.ai` files. + pub placed_pages: Vec, + /// The live envelopes read from the editing data, by id, with the drawn art each took the place + /// of: the importer puts that art back when the layers with the envelopes don't draw as the page. + pub envelopes_drawn: Vec<(NodeId, Node)>, + /// The warped text objects, checked against their drawn looks once their type is laid out. + pub warped_type: super::envelope::WarpedType, + /// The document's graphic styles are those of the file's style list, in place of the defaults. + pub styles_read: bool, + /// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not. + pub canvas_scale: f64, + /// The objects by their XML id (`AI10_ArtUID`), a text object by its slot's id: `None` for an + /// id two objects have. + pub xml_ids: HashMap>, + /// The objects the variable library binds to its variables, by their XML ids: the importer + /// binds those it keeps. + pub bindings: Vec, + /// How many objects the library binds that aren't in `bindings` ([`VariableRead::bindings_skipped`]). + pub bindings_skipped: usize, pub warnings: Vec, } +/// The most XML ids of objects ([`Structure::xml_ids`]) kept. +const MAX_XML_IDS: usize = 1_000_000; + +/// The most bytes of XML ids ([`Structure::xml_ids`]) kept, all ids together. +pub(super) const MAX_XML_ID_BYTES: usize = 16 << 20; + +/// Record that the object `id` has the XML id `uid` in `xml_ids`, whose ids take `bytes` bytes. Two +/// objects with one id are neither of them that id's. A new id is left out when `xml_ids` holds +/// [`MAX_XML_IDS`] ids or its bytes would pass [`MAX_XML_ID_BYTES`]. +pub(super) fn remember_xml_id(xml_ids: &mut HashMap>, bytes: &mut usize, uid: String, id: NodeId) { + if let Some(seen) = xml_ids.get_mut(&uid) { + if *seen != Some(id) { + *seen = None; + } + } else if xml_ids.len() < MAX_XML_IDS && bytes.saturating_add(uid.len()) <= MAX_XML_ID_BYTES { + *bytes += uid.len(); + xml_ids.insert(uid, Some(id)); + } +} + /// Read the structure of the editing data `data`, applying the file's `%AI24_LargeCanvasScale` only /// when `large_canvas` is set: an EPS's page is drawn at the full size, but a `.ai`'s PDF part may /// keep the reduced one, which the PDF import reads as it is (#2031). pub fn read(data: &[u8], large_canvas: bool) -> Result { - let mut r = Reader::new(data); + read_with(data, large_canvas, false) +} + +/// [`read`] for a file whose page art replaces the objects the reader doesn't read (see +/// [`Reader::unread_box`]): an image past the hard limits ([`raster::Limits`]) is then such an +/// object, where [`read`] leaves it out with a note. +pub(crate) fn read_over_page(data: &[u8], large_canvas: bool) -> Result { + read_with(data, large_canvas, true) +} + +fn read_with(data: &[u8], large_canvas: bool, page_art: bool) -> Result { + let mut r = Reader::with_names(data); r.large_canvas = large_canvas.then_some(1.0); + r.page_art = page_art; r.run()?; r.finish() } +/// [`read`] for editing data kept apart from the program `ps` it came with (an EPS's private +/// data): the program's header gives the author and the custom colors the editing data's header +/// doesn't. `page_art`: as [`read_over_page`] reads a file. +pub fn read_beside(data: &[u8], large_canvas: bool, ps: &[u8], page_art: bool) -> Result { + let header = Reader::header_of(ps); + let mut r = Reader::with_names(data); + r.large_canvas = large_canvas.then_some(1.0); + r.page_art = page_art; + // The program's custom colors have swatches of their names, which no gradient or pattern takes. + for n in &header.custom_colors { + r.global_names.reserve(&n.name); + } + r.run()?; + r.program_header(header); + r.finish() +} + +/// The names the gradients and patterns of the editing data `data` get in the document +/// ([`ShownNames`]), with the names its other swatches can have reserved first: Registration, the +/// default swatches of both color modes when the palette the reader keeps is missing or empty, the +/// names that palette gives, the named colors, and the names without a newline of the gradients +/// and patterns. Names come only from what the reader reads: not from the alternates of versioned +/// content, the prolog, resources, sections it skips (such as symbols and the text document) or +/// what follows the trailer. The palette the reader keeps is the last one outside those and the +/// sections it reads on their own. +fn swatch_names(data: &[u8]) -> (ShownNames, Option<&[u8]>) { + /// The sections the reader reads on their own whose definitions and colors it keeps. + const READ_APART: &[&str] = &["BeginPattern", "BeginBrushPattern", "BeginPluginObject", "BeginArtStyles", "BeginArtStyleList"]; + /// Whether the marker `m` ends what began with `begin` and ends with `end`, `depth` of its kind + /// open inside it. + fn closes(begin: &str, end: &str, depth: &mut usize, m: &str) -> bool { + if !begin.is_empty() && m == begin { + *depth += 1; + } else if m == end { + match depth.checked_sub(1) { + Some(d) => *depth = d, + None => return true, + } + } + false + } + let mut names = ShownNames::default(); + names.reserve(vectorcraft_color::swatch::REGISTRATION); + let mut colors = paint::ColorNames::default(); + let mut lex = Lexer::new(data); + // What the reader skips wherever it is (the marker of one of its kind nested in it, its end + // marker, how many are open inside it, and where reading goes on when it doesn't end), the + // top-level section being passed over (the first three, and whether the reader reads it on its + // own), and where the palette being found starts. + let mut skip: Option<(&str, &str, usize, Option)> = None; + let mut section: Option<(&str, &str, usize, bool)> = None; + let (mut palette_at, mut palette) = (None, None); + // Where the first art styles section starts, and that section. + let (mut styles_at, mut styles) = (None, None); + // A pattern's name is the first string of its definition. + let mut head = false; + // ASCII85 data in comment lines is skipped past, as the reader skips it. + let mut dictionaries = ops::Dictionaries::default(); + // The scan's state where the versioned content being skipped starts, to go back to. + let mut versioned = None; + loop { + let before = lex.offset(); + let Some(t) = lex.next_token() else { + // Versioned content that doesn't end is read whole, as the reader reads it. + match skip.take() { + Some((.., Some(at))) => { + lex.seek(at); + dictionaries = versioned.take().unwrap_or_default(); + continue; + } + _ => break, + } + }; + let markers = skip.map(|s| (s.0, s.1)).or(palette_at.map(|_| ("", "EndPalette"))).or(section.map(|s| (s.0, s.1))); + dictionaries.pass(&t.tok, &mut lex, markers); + match &t.tok { + Tok::Comment(c) => { + let line = String::from_utf8_lossy(c); + let m = marker(&line); + if let Some((begin, end, depth, _)) = skip.as_mut() { + if closes(begin, end, depth, m) { + skip = None; + } + } else if let Some(at) = palette_at { + if m == "EndPalette" { + palette = Some(lex.slice(at, before)); + palette_at = None; + } + } else if m.starts_with("Alternate_Content") && section.is_none_or(|s| s.3) { + skip = Some(("Begin_Content_if_version_gt", "End_Versioned_Content", 0, Some(lex.offset()))); + versioned = Some(dictionaries.clone()); + } else if m == "%BeginProlog" { + skip = Some(("", "%EndProlog", 0, None)); + } else if m == "%BeginResource" { + skip = Some(("", "%EndResource", 0, None)); + } else if let Some((begin, end, depth, _)) = section.as_mut() { + if closes(begin, end, depth, m) { + if let Some(at) = styles_at.take().filter(|_| *begin == "BeginArtStyles") { + styles = Some(lex.slice(at, before)); + } + section = None; + } + } else if m == "BeginPalette" { + palette_at = Some(lex.offset()); + } else if let Some((begin, end)) = types::SKIPPED.iter().find(|(b, _)| *b == m) { + section = Some((begin, end, 0, READ_APART.contains(begin))); + head = m == "BeginPattern"; + if m == "BeginArtStyles" && styles.is_none() { + styles_at = Some(lex.offset()); + } + } else if matches!(m, "%PageTrailer" | "%Trailer") { + break; + } + continue; + } + // A palette's names are those of the palette kept, as the palette reads them. + _ if skip.is_some() || palette_at.is_some() || section.is_some_and(|s| !s.3) => continue, + Tok::Str(s) | Tok::Hex(s) if std::mem::take(&mut head) => { + let text = obj::text(s); + if !text.contains('\n') { + names.reserve(&text); + } + } + _ => {} + } + colors.token(t.tok); + } + colors.gradients.iter().filter(|n| !n.contains('\n')).for_each(|n| names.reserve(n)); + let palette = palette.map(super::palette::palette).unwrap_or_default(); + if palette.is_empty() { + for mode in [ColorMode::Rgb, ColorMode::Cmyk] { + let (swatches, groups) = vectorcraft_color::default_swatches(mode.model()); + for g in &groups { + names.reserve(&g.name); + g.swatches.iter().for_each(|s| names.reserve(&s.name)); + } + swatches.iter().for_each(|s| names.reserve(&s.name)); + } + } + palette.own_names().for_each(|n| names.reserve(n)); + colors.names.iter().for_each(|n| names.reserve(n)); + (names, styles) +} + +/// What the brushes and brush art read so far give a brushed stroke. +#[derive(Default)] +struct BrushesKept { + /// The counts of brushes and art sections when this was worked out. + read: (usize, usize), + /// Which of [`Reader::brush_drafts`] are kept as brushes. + kept: Vec, + /// The art an Art brush draws as the file does. + bending: HashSet, +} + struct Reader<'a> { lex: Lexer<'a>, stack: Vec, @@ -127,16 +422,33 @@ struct Reader<'a> { gs: GState, frames: Vec, path: BezPath, + /// The kind of the anchor each segment of `path` ends on, in order: smooth for a lower-case + /// segment operator, corner for an upper-case one (version 7 specification §5.3.2). + path_kinds: Vec, points: usize, /// The path is a clipping path (`W`). clip_next: bool, doc: Document, to_doc: Option, cropmarks: Option, - artboards: Vec<(String, Rect)>, - /// The variables and data sets of the `/Document` dictionary's variable library. - variables: VariableLibrary, + artboards: Vec, + /// The index in `artboards` of the active artboard (`CropAreaActive`). + active_board: Option, + /// The user the header's `%%For` names. + author: Option, + /// The custom colors the header's `%%CMYKCustomColor` and `%%RGBCustomColor` define. + custom_colors: Vec, + /// The last header comment defined custom colors (CMYK when true), which a `%%+` line continues. + custom_more: Option, + /// The header ended (`%%EndComments`). + header_done: bool, + /// The `/Document` dictionary's variable library. + variables: VariableRead, + /// The Objects on Path records of the `/Document` dictionary and the ids of the objects. + on_path: on_path::OnPath, gradients: HashMap, + /// The names the gradients and patterns get in the document, by their names in the file. + global_names: ShownNames, gradient_def: Option, instance: Option, pending_fill: Option, @@ -147,10 +459,18 @@ struct Reader<'a> { /// a global process colour, so these make swatches only for names no colour operator defines. stop_spots: Vec, raster: Option, + /// The file `XG` names for the image after it (`XF`), until an image is read. + image_link: Option, /// The placed file being read (`%AI5_BeginPlace` … `~`). place: Option, + /// The placed files just read, until the dictionary after each: at most one for each depth of + /// frames, the innermost last. + placed_tails: Vec, /// The last object read is the last child of the innermost frame, and nothing started since. after_object: bool, + /// The last object read is an image, and only the operators that end its raster (`XH`, `Xr`, + /// `N`) came since: its name and opacity mask still follow. + image_tail: bool, nodes: usize, /// What layers that show have that this reader doesn't read (errors). unsupported: BTreeSet, @@ -158,6 +478,29 @@ struct Reader<'a> { unknown: BTreeSet, /// What layers that don't show have that this reader doesn't read. hidden_unread: BTreeSet, + unread: Vec<(NodeId, Vec)>, + /// The art boxes (symbol space) of symbols whose definition can be measured but not read + /// whole, by their name in the file: their instances come in as the page draws them. + symbol_bounds: HashMap, + /// The symbols read, by their name in the file → their name in the document. + symbol_names: HashMap, + /// The names the symbols read have in the document, and for each name read more than once, + /// the number its next copy is tried with. + symbol_taken: HashSet, + symbol_suffix: HashMap, + /// The art boxes (symbol space) of symbols read, by their name in the file, once measured for + /// an instance that comes in as the page draws it. + symbol_art_bounds: HashMap>, + /// The symbol list's names, in the Symbols panel's order (`%AI24_BeginSymbolList`). + symbol_list: Option>, + /// The symbols read were checked for instances of symbols the file doesn't have. + symbols_checked: bool, + /// This reader reads a symbol's definition (see [`Reader::define_symbol`]). + symbol: Option, + /// Depth shared by pattern and symbol readers. + subreader_depth: usize, + pending_unread_fill: bool, + pending_unread_stroke: bool, /// The header's bounding boxes and template box. bbox: Option<[f64; 4]>, hires: Option<[f64; 4]>, @@ -169,6 +512,12 @@ struct Reader<'a> { warnings: Vec, /// Objects read as their drawn look (several fills or strokes, effects, brushes). drawn_looks: usize, + /// The objects read as their drawn look in the art of [`Reader::brush_art`], by name: counted in + /// [`Reader::drawn_looks`] once a brush that is kept uses the art. + brush_art_looks: HashMap, + /// The objects read as their drawn look in the art of the patterns kept, by the name the document + /// has the pattern by: a pattern defined again counts only its last definition. + pattern_looks: HashMap, /// Nodes read from `%_` lines. hidden_ids: HashSet, /// The blend part each object's dictionary names (`ShapeBlendPathType`, `ShapeBlendPathID`). @@ -177,14 +526,41 @@ struct Reader<'a> { blend_record: Option<(usize, Vec)>, /// How many more objects blends may lay out in this import ([`super::blend::live_blend`]). blend_budget: usize, + /// The group on `%_` lines an envelope's dictionary just took (see [`Reader::drop_envelope_art`]). + envelope_art: Option, + /// Envelopes waiting for their drawn art, innermost last. + envelopes: Vec, + /// How many more envelopes and warped text objects this import may draw to check + /// ([`super::envelope::drawn_alike`]). + envelope_checks: usize, + /// How far the live envelopes read so far draw from their drawn art ([`super::envelope::Spent`]). + envelope_spent: super::envelope::Spent, + /// The text objects read with a Warp ([`super::envelope::WarpedType`]). + warped_type: Vec, + /// The live envelopes made so far and the drawn art each took the place of + /// ([`Structure::envelopes_drawn`]). + envelopes_drawn: Vec<(NodeId, Node)>, /// A group just ended, its state (`Xy`, `Xd`, `XW`) not yet read. group_ended: bool, + /// A gradient mesh just ended (`/End X!`), its own state (`Xy`) not yet read: also after its + /// dictionary (its name, its opacity mask and the mask's art). + mesh_ended: bool, /// A layer's own state (`Xy` after its art, before `LB`), until something says the art moves on. - layer_state: Option<(f32, BlendMode, bool, Knockout)>, - /// Painted copies of clipping paths that have a fill (drawn under what they clip). + layer_state: Option<(f32, BlendMode, bool, Knockout, bool)>, + /// The state a mesh or blend had before an `Xy` right after its end, which is the layer's + /// instead when the layer's `LB` follows rather than their own `6 () XW`. + mesh_undo: Option<(f32, BlendMode, bool, Knockout, bool)>, + /// The state a layer's last group or compound path had before an `Xy` right after its end, + /// which is the layer's instead when the layer's own `7 () XW` follows. + container_undo: Option<(f32, BlendMode, bool, Knockout, bool)>, + /// The fills of compound clipping paths whose subpaths paint differently, as compound paths of their own (drawn + /// under what they clip). clip_fills: HashSet, /// Groups closed as an object's drawn look (`9 () XW`). looks: HashSet, + /// Straight `(N) *` guide paths painted directly on a layer, by id: their two points in art + /// space. [`Reader::finish`] makes the ruler guides among them guides of their layer. + ruler_guides: HashMap, /// Legacy compound member groups, even when followed by the generic `9 () XW` marker. compound_groups: HashSet, /// Groups of a text object and its look (see [`Self::style_marker`]), which aren't a look. @@ -193,10 +569,22 @@ struct Reader<'a> { mesh: Option<(super::mesh::MeshReader, bool)>, /// The art styles (`%AI9_BeginArtStyles`), by name. styles: HashMap, + /// The style list (`%AI9_BeginArtStyleList`): the Graphic Styles panel's names, in its order. + style_list: Vec>, + /// The objects read as themselves with the style their `1 (style) XW` names: their id and the + /// style's name, as written. + style_links: Vec<(NodeId, String)>, /// The swatches (`%AI5_BeginPalette`). palette: super::palette::Palette, /// See [`Structure::restyled`]. restyled: Vec, + /// See [`Structure::placeholders`]. + placeholders: Vec, + /// See [`Structure::placed_elsewhere`]. + placed_elsewhere: Vec<(NodeId, Affine)>, + /// See [`Structure::placed_pages`]. + placed_pages: Vec, + unread_elsewhere: Vec<(NodeId, Rect)>, /// CMYK samples converted, by value. cmyk_cache: HashMap<[u8; 4], [u8; 3]>, /// A `/ForeignObject`'s `/Data`: its PDF as ASCII85 in comment lines, until the object closes. @@ -207,6 +595,10 @@ struct Reader<'a> { obj_hidden: bool, /// The names of text objects, by their slot's id. slot_names: HashMap, + /// [`Structure::xml_ids`]. + xml_ids: HashMap>, + /// The bytes of the ids in `xml_ids`. + xml_id_bytes: usize, /// The artboard's size and centre in files without artboards or crop marks. art_size: Option<(f64, f64)>, template_center: Option<(f64, f64)>, @@ -214,15 +606,42 @@ struct Reader<'a> { /// (see [`Reader::ensure_space`]); 1 (no scaling) when the file doesn't declare one, `None` /// when the declared factor is not applied ([`read`]). large_canvas: Option, + /// The file has page art to replace the objects that aren't read ([`read_over_page`]). + page_art: bool, + /// The declared `%AI24_LargeCanvasScale` (1 without one), applied or not. + canvas_scale: f64, /// `%AI5_RulerUnits` from the header (Illustrator 7 spec table 3, plus centimeters and pixels). ruler_units: Option, /// This reader reads a pattern's definition (see [`Reader::define_pattern`]). pattern: Option, /// The tile (y down) of each pattern read, by name. pattern_tiles: HashMap, + /// The patterns read from a definition in the version 7 form, whose fills apply their other + /// operands before the matrix (see [`Reader::pattern_paint`]). + v7_patterns: HashSet, /// The legacy text object being read (`To` … `TO`), and the modal type attributes. text: Option, type_state: legacy_text::TypeState, + /// The file has brush objects (the brush manager's order or a brush). + brush_objects: bool, + /// The brush manager's order. + brush_order: Option>, + /// The brushes read, in the order of their objects. + brush_drafts: Vec, + /// The art of the brushes (`%AI8_BeginBrushPattern`), by name. + brush_art: HashMap, + /// The colors of the art in [`Reader::brush_art`], by name. + brush_art_colors: HashMap, + /// The brush art sections read so far, repeated names included. + brush_art_sections: usize, + /// What the brushes and brush art read so far give a brushed stroke. + brushes_kept: BrushesKept, + /// Brush objects that weren't read. + brushes_unread: usize, + /// The graph being read (see [`Reader::graph_record`]). + graph: Option, + /// The multi-layer mask being read (`Mb` … `MB`), which goes on past a layer's end. + multi_mask: Option, } /// A section comment's marker without its `AI_` prefix and value (`AI14_BeginSymbol` → @@ -232,8 +651,29 @@ fn marker(c: &str) -> &str { word.strip_prefix("AI").map(|r| r.trim_start_matches(|ch: char| ch.is_ascii_digit())).and_then(|r| r.strip_prefix('_')).unwrap_or(word) } +/// Is `name` that of a text slot for type that a look draws ([`document::LOOK_SLOT`])? +pub(crate) fn is_look_slot(name: Option<&str>) -> bool { + name == Some(document::LOOK_SLOT) +} + impl<'a> Reader<'a> { + /// A reader of the editing data `data` as a whole, with the names its gradients and patterns + /// get in the document and its art styles found first ([`swatch_names`]): the symbols defined + /// before the art styles section use them too. + fn with_names(data: &'a [u8]) -> Self { + let mut r = Self::new(data); + let (names, styles) = swatch_names(data); + r.global_names = names; + if let Some(section) = styles { + r.styles = super::style::art_styles(section); + } + r + } + fn new(data: &'a [u8]) -> Self { + // An envelope's saved margins and its check against its drawn art measure type by its + // glyphs, as the app maps it. + vectorcraft_text::register_envelope_ink(); let mut doc = Document::new(1.0, 1.0); doc.layers.clear(); Self { @@ -243,14 +683,22 @@ impl<'a> Reader<'a> { gs: GState::default(), frames: Vec::new(), path: BezPath::new(), + path_kinds: Vec::new(), points: 0, clip_next: false, doc, to_doc: None, cropmarks: None, artboards: Vec::new(), - variables: VariableLibrary::default(), + active_board: None, + author: None, + custom_colors: Vec::new(), + custom_more: None, + header_done: false, + variables: VariableRead::default(), + on_path: on_path::OnPath::default(), gradients: HashMap::new(), + global_names: ShownNames::default(), gradient_def: None, instance: None, pending_fill: None, @@ -258,13 +706,27 @@ impl<'a> Reader<'a> { spots: Vec::new(), stop_spots: Vec::new(), raster: None, + image_link: None, place: None, foreign_data: None, after_object: false, + image_tail: false, nodes: 0, unsupported: BTreeSet::new(), unknown: BTreeSet::new(), hidden_unread: BTreeSet::new(), + unread: Vec::new(), + symbol_bounds: HashMap::new(), + symbol_names: HashMap::new(), + symbol_taken: HashSet::new(), + symbol_suffix: HashMap::new(), + symbol_art_bounds: HashMap::new(), + symbol_list: None, + symbols_checked: false, + symbol: None, + subreader_depth: 0, + pending_unread_fill: false, + pending_unread_stroke: false, bbox: None, hires: None, template: None, @@ -273,32 +735,66 @@ impl<'a> Reader<'a> { color_model: None, warnings: Vec::new(), drawn_looks: 0, + brush_art_looks: HashMap::new(), + pattern_looks: HashMap::new(), hidden_ids: HashSet::new(), blend_roles: HashMap::new(), blend_record: None, blend_budget: BLEND_BUDGET, + envelope_art: None, + envelopes: Vec::new(), + envelope_checks: super::envelope::MAX_CHECKED, + envelope_spent: super::envelope::Spent::default(), + warped_type: Vec::new(), + envelopes_drawn: Vec::new(), clip_fills: HashSet::new(), looks: HashSet::new(), + ruler_guides: HashMap::new(), compound_groups: HashSet::new(), text_looks: HashSet::new(), group_ended: false, + mesh_ended: false, layer_state: None, + mesh_undo: None, + container_undo: None, styles: HashMap::new(), + style_list: vec![], + style_links: vec![], palette: super::palette::Palette::default(), restyled: vec![], + placeholders: vec![], + placed_elsewhere: vec![], + placed_pages: vec![], + placed_tails: vec![], + unread_elsewhere: vec![], mesh: None, cmyk_cache: HashMap::new(), done: false, obj_hidden: false, slot_names: HashMap::new(), + xml_ids: HashMap::new(), + xml_id_bytes: 0, art_size: None, template_center: None, large_canvas: None, + page_art: false, + canvas_scale: 1.0, ruler_units: None, pattern: None, pattern_tiles: HashMap::new(), + v7_patterns: HashSet::new(), text: None, type_state: legacy_text::TypeState::default(), + brush_objects: false, + brush_order: None, + brush_drafts: Vec::new(), + brush_art: HashMap::new(), + brush_art_colors: HashMap::new(), + brush_art_sections: 0, + brushes_kept: BrushesKept::default(), + brushes_unread: 0, + graph: None, + multi_mask: None, } } @@ -317,18 +813,38 @@ impl<'a> Reader<'a> { let w = std::str::from_utf8(w).unwrap_or("?"); self.op(w, hidden)?; } - Tok::Comment(c) => self.comment(c)?, + Tok::Comment(c) => self.comment(c, hidden)?, Tok::Data(d) => self.image(d)?, Tok::Preview(d) => { if let Some(p) = self.place.as_mut() { p.preview = preview_png(d); } } + // A placed file's document, included whole: its art isn't read here. When no + // `%%EndDocument` ends it, the placed file isn't read. + Tok::Document(d) => { + if let Some(p) = self.place.as_mut() { + p.broken |= d.is_none(); + } + } } } + // A pattern's or symbol's reader opens a group of its own and checks it is the only frame + // left. In the document, a container still open after the last layer holds art no layer has. + let in_layer = self.frames.iter().any(|f| matches!(f.kind, Kind::Layer(_))); + if self.subreader_depth == 0 && !in_layer && self.frames.iter().any(|f| !matches!(f.kind, Kind::Obj(_) | Kind::Mask)) { + return Err("it ends inside a group or compound path".into()); + } if self.frames.iter().any(|f| matches!(f.kind, Kind::Layer(_))) { return Err("it ends inside a layer".into()); } + if self.multi_mask.is_some() { + return Err("it ends inside a multi-layer mask".into()); + } + // A placed file that no `~` ends isn't read. + if let Some(open) = self.place.take() { + self.unreadable("placed files", open.hidden); + } Ok(()) } } diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 52bd7e6857..7d2565172d 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -1,31 +1,45 @@ use super::containers::close; use super::document::TEXT_SLOT; -use super::types::{FLIP, IMAGE_TOO_LARGE, LINKED_PREVIEWS, MAX_PIXELS, MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, Place}; -use super::{ - Affine, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node, NodeKind, - Obj, OpacityMask, Paint, PathData, Point, Reader, Rect, StrokeLayer, V, ps, +use super::raster::{self, Limits, Shape}; +use super::types::{ + FLIP, Frame, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, + NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail, }; +use super::{ + Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node, + NodeId, NodeKind, Obj, OpacityMask, PageBox, Paint, PathData, PathEl, Point, Reader, Rect, StrokeLayer, V, ps, +}; +use vectorcraft_doc::links::missing_placeholder; +use vectorcraft_doc::placed_document::key_for; impl<'a> Reader<'a> { /// A text object (`/AI11Text`): an empty group standing for it, named after its story. pub(super) fn text_slot(&mut self, o: &Obj) -> Result<(), String> { if self.pattern.is_some() { - self.unreadable("type in a pattern"); - } - // `1 /FreeUndo`: the type in the drawn look of a text object that has an appearance. Its - // story is one of another text document (`/AI11UndoFreeTextDocument`), which counts its - // stories on its own; the object itself follows the look, on `%_` lines, and is the type. - if o.nums("FreeUndo").first() == Some(&1.0) { - return Ok(()); + self.unreadable("type in a pattern", false); } + self.left_out_of_symbol(); + // `1 /FreeUndo`: type in a drawn look. Its story is one of another text document + // (`/AI11UndoFreeTextDocument`), which counts its stories on its own, so its slot has none. + // In the look of a text object that has an appearance, the object itself follows the look, + // on `%_` lines, and is the type (`style_marker` takes the slot out); in the look of a layer + // or a group it is the type of a copy that the look draws. + let look = o.nums("FreeUndo").first() == Some(&1.0); let index = |key: &str| o.nums(key).first().copied().filter(|v| (0.0..f64::from(u32::MAX)).contains(v)).map(|v| v as u32); - let (story, frame) = (index("StoryIndex"), index("FrameIndex").unwrap_or(0)); + let (story, frame) = (index("StoryIndex").filter(|_| !look), index("FrameIndex").unwrap_or(0)); let gs = self.gs.clone(); let mut n = self.new_node(NodeKind::Group { children: vec![], clip: false }, &gs); - n.name = Some(story.map_or_else(|| TEXT_SLOT.to_string(), |s| format!("{TEXT_SLOT}{s}:{frame}"))); + n.name = Some(match story { + _ if look => super::document::LOOK_SLOT.to_string(), + Some(s) => format!("{TEXT_SLOT}{s}:{frame}"), + None => TEXT_SLOT.to_string(), + }); // The type takes the state's transparency, as a path does; an `Xy` after it sets the slot's own. n.opacity = gs.opacity; n.blend = gs.blend; + n.knockout_shape = gs.knockout_shape; + // An `Xy` before the text object was the object's, not its layer's, when the layer's `LB` follows. + self.layer_state = None; let hidden = self.obj_hidden; self.add(n, hidden) } @@ -38,6 +52,11 @@ impl<'a> Reader<'a> { /// group. Without data, or with a PDF that can't be read, nothing is drawn. pub(super) fn foreign_art(&mut self, o: &Obj) -> Result<(), String> { let Some(text) = self.foreign_data.take() else { return Ok(()) }; + // Where a symbol's art puts it isn't known. + if self.symbol.is_some() { + self.left_out_of_symbol(); + return Ok(()); + } // One `%` starts each line; the rest, `_` included, is data. let mut encoded = String::with_capacity(text.len()); for line in text.split(|b| matches!(b, b'\r' | b'\n')) { @@ -108,32 +127,45 @@ impl<'a> Reader<'a> { return Err("a path has too many points".into()); } let current = self.path.elements().last().and_then(|e| e.end_point()); - match w { + let kind = if w.starts_with(|c: char| c.is_ascii_lowercase()) { AnchorKind::Smooth } else { AnchorKind::Corner }; + let added = match w { "m" => { let Some(a) = p(2) else { return Ok(()) }; self.path.move_to(a); + return Ok(()); } - _ if current.is_none() => {} - "l" | "L" => { - if let Some(a) = p(2) { + _ if current.is_none() => false, + "l" | "L" => match p(2) { + Some(a) => { self.path.line_to(a); + true } - } - "c" | "C" => { - if let (Some(a), Some(b), Some(c)) = (p(6), p(4), p(2)) { + None => false, + }, + "c" | "C" => match (p(6), p(4), p(2)) { + (Some(a), Some(b), Some(c)) => { self.path.curve_to(a, b, c); + true } - } - "v" | "V" => { - if let (Some(cur), Some(b), Some(c)) = (current, p(4), p(2)) { + _ => false, + }, + "v" | "V" => match (current, p(4), p(2)) { + (Some(cur), Some(b), Some(c)) => { self.path.curve_to(cur, b, c); + true } - } - _ => { - if let (Some(a), Some(c)) = (p(4), p(2)) { + _ => false, + }, + _ => match (p(4), p(2)) { + (Some(a), Some(c)) => { self.path.curve_to(a, c, c); + true } - } + _ => false, + }, + }; + if added { + self.path_kinds.push(kind); } Ok(()) } @@ -141,27 +173,37 @@ impl<'a> Reader<'a> { /// A path left unpainted before a container opens. pub(crate) fn end_path_quietly(&mut self) { self.path = BezPath::new(); + self.path_kinds.clear(); self.points = 0; self.clip_next = false; + if let Some(head) = self.symbol.as_mut() { + (head.missing_fill, head.missing_stroke) = (false, false); + } } /// Paint the current path (`op`), as a guide when `guide`. pub(super) fn paint(&mut self, op: &str, hidden: bool, guide: bool) -> Result<(), String> { let mut bp = std::mem::take(&mut self.path); + let kinds = std::mem::take(&mut self.path_kinds); self.points = 0; let clip = std::mem::take(&mut self.clip_next); if let Some(i) = self.instance.take() { self.set_instance(&i); } let (fill_paint, stroke_paint) = (self.pending_fill.take(), self.pending_stroke.take()); + let missing = self.symbol.as_mut().map_or((false, false), |h| (std::mem::take(&mut h.missing_fill), std::mem::take(&mut h.missing_stroke))); if bp.elements().is_empty() { return Ok(()); } if op.chars().next().is_some_and(|c| c.is_ascii_lowercase()) { close(&mut bp); } + let line = match bp.elements() { + [PathEl::MoveTo(a), PathEl::LineTo(b)] => Some((*a, *b)), + _ => None, + }; let to_doc = self.space(); - let path = PathData::from_bezpath(&(to_doc * bp)); + let path = path_data(&(to_doc * bp), &kinds); let gs = self.gs.clone(); let (fill, stroke) = match op.to_ascii_lowercase().as_str() { "f" => (true, false), @@ -169,15 +211,20 @@ impl<'a> Reader<'a> { "b" => (true, true), _ => (false, false), }; - let mut items = Vec::new(); - if fill && !clip { - items.push(AppearanceItem::Fill(FillLayer { - overprint: gs.overprint_fill, - ..FillLayer::new(fill_paint.clone().unwrap_or(gs.fill.clone())) - })); + // A symbol's art painted with a gradient the file doesn't define is left out. + if (missing.0 && fill) || (missing.1 && stroke) { + self.left_out_of_symbol(); } - if stroke && !clip { - let mut st = StrokeLayer::new(stroke_paint.unwrap_or(gs.stroke.clone()), gs.width); + // A gradient instance's paint replaces the missing pattern. + let unread = (fill && self.pending_unread_fill && fill_paint.is_none()) || (stroke && self.pending_unread_stroke && stroke_paint.is_none()); + let mut items = Vec::new(); + // A clipping path keeps its fill and its stroke: its fill paints under the art it clips and its stroke over it + // (`Node::clip_paint`), as the file's PDF part draws them. + if fill { + items.push(AppearanceItem::Fill(FillLayer { overprint: gs.overprint_fill, ..FillLayer::new(fill_paint.unwrap_or(gs.fill.clone())) })); + } + if stroke { + let mut st = StrokeLayer::new(stroke_paint.unwrap_or(gs.stroke.clone()), gs.line_width()); st.cap = gs.cap; st.join = gs.join; st.miter_limit = gs.miter; @@ -187,6 +234,19 @@ impl<'a> Reader<'a> { } let kind = NodeKind::Path { path, rule: gs.rule, live: None, clipping: clip, guide }; let mut node = self.new_node(kind, &gs); + // A ruler guide is written as a straight `(N) *` guide path on its layer. + if guide + && op == "N" + && !hidden + && !gs.hidden + && !clip + && self.pattern.is_none() + && matches!(self.frames.last(), Some(Frame { kind: Kind::Layer(_), .. })) + && let Some((a, b)) = line + && [a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite()) + { + self.ruler_guides.insert(node.id, (a, b)); + } node.appearance = Appearance { items, ..Appearance::default() }.into(); node.opacity = gs.opacity; node.blend = gs.blend; @@ -194,26 +254,31 @@ impl<'a> Reader<'a> { if clip && let Some(f) = self.frames.last_mut() { f.clips.push(f.children.len()); } - // A clipping path's fill is painted too, under the art it clips, as the file's PDF part draws it. - let painted = clip && fill && !matches!(gs.fill, Paint::None); - let copy = painted.then(|| { - let mut copy = node.clone(); - copy.id = self.doc.alloc_id(); - if let NodeKind::Path { clipping, .. } = &mut copy.kind { - *clipping = false; - } - let paint = fill_paint.clone().unwrap_or_else(|| gs.fill.clone()); - copy.appearance = Appearance { - items: vec![AppearanceItem::Fill(FillLayer { overprint: gs.overprint_fill, ..FillLayer::new(paint) })], - ..Appearance::default() - } - .into(); - copy + node.edit_attrs(|a| { + a.note = gs.note.clone().unwrap_or_default(); + a.show_center = gs.show_center; }); + let unread_bounds = unread.then(|| node.visual_bounds()).flatten(); + let unread_id = node.id; self.add(node, hidden)?; - if let Some(copy) = copy { - self.clip_fills.insert(copy.id); - self.add(copy, hidden)?; + if unread && self.pattern.is_some() { + // Art in a pattern's definition painted with a pattern it doesn't have: the tile can't be read. + self.unsupported.insert("pattern fills".into()); + } else if unread && ((hidden && !self.in_mask()) || gs.hidden || !self.shown()) { + self.hidden_unread.insert("pattern fills".into()); + } else if unread && self.in_mask() { + self.unreadable("pattern fills", false); + } else if unread { + match unread_bounds { + Some(b) if sane(b) && b.area() > 0.0 => { + if !self.mark_unread("pattern fills".into()) { + self.unread.push((unread_id, vec!["pattern fills".into()])); + } + } + _ => { + self.unsupported.insert("pattern fills".into()); + } + } } Ok(()) } @@ -222,7 +287,7 @@ impl<'a> Reader<'a> { pub(super) fn end_mesh(&mut self) -> Result<(), String> { let Some((m, hidden)) = self.mesh.take() else { return Ok(()) }; if m.unread || m.patches.is_empty() { - self.unreadable("gradient meshes it can't read"); + self.unreadable("gradient meshes it can't read", hidden && self.pattern.is_none()); return Ok(()); } let gs = self.gs.clone(); @@ -233,7 +298,10 @@ impl<'a> Reader<'a> { let mut node = self.new_node(NodeKind::Mesh(one), &gs); node.opacity = gs.opacity; node.blend = gs.blend; - return self.add(node, hidden); + node.knockout_shape = gs.knockout_shape; + self.add(node, hidden)?; + self.mesh_ended = true; + return Ok(()); } Err(crate::import::ai::mesh::NotOne::Unjoined) => { self.warn("a gradient mesh whose patches don't join up comes in as a group of its patches") @@ -247,17 +315,23 @@ impl<'a> Reader<'a> { }; node.opacity = gs.opacity; node.blend = gs.blend; - self.add(node, hidden) + node.knockout_shape = gs.knockout_shape; + self.add(node, hidden)?; + self.mesh_ended = true; + Ok(()) } /// Stroke the path just painted (a gradient-filled one, `1 BB` or `2 BB`) with the stroke's state. pub(super) fn stroke_last(&mut self) { let gs = self.gs.clone(); - let Some(n) = self.last_object() else { return }; - if !matches!(n.kind, NodeKind::Path { clipping: false, .. }) || n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))) { + if !self.after_object { return; } - let mut st = StrokeLayer::new(gs.stroke.clone(), gs.width); + let Some(n) = self.frames.last_mut().and_then(|f| f.children.last_mut()) else { return }; + if !matches!(n.kind, NodeKind::Path { .. }) || n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))) { + return; + } + let mut st = StrokeLayer::new(gs.stroke.clone(), gs.line_width()); st.cap = gs.cap; st.join = gs.join; st.miter_limit = gs.miter; @@ -271,15 +345,20 @@ impl<'a> Reader<'a> { pub(super) fn set_instance(&mut self, i: &Instance) { let mut to_doc = self.space(); // In a pattern's definition a gradient's `Xm` and `Bm` are written y down about the canvas point of art space's - // origin, as the file's PDF part draws them. - if self.pattern.is_some() + // origin, as the file's PDF part draws them; in a symbol's, as the instances in its art are. + if (self.pattern.is_some() || self.symbol.is_some()) && i.has_matrix() && let Some(t) = self.template { let (cx, cy) = ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0); to_doc *= Affine::new([1.0, 0.0, 0.0, -1.0, CANVAS_CENTRE - cx, CANVAS_CENTRE + cy]); } - match i.paint(&self.gradients, to_doc) { + let paint = i.paint(&self.gradients, &self.global_names, to_doc); + if let Some(head) = self.symbol.as_mut() { + let missing = if i.stroke { &mut head.missing_stroke } else { &mut head.missing_fill }; + *missing = paint.is_none(); + } + match paint { Some(p) if i.stroke => self.pending_stroke = Some(p), Some(p) => self.pending_fill = Some(p), None => { @@ -299,64 +378,116 @@ impl<'a> Reader<'a> { Some(before) if !vals.iter().any(|v| matches!(v, V::Arr(_))) => before, _ => vals, }; - self.image_from(vals, data) + self.image_from(vals, data, false) } - /// An image of operands `vals` and samples `data`. - pub(super) fn image_from(&mut self, vals: Vec, data: &[u8]) -> Result<(), String> { + /// The matrix and the numbers of an image's operands (`[a b c d tx ty] llx lly urx ury w h bits + /// ImageType AlphaChannelCount reserved bin-ascii ImageMask`, as `XI` and `XF` take them); `None` + /// without a matrix or with fewer numbers than up to the encoding (bin-ascii). + fn image_operands(vals: &[V]) -> Option<(Vec, Vec)> { + let m = vals.iter().find_map(|v| if let V::Arr(a) = v { Some(Self::nums(a)) } else { None })?; + let n = Self::nums(vals); + (n.len() >= 11).then_some((m, n)) + } + + /// `XG` (`w`, which names the file of the image after it) or `XF` (that image), with their + /// operands `vals`. Before the art, the setup's procedures run: there they do nothing. + pub(super) fn image_link_op(&mut self, w: &str, vals: Vec, hidden: bool) -> Result<(), String> { + if self.frames.is_empty() { + return Ok(()); + } + if w == "XG" { + self.image_link = Self::image_link(&vals); + return Ok(()); + } + self.linked_image(vals, hidden) + } + + /// The file `XG`'s operands (`(path) modified`) name; `None` for operands of another shape or + /// an empty path. + fn image_link(vals: &[V]) -> Option { + match vals { + [.., V::Str(path), V::Num(_)] if !path.is_empty() => Some(super::obj::text(path)), + _ => None, + } + } + + /// The bytes of samples (colour and alpha) that the image of `XI` operands `vals` reads: 0 when + /// it isn't read (operands missing, or past the hard limits). + pub(super) fn sample_bytes(&self, vals: &[V]) -> usize { let space = self.raster.as_ref().and_then(|r| r.space.clone()).unwrap_or_default(); - let Some(m) = vals.iter().find_map(|v| if let V::Arr(a) = v { Some(Self::nums(a)) } else { None }) else { - self.warn("an image VectorCraft can't read was left out"); + let n = Self::nums(vals); + let [_, _, _, _, w, h, bits, kind, alpha, ..] = n.as_slice() else { return 0 }; + let shape = Shape { w: *w as u64, h: *h as u64, channels: channels(&space, *kind) as u64, bits: *bits as u64, alpha: *alpha > 0.0 }; + match (shape.step(&Limits::get()), shape.lens()) { + (Some(_), Some((colour, alpha))) => usize::try_from(colour + alpha).unwrap_or(0), + _ => 0, + } + } + + /// An image of operands `vals` and samples `data` (`decoded`: bytes already, whatever the + /// operands say). + pub(super) fn image_from(&mut self, vals: Vec, data: &[u8], decoded: bool) -> Result<(), String> { + // A file `XG` named before this image isn't the file of a later `XF`. + self.image_link = None; + let space = self.raster.as_ref().and_then(|r| r.space.clone()).unwrap_or_default(); + let Some((m, n)) = Self::image_operands(&vals) else { + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; - let n = Self::nums(&vals); - let [_, _, _, _, w, h, bits, kind, alpha, _, binary, ..] = n.as_slice() else { - self.warn("an image VectorCraft can't read was left out"); + let [_, _, _, _, w, h, bits, kind, alpha, _, binary, rest @ ..] = n.as_slice() else { + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; + // ImageMask 1: the image is transparent and takes a color (version 7 specification §8.1). + let image_mask = rest.first() == Some(&1.0); let (w, h) = (*w as u64, *h as u64); - if w.saturating_mul(h) > MAX_PIXELS { - self.warn(IMAGE_TOO_LARGE); - return Ok(()); - } if w == 0 || h == 0 || ![1.0, 8.0].contains(bits) { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); } - let channels: usize = match space.as_str() { - "DeviceGray" => 1, - "DeviceCMYK" => 4, - "DeviceRGB" => 3, - _ => match *kind as i64 { - 1 => 1, - 4 => 4, - _ => 3, - }, + let channels = channels(&space, *kind); + // The size is checked before anything is decoded or allocated. + let shape = Shape { w, h, channels: channels as u64, bits: *bits as u64, alpha: *alpha > 0.0 }; + let (Some(k), Some((need, alpha_len))) = (shape.step(&Limits::for_channels(channels)), shape.lens()) else { + return self.too_large_image(&m, w, h); }; - let decoded; - let data = if *binary == 0.0 { - let digits: Vec = data.iter().copied().filter(|b| b.is_ascii_hexdigit()).collect(); - decoded = crate::import::lex::hex_decode(&digits).unwrap_or_default(); - decoded.as_slice() + // Within the limits, these fit in memory (see `Limits::bytes`). + let (need, alpha_len) = (need as usize, alpha_len as usize); + let hex; + let data = if *binary == 0.0 && !decoded { + let (max, mut half) = (need + alpha_len, None); + let mut out = Vec::with_capacity(max.min(data.len() / 2)); + raster::push_hex(&mut out, &mut half, data, max); + raster::end_hex(&mut out, half, max); + hex = out; + hex.as_slice() } else { data }; - let row = if *bits == 1.0 { (w as usize * channels).div_ceil(8) } else { w as usize * channels }; - let need = row.saturating_mul(h as usize); + let row = shape.row().unwrap_or(0) as usize; // An alpha channel follows the colour samples, one byte a pixel. - let alpha_len = if *alpha > 0.0 { (w * h) as usize } else { 0 }; let (Some(samples), opacity) = (data.get(..need), data.get(need..need.saturating_add(alpha_len))) else { - self.warn("an image whose data is cut short was left out"); + self.image_left_out("an image whose data is cut short was left out"); return Ok(()); }; let opacity = opacity.filter(|_| alpha_len > 0); + let gray1 = *bits == 1.0 && channels == 1 && opacity.is_none(); + if k > 1 || w * h > raster::SMALL || (gray1 && !image_mask) { + // An image mask keeps the color that colorizes it. + let colorize = (image_mask && channels == 1 && *bits == 1.0).then(|| self.mask_paint()); + return self.large_image(samples, opacity, shape, k, &m, colorize); + } // CMYK samples keep their ink amounts as a CMYK TIFF, as the PDF importer keeps a CMYK // image's, and an alpha channel that hides part of the image becomes its opacity mask. if channels == 4 && *bits == 8.0 && let Some(blob) = Inks::new(w as u32, h as u32, samples.to_vec()).and_then(|i| ImageBlob::cmyk_tiff(&i)) { - return self.add_raster(blob, opacity, &m, (w as u32, h as u32)); + return self.add_raster(blob, opacity, &m, (w as u32, h as u32), None); + } + if image_mask && channels == 1 && *bits == 1.0 { + return self.colorized_raster(samples, row, opacity, &m, (w as u32, h as u32)); } let mut rgba = Vec::with_capacity((w * h * 4) as usize); for y in 0..h as usize { @@ -384,38 +515,206 @@ impl<'a> Reader<'a> { } } let Some(img) = image::RgbaImage::from_raw(w as u32, h as u32, rgba) else { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; let mut png = vec![]; if img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); } - self.add_raster(ImageBlob::new("image/png", png), None, &m, (w as u32, h as u32)) + self.add_raster(ImageBlob::new("image/png", png), None, &m, (w as u32, h as u32), None) + } + + /// A 1-bit gray image whose ImageMask is 1 (`samples`, `row` bytes a row): a grayscale image + /// colorized with the fill color. Its 0 bits, which open black with ImageMask 0, take that color, + /// and its 1 bits are transparent. A fill that isn't a solid color colorizes it black. + fn colorized_raster(&mut self, samples: &[u8], row: usize, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32)) -> Result<(), String> { + let mut gray = Vec::with_capacity(w as usize * h as usize); + for y in 0..h as usize { + let line = samples.get(y * row..(y + 1) * row).unwrap_or_default(); + for x in 0..w as usize { + let v = line.get(x / 8).map_or(0, |b| ((b >> (7 - x % 8)) & 1) * 255); + gray.push(v); + } + } + let mut png = vec![]; + let written = image::GrayImage::from_raw(w, h, gray).map(|img| img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)); + if !matches!(written, Some(Ok(()))) { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + } + let paint = self.mask_paint(); + self.add_raster(ImageBlob::new("image/png", png), alpha, m, (w, h), Some(paint)) + } + + /// The color that colorizes an image mask: the fill color, or black when the fill isn't a + /// solid color. + fn mask_paint(&self) -> Paint { + match &self.gs.fill { + p @ Paint::Solid { .. } => p.clone(), + _ => Paint::solid(vectorcraft_color::Color::BLACK), + } + } + + /// `XF` (§8.2): an image whose pixels are in the file the `XG` before it names becomes a linked + /// image of that file, of its `w` × `h` pixels placed as the matrix maps them, as `XI` places an + /// image. The data keeps no pixels or preview of it, so a placeholder is spread over those pixels + /// until its file is found. A 1-bit image mask is colorized as `XI` colorizes one. One without + /// that file name, or whose operands `XI` couldn't read (no + /// matrix, too few numbers, no pixels, or samples of other than 1 or 8 bits), is left out with a + /// warning. No pixels are read, so its size isn't held to the limit on `XI`'s samples. + fn linked_image(&mut self, vals: Vec, hidden: bool) -> Result<(), String> { + let path = self.image_link.take(); + let operands = Self::image_operands(&vals); + let (Some(path), Some((m, n))) = (path, operands) else { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + let (&[a, b, c, d, tx, ty], &[_, _, _, _, w, h, bits, ..]) = (m.as_slice(), n.as_slice()) else { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + if !(1.0..=MAX_SIDE).contains(&w) || !(1.0..=MAX_SIDE).contains(&h) || ![1.0, 8.0].contains(&bits) { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + } + let (w, h) = (w as u32, h as u32); + let Some(to_doc) = self.image_space() else { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + let xf = to_doc * Affine::new([a, b, c, d, tx, ty]) * FLIP; + if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + } + let Some(png) = missing_placeholder() else { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + // The placeholder is all the document has of the file: what a missing link shows. + let bytes = Arc::new(png); + let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }; + let key = linked_key(&blob, &path); + self.doc.images.entry(key.clone()).or_insert(blob); + self.warn(LINKED_PLACEHOLDERS); + // A PostScript page doesn't draw the placeholder: there its pixels are left out of the + // comparisons with the page. + if !hidden && !self.gs.hidden && self.shown() { + self.placeholders.push(xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(w), f64::from(h)))); + } + let im = ImageObject { key, width: w, height: h, xf, link: Some(LinkInfo::new(path)), placement: Default::default(), pixels: None }; + // A 1-bit image mask (ImageMask 1) keeps the color that colorizes it once its file is relinked. + let image_mask = bits == 1.0 && n.get(7) == Some(&1.0) && n.get(11) == Some(&1.0); + let colorize = image_mask.then(|| self.mask_paint()); + self.add_image_colorized(im, None, colorize, hidden) + } + + /// An image of `s` past [`raster::SMALL`] pixels, or reduced by the step `k`, or 1-bit gray: + /// 1-bit gray at full size is a 1-bit PNG of its rows as they are; other images keep their + /// channels a byte each (gray or RGB in a PNG with the alpha channel, CMYK in a TIFF with the + /// alpha channel as its opacity mask), averaged over blocks of `k` × `k` pixels. The matrix + /// `m` places the image where its full size would be. + fn large_image(&mut self, samples: &[u8], opacity: Option<&[u8]>, s: Shape, k: u64, m: &[f64], colorize: Option) -> Result<(), String> { + let (ow, oh) = (s.w.div_ceil(k) as u32, s.h.div_ceil(k) as u32); + if k == 1 && s.bits == 1 && s.channels == 1 && opacity.is_none() { + let Some(png) = raster::gray1_png(samples, ow, oh, s.row().unwrap_or(0) as usize) else { + return self.too_large_image(m, s.w, s.h); + }; + return self.add_raster(ImageBlob::new("image/png", png), None, m, (ow, oh), colorize); + } + let cmyk = s.channels == 4; + let (pixels, mask) = raster::reduce(samples, opacity, s, k, !cmyk); + let blob = if cmyk { + Inks::new(ow, oh, pixels).and_then(|i| ImageBlob::cmyk_tiff(&i)) + } else { + use image::ImageEncoder as _; + let colour = match (s.channels, opacity.is_some()) { + (1, false) => image::ExtendedColorType::L8, + (1, true) => image::ExtendedColorType::La8, + (_, false) => image::ExtendedColorType::Rgb8, + (_, true) => image::ExtendedColorType::Rgba8, + }; + let mut png = vec![]; + image::codecs::png::PngEncoder::new(&mut png).write_image(&pixels, ow, oh, colour).ok().map(|()| ImageBlob::new("image/png", png)) + }; + // One that can't be encoded is left to the page's art, as one past the hard limits. + let Some(blob) = blob else { + return self.too_large_image(m, s.w, s.h); + }; + // Each pixel as read stands for a block of the full size's. + let (sx, sy) = (s.w as f64 / f64::from(ow), s.h as f64 / f64::from(oh)); + let m: Vec = match m { + [a, b, c, d, tx, ty] => vec![a * sx, b * sx, c * sy, d * sy, *tx, *ty], + other => other.to_vec(), + }; + if k > 1 { + self.warn(&format!("an embedded image of {} × {} pixels was reduced to {ow} × {oh} pixels to keep the layers", s.w, s.h)); + } + self.add_raster(blob, mask.as_deref(), &m, (ow, oh), colorize) + } + + /// An image of `w` × `h` pixels past the hard limits, which matrix `m` maps into art space: a + /// box for the page's art to replace ([`Reader::unread_box`]), or, without page art, left out + /// with a note. + fn too_large_image(&mut self, m: &[f64], w: u64, h: u64) -> Result<(), String> { + if !self.page_art { + self.image_left_out(IMAGE_TOO_LARGE); + return Ok(()); + } + let [a, b, c, d, tx, ty] = m else { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + let xf = self.space() * Affine::new([*a, *b, *c, *d, *tx, *ty]) * FLIP; + let bounds = xf.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); + self.unread_box(LARGE_IMAGES, bounds, false).map(|_| ()) } /// Add the image `blob` (`w` × `h` pixels), which the matrix `m` maps into art space, with /// `alpha` (its alpha channel, one byte a pixel) as its opacity mask when it hides part of the - /// image. - fn add_raster(&mut self, blob: ImageBlob, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32)) -> Result<(), String> { + /// image, and `colorize` as the color that colorizes it. + fn add_raster(&mut self, blob: ImageBlob, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32), colorize: Option) -> Result<(), String> { // The matrix is an art-space matrix (y up) applied to the pixels with their rows running // downwards, (u, -v): pixels → (u, -v) → art space. Flipping the matrix's result instead // gives the same place only when the image isn't rotated (b = c = 0). let [a, b, c, d, tx, ty] = m else { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + let Some(to_doc) = self.image_space() else { + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; - let to_doc = self.space(); let xf = to_doc * Affine::new([*a, *b, *c, *d, *tx, *ty]) * FLIP; if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); } let mask = alpha.and_then(|a| self.alpha_mask(a, w, h, xf)); let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); - self.add_image_masked(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }, mask, false) + let im = ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }; + self.add_image_colorized(im, mask, colorize, false) + } + + /// An image that isn't read is left out, with `warning`; in a symbol's art, the symbol isn't + /// read whole, so its instances come in as the page draws them. + fn image_left_out(&mut self, warning: &str) { + if self.symbol.is_some() { + self.left_out_of_symbol(); + } else { + self.warn(warning); + } + } + + /// Note art of a symbol's definition that is left out: the symbol isn't kept, and its + /// instances come in as the page draws them, within the box of the art that is read. + pub(super) fn left_out_of_symbol(&mut self) { + if let Some(head) = self.symbol.as_mut() { + head.left_out = true; + } } /// An image's alpha channel (`w` × `h` bytes) as a grayscale image over the image (`xf`): its @@ -443,43 +742,147 @@ impl<'a> Reader<'a> { /// Add an image object with the state's transparency and `mask` as its opacity mask. fn add_image_masked(&mut self, im: ImageObject, mask: Option, hidden: bool) -> Result<(), String> { + self.add_image_colorized(im, mask, None, hidden) + } + + /// Add an image object with the state's transparency, `mask` as its opacity mask and + /// `colorize` as the color that colorizes it. + fn add_image_colorized(&mut self, im: ImageObject, mask: Option, colorize: Option, hidden: bool) -> Result<(), String> { let gs = self.gs.clone(); let mut node = self.new_node(NodeKind::Image(Box::new(im)), &gs); node.opacity = gs.opacity; node.blend = gs.blend; + node.knockout_shape = gs.knockout_shape; node.extras_mut().mask = mask.map(Box::new); - self.add(node, hidden) + node.extras_mut().colorize = colorize.map(Box::new); + self.add(node, hidden)?; + self.image_tail = self.after_object; + Ok(()) } /// `~`: the placed file read since `%AI5_BeginPlace` becomes a linked image in its place that /// shows the preview the data keeps of it, as a linked image whose file is missing does. One /// without a preview, a path or a matrix isn't read. pub(super) fn end_place(&mut self, hidden: bool) -> Result<(), String> { - let Some(Place { matrix: Some(m), bounds: Some(b), path, preview: Some((png, w, h)) }) = self.place.take().filter(|p| !p.path.is_empty()) - else { - self.unreadable("placed files"); + // Where a symbol's art puts a placed file's pixels isn't known. + if self.symbol.is_some() { + self.place = None; + self.left_out_of_symbol(); return Ok(()); + } + let (m, b, path, png, w, h, folder) = match self.place.take() { + Some(Place { broken: true, .. }) => { + self.unreadable("placed files", hidden); + return Ok(()); + } + Some(Place { matrix: Some(m), bounds: Some(b), path, preview: Some((png, w, h)), folder, .. }) if !path.is_empty() => { + (m, b, path, png, w, h, folder) + } + other => { + let boxed = other.as_ref().and_then(|p| Some((p.matrix?, p.bounds?))).filter(|(_, b)| sane(*b) && b.area() > 0.0); + let mut have_bounds = false; + if self.shown() + && !self.gs.hidden + && !hidden + && let Some((m, b)) = boxed + { + let centre = self.template.map(|t| ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0)); + let origin = centre.map_or(b.origin(), |(x, y)| Point::new(CANVAS_CENTRE - x, CANVAS_CENTRE + y)); + let box_at_canvas = Rect::new(origin.x, origin.y, origin.x + b.width(), origin.y + b.height()); + let bounds = (self.space() * m).transform_rect_bbox(box_at_canvas); + have_bounds = sane(bounds) && bounds.area() > 0.0; + if have_bounds { + let placeholder_id = self.unread_box("placed files", bounds, hidden)?; + if let Some(placeholder_id) = placeholder_id.filter(|_| self.unread_elsewhere.len() < MAX_PLACED_ELSEWHERE) { + let corner = (self.space() * m).transform_rect_bbox(b); + if sane(corner) && corner.area() > 0.0 && corner != bounds { + self.unread_elsewhere.push((placeholder_id, corner)); + } + } + return Ok(()); + } + } + if self.shown() && !self.gs.hidden && !hidden && !have_bounds { + self.unsupported.insert("placed files".into()); + } else { + self.unreadable("placed files", hidden); + } + return Ok(()); + } }; // The file's pixels (y down) start at the canvas point of art space's origin (the box's own // corner when the file doesn't say where the canvas is); the preview's are spread over them. let centre = self.template.map(|t| ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0)); let origin = centre.map_or(b.origin(), |(x, y)| Point::new(CANVAS_CENTRE - x, CANVAS_CENTRE + y)); - let over_file = Affine::translate(origin.to_vec2()) * Affine::scale_non_uniform(b.width() / f64::from(w), b.height() / f64::from(h)); + let (sx, sy) = (b.width() / f64::from(w), b.height() / f64::from(h)); + let over_file = Affine::translate(origin.to_vec2()) * Affine::scale_non_uniform(sx, sy); + // Many files put the pixels at the box's own corner instead: that placement is kept for + // when the layers don't draw as the page does with this one (a move in the preview's + // pixels, which later moves of the image keep). + let to_corner = b.origin() - origin; + let elsewhere = (to_corner.hypot() > 0.01 && sx.abs() > 1e-12 && sy.abs() > 1e-12) + .then(|| Affine::translate((to_corner.x / sx, to_corner.y / sy))) + .filter(|a| a.as_coeffs().iter().all(|v| v.is_finite())); let xf = self.space() * m * over_file; if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { - self.unreadable("placed files"); + self.unreadable("placed files", hidden); return Ok(()); } // The preview is all the document has of the file: what a missing link shows. let bytes = Arc::new(png); let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }; - let key = blob.content_key(); + let key = linked_key(&blob, &path); + let fresh = !self.doc.images.contains_key(&key); self.doc.images.entry(key.clone()).or_insert(blob); self.warn(LINKED_PREVIEWS); - self.add_image( - ImageObject { key, width: w, height: h, xf, link: Some(LinkInfo::new(path)), placement: Default::default(), pixels: None }, - hidden, - ) + let id = NodeId(self.doc.peek_next_id()); + if let Some(shift) = elsewhere + && self.placed_elsewhere.len() < MAX_PLACED_ELSEWHERE + { + self.placed_elsewhere.push((id, shift)); + } + // One waits at each depth: a placed file in another's opacity mask doesn't take the place of the outer one. + // An outer one waiting shares its blob with this one now: it no longer has it alone. + let depth = self.frames.len(); + self.placed_tails.retain(|t| t.depth < depth); + for t in self.placed_tails.iter_mut().filter(|t| t.key == key) { + t.fresh = false; + } + self.placed_tails.push(PlacedTail { id, key: key.clone(), size: (b.width(), b.height()), fresh, depth }); + let mut link = LinkInfo::new(path); + link.relative = folder.and_then(|f| relative_path(&f, link.name())); + self.add_image(ImageObject { key, width: w, height: h, xf, link: Some(link), placement: Default::default(), pixels: None }, hidden) + } + + /// The dictionary `o` after the placed file just read: with a page or a box in it, that file is + /// a page of a PDF or `.ai` file. Its image keeps the preview under a key of its own for that + /// page and box, so that it doesn't share one with an image of another page of the file. + pub(super) fn placed_page(&mut self, o: &Obj) { + // The dictionaries of art read inside the placed file's own (its opacity mask's) are not its. + let depth = self.frames.len(); + self.placed_tails.retain(|t| t.depth <= depth); + if self.placed_tails.last().is_none_or(|t| t.depth != depth) { + return; + } + let Some(tail) = self.placed_tails.pop() else { return }; + let (page, crop) = (o.get(PLACED_PAGE).map(|_| o.nums(PLACED_PAGE)), o.get(PLACED_CROP).map(|_| o.nums(PLACED_CROP))); + // A placed document's box runs from (0, 0) to a positive size: a box written backward stays a linked image. + if (page.is_none() && crop.is_none()) || !(tail.size.0 > 0.0 && tail.size.1 > 0.0) { + return; + } + // An entry that is there but not a number leaves a linked image, as an unknown number does. + let page = page.map_or(Some(1), |v| v.first().copied().and_then(placed_page_number)); + let crop = crop.map_or(Some((false, PageBox::Crop)), |v| v.first().copied().and_then(placed_crop)); + let (Some(page), Some((bounding, page_box))) = (page, crop) else { return }; + let Some(NodeKind::Image(im)) = self.last_object().filter(|n| n.id == tail.id).map(|n| &mut n.kind) else { return }; + let old = im.key.clone(); + let key = key_for(&old, page, bounding, page_box); + im.key.clone_from(&key); + let blob = if tail.fresh { self.doc.images.remove(&old) } else { self.doc.images.get(&old).cloned() }; + if let Some(blob) = blob { + self.doc.images.entry(key).or_insert(blob); + } + self.placed_pages.push(PlacedPage { id: tail.id, page, bounding, page_box, size: tail.size }); } pub(super) fn warn(&mut self, w: &str) { @@ -489,22 +892,73 @@ impl<'a> Reader<'a> { } } +/// `bp` as a path whose anchors take the kinds in `kinds`, one for each segment of `bp` in order, +/// for the anchor the segment ends on. A closed subpath's last segment ends on its first anchor +/// when it returns to the start point, and that anchor takes its kind. Anchors no segment ends on +/// (a subpath's start) keep the kind [`PathData::from_bezpath`] gives them, and so does a subpath +/// whose anchors don't match its segments. +pub(super) fn path_data(bp: &BezPath, kinds: &[AnchorKind]) -> PathData { + let mut path = PathData::from_bezpath(bp); + // Each subpath's anchors as `from_bezpath` starts them: one for its start, one for each segment. + let mut subpaths: Vec>> = Vec::new(); + let mut kinds = kinds.iter().copied(); + let mut open = false; + for el in bp.elements() { + match el { + PathEl::MoveTo(_) => { + subpaths.push(vec![None]); + open = true; + } + PathEl::ClosePath => open = false, + _ => { + let kind = kinds.next(); + match subpaths.last_mut() { + Some(s) if open => s.push(kind), + _ => { + subpaths.push(vec![None, kind]); + open = true; + } + } + } + } + } + if subpaths.len() != path.subpaths.len() { + return path; + } + for (sp, mut set) in path.subpaths.iter_mut().zip(subpaths) { + // The closing anchor merged into the first: its kind goes to the first. + if sp.closed + && set.len() == sp.anchors.len() + 1 + && let Some(last) = set.pop() + && let Some(first) = set.first_mut() + { + *first = last; + } + if set.len() != sp.anchors.len() { + continue; + } + for (a, kind) in sp.anchors.iter_mut().zip(set) { + if let Some(kind) = kind { + a.kind = kind; + } + } + } + path +} + /// The name of the XML node `o` (its `xmlnode-nodename`) without a namespace prefix (`v:`). pub(super) fn element_name(o: &Obj) -> Option { let name = o.text("xmlnode-nodename")?; Some(name.rsplit(':').next().unwrap_or(&name).to_string()) } -/// The child nodes named `name` (see [`element_name`]) of the XML node `o`. -pub(super) fn elements<'o>(o: &'o Obj, name: &'o str) -> impl Iterator { - o.obj("xmlnode-children").into_iter().flat_map(Obj::items).filter(move |c| c.ty == "XMLNode" && element_name(c).as_deref() == Some(name)) -} - /// A placed file's preview as a PNG, with its size: `w h rowBytes 32 n ` (each number followed by /// a space), then `h` rows of `rowBytes` bytes, premultiplied ARGB. `None` when it isn't that, is /// larger than [`MAX_PIXELS`] or is cut short. pub(super) fn preview_png(data: &[u8]) -> Option<(Vec, u32, u32)> { - let mut rest = data.trim_ascii_start(); + // A placed file's copy on `%_` lines has its header on one too: `%_512 256 2048 32 17 `. + let data = data.trim_ascii_start(); + let mut rest = data.strip_prefix(b"%_").unwrap_or(data); let mut head = [0usize; 5]; for v in &mut head { let n = rest.iter().position(|b| *b == b' ')?; @@ -532,6 +986,48 @@ pub(super) fn preview_png(data: &[u8]) -> Option<(Vec, u32, u32)> { Some((png, width, height)) } +/// The page a placed file's dictionary names: a whole number from 1. +fn placed_page_number(v: f64) -> Option { + (v.fract() == 0.0 && v >= 1.0 && v <= f64::from(u32::MAX)).then_some(v as u32) +} + +/// The box a placed file's dictionary names: whether the art's bounds are shown, and the box of +/// the page otherwise. +fn placed_crop(v: f64) -> Option<(bool, PageBox)> { + match v { + 0.0 => Some((false, PageBox::Art)), + 1.0 => Some((false, PageBox::Crop)), + 2.0 => Some((false, PageBox::Trim)), + 3.0 => Some((false, PageBox::Bleed)), + 4.0 => Some((false, PageBox::Media)), + 5.0 => Some((true, PageBox::Crop)), + _ => None, + } +} + +/// A placed file's path relative to the document's folder (`/` separators): its relative `folder` +/// (`src/`, `..\art`) followed by its file `name`; the name alone when the folder is empty (the +/// document's own folder). `None` when the folder is absolute or holds control characters, or +/// when there is no name. +pub(super) fn relative_path(folder: &str, name: &str) -> Option { + let folder = folder.replace('\\', "/"); + let absolute = folder.starts_with('/') || folder.as_bytes().get(1) == Some(&b':') || folder.contains("://"); + if absolute || name.is_empty() || folder.chars().chain(name.chars()).any(char::is_control) { + return None; + } + if folder.is_empty() { + return Some(name.to_string()); + } + Some(format!("{}/{name}", folder.trim_end_matches('/'))) +} + +/// The image key of a linked image of the file at `path` that shows `blob` (its preview or a +/// placeholder): the blob's own key and the path's. Images of other files that show the same pixels +/// have keys of their own, and reading one file's pixels in changes that file's images only. +fn linked_key(blob: &ImageBlob, path: &str) -> String { + format!("{}-{}", blob.content_key(), vectorcraft_doc::links::hash_bytes(path.as_bytes())) +} + pub(super) fn sane(r: Rect) -> bool { [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_SIDE) } @@ -559,8 +1055,22 @@ fn cmyk_rgb([c, m, y, k]: [u8; 4]) -> [u8; 3] { [rgb[0], rgb[1], rgb[2]] } +/// The colour channels of an image in the colour space `space` (`XN`), else of image type `kind`. +fn channels(space: &str, kind: f64) -> usize { + match space { + "DeviceGray" => 1, + "DeviceCMYK" => 4, + "DeviceRGB" => 3, + _ => match kind as i64 { + 1 => 1, + 4 => 4, + _ => 3, + }, + } +} + /// `a`, `a and b`, `a, b and c`. -pub(super) fn join_and(items: &[&str]) -> String { +pub(crate) fn join_and(items: &[&str]) -> String { match items { [] => String::new(), [one] => (*one).to_string(), diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 09ccd14aa6..a08f2ea1c9 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -1,7 +1,10 @@ use super::document::slot_of; use super::ops::{paints_apart, path_rule}; -use super::types::{Frame, GState, Kind, MAX_DEPTH, MAX_NODES}; -use super::{AppearanceItem, Arc, BezPath, BlendMode, FillRule, HashSet, LayerColor, Node, NodeId, NodeKind, Obj, Paint, PathEl, Rc, Reader, V, obj}; +use super::types::{Frame, GState, Kind, MAX_DEPTH, MAX_NODES, PendingEnvelope}; +use super::{ + AppearanceItem, Arc, BezPath, BlendMode, FillRule, HashMap, HashSet, LayerColor, Node, NodeId, NodeKind, Obj, Paint, PathEl, Rc, Reader, V, obj, +}; +use vectorcraft_doc::TextWrap; impl<'a> Reader<'a> { // ---- frames ---------------------------------------------------------------------------- @@ -12,6 +15,7 @@ impl<'a> Reader<'a> { } if matches!(kind, Kind::Layer(_)) { self.ensure_space(); + self.check_symbols(); } let base = if matches!(kind, Kind::Obj(_)) { self.stack.len() } else { self.frames.last().map_or(0, |f| f.base) }; self.frames.push(Frame { @@ -19,10 +23,15 @@ impl<'a> Reader<'a> { children: Vec::new(), hidden, after: self.after_object, + mesh_ended: self.mesh_ended, gs: self.gs.clone(), + pending_unread_fill: self.pending_unread_fill, + pending_unread_stroke: self.pending_unread_stroke, base, clips: Vec::new(), compound_members: false, + unread: Vec::new(), + state: None, }); self.after_object = false; Ok(()) @@ -69,15 +78,50 @@ impl<'a> Reader<'a> { } pub(super) fn end_container(&mut self, what: &str, hidden: bool) -> Result<(), String> { + self.multi_mask_container_ends()?; let f = match what { "U" => self.close(what, |k| matches!(k, Kind::Group))?, "*U" => self.close(what, |k| matches!(k, Kind::Compound))?, + "*W" => self.close(what, |k| matches!(k, Kind::Wrap))?, _ => self.close(what, |k| matches!(k, Kind::Clip))?, }; - let Frame { kind, children: kids, gs, clips, hidden: opened_hidden, compound_members, .. } = f; + let Frame { + kind, + children: mut kids, + gs, + clips, + hidden: opened_hidden, + compound_members, + unread, + pending_unread_fill, + pending_unread_stroke, + .. + } = f; + if matches!(kind, Kind::Clip) { + // `Q` restores the painting state, not the transparency: the writer sets `Xy` only when + // the next object's differs from the last one written, wherever that was, so a state set + // inside a clipping group stays after it (a glow set to Screen, then a clipping path set + // back to Normal: the type after the group has no `Xy` and is Normal). + let now = &self.gs; + let transparency = (now.opacity, now.blend, now.isolate, now.knockout, now.knockout_shape); + self.gs = gs.clone(); + (self.gs.opacity, self.gs.blend, self.gs.isolate, self.gs.knockout, self.gs.knockout_shape) = transparency; + self.pending_unread_fill = pending_unread_fill; + self.pending_unread_stroke = pending_unread_stroke; + } + // Wraparound text: every object in it other than type is a wrap object, before the text or + // after it, with no offset (the format gives none) unless its dictionary gives its options. + // One before the text is below it, so the text flows around it only once it is moved above. + if matches!(kind, Kind::Wrap) { + let graphics = kids.iter_mut().filter(|k| !matches!(k.kind, NodeKind::Text(_)) && slot_of(k.name.as_deref()).is_none()); + for k in graphics.filter(|k| k.extras().wrap.is_none()) { + k.extras_mut().wrap = Some(TextWrap { offset: 0.0, invert: false }); + } + } // A group holding only clipping paths (`q … u W n U … Q`) doesn't clip on its own: `u`/`U` don't save // the graphics state as `q`/`Q` do, so its paths clip the clipping group around it, as the file's PDF part draws it. if matches!(kind, Kind::Group) + && unread.is_empty() && !clips.is_empty() && clips.len() == kids.len() && matches!(self.frames.last(), Some(Frame { kind: Kind::Clip, .. })) @@ -99,20 +143,36 @@ impl<'a> Reader<'a> { // Some files mark every group so, the plain one holding the subpaths too (#980): one // paint for all its paths keeps it one compound path, its holes cut. Kind::Compound if kids.iter().any(|k| self.looks.contains(&k.id) && paints_apart(k)) => { - let (children, clip) = self.clip_first(kids, &clips); + let (children, clip) = self.clip_first(kids, &clips, true, self.nesting() + 1)?; self.new_node(NodeKind::Group { children, clip }, &gs) } Kind::Compound => { - // A group in a compound path (`*u u … U *U`) only holds its paths. Clipping subpaths' - // painted copies make a compound of their own, under what it clips. - let (fills, kids): (Vec, Vec) = ungrouped(kids).into_iter().partition(|n| self.clip_fills.contains(&n.id)); - painted = self.compound(fills, &gs); - let Some(n) = self.compound(kids, &gs) else { return Ok(()) }; + // A group in a compound path (`*u u … U *U`) only holds its paths. + let mut kids = ungrouped(kids); + // A compound clipping path keeps its subpaths' fill when they all paint alike. When they paint + // differently, the fills of the filled clipping ones are a compound path of their own, under what it clips. + let look = |n: &Node| (n.appearance.clone(), n.opacity, n.blend); + if clipping && kids.windows(2).any(|w| look(&w[0]) != look(&w[1])) { + let fills: Vec = kids + .iter_mut() + .filter(|k| matches!(k.kind, NodeKind::Path { clipping: true, .. })) + .filter_map(|k| self.fill_apart(k)) + .collect(); + painted = self.compound(fills, &gs); + } + let Some(n) = self.compound(kids, &gs) else { + if gs.hidden || !self.shown() { + self.hidden_unread.extend(unread); + } else { + self.unsupported.extend(unread); + } + return Ok(()); + }; n } // A group with a clipping path (`q` … `Q`, or a `W` path in a group) is a clipping group. _ => { - let (children, clip) = self.clip_first(kids, &clips); + let (children, clip) = self.clip_first(kids, &clips, false, self.nesting() + 1)?; self.new_node(NodeKind::Group { children, clip }, &gs) } }; @@ -122,6 +182,13 @@ impl<'a> Reader<'a> { if compound_members { self.compound_groups.insert(node.id); } + if !unread.is_empty() { + if !node.visible || !self.shown() { + self.hidden_unread.extend(unread); + } else { + self.unread.push((node.id, unread)); + } + } self.add(node, opened_hidden || hidden)?; if let Some(p) = painted { self.clip_fills.insert(p.id); @@ -135,10 +202,12 @@ impl<'a> Reader<'a> { // The compound path's paint is its last path's (a gradient's instance wraps only // that one); the last painted one, should the last have none. let shown = kids.iter().rev().find(|k| !k.appearance.items.is_empty()).or(kids.last())?; - let (appearance, opacity, blend, rule) = (shown.appearance.clone(), shown.opacity, shown.blend, path_rule(shown)); + let (appearance, opacity, blend, shape, rule) = + (shown.appearance.clone(), shown.opacity, shown.blend, shown.knockout_shape, path_rule(shown)); for k in &mut kids { k.opacity = 1.0; k.blend = BlendMode::Normal; + k.knockout_shape = false; k.visible = true; k.locked = false; } @@ -146,45 +215,194 @@ impl<'a> Reader<'a> { n.appearance = appearance; n.opacity = opacity; n.blend = blend; + n.knockout_shape = shape; Some(n) } + /// How deep in the document the objects the open frames hold are, less one: a dictionary adds no level, and an + /// opacity mask's art is two under the frames around the object it masks. + fn nesting(&self) -> usize { + self.frames + .iter() + .map(|f| match f.kind { + Kind::Obj(_) => 0, + Kind::Mask => 2, + _ => 1, + }) + .sum() + } + + /// `kids` with the clipping paths among them (indexes `clips`) first → the children and whether they clip. + /// + /// Several clipping paths in a clipping group or a layer clip to their intersection, as each `W` reduces the clip + /// set by the ones before it: each clipping path after the first clips a clipping group nested in the one before + /// it, and the innermost one holds the art. As with one clipping path, every object in the group is clipped by all + /// of them, wherever it is written. The fill of a compound clipping path read apart from it (`clip_fills`) stays at + /// its path's level. In a compound path (`union`), several clipping paths are one compound path. `at`: how deep the + /// group or layer made of them is in the document. + fn clip_first(&mut self, kids: Vec, clips: &[usize], union: bool, at: usize) -> Result<(Vec>, bool), String> { + if union || clips.len() < 2 { + return Ok(self.clip_union(kids, clips)); + } + let clips: std::collections::HashSet = clips.iter().copied().collect(); + let (clip, rest): (Vec, Vec) = kids.into_iter().enumerate().partition(|(i, _)| clips.contains(i)); + let innermost = clip.len() - 1; + // A fill read apart follows its clipping path; the art goes in the innermost level. + let level = |i: usize, n: &Node| { + if self.clip_fills.contains(&n.id) { clip.iter().rposition(|(c, _)| *c < i).unwrap_or(0) } else { innermost } + }; + // Each nested clipping group adds a level over the nodes placed in it, the clipping paths included. Past the + // reader's limit, or past the document's when the nodes fit in it without those levels (the document would merge + // the deepest groups and drop their clipping paths), the editing data isn't read. + let deepest = + rest.iter().map(|(i, n)| level(*i, n) + depth(n)).chain(clip.iter().enumerate().map(|(k, (_, n))| k + depth(n))).max().unwrap_or(0); + let flat = rest.iter().map(|(_, n)| depth(n)).chain(clip.iter().map(|(_, n)| depth(n))).max().unwrap_or(0); + if at + deepest > MAX_DEPTH || (at + deepest > vectorcraft_doc::MAX_DEPTH && at + flat <= vectorcraft_doc::MAX_DEPTH) { + return Err("its clipping masks are nested too deeply".into()); + } + // Each level: its clipping path, the fills read apart from it, which paint under the art they clip, then the art. + let mut fills_at: Vec> = clip.iter().map(|_| Vec::new()).collect(); + let mut art_at: Vec> = clip.iter().map(|_| Vec::new()).collect(); + for (i, n) in rest { + let k = level(i, &n); + let at = if self.clip_fills.contains(&n.id) { &mut fills_at } else { &mut art_at }; + if let Some(v) = at.get_mut(k) { + v.push(n); + } + } + let mut children: Vec> = Vec::new(); + let mut levels = clip.into_iter().map(|(_, n)| n).zip(fills_at.into_iter().zip(art_at)).rev().peekable(); + while let Some((path, (fills, art))) = levels.next() { + let mut inner: Vec> = Vec::with_capacity(fills.len() + art.len() + children.len() + 1); + inner.push(Arc::new(path)); + inner.extend(fills.into_iter().chain(art).map(Arc::new)); + inner.append(&mut children); + if levels.peek().is_none() { + return Ok((inner, true)); + } + children = vec![Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children: inner, clip: true }))]; + } + Ok((children, false)) + } + /// `kids` with the clipping paths among them (indexes `clips`) first, several as one compound /// path → the children and whether they clip. - fn clip_first(&mut self, kids: Vec, clips: &[usize]) -> (Vec>, bool) { + fn clip_union(&mut self, kids: Vec, clips: &[usize]) -> (Vec>, bool) { let clips: std::collections::HashSet = clips.iter().copied().collect(); let (mut clip, rest): (Vec, Vec) = kids.into_iter().enumerate().partition(|(i, _)| clips.contains(i)); + let mut fills = Vec::new(); let clip_node = match clip.len() { 0 => None, 1 => clip.pop().map(|(_, n)| n), _ => { let rule = clip.first().map_or(FillRule::NonZero, |(_, n)| path_rule(n)); + // Each clipping path's fill is a path of its own, under the art it clips, as each one paints it. The + // compound path keeps the clipping paths' stroke, opacity and blend mode when they all have the same ones, + // and the knockout shape flag when they all have it: it has one appearance for all its paths. + for (_, n) in &mut clip { + fills.extend(self.fill_apart(n)); + } + let shape = clip.iter().all(|(_, n)| n.knockout_shape); + let look = |n: &Node| (n.appearance.clone(), n.opacity, n.blend); + let shared = + clip.split_first().and_then(|((_, first), others)| others.iter().all(|(_, n)| look(n) == look(first)).then(|| look(first))); let children = clip.into_iter().map(|(_, n)| Arc::new(n)).collect(); - Some(Node::new(self.doc.alloc_id(), NodeKind::Compound { children, rule })) + let mut n = Node::new(self.doc.alloc_id(), NodeKind::Compound { children, rule }); + if let Some((appearance, opacity, blend)) = shared { + n.appearance = appearance; + n.opacity = opacity; + n.blend = blend; + } + n.knockout_shape = shape; + Some(n) } }; let clips = clip_node.is_some(); - // A clipping path's own fill paints under the art it clips. - let (fills, rest): (Vec, Vec) = rest.into_iter().partition(|(_, n)| self.clip_fills.contains(&n.id)); - let children = clip_node.into_iter().chain(fills.into_iter().chain(rest).map(|(_, n)| n)).map(Arc::new).collect(); + // A fill read apart paints under the art it clips. + let (apart, rest): (Vec, Vec) = rest.into_iter().partition(|(_, n)| self.clip_fills.contains(&n.id)); + let children = clip_node.into_iter().chain(fills).chain(apart.into_iter().chain(rest).map(|(_, n)| n)).map(Arc::new).collect(); (children, clips) } + /// Clipping path `n`'s fills as a path of their own, taken off `n`; `None` when it has no fill. The path keeps `n`'s + /// transparency, visibility, lock and opacity mask, and none of its other attributes. + pub(super) fn fill_apart(&mut self, n: &mut Node) -> Option { + let is_fill = |i: &AppearanceItem| matches!(i, AppearanceItem::Fill(_)); + if !n.appearance.items.iter().any(is_fill) { + return None; + } + let mut kind = n.kind.clone(); + if let NodeKind::Path { clipping, .. } = &mut kind { + *clipping = false; + } + let mut fill = Node::new(self.doc.alloc_id(), kind); + // The copies of a path read on `%_` lines are on those lines too, as `add` records them. + let hidden = self.hidden_ids.contains(&n.id); + if hidden { + self.hidden_ids.insert(fill.id); + } + // A compound clipping path's subpaths: copies with ids of their own, linked to the same swatches, that don't clip. + for c in fill.children_mut().into_iter().flatten() { + let mut copy = self.doc.reid(c); + self.reid_masks(&mut copy, 0); + if let NodeKind::Path { clipping, .. } = &mut copy.kind { + *clipping = false; + } + if hidden { + self.hidden_ids.insert(copy.id); + } + *c = Arc::new(copy); + } + (fill.opacity, fill.blend, fill.isolate, fill.knockout, fill.knockout_shape, fill.visible, fill.locked) = + (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape, n.visible, n.locked); + // The opacity mask's art is a copy with ids of its own, linked to the same swatches. + if let Some(mut mask) = n.extras().mask.clone() { + let mut art = self.doc.reid(&mask.art); + self.reid_masks(&mut art, 0); + mask.art = Arc::new(art); + fill.extras_mut().mask = Some(mask); + } + let (mut fills, mut rest) = ((*n.appearance).clone(), (*n.appearance).clone()); + fills.items.retain(is_fill); + rest.items.retain(|i| !is_fill(i)); + fill.appearance = fills.into(); + n.appearance = rest.into(); + // The new path, its subpaths and their points count toward the objects read, as a multi-layer mask's copies do. + let mut weight = fill.count_with_masks(); + fill.walk(&mut |p| { + if let NodeKind::Path { path, .. } = &p.kind { + weight = weight.saturating_add(path.anchor_count()); + } + }); + self.nodes = self.nodes.saturating_add(weight); + Some(fill) + } + pub(super) fn end_layer(&mut self) -> Result<(), String> { - let f = self.close("LB", |k| matches!(k, Kind::Layer(_)))?; + self.pending_unread_fill = false; + self.pending_unread_stroke = false; + let mut f = self.close("LB", |k| matches!(k, Kind::Layer(_)))?; + let state = self.layer_state.take(); + self.container_undo = None; + // An `Xy` right after the layer's last mesh or blend, then `LB`: the layer's, not theirs. + if let (Some(_), Some(before)) = (state, self.mesh_undo.take()) + && let Some(mesh) = f.children.last_mut().filter(|n| matches!(n.kind, NodeKind::Mesh(_) | NodeKind::Blend { .. })) + { + (mesh.opacity, mesh.blend, mesh.isolate, mesh.knockout, mesh.knockout_shape) = before; + } let Kind::Layer(a) = f.kind else { return Ok(()) }; - let (children, clip) = self.clip_first(f.children, &f.clips); + let (children, clip) = self.clip_first(f.children, &f.clips, false, self.nesting() + 1)?; let color = a.color.unwrap_or(LayerColor::Preset(0)); let mut layer = Node::new( self.doc.alloc_id(), - NodeKind::Layer { color, template: false, printable: a.printable, children, clip, preview: a.preview, dim_images: a.dim }, + NodeKind::Layer { color, template: a.template, printable: a.printable, children, clip, preview: a.preview, dim_images: a.dim }, ); layer.name = Some(a.name.clone()); layer.visible = a.visible; layer.locked = a.locked; // The layer's own opacity, blend and knockout, written after its art (#2003). - if let Some((opacity, blend, isolate, knockout)) = self.layer_state.take() { - (layer.opacity, layer.blend, layer.isolate, layer.knockout) = (opacity, blend, isolate, knockout); + if let Some((opacity, blend, isolate, knockout, shape)) = state { + (layer.opacity, layer.blend, layer.isolate, layer.knockout, layer.knockout_shape) = (opacity, blend, isolate, knockout, shape); } match self.frames.last_mut() { Some(parent) => { @@ -199,15 +417,16 @@ impl<'a> Reader<'a> { Ok(()) } - /// An operator the reader doesn't know: on hidden art it is only noted, on shown art the file - /// is read from its PDF part. - pub(super) fn note_unknown(&mut self, w: &str) { + /// An operator the reader doesn't know is scoped to its top-level object when possible. + pub(super) fn note_unknown(&mut self, w: &str, hidden: bool) { let op: String = w.chars().take(24).collect(); - if !self.shown() { + // A pattern definition or an owning mask can be on `%_` lines while still + // determining visible art. Unknown operators there must remain unread. + if (self.gs.hidden && self.pattern.is_none()) || (hidden && self.pattern.is_none() && !self.in_mask()) || !self.shown() { if self.hidden_unread.len() < 16 { self.hidden_unread.insert(format!("`{op}`")); } - } else if self.unknown.len() < 16 { + } else if !self.defer_to_mask(&format!("`{op}`")) && !self.mark_unread(format!("`{op}`")) && self.unknown.len() < 16 { self.unknown.insert(op); } } @@ -225,6 +444,8 @@ impl<'a> Reader<'a> { self.open(Kind::Obj(Box::new(Obj { ty, ..Obj::default() })), hidden)?; // A dictionary's state starts afresh (styles set theirs inside). self.gs = GState::default(); + self.pending_unread_fill = false; + self.pending_unread_stroke = false; Ok(()) } @@ -232,16 +453,26 @@ impl<'a> Reader<'a> { pub(super) fn end_mask(&mut self) -> Result<(), String> { self.end_path_quietly(); let f = self.close("X+", |k| matches!(k, Kind::Mask))?; - let (children, clip) = self.clip_first(f.children, &f.clips); - let art = self.new_node(NodeKind::Group { children, clip }, &f.gs); + // The mask's art is one level under the object it masks. + let (children, clip) = self.clip_first(f.children, &f.clips, false, self.nesting() + 2)?; + // One shown object is the art itself. A hidden object or a guide stays in a group: the canvas draws the art's root + // whether it is shown or not and whether guides show, and a group doesn't draw a hidden member or a left-out guide. + let art = match children.as_slice() { + [only] if !clip && only.visible && !matches!(only.kind, NodeKind::Path { guide: true, .. }) => only.clone(), + _ => Arc::new(self.new_node(NodeKind::Group { children, clip }, &f.gs)), + }; self.gs = f.gs; + self.pending_unread_fill = f.pending_unread_fill; + self.pending_unread_stroke = f.pending_unread_stroke; self.after_object = f.after; + self.mesh_ended = f.mesh_ended; let Some(Frame { kind: Kind::Obj(o), .. }) = self.frames.last_mut() else { return Err("mask art ends outside a mask dictionary".into()); }; - if o.art.replace(Arc::new(art)).is_some() { + if o.art.replace(art).is_some() { return Err("a mask has more than one art block".into()); } + o.unread = f.unread; Ok(()) } @@ -251,13 +482,20 @@ impl<'a> Reader<'a> { return Ok(()); } let Some(f) = self.frames.pop() else { return Ok(()) }; - let Frame { kind, children, base, hidden, gs, after, .. } = f; + let Frame { kind, children, base, hidden, gs, pending_unread_fill, pending_unread_stroke, after, mesh_ended, state, .. } = f; let Kind::Obj(mut o) = kind else { return Ok(()) }; obj::close(&mut o, &mut self.stack, base); self.obj_hidden = hidden; - // Art made inside a dictionary (type's paths) isn't kept. + // Art made inside a dictionary (type's paths, a mask's art) isn't kept, and doesn't end what + // follows the object the dictionary is about: a mesh's state comes after its mask. self.gs = gs; + self.pending_unread_fill = pending_unread_fill; + self.pending_unread_stroke = pending_unread_stroke; + if let Some(state) = state { + self.keep_state(state); + } self.after_object = after; + self.mesh_ended = mesh_ended; if matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(_), .. })) { return self.push(V::Obj(Rc::new(*o))); } @@ -265,22 +503,35 @@ impl<'a> Reader<'a> { "ArtDictionary" => { let envelope = o.get("AIDeformOptionsKey").is_some(); self.art_dictionary(&o); + let before = self.envelope_art.take(); if envelope { let mut slots = vec![]; for child in &children { envelope_text_slots(child, &mut slots); } + let typed = !slots.is_empty() || before.as_ref().is_some_and(has_text_slot); for mut slot in slots { // The editing data keeps the source text inside the envelope's options; // its visible result is the outlined art the PDF page carries. slot.visible = false; self.add(slot, false)?; } + // An envelope of type keeps its drawn art and its type, hidden, as above: the + // type is filled in after reading, which the envelope can't wait for. + if typed { + return Ok(()); + } + if self.envelopes.len() >= crate::import::ai::envelope::MAX_PENDING { + self.warn(crate::import::ai::envelope::DRAWN); + } else { + let siblings = self.frames.last().map_or(0, |f| f.children.len()); + self.envelopes.push(PendingEnvelope { obj: *o, before, inner: children, depth: self.frames.len(), siblings }); + } } } "Document" => self.document(&o), "AI11Text" => self.text_slot(&o)?, - "SymbolInstance" => self.unreadable("symbols"), + "SymbolInstance" => self.symbol_instance(&o)?, "ForeignObject" => self.foreign_art(&o)?, _ => {} } @@ -315,31 +566,232 @@ impl<'a> Reader<'a> { /// Note something the data has that isn't read: an error on a layer that shows, left out of a /// layer that doesn't. - pub(super) fn unreadable(&mut self, what: &str) { - if self.shown() { - self.unsupported.insert(what.into()); + pub(super) fn unreadable(&mut self, what: &str, hidden: bool) { + if (!hidden || self.in_mask()) && !self.gs.hidden && self.shown() { + if !self.defer_to_mask(what) && !self.mark_unread(what.to_string()) { + self.unsupported.insert(what.into()); + } } else { self.hidden_unread.insert(what.into()); } } - /// Drop the object just read when it is an envelope's own mesh: a group on `%_` lines holding - /// only gradient meshes. Whether it was dropped. - pub(super) fn drop_envelope_mesh(&mut self) -> bool { - fn only_meshes(n: &Node) -> bool { - match &n.kind { - NodeKind::Mesh(_) => true, - NodeKind::Group { children, .. } => !children.is_empty() && children.iter().all(|c| only_meshes(c)), - _ => false, + /// Keep what an opacity mask's art doesn't read with the mask, until its dictionary says + /// whether the mask is enabled. Whether art of a mask is being read. Operators it doesn't know + /// are kept up to 16, as [`Reader::note_unknown`] keeps them. + fn defer_to_mask(&mut self, what: &str) -> bool { + let Some(f) = self.frames.iter_mut().rev().find(|f| matches!(f.kind, Kind::Mask)) else { return false }; + let full = what.starts_with('`') && f.unread.iter().filter(|w| w.starts_with('`')).count() >= 16; + if !full && !f.unread.iter().any(|w| w == what) { + f.unread.push(what.into()); + } + true + } + + /// Mark the first object container below the innermost layer. + pub(super) fn mark_unread(&mut self, what: String) -> bool { + let Some(layer) = self.frames.iter().rposition(|f| matches!(f.kind, Kind::Layer(_))) else { return false }; + let Some(frame) = self.frames.get_mut(layer + 1).filter(|f| matches!(f.kind, Kind::Group | Kind::Wrap | Kind::Compound | Kind::Clip)) else { + return false; + }; + if !frame.unread.contains(&what) { + frame.unread.push(what); + } + true + } + + /// Stand in for one unread object with a box that the page can match. + pub(super) fn unread_box(&mut self, what: &str, bounds: super::Rect, hidden: bool) -> Result, String> { + if (hidden && !self.in_mask()) || self.gs.hidden || !self.shown() { + self.hidden_unread.insert(what.into()); + return Ok(None); + } + // A mask's art isn't an object of the layers: its object, or the file, is what isn't read. + if self.in_mask() { + self.unreadable(what, false); + return Ok(None); + } + let in_container = self.frames.iter().rposition(|f| matches!(f.kind, Kind::Layer(_))).is_some_and(|layer| { + self.frames.get(layer + 1).is_some_and(|f| matches!(f.kind, Kind::Group | Kind::Wrap | Kind::Compound | Kind::Clip)) + }); + if !super::art::sane(bounds) || bounds.area() <= 0.0 { + self.unsupported.insert(what.into()); + return Ok(None); + } + let path = vectorcraft_geom::shapes::rectangle(bounds); + let gs = self.gs.clone(); + let node = self.new_node(NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }, &gs); + let id = node.id; + if in_container { + self.mark_unread(what.into()); + } + self.add(node, hidden)?; + if !in_container { + self.unread.push((id, vec![what.into()])); + } + Ok(Some(id)) + } + + /// A symbol instance (`/SymbolInstance`): the symbol its `SymbolRef` names, placed by its + /// `RTransformMatrix`, hidden and locked as the state says. In a symbol's art the matrix is + /// written about the canvas point of art space's origin, and the name is the file's until the + /// symbols are checked ([`Self::check_symbols`]). An instance of a symbol that wasn't read, one + /// whose appearance differs from its symbol's, or one placed only by a `Matrix` or `Transform`, + /// comes in as the page draws it, within the symbol's box placed by the matrix when the box is + /// known. + fn symbol_instance(&mut self, o: &Obj) -> Result<(), String> { + let name = o.text("SymbolRef"); + let affine = |n: &[f64]| match n { + [a, b, c, d, e, f] if [a, b, c, d, e, f].iter().all(|v| v.is_finite()) => Some(super::Affine::new([*a, *b, *c, *d, *e, *f])), + _ => None, + }; + let live = affine(&o.nums("RTransformMatrix")); + let boxed_only = live.is_none(); + let matrix = live.or_else(|| { + o.get("Matrix") + .or_else(|| o.get("Transform")) + .map(|v| v.iter().find_map(|item| if let V::Arr(a) = item { Some(Self::nums(a)) } else { None }).unwrap_or_else(|| Self::nums(v))) + .and_then(|n| affine(&n)) + }); + let hidden = self.obj_hidden; + let place = if self.symbol.is_some() { + self.canvas_origin().map(|o| super::Affine::new([1.0, 0.0, 0.0, -1.0, o.x, o.y])) + } else { + Some(self.space()) + }; + let (Some(name), Some(m), Some(place)) = (name, matrix, place) else { + self.unreadable("symbols", hidden); + return Ok(()); + }; + let xf = place * m; + let usable = xf.determinant().abs() >= 1e-12 && xf.as_coeffs().iter().all(|v| v.is_finite()); + let symbol = if self.symbol.is_some() { Some(name.clone()) } else { self.symbol_names.get(&name).cloned() }; + match symbol.filter(|_| usable && !boxed_only && !overrides(o)) { + Some(symbol) => { + // Its transparency is the `Xy` after it, as a group's is. + let gs = self.gs.clone(); + let node = self.new_node(NodeKind::SymbolInstance { symbol, xf }, &gs); + self.add(node, hidden) + } + None => { + let bounds = self.symbol_art_bounds(&name).or_else(|| self.symbol_bounds.get(&name).copied()); + match bounds.map(|b| xf.transform_rect_bbox(b)).filter(|_| usable && self.symbol.is_none()) { + Some(b) => self.unread_box("symbols", b, hidden).map(|_| ()), + None => { + self.unreadable("symbols", hidden); + Ok(()) + } + } } } + } + + /// The art box (symbol space) of the symbol read under `name` (its name in the file), measured + /// once. + fn symbol_art_bounds(&mut self, name: &str) -> Option { + if let Some(b) = self.symbol_art_bounds.get(name) { + return *b; + } + let named = self.symbol_names.get(name)?; + let boxes = self.doc.symbol_boxes(); + let b = self.doc.symbols.iter().find(|s| &s.name == named).and_then(|s| s.art.visual_bounds_with(&boxes)); + drop(boxes); + self.symbol_art_bounds.insert(name.to_string(), b); + b + } + + /// Check the symbols read for instances in their art of symbols the file doesn't have, before + /// the first layer: a symbol with one isn't kept, and so on for the symbols holding its + /// instances. The instances in the art kept then name the symbols as the document does. + pub(super) fn check_symbols(&mut self) { + if std::mem::replace(&mut self.symbols_checked, true) { + return; + } + // Each symbol's name in the file (none for one named as an earlier one), and the names its + // instances use. + let files: HashMap<&str, &str> = self.symbol_names.iter().map(|(file, named)| (named.as_str(), file.as_str())).collect(); + let defs: Vec<(Option, Vec)> = self + .doc + .symbols + .iter() + .map(|s| { + let mut uses = vec![]; + symbol_uses(&s.art, &mut uses, 0); + (files.get(s.name.as_str()).map(|f| f.to_string()), uses.into_iter().map(str::to_string).collect()) + }) + .collect(); + // A symbol goes when one of its instances names a symbol that isn't kept: first those + // naming one the file doesn't have, then, one at a time, those using a symbol that went. + let mut kept: Vec = vec![true; defs.len()]; + let mut users: HashMap<&str, Vec> = HashMap::new(); + let mut going: Vec = vec![]; + for (i, (_, uses)) in defs.iter().enumerate() { + for u in uses { + users.entry(u.as_str()).or_default().push(i); + } + if uses.iter().any(|u| !self.symbol_names.contains_key(u)) { + going.push(i); + } + } + while let Some(i) = going.pop() { + match kept.get_mut(i) { + Some(k) if *k => *k = false, + _ => continue, + } + if let Some(file) = defs.get(i).and_then(|(file, _)| file.as_deref()) { + going.extend(users.get(file).into_iter().flatten().copied().filter(|j| kept.get(*j).copied().unwrap_or(false))); + } + } + drop(users); + if kept.iter().any(|k| !k) { + let left: Vec<(Option, String)> = defs + .iter() + .zip(&self.doc.symbols) + .zip(&kept) + .filter(|(_, k)| !**k) + .map(|(((file, _), s), _)| (file.clone(), s.name.clone())) + .collect(); + let mut i = 0; + self.doc.symbols.retain(|_| { + i += 1; + kept.get(i - 1).copied().unwrap_or(false) + }); + // Their art's box isn't known (the instances that made them go have none), so their + // instances have no box either. + for (file, named) in left { + self.doc.set_symbol_registration(&named, vectorcraft_doc::SymbolRegistration::CENTER); + let Some(file) = file else { continue }; + self.symbol_names.remove(&file); + } + } + let names = self.symbol_names.clone(); + for s in &mut self.doc.symbols { + rename_uses(Arc::make_mut(&mut s.art), &names, 0); + } + } + + /// Drop the object just read when it is an envelope's own: a group on `%_` lines, before the + /// envelope's dictionary. It holds the mesh that shapes the envelope, or, while the envelope's + /// contents are being edited, those contents (the mesh then is in the dictionary); either way the + /// distorted art follows on plain lines. The source text in the contents stays, hidden, as the + /// dictionary's does. The group is kept in [`Reader::envelope_art`] for the envelope to be made + /// of. Whether it was dropped. + pub(super) fn drop_envelope_art(&mut self) -> bool { let Some(n) = self.last_object() else { return false }; let id = n.id; - if !matches!(n.kind, NodeKind::Group { .. }) || !only_meshes(n) || !self.hidden_ids.contains(&id) { + if !matches!(n.kind, NodeKind::Group { .. }) || !self.hidden_ids.contains(&id) { return false; } - if let Some(f) = self.frames.last_mut() { - f.children.pop(); + let mut slots = vec![]; + if let Some(f) = self.frames.last_mut() + && let Some(group) = f.children.pop() + { + envelope_text_slots(&group, &mut slots); + for mut slot in slots { + slot.visible = false; + f.children.push(slot); + } + self.envelope_art = Some(group); } self.hidden_ids.remove(&id); self.after_object = false; @@ -347,16 +799,21 @@ impl<'a> Reader<'a> { } /// Do the layers being read show? - fn shown(&self) -> bool { + pub(super) fn shown(&self) -> bool { self.frames.iter().all(|f| !matches!(&f.kind, Kind::Layer(a) if !a.visible)) } + /// Is the art being read an opacity mask's? It is on `%_` lines and still shapes what shows. + pub(super) fn in_mask(&self) -> bool { + self.frames.iter().any(|f| matches!(f.kind, Kind::Mask)) + } + /// A blend's record read: the blend's own art (the group of its key objects and spine, on `%_` /// lines) and its drawn steps (the group after it) become one live blend, or, where they can't, /// the drawn steps stay, without the blend's own art drawn over them (see [`super::blend`]). pub(super) fn end_blend(&mut self) { let Some((_, hex)) = self.blend_record.take() else { return }; - let ids = crate::import::ai::blend::hex_bytes(&hex).as_deref().and_then(crate::import::ai::blend::record_ids); + let record = crate::import::ai::blend::hex_bytes(&hex).as_deref().and_then(crate::import::ai::blend::record); let roles = &self.blend_roles; let Some(f) = self.frames.last_mut() else { return }; let n = f.children.len(); @@ -374,7 +831,7 @@ impl<'a> Reader<'a> { return; } let mut budget = self.blend_budget; - let live = ids.and_then(|ids| crate::import::ai::blend::live_blend(edit, steps, &ids, roles, &mut budget)); + let live = record.and_then(|record| crate::import::ai::blend::live_blend(edit, steps, &record, roles, &mut budget)); self.blend_budget = budget; let Some(mut steps) = f.children.pop() else { return }; let Some(_edit) = f.children.pop() else { return }; @@ -384,7 +841,10 @@ impl<'a> Reader<'a> { // did (they were counted as read). let mut blend = Node::new(self.doc.alloc_id(), kind); (blend.name, blend.visible, blend.locked) = (steps.name.take(), steps.visible, steps.locked); - (blend.opacity, blend.blend, blend.isolate, blend.knockout) = (steps.opacity, steps.blend, steps.isolate, steps.knockout); + (blend.opacity, blend.blend, blend.isolate, blend.knockout, blend.knockout_shape) = + (steps.opacity, steps.blend, steps.isolate, steps.knockout, steps.knockout_shape); + // Its note, URL and data (object tags) too. + blend.extras_mut().attrs = steps.extras_mut().attrs.take(); f.children.push(blend); } None => { @@ -392,11 +852,98 @@ impl<'a> Reader<'a> { self.warn(crate::import::ai::blend::DRAWN); } } + // The blend's own state block follows its record, as a group's follows its end. + self.after_object = true; + } + + /// An envelope's plugin `XP`: the envelope whose dictionary was read last in this container + /// and its drawn art, the one object read since, become one live envelope, or, where they + /// can't, the drawn art stays (see [`crate::import::ai::envelope`]). Envelopes left waiting + /// in containers that closed keep their drawn art. + pub(super) fn end_envelope(&mut self) { + let depth = self.frames.len(); + while self.envelopes.last().is_some_and(|p| p.depth > depth) { + self.envelopes.pop(); + self.warn(crate::import::ai::envelope::DRAWN); + } + if self.envelopes.last().is_none_or(|p| p.depth != depth) { + return; + } + let Some(p) = self.envelopes.pop() else { return }; + let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last()); + let Some(drawn) = drawn else { + self.warn(crate::import::ai::envelope::DRAWN); + return; + }; + let live = (self.envelope_checks > 0).then(|| crate::import::ai::envelope::live(&p.obj, p.before, p.inner)).flatten(); + let Some(kind) = live else { + self.warn(crate::import::ai::envelope::DRAWN); + return; + }; + // Objects the reader couldn't read come in as the page's art in their place: the envelope's + // drawn art stays round them. + let mut ids = HashSet::new(); + fn collect(n: &Node, ids: &mut HashSet) { + ids.insert(n.id); + for c in n.children().into_iter().flatten() { + collect(c, ids); + } + } + collect(drawn, &mut ids); + if let NodeKind::Envelope { content, .. } = &kind { + content.iter().for_each(|c| collect(c, &mut ids)); + } + if self.unread.iter().any(|(id, _)| ids.contains(id)) { + self.warn(crate::import::ai::envelope::DRAWN); + return; + } + self.envelope_checks -= 1; + // The drawn art's own properties (name, visibility, lock, transparency, appearance, mask, + // attributes) become the envelope's. + let mut envelope = drawn.clone(); + (envelope.id, envelope.kind) = (self.doc.alloc_id(), kind); + let layer = self.doc.alloc_id(); + let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; + let mut shown = envelope.clone(); + (shown.visible, shown.opacity) = (true, 1.0); + let mut plain = drawn.clone(); + (plain.visible, plain.opacity) = (true, 1.0); + let page = self.page_in_doc(); + if !crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent) { + self.warn(crate::import::ai::envelope::DRAWN); + return; + } + // The contents are the envelope's own now, not a copy on `%_` lines. + fn forget(n: &Node, hidden: &mut HashSet) { + hidden.remove(&n.id); + for c in n.children().into_iter().flatten() { + forget(c, hidden); + } + } + forget(&envelope, &mut self.hidden_ids); + if let Some(f) = self.frames.last_mut() + && let Some(slot) = f.children.last_mut() + { + let id = envelope.id; + let drawn = std::mem::replace(slot, envelope); + self.envelopes_drawn.push((id, drawn)); + } } } -/// The source text inside an envelope options dictionary, carried through its containing metadata. +/// Does `node` hold a text slot? +fn has_text_slot(node: &Node) -> bool { + let mut slots = vec![]; + envelope_text_slots(node, &mut slots); + !slots.is_empty() +} + +/// The source text inside an envelope options dictionary, carried through its containing metadata +/// (not type that a look draws, which isn't the envelope's source text). fn envelope_text_slots(node: &Node, out: &mut Vec) { + if super::is_look_slot(node.name.as_deref()) { + return; + } if slot_of(node.name.as_deref()).is_some() { out.push(node.clone()); } else if let Some(children) = node.children() { @@ -448,6 +995,68 @@ pub(super) fn drop_commented_copies(layers: &mut [Arc], hidden: &HashSet(node: &'n Node, out: &mut Vec<&'n str>, depth: usize) { + if depth > MAX_DEPTH { + return; + } + if let NodeKind::SymbolInstance { symbol, .. } = &node.kind { + out.push(symbol); + } + if let Some(m) = &node.extras().mask { + symbol_uses(&m.art, out, depth + 1); + } + for c in node.children().into_iter().flatten() { + symbol_uses(c, out, depth + 1); + } +} + +/// The instances in `node`, and in the art of its opacity masks, named by `names` (a name in the +/// file → the symbol's in the document). +fn rename_uses(node: &mut Node, names: &HashMap, depth: usize) { + if depth > MAX_DEPTH { + return; + } + if let NodeKind::SymbolInstance { symbol, .. } = &mut node.kind + && let Some(named) = names.get(symbol.as_str()) + { + symbol.clone_from(named); + } + if let Some(m) = node.extras_if_any().and_then(|e| e.mask.as_mut()) { + rename_uses(Arc::make_mut(&mut m.art), names, depth + 1); + } + for c in node.children_mut().into_iter().flatten() { + rename_uses(Arc::make_mut(c), names, depth + 1); + } +} + +/// Whether a symbol instance's dictionary carries appearance of its own (a dynamic symbol's +/// edits), which isn't read. +fn overrides(o: &Obj) -> bool { + const KEYS: [&str; 5] = [ + "AI19SymbolAppearanceMap", + "AI19SymbolOverriddenSymbolMap", + "AI Local Art of Symbol Instance", + "AI15 Layer In Symbol", + "AI15 Color Of Layer In Symbol", + ]; + // In a dictionary or array nested in it, as a keyed entry's value, in an array or among the + // values closed without a key. + fn has(o: &Obj, depth: usize) -> bool { + depth <= 8 + && (o.entries.iter().any(|(k, v)| k.as_deref().is_some_and(|k| KEYS.contains(&k)) || v.iter().any(|v| in_value(v, depth + 1))) + || o.content.iter().any(|v| in_value(v, depth + 1))) + } + fn in_value(v: &V, depth: usize) -> bool { + match v { + V::Obj(c) => has(c, depth), + V::Arr(items) => depth <= 8 && items.iter().any(|v| in_value(v, depth + 1)), + _ => false, + } + } + has(o, 0) +} + /// Close the subpath `bp` ends with, if it has one open. pub(super) fn close(bp: &mut BezPath) { if bp.elements().last().is_some_and(|e| !matches!(e, PathEl::ClosePath)) { @@ -455,6 +1064,20 @@ pub(super) fn close(bp: &mut BezPath) { } } +/// How many levels of nodes `n` holds, itself included, its opacity masks' art included. +fn depth(n: &Node) -> usize { + let mut deepest = 0; + let mut todo = vec![(n, 1)]; + while let Some((n, d)) = todo.pop() { + deepest = deepest.max(d); + todo.extend(n.children().into_iter().flatten().map(|c| (c.as_ref(), d + 1))); + if let Some(m) = n.extras().mask.as_ref() { + todo.push((m.art.as_ref(), d + 1)); + } + } + deepest +} + /// The fill rule of a path or compound node. /// `kids` with the members of each plain group among them in the group's place, at any depth. fn ungrouped(kids: Vec) -> Vec { diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index 47eef88dd0..ef27e5f747 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -1,6 +1,15 @@ +use std::collections::HashMap; + +use super::super::brush; use super::art::{four, sane, two}; -use super::types::{FLIP, Kind, MAX_HEX, MAX_PATTERNS, MAX_STACK, PatternHead, Place, Raster, SKIPPED}; -use super::{Arc, Node, PatternDef, Reader, Rect, Tok, V, marker}; +use super::ops::Dictionaries; +use super::raster::{end_hex, push_hex}; +use super::types::{ + FLIP, GState, Kind, MAX_DEPTH, MAX_LISTED, MAX_NODES, MAX_NOTE, MAX_PATTERNS, MAX_PLACED_FOLDER, MAX_STACK, MAX_SUBREADERS, MAX_SYMBOLS, + PatternHead, Place, Raster, SKIPPED, SymbolHead, VERSIONED_UNENDED, +}; +use super::{Arc, BrushArtColors, Global, Lexer, Node, NodeKind, PatternDef, Reader, Rect, Tok, V, marker, obj}; +use vectorcraft_doc::{NodeId, Symbol, SymbolRegistration}; impl<'a> Reader<'a> { pub(super) fn push(&mut self, v: V) -> Result<(), String> { @@ -23,7 +32,7 @@ impl<'a> Reader<'a> { // ---- comments -------------------------------------------------------------------------- - pub(super) fn comment(&mut self, c: &[u8]) -> Result<(), String> { + pub(super) fn comment(&mut self, c: &[u8], hidden: bool) -> Result<(), String> { let line = String::from_utf8_lossy(c); let line = line.trim_end(); if let Some((len, hex)) = self.blend_record.as_mut() { @@ -44,21 +53,83 @@ impl<'a> Reader<'a> { && !line.is_empty() && line.bytes().all(|b| b.is_ascii_hexdigit()) { - if r.hex.len() < MAX_HEX { - r.hex.extend_from_slice(line.as_bytes()); + push_hex(&mut r.samples, &mut r.half, line.as_bytes(), r.max); + return Ok(()); + } + // The header's comments (AI7 specification §2.1.1; DSC 3.0). + let more = self.custom_more.take(); + if !self.header_done && self.frames.is_empty() { + let bytes = c.trim_ascii_end(); + if let (Some(cmyk), Some(v)) = (more, bytes.strip_prefix(b"%+")) { + self.custom_color(v, cmyk); + return Ok(()); } + if let Some(v) = bytes.strip_prefix(b"%CMYKCustomColor:") { + self.custom_color(v, true); + return Ok(()); + } + if let Some(v) = bytes.strip_prefix(b"%RGBCustomColor:") { + self.custom_color(v, false); + return Ok(()); + } + if let Some(v) = bytes.strip_prefix(b"%For:") { + // `(username) (organization)`: the user who created the file. + if self.author.is_none() { + self.author = ps_string(v).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); + } + return Ok(()); + } + if bytes == b"%EndComments" { + self.header_done = true; + } + } + if self.note_comment(c) { return Ok(()); } let m = marker(line); - // A pattern's definition (one inside another's isn't read). - if m == "BeginPattern" && self.pattern.is_none() { + // A pattern's definition. One inside another's isn't read, and the outer tile is then incomplete. + if m == "BeginPattern" && self.symbol.is_none() { let section = self.section("EndPattern")?; - self.define_pattern(section); + if self.pattern.is_some() { + self.unsupported.insert("patterns inside patterns".into()); + } else { + self.define_pattern(section); + } + return Ok(()); + } + if m == "BeginSymbol" { + let section = self.section("EndSymbol")?; + self.define_symbol(section); + return Ok(()); + } + if m == "BeginSymbolList" { + let section = self.section("EndSymbolList")?; + self.symbol_list(section); + return Ok(()); + } + // Brushes and their art (those in a pattern's or a brush's art aren't read). + if m == "BeginPluginObject" && self.pattern.is_none() { + let section = self.section("EndPluginObject")?; + self.plugin_object(section); + return Ok(()); + } + if m == "BeginBrushPattern" && self.pattern.is_none() { + let section = self.section("EndBrushPattern")?; + self.define_brush_art(section); return Ok(()); } if m == "BeginArtStyles" { let section = self.section("EndArtStyles")?; - self.styles = crate::import::ai::style::art_styles(section); + // GUARDS: a definition's art takes the file's art styles and hands them back, so a + // section inside it would replace the file's own. + if self.subreader_depth == 0 { + self.styles = crate::import::ai::style::art_styles(section); + } + return Ok(()); + } + if m == "BeginArtStyleList" { + let section = self.section("EndArtStyleList")?; + self.style_list = crate::import::ai::style::art_style_list(section); return Ok(()); } if m == "BeginPalette" { @@ -68,6 +139,21 @@ impl<'a> Reader<'a> { } if m == "BeginEncoding" { self.type_state.encoding_comment(line); + let section = self.section("EndEncoding")?; + self.encoding_section(section); + return Ok(()); + } + // Versioned content holds alternatives of the same art, the newest first: the first is + // read, and the next one (`%AI17_Alternate_Content`, or `…_if_version_gt:` for a version + // in between) starts what is skipped, up to the end of the block, nested blocks included. + if m.starts_with("Alternate_Content") { + let at = self.lex.offset(); + if self.skip_to("End_Versioned_Content").is_err() { + // A block that doesn't end: the rest of the file is read rather than lost. + self.lex.seek(at); + self.warn(VERSIONED_UNENDED); + } + return Ok(()); } if let Some((_, end)) = SKIPPED.iter().find(|(b, _)| *b == m) { return self.skip_to(end); @@ -83,20 +169,49 @@ impl<'a> Reader<'a> { _ => {} } if line.starts_with("AI5_BeginLayer") { - return self.open(Kind::Layer(Box::default()), false); + self.multi_mask_layer_starts()?; + self.open(Kind::Layer(Box::default()), false)?; + self.multi_mask_go_on(); + return Ok(()); } if line.starts_with("AI5_BeginRaster") { + // An `XG` outside a raster object names no image in it. + self.image_link = None; self.raster = Some(Raster::default()); } else if line.starts_with("AI5_EndRaster") { - if let Some(Raster { operands: Some(vals), hex, .. }) = self.raster.take() { - return self.image_from(vals, &hex); + // A file `XG` named in this raster object is no later one's. + self.image_link = None; + if let Some(Raster { operands: Some(vals), mut samples, half, max, .. }) = self.raster.take() { + end_hex(&mut samples, half, max); + return self.image_from(vals, &samples, true); } } else if line.starts_with("AI5_BeginPlace") { - self.place = Some(Place::default()); + // One that is still open (no `~` ended it) isn't read. + let unseen = hidden || self.gs.hidden || !self.shown(); + if let Some(open) = self.place.replace(Place { hidden: unseen, ..Place::default() }) { + self.unreadable("placed files", open.hidden); + } } else if line.starts_with("AI5_EndPlace") { // One that `~` didn't end isn't read. - if self.place.take().is_some() { - self.unreadable("placed files"); + if self.place.is_some() { + self.end_place(hidden)?; + } + } else if m == "BeginPlacedRelativePath" { + let at = self.stack.len(); + if let Some(p) = self.place.as_mut() { + p.folder_at = Some(at); + } + } else if m == "EndPlacedRelativePath" { + // The folder is the string between the markers, taken off the stack. + let base = self.frames.last().map_or(0, |f| f.base); + if let Some(at) = self.place.as_mut().and_then(|p| p.folder_at.take()).filter(|at| (base..=self.stack.len()).contains(at)) { + let vals = self.stack.split_off(at); + if let Some(p) = self.place.as_mut() { + p.folder = vals + .iter() + .find_map(|v| if let V::Str(s) = v { Some(super::obj::text(s)) } else { None }) + .filter(|f| f.len() <= MAX_PLACED_FOLDER); + } } } else if self.frames.is_empty() && let Some(v) = line.strip_prefix("%HiResBoundingBox:") @@ -121,40 +236,117 @@ impl<'a> Reader<'a> { self.ruler_units = Some(n); } else if let Some(v) = line.strip_prefix("AI5_ArtSize:") { self.art_size = two(v); - } else if let Some(v) = line.strip_prefix("AI3_TemplateBox:") { + } else if let Some(v) = line.strip_prefix("AI3_TemplateBox:").or_else(|| line.strip_prefix("%TemplateBox:")) { self.template_center = two(v); self.template = four(v).or(self.template); } else if let Some(v) = line.strip_prefix("AI24_LargeCanvasScale:") { - // Illustrator's Large Canvas writes the editing data (art and boxes) at 1/N scale, N - // being this; the printed page applies the same factor, so the art reaches the page's - // size once it is applied to the art space ([`Self::ensure_space`]). A value outside - // the range Illustrator writes is left alone. - if let (Some(scale), Ok(n)) = (&mut self.large_canvas, v.trim().parse::()) - && (1.0..=100.0).contains(&n) - { - *scale = n; - } + self.large_canvas_scale(v); } else if let Some(v) = line.strip_prefix("AI9_ColorModel:") { self.color_model = Some(v.trim() == "2"); } Ok(()) } + /// `%AI24_LargeCanvasScale:` with its value `v`. + fn large_canvas_scale(&mut self, v: &str) { + // Illustrator's Large Canvas writes the editing data (art and boxes) at 1/N scale, N + // being this; the printed page applies the same factor, so the art reaches the page's + // size once it is applied to the art space ([`Self::ensure_space`]). A value outside + // the range Illustrator writes is left alone. + if let Ok(n) = v.trim().parse::() + && (1.0..=100.0).contains(&n) + { + self.canvas_scale = n; + if let Some(scale) = &mut self.large_canvas { + *scale = n; + } + } + } + + /// `%AI3_Note:` (or `%%Note:`) sets the note of the paths that follow, an empty one clearing it, + /// and `%AI5_NoteMore:` adds a line to it. The text is kept as written, up to [`MAX_NOTE`] + /// characters. + fn note_comment(&mut self, c: &[u8]) -> bool { + let (text, more) = if let Some(t) = c.strip_prefix(b"AI3_Note:").or_else(|| c.strip_prefix(b"%Note:")) { + (t, false) + } else if let Some(t) = c.strip_prefix(b"AI5_NoteMore:") { + (t, true) + } else { + return false; + }; + // Only as much of the line as the note can keep is decoded; a UTF-8 character the cut + // splits is left out. + let mut head = text.get(..text.len().min(4 * MAX_NOTE)).unwrap_or(text); + if head.len() < text.len() + && let Err(e) = std::str::from_utf8(head) + && e.error_len().is_none() + { + head = head.get(..e.valid_up_to()).unwrap_or(head); + } + let text = super::obj::text(head); + match (&mut self.gs.note, more) { + (Some(note), true) => { + note.push('\n'); + note.push_str(&text); + } + // A continuation with no note to continue. + (None, true) => return true, + (note, false) => *note = Some(text), + } + if let Some(note) = self.gs.note.as_mut() + && let Some((at, _)) = note.char_indices().nth(MAX_NOTE) + { + note.truncate(at); + } + true + } + + /// A custom color of the header, `cyan magenta yellow black (name)` (`cmyk`) or + /// `red green blue (name)`, each component from 0 to 1. One written otherwise isn't kept. + fn custom_color(&mut self, v: &[u8], cmyk: bool) { + self.custom_more = Some(cmyk); + if self.custom_colors.len() >= MAX_CUSTOM_COLORS { + return; + } + let Some(open) = v.iter().position(|&b| b == b'(') else { return }; + let (Some(head), Some(name)) = (v.get(..open), v.get(open..).and_then(ps_string)) else { return }; + // One more than a color has, so that too many are seen. + let parts: Vec> = head + .split(u8::is_ascii_whitespace) + .filter(|w| !w.is_empty()) + .take(5) + .map(|w| std::str::from_utf8(w).ok()?.parse::().ok().filter(|n| (0.0..=1.0).contains(n))) + .collect(); + let color = match parts.as_slice() { + [Some(c), Some(m), Some(y), Some(k)] if cmyk => vectorcraft_color::Color::cmyk(*c, *m, *y, *k), + [Some(r), Some(g), Some(b)] if !cmyk => vectorcraft_color::Color::rgb(*r, *g, *b), + _ => return, + }; + if !name.trim().is_empty() && !self.custom_colors.iter().any(|n| n.name == name) { + // A gradient or pattern defined after it does not take its swatch's name. + self.global_names.reserve(&name); + self.custom_colors.push(super::Named { name, color, tint: 1.0, spot: true }); + } + } + /// Skip to the comment with marker `end` (sections of the same kind nested in it count, and /// versioned content in an alternate). fn skip_to(&mut self, end: &str) -> Result<(), String> { self.section(end).map(|_| ()) } - /// [`Self::skip_to`] → what was skipped, up to the comment that ends it. + /// [`Self::skip_to`] → what was skipped, up to the comment that ends it. ASCII85 data in comment + /// lines is skipped past as [`Self::add_object_entry`] skips it. fn section(&mut self, end: &str) -> Result<&'a [u8], String> { let begin = SKIPPED.iter().find(|(_, e)| *e == end).map_or("", |(b, _)| *b); let begin = if end == "End_Versioned_Content" { "Begin_Content_if_version_gt" } else { begin }; let start = self.lex.offset(); let mut depth = 0usize; + let mut dictionaries = Dictionaries::default(); loop { let before = self.lex.offset(); let Some(t) = self.lex.next_token() else { break }; + dictionaries.pass(&t.tok, &mut self.lex, Some((begin, end))); if let Tok::Comment(c) = t.tok { let line = String::from_utf8_lossy(c); let m = marker(&line); @@ -173,32 +365,180 @@ impl<'a> Reader<'a> { /// A pattern's definition (`section`: what follows `%AI3_BeginPattern`), read by a reader of its /// own into a pattern swatch, its art in the pattern's space (y down). A definition it can't - /// read whole (an operator it doesn't know, type, unbalanced groups, no tile) isn't kept: art + /// read whole (an operator it doesn't know, type, a pattern it doesn't have, unbalanced groups, + /// no tile) isn't kept: art /// filled with it can't be read. fn define_pattern(&mut self, section: &[u8]) { - if self.pattern_tiles.len() >= MAX_PATTERNS { + if self.pattern_tiles.len() >= MAX_PATTERNS || self.subreader_depth >= MAX_SUBREADERS { return; } + match legacy_pattern(section) { + Legacy::No => {} + Legacy::Malformed => return, + Legacy::Yes(def) => return self.define_legacy_pattern(&def), + } let mut sub = Reader::new(section); + sub.subreader_depth = self.subreader_depth + 1; sub.pattern = Some(PatternHead::default()); - // The gradients defined so far, lent (and those it defines kept). + // The gradients and art styles defined so far and the names given, lent (and the gradients + // it defines kept). sub.gradients = std::mem::take(&mut self.gradients); + sub.global_names = std::mem::take(&mut self.global_names); + sub.styles = std::mem::take(&mut self.styles); sub.nodes = self.nodes; sub.template = self.template; + self.lend_budgets(&mut sub); let read = sub.open(Kind::Group, false).and_then(|()| sub.run()); + self.take_back_budgets(&mut sub); self.nodes = sub.nodes; self.gradients = std::mem::take(&mut sub.gradients); - let whole = read.is_ok() && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1; + self.global_names = std::mem::take(&mut sub.global_names); + self.styles = std::mem::take(&mut sub.styles); + // Unread art in the definition, hidden or not, leaves the tile incomplete. + let whole = read.is_ok() + && sub.unsupported.is_empty() + && sub.unknown.is_empty() + && sub.unread.is_empty() + && sub.hidden_unread.is_empty() + && sub.frames.len() == 1; + self.keep_pattern(sub, whole, false); + } + + /// A definition in the version 7 form ([`legacy_pattern`]), read layer by layer into one group: + /// each layer's colors (`@`) set the state its tile string (`&`) is read with, or the fill of the + /// tile's box (`_ &`). Each layer starts from the state the definition starts with. + fn define_legacy_pattern(&mut self, def: &LegacyPattern) { + let mut sub = Reader::new(b""); + sub.subreader_depth = self.subreader_depth + 1; + sub.pattern = Some(PatternHead { taken: true, name: def.name.clone(), tile: Some(def.tile) }); + sub.gradients = std::mem::take(&mut self.gradients); + sub.global_names = std::mem::take(&mut self.global_names); + sub.styles = std::mem::take(&mut self.styles); + sub.nodes = self.nodes; + sub.template = self.template; + self.lend_budgets(&mut sub); + let mut read = sub.open(Kind::Group, false); + for layer in &def.layers { + if read.is_err() { + break; + } + read = sub.pattern_layer(layer, def.tile); + } + self.take_back_budgets(&mut sub); + self.nodes = sub.nodes; + self.gradients = std::mem::take(&mut sub.gradients); + self.global_names = std::mem::take(&mut sub.global_names); + self.styles = std::mem::take(&mut sub.styles); + let whole = read.is_ok() + && sub.unsupported.is_empty() + && sub.unknown.is_empty() + && sub.unread.is_empty() + && sub.hidden_unread.is_empty() + && sub.frames.len() == 1; + self.keep_pattern(sub, whole, true); + } + + /// One layer of a definition in the version 7 form, read into the definition's group. + fn pattern_layer(&mut self, layer: &'a LegacyLayer, tile: Rect) -> Result<(), String> { + self.gs = GState::default(); + self.pending_fill = None; + self.pending_stroke = None; + self.pending_unread_fill = false; + self.pending_unread_stroke = false; + self.instance = None; + self.end_path_quietly(); + // The color part has the overprint and the colors only. + let mut lex = super::Lexer::new(&layer.color); + while let Some(t) = lex.next_token() { + match t.tok { + Tok::Num(_) | Tok::Str(_) | Tok::Hex(_) => {} + Tok::Word(w) if LAYER_COLOR_OPS.contains(&w) => {} + _ => return Err("a pattern layer's colors hold something else".into()), + } + } + self.run_string(&layer.color)?; + match &layer.tile { + Some(art) => self.run_string(art)?, + None => { + let corner = |x: f64, y: f64| [V::Num(x), V::Num(y)]; + self.path_op("m", &corner(tile.x0, tile.y0))?; + for (x, y) in [(tile.x0, tile.y1), (tile.x1, tile.y1), (tile.x1, tile.y0)] { + self.path_op("L", &corner(x, y))?; + } + self.paint("f", false, false)?; + } + } + // A path the layer leaves unpainted paints nothing. + self.end_path_quietly(); + Ok(()) + } + + /// Run this reader on one of a pattern layer's strings, which must end everything it starts. + fn run_string(&mut self, bytes: &'a [u8]) -> Result<(), String> { + let depth = self.frames.len(); + self.lex = super::Lexer::new(bytes); + let read = self.run(); + let open = self.done + || self.frames.len() != depth + || self.stack.iter().any(|v| matches!(v, V::Mark)) + || !self.marks.is_empty() + || self.text.is_some() + || self.raster.is_some() + || self.place.is_some() + || self.mesh.is_some() + || self.gradient_def.is_some(); + self.stack.clear(); + self.marks.clear(); + read?; + if open { + return Err("a pattern layer doesn't end what it starts".into()); + } + Ok(()) + } + + /// Keep the pattern `sub` read, when it read it `whole`, as a pattern swatch; `v7` when it was + /// defined in the version 7 form. + fn keep_pattern(&mut self, mut sub: Reader<'_>, whole: bool, v7: bool) { let (Some(head), Some(frame)) = (sub.pattern.take(), sub.frames.pop()) else { return }; let Some(tile) = head.tile.filter(|t| whole && sane(*t) && t.width() > 0.0 && t.height() > 0.0 && !frame.children.is_empty()) else { return; }; - let art: Vec> = frame.children.iter().map(|n| Arc::new(self.doc.reid(n))).collect(); - let mut def = PatternDef::new(&head.name, art); + let art: Vec> = frame + .children + .iter() + .map(|n| { + let mut kept = self.doc.reid(n); + self.reid_masks(&mut kept, 0); + Arc::new(kept) + }) + .collect(); + // The objects of the art linked to graphic styles, by their ids in the document. + if !sub.style_links.is_empty() { + let mut ids = HashMap::new(); + for (read, kept) in frame.children.iter().zip(&art) { + pair_ids(read, kept, &mut ids, 0); + } + for (id, style) in &sub.style_links { + if let Some(new) = ids.get(id) + && self.style_links.len() < MAX_NODES + { + self.style_links.push((*new, style.clone())); + } + } + } + // Fills and the tables look the pattern up by its name in the file; the document has it by + // the name it shows. + let mut def = PatternDef::new(&self.global_names.define(Global::Pattern, &head.name), art); def.tile = FLIP.transform_rect_bbox(tile); - if self.pattern_tiles.insert(def.name.clone(), def.tile).is_some() { + if self.pattern_tiles.insert(head.name.clone(), def.tile).is_some() { self.doc.patterns.retain(|p| p.name != def.name); } + if v7 { + self.v7_patterns.insert(head.name); + } else { + self.v7_patterns.remove(&head.name); + } + self.pattern_looks.insert(def.name.clone(), sub.drawn_looks); self.doc.patterns.push(def); for (key, blob) in sub.doc.images { self.doc.images.entry(key).or_insert(blob); @@ -212,6 +552,281 @@ impl<'a> Reader<'a> { } } + /// A symbol's definition (`section`: what follows `%AI14_BeginSymbol`), read by a reader of its + /// own into a symbol of the document, its art in the symbol's space (y down), named as the file + /// names it unless another symbol has that name. A definition inside another one or inside a + /// pattern's isn't read, nor is one after the first layer (the symbols were checked there, see + /// [`Reader::check_symbols`]). One it can't read whole (an operator it doesn't know, type, unbalanced + /// groups, art it leaves out) isn't kept: its instances come in as the page draws them, within + /// its art's box when that can be measured. + fn define_symbol(&mut self, section: &[u8]) { + if self.symbol.is_some() + || self.pattern.is_some() + || self.symbols_checked + || self.subreader_depth >= MAX_SUBREADERS + || self.doc.symbols.len() + self.symbol_bounds.len() >= MAX_SYMBOLS + { + return; + } + let name = match Lexer::new(section).next_token().map(|t| t.tok) { + Some(Tok::Str(bytes)) => obj::text(&bytes), + _ => return, + }; + let mut sub = Reader::new(section); + sub.subreader_depth = self.subreader_depth + 1; + sub.symbol = Some(SymbolHead::default()); + sub.template = self.template; + // The gradients, art styles and patterns defined so far and the names given, lent. + sub.gradients = std::mem::take(&mut self.gradients); + sub.global_names = std::mem::take(&mut self.global_names); + sub.styles = std::mem::take(&mut self.styles); + sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles); + sub.v7_patterns.clone_from(&self.v7_patterns); + sub.nodes = self.nodes; + self.lend_budgets(&mut sub); + let read = sub.open(Kind::Group, false).and_then(|()| sub.run()); + self.take_back_budgets(&mut sub); + self.nodes = sub.nodes; + self.gradients = std::mem::take(&mut sub.gradients); + self.global_names = std::mem::take(&mut sub.global_names); + self.styles = std::mem::take(&mut sub.styles); + self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles); + // Art stopped by a trailer, or with an array, type, image, placed file, gradient mesh or + // gradient still open at the end (as [`Reader::run_string`] checks), isn't whole. + let open = sub.done + || sub.stack.iter().any(|v| matches!(v, V::Mark)) + || !sub.marks.is_empty() + || sub.text.is_some() + || sub.raster.is_some() + || sub.place.is_some() + || sub.mesh.is_some() + || sub.gradient_def.is_some(); + let head = sub.symbol.take().unwrap_or_default(); + let registration = head.registration; + let measured = read.is_ok() && !open && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1; + let Some(frame) = sub.frames.pop().filter(|_| measured) else { return }; + let mut kids = frame.children; + // Where a symbol's art puts a pattern's tiles isn't known. + let whole = !head.left_out && sub.unread.is_empty() && sub.hidden_unread.is_empty() && !kids.iter().any(|n| paints_pattern(n, 0)); + if !whole { + let boxes = self.doc.symbol_boxes(); + let bounds = kids.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds_with(&boxes))); + drop(boxes); + if let Some(b) = bounds.filter(|b| sane(*b) && b.area() > 0.0) { + self.symbol_bounds.insert(name, b); + } + return; + } + let art = match (kids.len(), kids.pop()) { + (1, Some(one)) => one, + (_, last) => Node::group(self.doc.alloc_id(), kids.into_iter().chain(last).map(Arc::new).collect()), + }; + // The group a definition holds its art in, when it holds one object and isn't linked to a + // graphic style. + let linked = sub.style_links.iter().any(|(id, _)| *id == art.id); + let art = match symbol_art_member(&art).filter(|_| !linked).cloned() { + Some(m) => Arc::unwrap_or_clone(m), + None => art, + }; + let read_art = art; + let mut art = self.doc.reid(&read_art); + self.reid_masks(&mut art, 0); + // The objects of the art linked to graphic styles, by their ids in the document. + if !sub.style_links.is_empty() { + let mut ids = HashMap::new(); + pair_ids(&read_art, &art, &mut ids, 0); + for (id, style) in &sub.style_links { + if let Some(new) = ids.get(id) + && self.style_links.len() < MAX_NODES + { + self.style_links.push((*new, style.clone())); + } + } + } + let named = self.unique_symbol_name(if name.is_empty() { "Symbol" } else { &name }); + self.doc.symbols.push(Symbol { name: named.clone(), art: Arc::new(art), dynamic: false }); + if let Some(reg) = registration.and_then(symbol_registration) { + self.doc.set_symbol_registration(&named, reg); + } + self.symbol_names.entry(name).or_insert(named); + for (key, blob) in sub.doc.images { + self.doc.images.entry(key).or_insert(blob); + } + self.spots.extend(sub.spots); + self.stop_spots.extend(sub.stop_spots); + self.cmyk_colors += sub.cmyk_colors; + self.rgb_colors += sub.rgb_colors; + self.drawn_looks += sub.drawn_looks; + for w in &sub.warnings { + self.warn(w); + } + } + + /// `base`, or the first free "`base` N" (N from 2) when a symbol read has that name, as + /// [`vectorcraft_doc::Document::unique_symbol_name`] names it, without looking at every symbol + /// for each N. + fn unique_symbol_name(&mut self, base: &str) -> String { + let mut named = base.to_string(); + if self.symbol_taken.contains(&named) { + let next = self.symbol_suffix.entry(named.clone()).or_insert(2); + while self.symbol_taken.contains(&format!("{base} {next}")) { + *next += 1; + } + named = format!("{base} {next}"); + *next += 1; + } + self.symbol_taken.insert(named.clone()); + named + } + + /// Give the art of the opacity masks in `n` (a copy of a symbol's, a pattern's or a brush's art, or of a clipping path, with ids of this + /// document, [`vectorcraft_doc::Document::reid`], which leaves masks as they are) ids of this + /// document too. + pub(super) fn reid_masks(&mut self, n: &mut Node, depth: usize) { + if depth > MAX_DEPTH { + return; + } + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + let mut art = self.doc.reid(&m.art); + self.reid_masks(&mut art, depth + 1); + m.art = Arc::new(art); + } + for c in n.children_mut().into_iter().flatten() { + self.reid_masks(Arc::make_mut(c), depth + 1); + } + } + + /// The symbol list (`section`: what follows `%AI24_BeginSymbolList`): the symbols' names in the + /// Symbols panel's order. The first list is kept. + fn symbol_list(&mut self, section: &[u8]) { + if self.symbol.is_some() || self.pattern.is_some() || self.symbol_list.is_some() { + return; + } + let mut lex = Lexer::new(section); + let mut names = vec![]; + while let Some(t) = lex.next_token() { + if let Tok::Str(bytes) = t.tok { + if names.len() >= MAX_LISTED { + break; + } + names.push(obj::text(&bytes)); + } + } + self.symbol_list = Some(names); + } + + /// A plug-in object (`section`: what follows `%AI8_BeginPluginObject`): the brush manager's + /// order or a brush ([`brush`]); other objects are left alone. A brush without a name is counted + /// as not read. + fn plugin_object(&mut self, section: &[u8]) { + let Some((kind, name, params)) = brush::plugin_strings(section) else { return }; + if kind == brush::MANAGER { + if name.is_some() { + self.brush_objects = true; + self.brush_order = brush::parse_brush_manager(¶ms); + } + return; + } + let Some(tool) = brush::tool(&kind) else { return }; + self.brush_objects = true; + let Some(name) = name else { + self.brushes_unread += 1; + return; + }; + if self.brush_drafts.len() >= brush::MAX_BRUSHES { + self.brushes_unread += 1; + return; + } + match brush::parse_tool_object(tool, &name, ¶ms) { + Ok(d) => self.brush_drafts.push(d), + Err(_) => self.brushes_unread += 1, + } + } + + /// A brush's art (`section`: what follows `%AI8_BeginBrushPattern`, its name as a string, then + /// the art), read by a reader of its own as a pattern's is, in a space with y down. Art it can't + /// read whole isn't kept: the brushes that use it aren't read. Kept art's colors are kept with + /// it, and count as the page's once a brush that is kept uses the art + /// ([`Reader::count_brush_art_colors`]): each name's first definition in the art, at most + /// [`brush::MAX_BRUSH_ART_COLORS`] names. + fn define_brush_art(&mut self, section: &[u8]) { + if self.brush_art_sections >= brush::MAX_BRUSH_ART || self.subreader_depth >= MAX_SUBREADERS { + return; + } + self.brush_art_sections += 1; + let mut lex = Lexer::new(section); + let Some(Tok::Str(name) | Tok::Hex(name)) = lex.next_token().map(|t| t.tok) else { return }; + let name = obj::text(&name); + let mut sub = Reader::new(lex.slice(lex.offset(), section.len())); + // In a space of its own (y down), with no head to take. + sub.pattern = Some(PatternHead { taken: true, ..PatternHead::default() }); + sub.subreader_depth = self.subreader_depth + 1; + // The gradients, art styles and patterns defined so far, and which patterns are in the + // version 7 form, lent. + sub.gradients = std::mem::take(&mut self.gradients); + sub.styles = std::mem::take(&mut self.styles); + sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles); + sub.v7_patterns = std::mem::take(&mut self.v7_patterns); + sub.global_names = std::mem::take(&mut self.global_names); + sub.nodes = self.nodes; + sub.template = self.template; + self.lend_budgets(&mut sub); + let read = sub.open(Kind::Group, false).and_then(|()| sub.run()); + self.take_back_budgets(&mut sub); + self.nodes = sub.nodes; + self.gradients = std::mem::take(&mut sub.gradients); + self.styles = std::mem::take(&mut sub.styles); + self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles); + self.v7_patterns = std::mem::take(&mut sub.v7_patterns); + self.global_names = std::mem::take(&mut sub.global_names); + // Images aren't kept: the document's images don't count a brush's art among their users. Art + // read with a note (something left out of it) isn't kept either. + let whole = read.is_ok() + && sub.unsupported.is_empty() + && sub.unknown.is_empty() + && sub.unread.is_empty() + && sub.hidden_unread.is_empty() + && sub.warnings.is_empty() + && sub.frames.len() == 1 + && sub.doc.images.is_empty(); + let Some(frame) = sub.frames.pop().filter(|f| whole && !f.children.is_empty()) else { return }; + self.brush_art_looks.insert(name.clone(), sub.drawn_looks); + let mut art: Vec> = frame + .children + .iter() + .map(|n| { + let mut kept = self.doc.reid(n); + self.reid_masks(&mut kept, 0); + Arc::new(kept) + }) + .collect(); + let node = match art.len() { + 1 => art.pop().map(Arc::unwrap_or_clone), + _ => Some(Node::group(self.doc.alloc_id(), art)), + } + .map(brush::without_frame); + let Some(node) = node else { return }; + self.brush_art.insert(name.clone(), node); + let mut colors = BrushArtColors { spots: sub.spots, stop_spots: sub.stop_spots, cmyk: sub.cmyk_colors, rgb: sub.rgb_colors }; + colors.keep_first(brush::MAX_BRUSH_ART_COLORS); + self.brush_art_colors.insert(name, colors); + } + + /// Lend `sub`, a reader of a definition, what this import may still spend on laying out blends + /// and checking envelopes ([`Reader::take_back_budgets`] takes back what is left). + fn lend_budgets(&mut self, sub: &mut Reader<'_>) { + sub.blend_budget = self.blend_budget; + sub.envelope_checks = self.envelope_checks; + sub.envelope_spent = std::mem::take(&mut self.envelope_spent); + } + + /// Take back from `sub` what [`Self::lend_budgets`] lent it, less what it spent. + fn take_back_budgets(&mut self, sub: &mut Reader<'_>) { + self.blend_budget = sub.blend_budget; + self.envelope_checks = sub.envelope_checks; + self.envelope_spent = std::mem::take(&mut sub.envelope_spent); + } + /// In a pattern's definition, the operands of its first operator start with its head, /// `(name) llx lly urx ury`: taken off them. pub(super) fn take_head(&mut self, mut vals: Vec) -> Vec { @@ -225,3 +840,412 @@ impl<'a> Reader<'a> { vals.split_off(at + 5) } } + +/// The operators a pattern layer's colors (`@`) may hold: overprint, gray, process and custom colors. +const LAYER_COLOR_OPS: &[&[u8]] = &[b"O", b"R", b"g", b"G", b"k", b"K", b"x", b"X"]; + +/// The longest string a pattern layer may have (the format's limit, 64K bytes). +const MAX_LAYER_STRING: usize = 65_535; + +/// Most layers in one pattern's definition. +const MAX_LAYERS: usize = 65_536; + +/// A pattern's definition in the version 7 form: its head, then a list of layers painted in order, +/// the first the lowest. +struct LegacyPattern { + name: String, + /// The tile in the pattern's space (y up). + tile: Rect, + layers: Vec, +} + +/// `(colors) @ (tile) &`, or `(colors) @ _ &` (no tile: the tile's box is filled with the colors' fill). +struct LegacyLayer { + color: Vec, + tile: Option>, +} + +enum Legacy { + /// Another form: the definition's art follows its head as operators. + No, + /// The version 7 form, which can't be read. + Malformed, + Yes(LegacyPattern), +} + +/// The next token that isn't a comment; `Err` at a pattern's definition inside this one. +fn next_operand<'s>(lex: &mut super::Lexer<'s>) -> Result>, ()> { + while let Some(t) = lex.next_token() { + match t.tok { + Tok::Comment(c) if marker(&String::from_utf8_lossy(c)) == "BeginPattern" => return Err(()), + Tok::Comment(_) => {} + _ => return Ok(Some(t)), + } + } + Ok(None) +} + +/// A pattern's definition in the version 7 form: `(name) llx lly urx ury [`, then for each layer +/// `(colors) @` and `(tile) &` or `_ &`, then `] E` (version 7 specification §3.4). It is that form +/// when a `[` that isn't on a `%_` line follows the head. +fn legacy_pattern(section: &[u8]) -> Legacy { + let mut lex = super::Lexer::new(section); + let mut next = || next_operand(&mut lex).ok().flatten().map(|t| (t.tok, t.hidden)); + let name = match next() { + Some((Tok::Str(s), _)) => super::obj::text(&s), + _ => return Legacy::No, + }; + let mut tile = [0.0; 4]; + for v in &mut tile { + match next() { + Some((Tok::Num(n), _)) => *v = n, + _ => return Legacy::No, + } + } + if !matches!(next(), Some((Tok::Word(b"["), false))) { + return Legacy::No; + } + let [x0, y0, x1, y1] = tile; + let mut layers = vec![]; + let string = |t: Option<(Tok, bool)>| match t { + Some((Tok::Str(s) | Tok::Hex(s), _)) if s.len() <= MAX_LAYER_STRING => Some(s), + _ => None, + }; + let word = |t: Option<(Tok, bool)>, w: &[u8]| matches!(t, Some((Tok::Word(x), _)) if x == w); + loop { + // Before the first layer, anything but a string or `] E` is the newer form's art (`[]0 d`). + let first = layers.is_empty(); + let color = match next() { + Some((Tok::Word(b"]"), _)) if !first => break, + Some((Tok::Word(b"]"), _)) => { + return match next() { + Some((Tok::Word(b"E"), _)) => Legacy::Yes(LegacyPattern { name, tile: Rect::new(x0, y0, x1, y1), layers }), + _ => Legacy::No, + }; + } + t @ Some((Tok::Str(_) | Tok::Hex(_), _)) => match string(t) { + Some(s) => s, + None => return Legacy::Malformed, + }, + _ if first => return Legacy::No, + _ => return Legacy::Malformed, + }; + if !word(next(), b"@") { + return Legacy::Malformed; + } + let tile = match next() { + Some((Tok::Word(b"_"), _)) => None, + t => match string(t) { + Some(s) => Some(s), + None => return Legacy::Malformed, + }, + }; + if !word(next(), b"&") || layers.len() >= MAX_LAYERS { + return Legacy::Malformed; + } + layers.push(LegacyLayer { color, tile }); + } + // `] E` ends the definition: nothing but comments may follow it. + if !word(next(), b"E") || !matches!(next_operand(&mut lex), Ok(None)) { + return Legacy::Malformed; + } + Legacy::Yes(LegacyPattern { name, tile: Rect::new(x0, y0, x1, y1), layers }) +} + +/// How many custom colors the header may define. +pub(super) const MAX_CUSTOM_COLORS: usize = 1000; + +/// The longest string the header's comments may give, in bytes. +const MAX_STRING: usize = 4096; + +/// The PostScript string `v` starts with (after spaces), its escapes read, when it ends on the line +/// and holds at most [`MAX_STRING`] bytes. +fn ps_string(v: &[u8]) -> Option { + let mut bytes = v.trim_ascii_start().iter().copied().peekable(); + if bytes.next()? != b'(' { + return None; + } + let (mut out, mut depth) = (Vec::new(), 0usize); + while let Some(b) = bytes.next() { + if out.len() > MAX_STRING { + return None; + } + match b { + b'\\' => match bytes.next()? { + b'n' => out.push(b'\n'), + b'r' => out.push(b'\r'), + b't' => out.push(b'\t'), + b'b' => out.push(8), + b'f' => out.push(12), + d @ b'0'..=b'7' => { + let mut n = u32::from(d - b'0'); + for _ in 0..2 { + match bytes.peek() { + Some(&o @ b'0'..=b'7') => { + n = n * 8 + u32::from(o - b'0'); + bytes.next(); + } + _ => break, + } + } + out.push((n & 0xff) as u8); + } + other => out.push(other), + }, + b'(' => { + depth += 1; + out.push(b); + } + b')' => { + let Some(d) = depth.checked_sub(1) else { return Some(super::obj::text(&out)) }; + depth = d; + out.push(b); + } + _ => out.push(b), + } + } + None +} + +/// The one member of `n` when `n` is a plain group holding only it (not clipping, unnamed, shown, +/// unlocked, opaque, Normal, not isolated, knockout neutral, no knockout shape, appearance, opacity +/// mask or other extras such as object attributes): a symbol's art written as such a group +/// (definitions hold a group) is that member. +pub(crate) fn symbol_art_member(n: &Node) -> Option<&Arc> { + let NodeKind::Group { children, clip: false } = &n.kind else { return None }; + let [one] = children.as_slice() else { return None }; + let plain = n.name.as_deref().is_none_or(str::is_empty) + && n.visible + && !n.locked + && n.opacity == 1.0 + && n.blend == vectorcraft_color::BlendMode::Normal + && !n.isolate + && n.knockout == vectorcraft_doc::Knockout::Neutral + && !n.knockout_shape + && n.appearance.items.is_empty() + && n.appearance.effects.is_empty() + && *n.extras() == vectorcraft_doc::NodeExtras::default(); + plain.then_some(one) +} + +/// Whether `n`, an object in it or the art of an opacity mask in it is filled or stroked with a +/// pattern. +fn paints_pattern(n: &Node, depth: usize) -> bool { + if depth > MAX_DEPTH { + return true; + } + let pattern = |p: &super::Paint| matches!(p, super::Paint::Pattern { .. }); + n.appearance.items.iter().any(|item| match item { + super::AppearanceItem::Fill(f) => pattern(&f.paint), + super::AppearanceItem::Stroke(s) => pattern(&s.paint), + }) || n.extras().mask.as_ref().is_some_and(|m| paints_pattern(&m.art, depth + 1)) + || n.children().into_iter().flatten().any(|c| paints_pattern(c, depth + 1)) +} + +/// Each id of `old` and its descendants → the id of the object in its place in `new`, a copy of +/// `old` with new ids ([`vectorcraft_doc::Document::reid`]). +fn pair_ids(old: &Node, new: &Node, ids: &mut HashMap, depth: usize) { + ids.insert(old.id, new.id); + if depth > MAX_DEPTH { + return; + } + if let (Some(a), Some(b)) = (old.extras().mask.as_ref(), new.extras().mask.as_ref()) { + pair_ids(&a.art, &b.art, ids, depth + 1); + } + if let (Some(a), Some(b)) = (old.children(), new.children()) { + for (a, b) in a.iter().zip(b) { + pair_ids(a, b, ids, depth + 1); + } + } +} + +/// The registration point `AI13PatternRegistrationType` `v` gives a symbol: 1 to 9 from the top +/// left, row by row (5 the center); `None` for other numbers. +pub(super) fn symbol_registration(v: f64) -> Option { + (v.fract() == 0.0 && (1.0..=9.0).contains(&v)).then(|| SymbolRegistration(v as u8 - 1)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn postscript_strings_read_their_escapes_and_end_on_the_line() { + assert_eq!(ps_string(b" (Ann \\(R\\) (x) \\101\\0618) (Org)").as_deref(), Some("Ann (R) (x) A18")); + assert_eq!(ps_string(b"(a\\nb\\\\)").as_deref(), Some("a\nb\\")); + assert_eq!(ps_string(b"(never ends \\)"), None); + assert_eq!(ps_string(b"(ends in a backslash\\"), None); + assert_eq!(ps_string(b"no string"), None); + let long = format!("({})", "x".repeat(MAX_STRING + 1)); + assert_eq!(ps_string(long.as_bytes()), None); + let longest = format!("({})", "x".repeat(MAX_STRING)); + assert_eq!(ps_string(longest.as_bytes()).map(|s| s.len()), Some(MAX_STRING)); + } + + /// Definitions nested in a definition aren't read, however deep, and none is read past the + /// limit of nested readers. + #[test] + fn deeply_nested_symbol_definitions_stop_at_subreader_limit() { + let mut definition = String::from("(Outer) 0 A 0 Xw 0 Ae\n"); + for i in 0..300 { + definition.push_str(&format!("%AI14_BeginSymbol\n(S{i}) 0 Ae\n")); + } + definition.push_str("0 0 m\n4 0 L\n4 4 L\n0 4 L\nf\n"); + for _ in 0..300 { + definition.push_str("%AI10_EndSymbol\n0 0 m\n4 0 L\n4 4 L\n0 4 L\nf\n"); + } + let mut reader = Reader::new(b""); + reader.subreader_depth = MAX_SUBREADERS; + reader.define_symbol(definition.as_bytes()); + assert!(reader.doc.symbols.is_empty()); + reader.subreader_depth = 0; + reader.define_symbol(definition.as_bytes()); + let names: Vec<&str> = reader.doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["Outer"]); + } + + /// Definitions past the limit aren't read, however they are named. + #[test] + fn symbol_definitions_stop_at_the_limit_even_with_one_name() { + let mut reader = Reader::new(b""); + for _ in 0..MAX_SYMBOLS + 10 { + reader.define_symbol(b"(Same) 0 A 0 Xw 0 Ae\nu\nU\n"); + } + assert_eq!(reader.doc.symbols.len(), MAX_SYMBOLS); + assert_eq!(reader.doc.symbols.last().map(|s| s.name.as_str()), Some(format!("Same {MAX_SYMBOLS}").as_str())); + } + + /// The registration points 1 to 9 run from the top left, row by row; other numbers give none. + #[test] + fn symbol_registration_numbers_run_row_by_row() { + assert_eq!(symbol_registration(1.0), Some(SymbolRegistration(0))); + assert_eq!(symbol_registration(5.0), Some(SymbolRegistration::CENTER)); + assert_eq!(symbol_registration(9.0), Some(SymbolRegistration(8))); + for v in [0.0, 10.0, 2.5, -1.0, f64::NAN] { + assert_eq!(symbol_registration(v), None); + } + } + + #[test] + fn brush_art_stops_at_subreader_limit() { + let art = b"(A)\n0 g\n0 0 m\n4 0 L\n4 4 L\nf\n"; + let mut reader = Reader::new(b""); + reader.define_brush_art(art); + assert_eq!(reader.brush_art.len(), 1); + let mut reader = Reader::new(b""); + reader.subreader_depth = MAX_SUBREADERS; + reader.define_brush_art(art); + assert!(reader.brush_art.is_empty()); + } + + #[test] + fn brush_art_sections_stop_at_their_limit_with_repeated_names() { + let mut reader = Reader::new(b""); + reader.brush_art_sections = brush::MAX_BRUSH_ART - 1; + reader.define_brush_art(b"(A)\n0 g\n0 0 m\n4 0 L\n4 4 L\nf\n"); + let first = reader.brush_art.get("A").map(|n| n.id); + assert!(first.is_some()); + // The same name again is past the limit: the first art stays. + reader.define_brush_art(b"(A)\n0 g\n0 0 m\n8 0 L\n8 8 L\nf\n"); + assert_eq!(reader.brush_art.get("A").map(|n| n.id), first); + } + + #[test] + fn brushes_sharing_art_stop_at_the_budget_of_copied_nodes() { + let mut reader = Reader::new(b""); + reader.define_brush_art(b"(A)\n0 g\n0 0 m\n4 0 L\n4 4 L\nf\n"); + let nodes = reader.brush_art.get("A").map(brush::art_weight).unwrap_or_default(); + assert!(nodes > 0); + let draft = |i: usize| brush::BrushDraft { + name: format!("Brush {i}"), + kind: brush::DraftKind::Art { brush: vectorcraft_brush::ArtBrush::default(), art: "A".to_string(), plain: false }, + }; + let drafts: Vec<_> = (0..5).map(draft).collect(); + let (kept, left_out) = brush::finish_brushes_within(drafts.clone(), &reader.brush_art, None, 3 * nodes); + assert_eq!((kept.len(), left_out), (3, 2)); + let (kept, left_out) = brush::finish_brushes_within(drafts, &reader.brush_art, None, 5 * nodes); + assert_eq!((kept.len(), left_out), (5, 0)); + // A second brush of the same name is left out without using the budget. + let mut repeated: Vec<_> = (0..2).map(draft).collect(); + repeated.insert(1, draft(0)); + assert_eq!(brush::kept_brushes(&repeated, &reader.brush_art, 2 * nodes), [true, false, true]); + let (kept, left_out) = brush::finish_brushes_within(repeated, &reader.brush_art, None, 2 * nodes); + assert_eq!((kept.len(), left_out), (2, 1)); + } + + #[test] + fn brush_art_with_an_unread_object_is_not_kept() { + // A placed file the data keeps no preview of, shown and hidden. + let placed = + "%AI5_BeginPlace\n%%FileType: 1\n[5 0 0 -5 0 200] 10 20 14 22 4 4 0\n(missing.png)`\n%%IncludeFile:missing.png\n~\n%AI5_EndPlace\n"; + let hidden: String = placed.lines().map(|l| format!("%_{l}\n")).collect(); + for placed in [placed, hidden.as_str()] { + let art = format!("(A)\n0 g\n0 0 m\n4 0 L\n4 4 L\nf\n{placed}"); + let mut reader = Reader::new(b""); + reader.define_brush_art(art.as_bytes()); + assert!(reader.brush_art.is_empty(), "{placed:?}"); + } + } + + /// A blend of two keys along a straight spine, with its drawn steps and its record. + fn blend() -> String { + use crate::import::ai::tests::{blend_file, blend_record}; + blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &blend_record(&['A', 'B'])) + } + + /// A symbol's definition named `name` whose art is `art`. + fn symbol_section(name: &str, art: &str) -> String { + format!("({name})\n0 A\n0 Xw\n0 Ae\nu\n{art}U\n") + } + + /// Whether `n` or an object in it is a live blend. + fn holds_blend(n: &Node) -> bool { + matches!(n.kind, NodeKind::Blend { .. }) || n.children().is_some_and(|c| c.iter().any(|k| holds_blend(k))) + } + + /// Blends in symbols' definitions lay out their objects from the import's one budget: once a + /// definition has spent it, the next definition's blend keeps its drawn steps. + #[test] + fn blends_in_symbol_definitions_spend_the_imports_budget() { + let mut reader = Reader::new(b""); + reader.define_symbol(symbol_section("One", &blend()).as_bytes()); + let one = super::super::types::BLEND_BUDGET - reader.blend_budget; + assert!(one > 0, "the definition's blend spends from the reader's budget"); + let mut reader = Reader::new(b""); + reader.blend_budget = one; + reader.define_symbol(symbol_section("One", &blend()).as_bytes()); + reader.define_symbol(symbol_section("Two", &blend()).as_bytes()); + assert_eq!(reader.blend_budget, 0); + let live: Vec = reader.doc.symbols.iter().map(|s| holds_blend(&s.art)).collect(); + assert_eq!(live, [true, false]); + } + + /// Blends in patterns' and brushes' art spend from the same budget. + #[test] + fn blends_in_pattern_and_brush_art_spend_the_imports_budget() { + let mut reader = Reader::new(b""); + reader.define_pattern(format!("(P) 0 0 200 100\n0 A\n0 Xw\n0 Ae\n{}E\n", blend()).as_bytes()); + assert!(reader.blend_budget < super::super::types::BLEND_BUDGET, "a pattern's blend"); + let mut reader = Reader::new(b""); + reader.define_brush_art(format!("(A)\n0 A\n{}", blend()).as_bytes()); + assert!(reader.blend_budget < super::super::types::BLEND_BUDGET, "a brush's blend"); + } + + /// Envelopes in symbols' definitions are checked within the import's one count of checks. + #[test] + fn envelopes_in_symbol_definitions_spend_the_imports_checks() { + use crate::import::ai::tests::{drawn_content, envelope_content, envelope_of, straight_mesh, warp_keys}; + use vectorcraft_doc::live::EnvelopeKind; + let want = EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true }; + let envelope = + envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(1, 0.5, 0.0, 0.0, 0), &envelope_content(), 1, &drawn_content(&want)); + let mut reader = Reader::new(b""); + reader.define_symbol(symbol_section("One", &envelope).as_bytes()); + assert_eq!(reader.envelope_checks, crate::import::ai::envelope::MAX_CHECKED - 1); + let mut reader = Reader::new(b""); + reader.envelope_checks = 1; + reader.define_symbol(symbol_section("One", &envelope).as_bytes()); + reader.define_symbol(symbol_section("Two", &envelope).as_bytes()); + assert_eq!(reader.envelope_checks, 0); + } +} diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index b7d30aa4f9..9277bcc62b 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1,8 +1,13 @@ -use super::art::{element_name, elements, join_and, sane}; +use super::super::brush; +use super::art::{element_name, join_and, sane}; use super::containers::drop_commented_copies; +use super::ops::appearance_from_art_style; use super::types::{FLIP, Kind, MAX_DEPTH}; -use super::{Affine, Artboard, ColorMode, Document, NodeKind, Obj, OpacityMask, Paint, Point, Reader, Rect, Structure, Swatch, Unit, V, obj}; -use vectorcraft_doc::{ImageBlob, PatternDef}; +use super::{ + Affine, Arc, Artboard, CANVAS_CENTRE, ColorMode, Document, Global, HashMap, Node, NodeId, NodeKind, Obj, OpacityMask, Paint, Point, Reader, Rect, + Structure, Swatch, Unit, V, obj, +}; +use vectorcraft_doc::{DataSet, DataValue, GraphicStyle, Guide, ImageBlob, PatternDef, Symbol, TextWrap, Variable, VariableKind, Variables}; /// `%AI5_RulerUnits` → [`Unit`] (Illustrator 7 spec table 3; centimeters is 4; pixels is 6 in later files). fn ruler_unit(v: u8) -> Option { @@ -17,6 +22,105 @@ fn ruler_unit(v: u8) -> Option { }) } +/// `base`, or the first of "base 2", "base 3"… not in `taken`, as [`Document::free_swatch_name`] +/// gives it when `taken` holds the document's swatch and colour group names; `taken` takes the +/// name returned. +fn free_swatch_name(taken: &mut std::collections::HashSet, base: &str) -> String { + let name = if taken.contains(base) { + (2..).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n)).unwrap_or_else(|| base.to_string()) + } else { + base.to_string() + }; + taken.insert(name.clone()); + name +} + +/// An artboard of the `/Document`'s `ArtboardArray`: its name, its rect in art space and its +/// display options. +#[derive(Clone, Debug)] +pub(super) struct AiArtboard { + pub name: String, + pub rect: Rect, + pub center_mark: bool, + pub cross_hairs: bool, + pub safe_areas: bool, + /// The video ruler's pixel aspect ratio. + pub par: f64, +} + +impl AiArtboard { + fn new(name: String, rect: Rect) -> Self { + Self { name, rect, center_mark: false, cross_hairs: false, safe_areas: false, par: 1.0 } + } +} + +/// The number of entry `key` in `o` when it is written as one finite number of the type `ty` +/// (`/Int`, `/Real`, `/Bool`; a whole number unless `/Real`), else `None`. +fn typed(o: &Obj, key: &str, ty: &str) -> Option { + match o.get(key)? { + [V::Num(v), V::Name(t)] if t == ty && v.is_finite() && (ty == "Real" || v.fract() == 0.0) => Some(*v), + _ => None, + } +} + +/// The `/Bool` entry `key` of `o`: 0 or 1. +fn boolean(o: &Obj, key: &str) -> Option { + match typed(o, key, "Bool")? { + 0.0 => Some(false), + 1.0 => Some(true), + _ => None, + } +} + +/// An `ArtboardArray` entry's display options: `DisplayMark` (`/Int`, bits: 1 the center mark, +/// 2 cross hairs, 4 video safe areas) and `PAR` (`/Real`, the video ruler's pixel aspect ratio, +/// 0.1 to 10). A value of another type or out of range leaves the option off, or 1. +fn display_options(ab: &Obj, board: &mut AiArtboard) { + if let Some(mark) = typed(ab, "DisplayMark", "Int").filter(|m| (0.0..=f64::from(u32::MAX)).contains(m)) { + let mark = mark as u32; + (board.center_mark, board.cross_hairs, board.safe_areas) = (mark & 1 != 0, mark & 2 != 0, mark & 4 != 0); + } + if let Some(par) = typed(ab, "PAR", "Real").filter(|p| (0.1..=10.0).contains(p)) { + board.par = par; + } +} + +/// The `AI Auto Rasterize` dictionary of the `/Document` (Document Raster Effects Settings) into +/// `doc`: `dpi.` the resolution (`/Int`, 1 to 2400), `mask`, `alis` and `spot` the clipping mask, +/// anti-aliasing and Preserve Spot Colors (`/Bool`), `padd` the room added around the object +/// (`/Real`, points), and `colr` the color model and background (`/Int`: 0 the document's model on +/// white, 4 the document's model, transparent, 6 grayscale, transparent). A value of another type, +/// out of range or not one of these leaves the setting as it is. +fn raster_settings(r: &Obj, doc: &mut Document) { + use vectorcraft_doc::rastersettings::{MAX_ADD_AROUND, RasterColorModel}; + use vectorcraft_doc::setup::Background; + if let Some(ppi) = typed(r, "dpi.", "Int").filter(|p| (1.0..=2400.0).contains(p)) { + doc.raster_effects_ppi = ppi; + } + let s = &mut doc.raster_effects; + if let Some(on) = boolean(r, "mask") { + s.clipping_mask = on; + } + if let Some(on) = boolean(r, "alis") { + s.anti_alias = on; + } + if let Some(on) = boolean(r, "spot") { + s.preserve_spot_colors = on; + } + if let Some(pad) = typed(r, "padd", "Real").filter(|p| (0.0..=MAX_ADD_AROUND).contains(p)) { + s.add_around = pad; + } + let model = match typed(r, "colr", "Int") { + Some(0.0) => Some((RasterColorModel::Document, Background::White)), + Some(4.0) => Some((RasterColorModel::Document, Background::Transparent)), + Some(6.0) => Some((RasterColorModel::Grayscale, Background::Transparent)), + _ => None, + }; + if let Some((model, background)) = model { + (s.color_model, s.background) = (model, background); + } +} + /// The name of the empty group that stands for a text object, followed by the number of its /// story in the text document when the file says. pub(crate) const TEXT_SLOT: &str = "\u{0}text"; @@ -31,29 +135,62 @@ pub(crate) fn slot_frame(name: Option<&str>) -> usize { name.and_then(|n| n.strip_prefix(TEXT_SLOT)).and_then(|rest| rest.split_once(':')).and_then(|(_, f)| f.parse().ok()).unwrap_or(0) } +/// The name of the text slot for type that a look draws (`1 /FreeUndo`): [`TEXT_SLOT`] with no +/// story, as [`slot_of`] reads it. +pub(crate) const LOOK_SLOT: &str = "\u{0}text:look"; + /// The artboards (names, and rects in art space) of the editing data `data` that [`read`] can't /// read as a whole, as far as it gets: where to put the pages of its PDF part instead, and what to -/// call them (#1068). -pub fn artboards(data: &[u8]) -> Vec<(String, Rect)> { +/// call them (#1068); and the index among them of the active artboard (`CropAreaActive`). +pub fn artboards(data: &[u8]) -> (Vec<(String, Rect)>, Option) { let found = artboards_read(data); - if !found.is_empty() { + if !found.0.is_empty() && found.1.is_some() { return found; } - // Reading can stop before the artboards (art kept in the document's data comes first): read - // their array on its own. - artboard_array(data).map_or(found, |array| { - let mut alone = b"%_/Document :\n%_/Dictionary :\n".to_vec(); - alone.extend_from_slice(array); - alone.extend_from_slice(b"\n%_; /NotRecorded ,\n%_;\n"); - artboards_read(&alone) - }) + // Reading can stop before the artboards (art kept in the document's data comes first), or + // between them and the active artboard's entry: read their array on its own. + let Some((boards, active)) = artboard_array_read(data) else { return found }; + if found.0.is_empty() { + (boards, active) + } else if boards == found.0 { + // The same array: its names and rects read alike. + (found.0, active) + } else { + found + } } +/// The index of the active artboard (`CropAreaActive`) in the `ArtboardArray` of the editing data +/// `data`, as [`artboards`] reads it, from that array and the entry beside it alone. +pub fn active_artboard(data: &[u8]) -> Option { + artboard_array_read(data)?.1 +} + +/// Artboards as [`artboards`] gives them: names and rects in art space, and the active one's index. +type ArtboardsRead = (Vec<(String, Rect)>, Option); + +/// The `ArtboardArray` entry of the editing data `data` ([`artboard_array`]), with the +/// `CropAreaActive` entry beside it, read on their own as [`artboards_read`] reads them. +fn artboard_array_read(data: &[u8]) -> Option { + let (array, active) = artboard_array(data)?; + let mut alone = b"%_/Document :\n%_/Dictionary :\n".to_vec(); + alone.extend_from_slice(array); + if let Some(active) = active { + alone.push(b'\n'); + alone.extend_from_slice(active); + } + alone.extend_from_slice(b"\n%_; /NotRecorded ,\n%_;\n"); + Some(artboards_read(&alone)) +} + +/// The key that ends the `ArtboardArray` entry of the editing data. +const ARTBOARD_ARRAY: &[u8] = b"%_; (ArtboardArray) ,"; + /// The `ArtboardArray` entry of the editing data `data`, from its `/Array :` to its key: found -/// from the key back, counting the dictionaries its artboards open and close. -fn artboard_array(data: &[u8]) -> Option<&[u8]> { - const KEY: &[u8] = b"%_; (ArtboardArray) ,"; - let end = data.windows(KEY.len()).rposition(|w| w == KEY)? + KEY.len(); +/// from the key back, counting the dictionaries its artboards open and close; and the +/// `CropAreaActive` entry of the dictionary that holds it ([`crop_area_active`]). +fn artboard_array(data: &[u8]) -> Option<(&[u8], Option<&[u8]>)> { + let end = data.windows(ARTBOARD_ARRAY.len()).rposition(|w| w == ARTBOARD_ARRAY)? + ARTBOARD_ARRAY.len(); let head = data.get(..end)?; let mut depth = 0usize; let mut line_end = head.len(); @@ -65,7 +202,10 @@ fn artboard_array(data: &[u8]) -> Option<&[u8]> { } else if text.starts_with(b"/") && text.windows(2).any(|w| w == b" :") { depth = depth.checked_sub(1)?; if depth == 0 { - return head.get(line_start..); + let breaks = |b: &u8| *b == b'\n' || *b == b'\r'; + let after = data.get(end..).and_then(|rest| crop_area_active(rest.split(breaks), true)); + let active = after.or_else(|| data.get(..line_start).and_then(|before| crop_area_active(before.rsplit(breaks), false))); + return Some((head.get(line_start..)?, active)); } } } @@ -73,33 +213,116 @@ fn artboard_array(data: &[u8]) -> Option<&[u8]> { } } +/// The `CropAreaActive` entry (`%_ /Int (CropAreaActive) ,`) among the entries of the dictionary +/// that holds the `ArtboardArray` entry, skipping the dictionaries and arrays inside it: `lines` are +/// the lines after that entry, in order (`forward`), or those before it, last first. +fn crop_area_active<'a>(lines: impl Iterator, forward: bool) -> Option<&'a [u8]> { + const KEY: &[u8] = b" /Int (CropAreaActive) ,"; + let mut depth = 0usize; + for line in lines { + let Some(text) = line.strip_prefix(b"%_") else { continue }; + let closes = text.starts_with(b";") || text.starts_with(b"/Def ;"); + let opens = !closes && text.starts_with(b"/") && text.windows(2).any(|w| w == b" :"); + let (enters, leaves) = if forward { (opens, closes) } else { (closes, opens) }; + if enters { + // Into a dictionary or array inside the holder. + depth += 1; + } else if leaves { + // Out of one, or out of the holder itself. + depth = depth.checked_sub(1)?; + } else if depth == 0 { + let digits = text.iter().take_while(|b| b.is_ascii_digit()).count(); + if digits > 0 && text.get(digits..) == Some(KEY) { + return Some(line); + } + } + } + None +} + /// The palette of a `.ai` file's editing data, as [`palette`] reads it. pub struct PaletteSwatches { pub swatches: Vec, pub groups: Vec, - /// The patterns the editing data defines that the given patterns lack and a swatch paints with. + /// The patterns the editing data defines that a swatch paints with, named apart from the given + /// patterns ([`beside`]). pub patterns: Vec, /// The image blobs the art of `patterns` shows, by key. pub images: std::collections::BTreeMap, } +/// The editing data's patterns `defined`, for a document that has the patterns `have` (those of a +/// file's PDF part or page): each keeps its name, except one whose name a pattern of `have` already +/// has (the PDF part names its tilings `Pattern 1`, `Pattern 2` and so on), which takes a free +/// variant (`Pattern 1 2`). The art of each pattern paints with the names they got. Also the names +/// changed, old to new. The same `defined` and `have` always give the same names. +fn beside(mut defined: Vec, have: &[PatternDef]) -> (Vec, std::collections::BTreeMap) { + let mut renamed = std::collections::BTreeMap::new(); + let mut taken: std::collections::BTreeSet = have.iter().chain(&defined).map(|p| p.name.clone()).collect(); + let tries = taken.len() + 2; + for d in &mut defined { + if !have.iter().any(|p| p.name == d.name) { + continue; + } + let Some(name) = (2..=tries).map(|i| format!("{} {i}", d.name)).find(|n| !taken.contains(n)) else { continue }; + taken.insert(name.clone()); + renamed.insert(std::mem::replace(&mut d.name, name.clone()), name); + } + if !renamed.is_empty() { + for d in &mut defined { + for a in &mut d.art { + repoint(Arc::make_mut(a), &renamed); + } + } + } + (defined, renamed) +} + +/// `n` and what it holds painting with the patterns `renamed` renames (old to new) by their new names. +fn repoint(n: &mut Node, renamed: &std::collections::BTreeMap) { + for p in vectorcraft_doc::swatches::node_paints_mut(n) { + if let Paint::Pattern { pattern, .. } = p + && let Some(new) = renamed.get(pattern) + { + pattern.clone_from(new); + } + } + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + repoint(Arc::make_mut(&mut mask.art), renamed); + } + if let Some(children) = n.children_mut() { + for c in children { + repoint(Arc::make_mut(c), renamed); + } + } +} + /// The swatches and color groups of the palette of the editing data `data`, for a file whose /// layers aren't read: the swatches its PDF part has are the defaults (#4036). They come as /// [`read`] makes them, with pattern swatches only for the patterns in `patterns` and those the -/// editing data defines; `None` when the palette is empty or reading stops before it. +/// editing data defines, which are named apart from `patterns` ([`beside`]); `None` when the +/// palette is empty or reading stops before it. pub fn palette(data: &[u8], patterns: &[PatternDef]) -> Option { - let mut r = Reader::new(data); + let mut r = Reader::with_names(data); // The palette, the gradients and the patterns it names come before the art, so an error in the // art leaves them read. let _ = r.run(); + let (defined, renamed) = beside(std::mem::take(&mut r.doc.patterns), patterns); let mut known = patterns.to_vec(); - let defined = std::mem::take(&mut r.doc.patterns); - known.extend(defined.iter().filter(|d| !patterns.iter().any(|p| p.name == d.name)).cloned()); - let (swatches, groups) = r.palette_swatches(&known)?; + known.extend(defined.iter().cloned()); + let (mut swatches, mut groups) = r.palette_swatches(&known)?; + // A swatch of a pattern the editing data defines paints with that pattern, under the name it got. + for s in swatches.iter_mut().chain(groups.iter_mut().flat_map(|g| &mut g.swatches)) { + if let Paint::Pattern { pattern, .. } = &mut s.paint + && let Some(new) = renamed.get(pattern) + { + pattern.clone_from(new); + } + } let painted = |name: &str| { swatches.iter().chain(groups.iter().flat_map(|g| &g.swatches)).any(|s| matches!(&s.paint, Paint::Pattern { pattern, .. } if pattern == name)) }; - let added: Vec = defined.into_iter().filter(|d| !patterns.iter().any(|p| p.name == d.name) && painted(&d.name)).collect(); + let added: Vec = defined.into_iter().filter(|d| painted(&d.name)).collect(); let mut shown = Document::new(1.0, 1.0); shown.patterns.clone_from(&added); let mut images = std::collections::BTreeMap::new(); @@ -111,9 +334,147 @@ pub fn palette(data: &[u8], patterns: &[PatternDef]) -> Option Some(PaletteSwatches { swatches, groups, patterns: added, images }) } +/// The brushes of a `.ai` file's editing data, as [`brushes`] reads them. +pub struct Brushes { + pub brushes: Vec, + /// The patterns the editing data defines that the brushes' art paints with, named apart from + /// the given patterns ([`beside`]). + pub patterns: Vec, + /// The image blobs the art of `patterns` shows, by key. + pub images: std::collections::BTreeMap, + /// The note for the brushes left out. + pub note: Option, +} + +/// The brushes of the editing data `data`, for a file whose layers aren't read (a brush library +/// has none), as [`read`] makes them, with the patterns of the editing data their art paints with, +/// named apart from `patterns` ([`beside`]) as [`palette`] names them. `None` when the file has no +/// brush objects or reading stops before them. +pub fn brushes(data: &[u8], patterns: &[PatternDef]) -> Option { + // Brush objects are plug-in objects: data without one isn't read again. + memchr::memmem::find(data, b"BeginPluginObject")?; + let mut r = Reader::with_names(data); + // The brushes come before the art, so an error in the art leaves them read. + let _ = r.run(); + let (mut lib, unread) = r.brush_library()?; + let (defined, renamed) = beside(std::mem::take(&mut r.doc.patterns), patterns); + if !renamed.is_empty() { + for a in lib.iter_mut().flat_map(|b| b.art_mut()) { + repoint(a, &renamed); + } + } + // The patterns the brushes' art paints with, and those their art paints with, and so on. + let mut stack: Vec<&vectorcraft_doc::Node> = lib.iter().flat_map(|b| b.art()).collect(); + let mut used = std::collections::BTreeSet::new(); + while let Some(n) = stack.pop() { + stack.extend(n.children().into_iter().flatten().chain(n.extras().mask.as_ref().map(|m| &m.art)).map(|c| &**c)); + for p in vectorcraft_doc::swatches::node_paints(n) { + if let Paint::Pattern { pattern, .. } = p + && used.insert(pattern.clone()) + && let Some(d) = defined.iter().find(|d| &d.name == pattern) + { + stack.extend(d.art.iter().map(|a| &**a)); + } + } + } + let added: Vec = defined.into_iter().filter(|d| used.contains(&d.name)).collect(); + let mut shown = Document::new(1.0, 1.0); + shown.patterns.clone_from(&added); + let mut images = std::collections::BTreeMap::new(); + shown.visit_images(|_, im| { + if let Some(blob) = r.doc.images.get(&im.key) { + images.insert(im.key.clone(), blob.clone()); + } + }); + Some(Brushes { brushes: lib, patterns: added, images, note: (unread > 0).then(|| brush::left_out_note(unread)) }) +} + +/// The graphic styles of the editing data `data`, for a file whose layers aren't read (a graphic +/// style library has none), as [`read`] makes them, with ids from 1, and the data's declared large +/// canvas scale (1 when it declares none). `large_canvas`: as [`read`] takes it. The styles are +/// those the list names before reading stops, and none when the data has no style list or lists no +/// style this reads. +pub fn graphic_styles(data: &[u8], large_canvas: bool) -> (Vec, f64) { + if crate::import::ai::find(data, b"BeginArtStyleList").is_none() { + return (vec![], 1.0); + } + let mut r = Reader::with_names(data); + r.large_canvas = large_canvas.then_some(1.0); + // The styles come before the art, so an error in the art leaves them read. + let _ = r.run(); + (r.graphic_styles().0, r.canvas_scale) +} + +/// The symbols of a `.ai` file's editing data, as [`symbols`] reads them. +pub struct Symbols { + /// The symbols in the Symbols panel's order, each with its Symbol Options › Registration. + pub symbols: Vec<(Symbol, vectorcraft_doc::SymbolRegistration)>, + /// The image blobs the symbols' art shows, by key. + pub images: std::collections::BTreeMap, + /// The global and spot colors the symbols' art is linked to, as swatches, as [`read`] adds + /// them to a document read from the layers. + pub swatches: Vec, +} + +/// The symbols of the editing data `data`, for a file whose layers aren't read (a symbol library +/// has none), as [`read`] makes them: in the symbol list's order, without those that hold an +/// instance of a symbol the data doesn't define, and with each object of their art that is linked +/// to a listed graphic style linked to it by the id [`graphic_styles`] gives that style. The +/// symbols are those defined before reading stops and before the first layer; `None` when there +/// are none. +pub fn symbols(data: &[u8]) -> Option { + crate::import::ai::find(data, b"BeginSymbol")?; + let mut r = Reader::with_names(data); + // The symbols come before the art, so an error in the art leaves them read. + let _ = r.run(); + r.check_symbols(); + r.order_symbols(); + if r.doc.symbols.is_empty() { + return None; + } + let (styles, ids) = r.graphic_styles(); + let links: HashMap = r.style_links.iter().filter_map(|(node, name)| Some((*node, *ids.get(name)?))).collect(); + if !links.is_empty() { + for symbol in &mut r.doc.symbols { + link_styles(std::slice::from_mut(&mut symbol.art), &links, &styles, 0); + } + } + let mut shown = Document::new(1.0, 1.0); + shown.symbols = std::mem::take(&mut r.doc.symbols); + let mut images = std::collections::BTreeMap::new(); + shown.visit_images(|_, im| { + if let Some(blob) = r.doc.images.get(&im.key) { + images.insert(im.key.clone(), blob.clone()); + } + }); + // The colors the art is linked to that the file defines, once each. + let mut linked = std::collections::HashSet::new(); + for s in &mut shown.symbols { + vectorcraft_doc::swatches::map_node_solid_paints(Arc::make_mut(&mut s.art), &mut |_, link, _| { + linked.extend(link.clone()); + false + }); + } + let mut swatches: Vec = vec![]; + let colors = r.spots.iter().chain(&r.stop_spots).map(|n| (n, n.spot)).chain(r.custom_colors.iter().map(|n| (n, true))); + for (n, spot) in colors { + if linked.remove(&n.name) { + swatches.push(Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot }); + } + } + let symbols = std::mem::take(&mut shown.symbols) + .into_iter() + .map(|s| { + let reg = r.doc.symbol_registration(&s.name); + (s, reg) + }) + .collect(); + Some(Symbols { symbols, images, swatches }) +} + /// [`artboards`] as far as reading `data` from its start gets: those read before an error, and /// those of a `/Document` still open when it stopped (its art can be what stopped it). -fn artboards_read(data: &[u8]) -> Vec<(String, Rect)> { +fn artboards_read(data: &[u8]) -> (Vec<(String, Rect)>, Option) { let mut r = Reader::new(data); let _ = r.run(); let open: Vec = r.frames.iter().filter_map(|f| if let Kind::Obj(o) = &f.kind { Some((**o).clone()) } else { None }).collect(); @@ -122,45 +483,72 @@ fn artboards_read(data: &[u8]) -> Vec<(String, Rect)> { r.document(o); } } - r.artboards + let active = r.active_board.filter(|i| *i < r.artboards.len()); + (r.artboards.into_iter().map(|b| (b.name, b.rect)).collect(), active) } -/// How many variables and data sets the variable library of the editing data has: XML nodes -/// (`/XMLNode`) of the `/Document` dictionary, a `variableSets` element holding `variableSet`s, each -/// with its `variables` (`variable` elements) and `sampleDataSets` (`sampleDataSet` elements). -/// VectorCraft doesn't read them. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct VariableLibrary { - pub variables: usize, - pub data_sets: usize, +/// An object bound to a variable of the library: the variable's name, and the XML id of the object +/// (the `AI10_ArtUID` of its dictionary). The id is `None` when the reference can't be read. +#[derive(Clone, Debug, PartialEq)] +pub struct BindingRef { + pub variable: String, + pub target: Option, } -impl VariableLibrary { - /// The import's note that the library wasn't read, when it has a variable or a data set. - pub fn note(self) -> Option { - let Self { variables, data_sets } = self; - // Counts after a colon need no plural, so every language can translate the note whole. - (variables + data_sets > 0).then(|| { - format!("the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them") - }) +/// The variable library of the editing data, as [`variable_library`] reads it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct VariableRead { + /// Its variables, data sets, active data set and lock, without bindings. + pub variables: Variables, + /// The objects bound to its variables, in the order the library declares them. + pub bindings: Vec, + /// How many objects its declarations bind that aren't in `bindings`: those of a declaration + /// left out, and those past [`MAX_LIBRARY_BINDINGS`]. + pub bindings_skipped: usize, + /// How many of its declarations, data sets, values and settings were left out. + pub skipped: usize, + /// Whether the editing data has a variable library (a `variableSets` element). + pub present: bool, +} + +/// The import's note about the library's bindings when `skipped` of them weren't made: nothing +/// when all of them were. +pub fn bindings_note(skipped: usize) -> Option { + // A count after a colon needs no plural, so every language can translate the note whole. + (skipped > 0).then(|| { + format!("the file's variable bindings weren't all read (bindings skipped: {skipped}): those objects aren't bound to their variables") + }) +} + +impl VariableRead { + /// The import's note about what of the library wasn't read: nothing when all of it was. + pub fn note(&self) -> Option { + if !self.present || self.skipped == 0 { + return None; + } + if self.variables.variables.is_empty() && self.variables.datasets.is_empty() { + return Some("the file's variable library couldn't be read: the Variables panel doesn't list it".into()); + } + // A count after a colon needs no plural, so every language can translate the note whole. + Some(format!("the file's variable library was partly read (entries skipped: {}): the Variables panel lists the rest", self.skipped)) } } -/// The variable library of the editing data `data` ([`VariableLibrary`]), for a file whose layers +/// The variable library of the editing data `data` ([`VariableRead`]), for a file whose layers /// [`read`] can't read. Data without a `variableSets` element isn't read. -pub fn variables(data: &[u8]) -> VariableLibrary { +pub fn variables(data: &[u8]) -> VariableRead { if crate::import::ai::find(data, b"variableSets").is_none() { - return VariableLibrary::default(); + return VariableRead::default(); } let mut r = Reader::new(data); let _ = r.run(); + if r.variables.present { + return r.variables; + } // A `/Document` still open when reading stopped. let open: Vec = r.frames.iter().filter_map(|f| if let Kind::Obj(o) = &f.kind { Some((**o).clone()) } else { None }).collect(); - for o in open.iter().filter(|o| o.ty == "Document") { - variable_library(o, 0, &mut r.variables); - } - if r.variables != VariableLibrary::default() { - return r.variables; + if let Some(found) = open.iter().filter(|o| o.ty == "Document").map(variable_library).find(|v| v.present) { + return found; } // Reading can stop before the library: read its node on its own. variable_sets_node(data).map_or(r.variables, |node| { @@ -173,6 +561,40 @@ pub fn variables(data: &[u8]) -> VariableLibrary { }) } +impl<'a> Reader<'a> { + /// Take the author and custom colors that the header of a program gives (`outer`, from + /// [`Self::header_of`]), where the editing data's own header gives none: the program of an EPS + /// whose editing data is kept apart from it. + pub(super) fn program_header(&mut self, outer: Reader<'_>) { + if self.author.is_none() { + self.author = outer.author; + } + for n in outer.custom_colors { + if self.custom_colors.len() < super::directives::MAX_CUSTOM_COLORS && !self.custom_colors.iter().any(|c| c.name == n.name) { + self.custom_colors.push(n); + } + } + } + + /// A reader that has read the header of the program `ps` (its comment lines up to + /// `%%EndComments`). + pub(super) fn header_of(ps: &[u8]) -> Reader<'_> { + let mut end = 0; + for line in ps.split_inclusive(|&b| b == b'\n' || b == b'\r') { + if !line.starts_with(b"%") && !line.trim_ascii().is_empty() { + break; + } + end += line.len(); + if line.trim_ascii_end() == b"%%EndComments" { + break; + } + } + let mut outer = Reader::new(ps.get(..end).unwrap_or_default()); + let _ = outer.run(); + outer + } +} + /// The `variableSets` XML node of the editing data `data`, from its `/XMLNode :` line to the line /// that closes it: found from its name back, counting the dictionaries and arrays it holds. fn variable_sets_node(data: &[u8]) -> Option<&[u8]> { @@ -217,10 +639,47 @@ fn variable_sets_node(data: &[u8]) -> Option<&[u8]> { } } +/// The text wrap options an object's dictionary gives: its offset in points (`AI11TextWrapOffset`, +/// times `scale`, the factor that takes the art onto the document) and Invert Wrap +/// (`AI11TextWrapInvert`). The outline the file may keep with them (`AI11TextWrapPath`) is not +/// read: the object's own shape gives it. A value that isn't a number is left at its default, and +/// a dictionary without a readable entry gives none. +fn text_wrap(o: &Obj, scale: f64) -> Option { + let num = |key: &str| o.get(key).and_then(|v| v.iter().find_map(V::num)).filter(|v| v.is_finite()); + let offset = num("AI11TextWrapOffset"); + let invert = num("AI11TextWrapInvert").filter(|v| *v == 0.0 || *v == 1.0); + if offset.is_none() && invert.is_none() && o.get("AI11TextWrapPath").is_none() { + return None; + } + let default = TextWrap::default(); + let offset = offset.map(|v| v * scale).filter(|v| !v.is_nan()).map_or(default.offset, |v| v.clamp(-1000.0, 1000.0)); + Some(TextWrap { offset, invert: invert == Some(1.0) }) +} + impl<'a> Reader<'a> { - /// An object's dictionary: its name (`AIArtName`, or the XML id `AI10_ArtUID`), and the - /// opacity mask it may carry. + /// An object's dictionary: its name (`AIArtName`, or the XML id `AI10_ArtUID`), the opacity + /// mask it may carry, and in a pattern's definition the mark of the tile's box + /// (`AIPattern_Editor_Backing_Tile_Rect`), which leaves that box out of the art. pub(super) fn art_dictionary(&mut self, o: &Obj) { + // The unpainted box that a pattern's definition marks as its tile's box isn't art. + if self.pattern.is_some() + && o.nums("AIPattern_Editor_Backing_Tile_Rect").first().copied() == Some(1.0) + && self.after_object + && let Some(f) = self.frames.last_mut() + && f.children.last().is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }) && n.appearance.items.iter().all(|i| i.paint().is_none())) + { + f.children.pop(); + return; + } + // The dictionary after a symbol's art: its registration point. + if self.frames.len() == 1 + && let Some(head) = self.symbol.as_mut() + && let Some(r) = o.nums("AI13PatternRegistrationType").first() + { + head.registration = Some(*r); + } + self.constraint_art(o); + self.placed_page(o); // A blend's key object or spine. if let Some(kind) = o.text("ShapeBlendPathType") && let Some(id) = self.last_object().map(|n| n.id) @@ -229,9 +688,10 @@ impl<'a> Reader<'a> { self.blend_roles.insert(id, (kind, o.text("ShapeBlendPathID"))); } // An envelope (a distortion, `AIDeformStyle` / `DeformValue`) is written on `%_` lines as - // a group holding the mesh that shapes it; the distorted art the file's PDF part draws - // follows on plain lines. That mesh isn't art, so it goes (#2405). - if (o.get("AIDeformStyle").is_some() || o.get("DeformValue").is_some()) && self.drop_envelope_mesh() { + // a group holding the mesh that shapes it (or its contents, while they are being edited); + // the distorted art the file's PDF part draws follows on plain lines. That group isn't + // art, so it goes (#2405), kept aside for the live envelope ([`Reader::end_envelope`]). + if (o.get("AIDeformStyle").is_some() || o.get("DeformValue").is_some()) && self.drop_envelope_art() { return; } if let Some(mask) = o.obj("AI9_Mask").or_else(|| o.obj("Mask")) { @@ -240,14 +700,38 @@ impl<'a> Reader<'a> { let value = OpacityMask { art: art.clone(), clip: on("Clipping"), invert: on("Inverted"), disabled: on("Disabled"), linked: on("Linked") }; if let Some(n) = self.last_object().filter(|n| !matches!(n.kind, NodeKind::Layer { .. })) { - n.extras_mut().mask = Some(Box::new(value)); + n.extras_mut().mask = Some(Box::new(value.clone())); + self.each_linked_frame(|n| n.extras_mut().mask = Some(Box::new(value.clone()))); } else if !on("Disabled") { - self.unreadable("opacity masks without an owning object"); + self.unreadable("opacity masks without an owning object", false); + } + // What the art doesn't read matters only when the mask shapes what shows. + for what in &mask.unread { + if on("Disabled") { + self.hidden_unread.insert(what.clone()); + } else if let Some(op) = what.strip_prefix('`').and_then(|w| w.strip_suffix('`')) { + self.note_unknown(op, false); + } else { + self.unreadable(what, false); + } } } else if mask.nums("Disabled").first().copied() != Some(1.0) { - self.unreadable("opacity masks without readable art"); + self.unreadable("opacity masks without readable art", false); } } + // Text wrap: area type below the object in its layer flows around it. + if let Some(wrap) = text_wrap(o, self.large_canvas.unwrap_or(1.0)) + && let Some(n) = self.last_object().filter(|n| !matches!(n.kind, NodeKind::Layer { .. })) + { + n.extras_mut().wrap = Some(wrap); + self.each_linked_frame(|n| n.extras_mut().wrap = Some(wrap)); + } + // The object's XML id, which the variable library's bindings name it by. + if let Some(uid) = o.obj("AI10_ArtUID").and_then(Obj::content_text).filter(|u| !u.is_empty()) + && let Some(id) = self.last_object().filter(|n| !matches!(n.kind, NodeKind::Layer { .. })).map(|n| n.id) + { + super::remember_xml_id(&mut self.xml_ids, &mut self.xml_id_bytes, uid, id); + } let name = match o.text("AIArtName") { Some(name) => name, None => match o.obj("AI10_ArtUID").and_then(Obj::content_text) { @@ -264,11 +748,20 @@ impl<'a> Reader<'a> { } } - /// The `/Document` dictionary: the artboards, and how many variables and data sets its variable - /// library has. + /// The `/Document` dictionary: the artboards and their display options, the active artboard + /// (`CropAreaActive`, `/Int`: its index in the `ArtboardArray`, next to it), Document Raster + /// Effects Settings, its variable library (the first one read), and its Objects on Path records. pub(super) fn document(&mut self, o: &Obj) { - variable_library(o, 0, &mut self.variables); - let Some(list) = find_entry(o, "ArtboardArray", 0) else { return }; + if !self.variables.present { + self.variables = variable_library(o); + } + self.constraint_data(o); + if let Some(r) = find_entry(o, "AI Auto Rasterize", 0) { + raster_settings(r, &mut self.doc); + } + let Some(holder) = find_holder(o, "ArtboardArray", 0) else { return }; + let Some(list) = holder.obj("ArtboardArray") else { return }; + let active = typed(holder, "CropAreaActive", "Int"); for (i, ab) in list.items().enumerate().take(1000) { let (p1, p2) = (ab.nums("PositionPoint1"), ab.nums("PositionPoint2")); let ([x0, y0, ..], [x1, y1, ..]) = (p1.as_slice(), p2.as_slice()) else { continue }; @@ -277,7 +770,12 @@ impl<'a> Reader<'a> { continue; } let name = ab.text("Name").unwrap_or_else(|| format!("Artboard {}", i + 1)); - self.artboards.push((name, r)); + let mut board = AiArtboard::new(name, r); + display_options(ab, &mut board); + if active == Some(i as f64) { + self.active_board = Some(self.artboards.len()); + } + self.artboards.push(board); } } @@ -298,7 +796,13 @@ impl<'a> Reader<'a> { /// The first artboard: the `/Document`'s first, else the crop marks, else [`Self::sized_board`]. fn first_board(&self) -> Option { - self.artboards.first().map(|(_, r)| *r).or(self.cropmarks).or_else(|| self.sized_board()) + self.artboards.first().map(|b| b.rect).or(self.cropmarks).or_else(|| self.sized_board()) + } + + /// The page the art is compared with in the document's space, once the art has started. + pub(super) fn page_in_doc(&self) -> Option { + let board = self.first_board().or_else(|| self.bbox_board())?; + Some(self.to_doc?.transform_rect_bbox(board)) } /// The page of a file that says nothing of its artboard (the legacy format as other apps write @@ -324,9 +828,50 @@ impl<'a> Reader<'a> { } /// Art space → where the art being read goes: the document, or while a pattern's definition is - /// read, the pattern's space (y down). + /// read, the pattern's space (y down). A symbol's definition is written in the symbol's space. pub(crate) fn space(&mut self) -> Affine { - if self.pattern.is_some() { FLIP } else { self.ensure_space() } + if self.pattern.is_some() { + FLIP + } else if self.symbol.is_some() { + Affine::IDENTITY + } else { + self.ensure_space() + } + } + + /// The space an image's matrix is in → where the art being read goes: [`Self::space`], and in a + /// symbol's art (outside a pattern's definition) the canvas's space turned y up about art space's + /// origin there, as an instance's matrix in it is; `None` there without a template box. + pub(super) fn image_space(&mut self) -> Option { + if self.pattern.is_none() && self.symbol.is_some() { + return self.canvas_origin().map(|o| Affine::new([1.0, 0.0, 0.0, -1.0, o.x, o.y])); + } + Some(self.space()) + } + + /// The canvas point of art space's origin, from the template box's center (the canvas's): what + /// a pattern's gradients and the instances in a symbol's art are written about. + pub(super) fn canvas_origin(&self) -> Option { + let t = self.template?; + let (cx, cy) = ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0); + let origin = Point::new(CANVAS_CENTRE - cx, CANVAS_CENTRE + cy); + (origin.x.is_finite() && origin.y.is_finite()).then_some(origin) + } + + /// The symbols in the symbol list's order, those it doesn't name after them as they were + /// defined; names it has twice or that no symbol has don't count. + fn order_symbols(&mut self) { + let Some(list) = self.symbol_list.take() else { return }; + let mut slots: Vec> = std::mem::take(&mut self.doc.symbols).into_iter().map(Some).collect(); + let at: HashMap = slots.iter().enumerate().filter_map(|(i, s)| s.as_ref().map(|s| (s.name.clone(), i))).collect(); + let mut ordered = Vec::with_capacity(slots.len()); + for name in &list { + if let Some(s) = self.symbol_names.get(name).and_then(|named| at.get(named)).and_then(|i| slots.get_mut(*i)).and_then(Option::take) { + ordered.push(s); + } + } + ordered.extend(slots.into_iter().flatten()); + self.doc.symbols = ordered; } /// The swatches of the palette, `[None]` first, in its order, and its color groups; a gradient @@ -337,18 +882,27 @@ impl<'a> Reader<'a> { return None; } let palette = std::mem::take(&mut self.palette); - let swatch = |e: crate::import::ai::palette::Entry| -> Option { + let swatch = |mut e: crate::import::ai::palette::Entry| -> Option { use crate::import::ai::palette::Cell; let (paint, global, spot) = match e.cell { Cell::Color { color, global, spot } => (Paint::solid(color), global, spot), + // A swatch named by its gradient or pattern takes the name that got in the document. + // A gradient swatch's own paint does not link to a swatch; art painted with the + // gradient links to it. Cell::Gradient(g) => { - let mut gp = vectorcraft_color::gradient::GradientPaint::new(self.gradients.get(&g)?.clone()); - gp.swatch = Some(e.name.clone()); + let gp = vectorcraft_color::gradient::GradientPaint::new(self.gradients.get(&g)?.clone()); + if e.name == g { + e.name = self.global_names.get(Global::Gradient, &g).to_string(); + } (Paint::Gradient(Box::new(gp)), false, false) } Cell::Pattern(p) => { - patterns.iter().find(|d| d.name == p)?; - (Paint::Pattern { pattern: p, xf: Affine::IDENTITY }, false, false) + let pattern = self.global_names.get(Global::Pattern, &p).to_string(); + patterns.iter().find(|d| d.name == pattern)?; + if e.name == p { + e.name.clone_from(&pattern); + } + (Paint::Pattern { pattern, xf: Affine::IDENTITY }, false, false) } }; Some(Swatch { name: e.name, paint, global, spot }) @@ -363,7 +917,177 @@ impl<'a> Reader<'a> { Some((swatches, groups)) } + /// The swatches of the file's named colors and patterns, added to `doc`'s, and the new name of + /// each color that took a numbered one. + /// + /// The colour operators' definitions come first: a gradient, defined before the art, names a + /// global process colour as a stop and would otherwise make it an ink (#1771). The header's + /// custom colors follow. The first definition of a name makes its swatch, and takes the place + /// of a default swatch of that name when the file has no palette of its own (`own_palette`; a + /// reserved name in brackets, such as `[None]`, keeps its swatch). Then each pattern gets a + /// swatch. A color whose name a gradient or pattern swatch of the palette has, and a pattern + /// whose name another swatch has, take the first free "Name 2", "Name 3"… + /// ([`Document::free_swatch_name`]) once the other colors and the patterns have their swatches; + /// a pattern a swatch already paints with gets no other. + fn file_swatches(&self, doc: &mut Document, own_palette: bool) -> HashMap { + let mut defined = std::collections::HashSet::new(); + let mut clashes = vec![]; + // The swatch names there are, looked up rather than scanned for each name a file defines + // (`Document::swatch` also knows the registration colour). + let mut have: std::collections::HashSet = doc.swatches_iter().map(|s| s.name.clone()).collect(); + have.insert(vectorcraft_color::swatch::REGISTRATION.to_string()); + // The names a swatch of another kind than a gradient or pattern has. + let mut solid: std::collections::HashSet = + doc.swatches_iter().filter(|s| !matches!(s.paint, Paint::Gradient(_) | Paint::Pattern { .. })).map(|s| s.name.clone()).collect(); + let colors = self.spots.iter().chain(&self.stop_spots).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true))); + for (n, spot) in colors { + let first = defined.insert(n.name.clone()); + let swatch = Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot }; + let reserved = n.name.starts_with('[') && n.name.ends_with(']'); + if have.insert(n.name.clone()) { + solid.insert(n.name.clone()); + doc.swatches.push(swatch); + } else if first && !reserved { + if !own_palette && let Some(default) = doc.swatch_mut(&n.name) { + *default = swatch; + solid.insert(n.name.clone()); + } else if !solid.contains(&n.name) { + clashes.push(swatch); + } + } + } + let mut unnamed = vec![]; + for pattern in doc.patterns.iter().map(|p| p.name.clone()).collect::>() { + if have.insert(pattern.clone()) { + doc.swatches.push(Swatch { + paint: Paint::Pattern { pattern: pattern.clone(), xf: Affine::IDENTITY }, + name: pattern, + global: false, + spot: false, + }); + } else { + unnamed.push(pattern); + } + } + // Every color and pattern name now has a swatch, so a numbered name takes none of them. The + // names taken and the patterns painted with are looked up rather than scanned for each one. + let mut taken: std::collections::HashSet = doc.swatches_iter().map(|s| s.name.clone()).collect(); + taken.extend(doc.swatch_groups.iter().map(|g| g.name.clone())); + taken.insert(vectorcraft_color::swatch::REGISTRATION.to_string()); + let mut painted: std::collections::HashSet = doc + .swatches_iter() + .filter_map(|s| match &s.paint { + Paint::Pattern { pattern, .. } => Some(pattern.clone()), + _ => None, + }) + .collect(); + let mut renamed = HashMap::new(); + for swatch in clashes { + let name = free_swatch_name(&mut taken, &swatch.name); + renamed.insert(swatch.name.clone(), name.clone()); + doc.swatches.push(Swatch { name, ..swatch }); + } + for pattern in unnamed { + if !painted.insert(pattern.clone()) { + continue; + } + let name = free_swatch_name(&mut taken, &pattern); + doc.swatches.push(Swatch { paint: Paint::Pattern { pattern, xf: Affine::IDENTITY }, name, global: false, spot: false }); + } + renamed + } + + /// The brushes read ([`brush::finish_brushes`]) and how many weren't; `None` when the file has + /// no brush objects (the document keeps the default brushes). The objects read as their drawn + /// look in the art the brushes use count toward the note on drawn looks, once for each art. + fn brush_library(&mut self) -> Option<(Vec, usize)> { + if !self.brush_objects { + return None; + } + let drafts = std::mem::take(&mut self.brush_drafts); + let (lib, left_out) = brush::finish_brushes(drafts, &self.brush_art, self.brush_order.as_deref()); + let used: std::collections::HashSet = lib.iter().flat_map(|b| b.art()).map(|a| a.id).collect(); + for (name, art) in &self.brush_art { + if used.contains(&art.id) { + self.drawn_looks += self.brush_art_looks.get(name).copied().unwrap_or(0); + } + } + Some((lib, left_out + self.brushes_unread)) + } + + /// Count the colors of the brush art that the brushes `lib` use after the colors read so far, + /// in the order the art was read: its spot colors make swatches, and its colors count toward + /// the color mode. Art that no brush of `lib` uses brings none of its colors. The art brings + /// at most [`brush::MAX_BRUSH_ART_COLORS`] different color names in all, each name's color + /// operators before its gradient stops, as [`Self::file_swatches`] takes them; its colors past + /// them still count toward the color mode. + fn count_brush_art_colors(&mut self, lib: &[vectorcraft_brush::Brush]) { + let used: std::collections::HashSet = lib.iter().flat_map(|b| b.art()).map(|a| a.id).collect(); + let mut names: Vec<(NodeId, String)> = self.brush_art.iter().filter(|(_, a)| used.contains(&a.id)).map(|(n, a)| (a.id, n.clone())).collect(); + names.sort(); + // The names brought so far: every section's color operators', then every section's stops'. + let mut brought = std::collections::HashSet::new(); + let mut stops = vec![]; + for (_, name) in names { + let Some(colors) = self.brush_art_colors.remove(&name) else { continue }; + for n in colors.spots { + if brought.contains(&n.name) || brought.len() >= brush::MAX_BRUSH_ART_COLORS { + continue; + } + brought.insert(n.name.clone()); + self.spots.push(n); + } + stops.push(colors.stop_spots); + self.cmyk_colors += colors.cmyk; + self.rgb_colors += colors.rgb; + } + for n in stops.into_iter().flatten() { + if brought.contains(&n.name) || brought.len() >= brush::MAX_BRUSH_ART_COLORS { + continue; + } + brought.insert(n.name.clone()); + self.stop_spots.push(n); + } + } + + /// The graphic styles of the style list, in its order: each listed name the art styles define with + /// an appearance [`appearance_from_art_style`] reads, once (a name listed again, empty or not + /// defined is left out), with ids from 1. Also the id of each kept name. + fn graphic_styles(&self) -> (Vec, HashMap) { + let mut styles: Vec = vec![]; + let mut ids = HashMap::new(); + for raw in &self.style_list { + let name = obj::text(raw); + if name.is_empty() || ids.contains_key(&name) { + continue; + } + let Some(st) = self.styles.get(&name) else { continue }; + let Some(mut appearance) = appearance_from_art_style(st) else { continue }; + // A Large Canvas copy's styles are at its art's scale ([`Self::ensure_space`]). + if let Some(s) = self.large_canvas.filter(|s| *s != 1.0) { + appearance.scale_strokes(s); + appearance.scale_effects(s, vectorcraft_effects::scale_effect); + } + let id = u32::try_from(styles.len() + 1).unwrap_or(u32::MAX); + ids.insert(name.clone(), id); + let mut style = GraphicStyle { id, ..GraphicStyle::new(name, appearance) }; + if let Some((opacity, blend, isolate, knockout)) = st.transparency { + (style.opacity, style.blend, style.isolate, style.knockout) = (opacity, blend, isolate, knockout); + } + styles.push(style); + } + (styles, ids) + } + pub(super) fn finish(mut self) -> Result { + if self.graph.take().is_some() { + self.warn(super::types::GRAPH_UNENDED); + } + // Envelopes whose plugin never closed them keep their drawn art. + if !self.envelopes.is_empty() { + self.envelopes.clear(); + self.warn(crate::import::ai::envelope::DRAWN); + } if !self.unknown.is_empty() { let ops: Vec = self.unknown.iter().map(|o| format!("`{o}`")).collect(); self.unsupported.insert(format!("operators VectorCraft doesn't know ({})", ops.join(", "))); @@ -377,25 +1101,33 @@ impl<'a> Reader<'a> { } let to_doc = self.ensure_space(); let artboard = self.first_board(); + // Before the artboards are taken below: the page is the first artboard's. + let page = self.page_in_doc(); + self.check_symbols(); + self.order_symbols(); drop_commented_copies(&mut self.doc.layers, &self.hidden_ids); + super::on_path::apply(&mut self.doc, &self.on_path); let mut doc = std::mem::replace(&mut self.doc, Document::new(1.0, 1.0)); - let boards: Vec<(String, Rect)> = if self.artboards.is_empty() { - artboard.or_else(|| self.bbox_board()).map(|r| vec![("Artboard 1".to_string(), r)]).unwrap_or_default() + // The active artboard, when it is not the first (the default). + let active = self.active_board.filter(|i| *i > 0 && *i < self.artboards.len()); + let boards: Vec = if self.artboards.is_empty() { + artboard.or_else(|| self.bbox_board()).map(|r| vec![AiArtboard::new("Artboard 1".to_string(), r)]).unwrap_or_default() } else { - self.artboards.clone() + std::mem::take(&mut self.artboards) }; + let board_rects: Vec = boards.iter().map(|b| b.rect).collect(); doc.artboards = boards .into_iter() .enumerate() - .map(|(i, (name, r))| Artboard { + .map(|(i, b)| Artboard { id: i as u32 + 1, - name, - rect: to_doc.transform_rect_bbox(r), + name: b.name, + rect: to_doc.transform_rect_bbox(b.rect), locked: false, - show_center_mark: false, - show_cross_hairs: false, - show_video_safe_areas: false, - video_ruler_pixel_aspect_ratio: 1.0, + show_center_mark: b.center_mark, + show_cross_hairs: b.cross_hairs, + show_video_safe_areas: b.safe_areas, + video_ruler_pixel_aspect_ratio: b.par, color: None, }) .collect(); @@ -413,6 +1145,27 @@ impl<'a> Reader<'a> { color: None, }]; } + doc.opened_artboard = active.and_then(|i| doc.artboards.get(i)).map(|a| a.id); + if !self.ruler_guides.is_empty() { + let ids: Vec = doc.artboards.iter().map(|a| a.id).collect(); + let (candidates, centre) = (std::mem::take(&mut self.ruler_guides), self.template_center); + let pick = |id: NodeId| -> Option { + let (a, b) = candidates.get(&id)?; + let (vertical, board) = ruler_guide(*a, *b, centre, &board_rects)?; + let p = to_doc * *a; + let artboard = match board { + Some(i) => Some(*ids.get(i)?), + None => None, + }; + let pos = if vertical { p.x } else { p.y }; + pos.is_finite().then_some(Guide { vertical, pos, artboard, layer: None }) + }; + take_ruler_guides(&mut doc.layers, &pick, &mut doc.guides, 0); + } + let mut brushes = self.brush_library(); + if let Some((lib, _)) = &brushes { + self.count_brush_art_colors(lib); + } if self.color_model.unwrap_or(self.cmyk_colors > self.rgb_colors) { doc.color_mode = ColorMode::Cmyk; let (swatches, groups) = vectorcraft_color::default_swatches(ColorMode::Cmyk.model()); @@ -422,29 +1175,73 @@ impl<'a> Reader<'a> { doc.units = u; } // The file's own swatches in place of the defaults, in its order and colour groups. - if let Some((swatches, groups)) = self.palette_swatches(&doc.patterns) { - (doc.swatches, doc.swatch_groups) = (swatches.into(), groups.into()); - } - // The colour operators' definitions first: a gradient, defined before the art, names a - // global process colour as a stop and would otherwise make it an ink (#1771). - for n in self.spots.iter().chain(&self.stop_spots) { - if doc.swatch(&n.name).is_none() { - doc.swatches.push(Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot: n.spot }); + let own_palette = match self.palette_swatches(&doc.patterns) { + Some((swatches, groups)) => { + (doc.swatches, doc.swatch_groups) = (swatches.into(), groups.into()); + true } + None => false, + }; + let renamed = self.file_swatches(&mut doc, own_palette); + if let Some(author) = self.author.take() { + doc.metadata.author = author; } - for name in doc.patterns.iter().map(|p| p.name.clone()).collect::>() { - if doc.swatch(&name).is_none() { - doc.swatches.push(Swatch { paint: Paint::Pattern { pattern: name.clone(), xf: Affine::IDENTITY }, name, global: false, spot: false }); + // The file's graphic styles in place of the defaults, and the objects linked to them. + let (styles, ids) = self.graphic_styles(); + let styles_read = !styles.is_empty(); + if styles_read { + let links: HashMap = self.style_links.iter().filter_map(|(node, name)| Some((*node, *ids.get(name)?))).collect(); + if !links.is_empty() { + link_styles(&mut doc.layers, &links, &styles, 0); + for symbol in &mut doc.symbols { + link_styles(std::slice::from_mut(&mut symbol.art), &links, &styles, 0); + } + for pattern in &mut doc.patterns { + link_styles(&mut pattern.art, &links, &styles, 0); + } + } + doc.graphic_styles = styles.into(); + } + // The colors linked to a color that took a free name follow it. + if !renamed.is_empty() { + let mut follow = |_: &mut vectorcraft_color::Color, link: &mut Option, _: &mut f32| { + let Some(new) = link.as_ref().and_then(|l| renamed.get(l)) else { return false }; + *link = Some(new.clone()); + true + }; + doc.map_solid_paints(&mut follow); + for a in brushes.iter_mut().flat_map(|(lib, _)| lib.iter_mut().flat_map(|b| b.art_mut())) { + vectorcraft_doc::swatches::map_node_solid_paints(a, &mut follow); + } + for w in &mut self.warped_type { + vectorcraft_doc::swatches::map_node_solid_paints(&mut w.look, &mut follow); } } let mut warnings = self.warnings; + if let Some((lib, unread)) = brushes { + vectorcraft_brush::store(&mut doc, &lib); + if unread > 0 { + warnings.push(brush::left_out_note(unread)); + } + } + self.drawn_looks += self.pattern_looks.values().sum::(); if self.drawn_looks > 0 { warnings.push(format!( "objects with several fills or strokes, effects or brushes came in as their drawn look ({}): their appearance isn't editable yet", self.drawn_looks )); } - warnings.extend(self.variables.note()); + let variables = std::mem::take(&mut self.variables); + warnings.extend(variables.note()); + if variables.present { + doc.variables = variables.variables.into(); + } + let (bindings, bindings_skipped) = (variables.bindings, variables.bindings_skipped); + // Symbols that hold instances of themselves can't be drawn: those instances go before the + // layers are compared with the page. + if !doc.symbols.is_empty() { + doc.limit_depth_noting(&mut warnings); + } Ok(Structure { doc, to_doc, @@ -452,35 +1249,538 @@ impl<'a> Reader<'a> { artboard, template: self.template, hidden_unread: self.hidden_unread, + unread: self.unread, + unread_elsewhere: self.unread_elsewhere, slot_names: self.slot_names, restyled: self.restyled, + placeholders: self.placeholders, + placed_elsewhere: self.placed_elsewhere, + placed_pages: self.placed_pages, + envelopes_drawn: self.envelopes_drawn, + warped_type: super::super::envelope::WarpedType { + looks: self.warped_type, + checks: self.envelope_checks, + spent: self.envelope_spent, + page, + }, + styles_read, + canvas_scale: self.canvas_scale, + xml_ids: self.xml_ids, + bindings, + bindings_skipped, warnings, }) } } -/// The dictionary of entry `key` in `o` or the dictionaries it holds. -fn find_entry<'o>(o: &'o Obj, key: &str, depth: usize) -> Option<&'o Obj> { - if depth > 8 { - return None; - } - o.obj(key).or_else(|| o.entries.iter().flat_map(|(_, v)| v.iter()).filter_map(V::obj).find_map(|c| find_entry(c, key, depth + 1))) -} - -/// Add the variables and data sets of the variable libraries in `o` or the dictionaries it holds -/// (see [`VariableLibrary`]) to `found`. -fn variable_library(o: &Obj, depth: usize, found: &mut VariableLibrary) { +/// Link the objects of `links` among `nodes` to their graphic style's id, each only when it has its +/// style's appearance and transparency (`styles`, whose ids are 1, 2, … in order). A path, which +/// has no contents, takes the style's contents slot. +fn link_styles(nodes: &mut [Arc], links: &HashMap, styles: &[GraphicStyle], depth: usize) { if depth > MAX_DEPTH { return; } - if o.ty == "XMLNode" && element_name(o).as_deref() == Some("variableSets") { - for set in elements(o, "variableSet") { - found.variables += elements(set, "variables").flat_map(|v| elements(v, "variable")).count(); - found.data_sets += elements(set, "sampleDataSets").flat_map(|d| elements(d, "sampleDataSet")).count(); + for n in nodes { + if let Some(id) = links.get(&n.id) + && let Some(g) = id.checked_sub(1).and_then(|i| styles.get(usize::try_from(i).ok()?)).filter(|g| g.id == *id) + { + let mut appearance = (*n.appearance).clone(); + if !n.is_container() && !matches!(n.kind, NodeKind::Text(_) | NodeKind::Image(_)) { + appearance.contents_index = g.appearance.contents_index; + } + if g.transparency_matches(n) && g.appearance_on(n).approx_eq(&appearance) { + let n = Arc::make_mut(n); + n.appearance = appearance.into(); + n.extras_mut().graphic_style = Some(*id); + } + } + if n.children().is_some_and(|c| !c.is_empty()) + && let Some(c) = Arc::make_mut(n).children_mut() + { + link_styles(c, links, styles, depth + 1); } - return; - } - for c in o.items() { - variable_library(c, depth + 1, found); } } + +/// The dictionary of entry `key` in `o` or the dictionaries it holds. +/// How far (points) a ruler guide's ends may lie from the canvas's or an artboard's edges. +const GUIDE_TOLERANCE: f64 = 0.01; + +/// Whether the straight guide path from `a` to `b` (art space) is a ruler guide → whether it is +/// vertical, and the index in `boards` of the artboard it belongs to (`None`: a canvas guide). A +/// canvas guide runs across the whole canvas, 16,383 points centred on the template box's +/// centre `centre`; an artboard guide runs from edge to edge of one artboard of `boards`, inside it. +fn ruler_guide(a: Point, b: Point, centre: Option<(f64, f64)>, boards: &[Rect]) -> Option<(bool, Option)> { + let near = |u: f64, v: f64| (u - v).abs() <= GUIDE_TOLERANCE; + let vertical = match (near(a.x, b.x), near(a.y, b.y)) { + (true, false) => true, + (false, true) => false, + _ => return None, + }; + let (along, across) = if vertical { ((a.y.min(b.y), a.y.max(b.y)), a.x) } else { ((a.x.min(b.x), a.x.max(b.x)), a.y) }; + if let Some((cx, cy)) = centre { + let c = if vertical { cy } else { cx }; + if near(along.0, c - CANVAS_CENTRE) && near(along.1, c + CANVAS_CENTRE) { + return Some((vertical, None)); + } + } + let mut on = boards.iter().enumerate().filter(|(_, r)| { + let (ends, sides) = + if vertical { ((r.min_y(), r.max_y()), (r.min_x(), r.max_x())) } else { ((r.min_x(), r.max_x()), (r.min_y(), r.max_y())) }; + near(along.0, ends.0) && near(along.1, ends.1) && (sides.0..=sides.1).contains(&across) + }); + match (on.next(), on.next()) { + (Some((i, _)), None) => Some((vertical, Some(i))), + _ => None, + } +} + +/// Moves the children of the layers and sublayers of `nodes` that `pick` makes a guide of into +/// `guides`, each on its layer. +fn take_ruler_guides(nodes: &mut [Arc], pick: &dyn Fn(NodeId) -> Option, guides: &mut Vec, depth: usize) { + if depth > MAX_DEPTH { + return; + } + for n in nodes { + if !matches!(n.kind, NodeKind::Layer { .. }) { + continue; + } + let id = n.id; + let Some(kids) = Arc::make_mut(n).children_mut() else { continue }; + kids.retain(|k| match pick(k.id) { + Some(g) => { + guides.push(Guide { layer: Some(id), ..g }); + false + } + None => true, + }); + take_ruler_guides(kids, pick, guides, depth + 1); + } +} + +pub(super) fn find_entry<'o>(o: &'o Obj, key: &str, depth: usize) -> Option<&'o Obj> { + find_holder(o, key, depth).and_then(|h| h.obj(key)) +} + +/// The dictionary that [`find_entry`] finds the entry `key` in: `o` or one it holds. +fn find_holder<'o>(o: &'o Obj, key: &str, depth: usize) -> Option<&'o Obj> { + if depth > 8 { + return None; + } + if o.obj(key).is_some() { + return Some(o); + } + o.entries.iter().flat_map(|(_, v)| v.iter()).filter_map(V::obj).find_map(|c| find_holder(c, key, depth + 1)) +} + +// ---- the variable library ----------------------------------------------------------------- + +/// Caps on the variable library of the editing data, as Load Variable Library has them: the XML +/// nodes read, the variables and data sets kept, the characters of a name, and the bytes of the +/// names and values kept. Past those, the objects bound to the variables. +const MAX_LIBRARY_NODES: usize = 2_000_000; +const MAX_LIBRARY_VARIABLES: usize = 256; +const MAX_LIBRARY_BINDINGS: usize = 100_000; +const MAX_LIBRARY_DATASETS: usize = 1_000; +const MAX_LIBRARY_NAME: usize = 255; +const MAX_LIBRARY_BYTES: usize = 8 << 20; + +/// The variable library in `o` or the dictionaries it holds: XML nodes (`/XMLNode`), each with its +/// name (`xmlnode-nodename`), value (`xmlnode-nodevalue`), type (`xmlnode-nodetype`: 1 an element, 2 +/// an attribute, 3 text), children (`xmlnode-children`, an array in order) and attributes +/// (`xmlnode-attributes`, a dictionary of attribute nodes). The library is a `variableSets` element +/// holding a `variableSet` (its `locked` attribute `none`, or `variableAndTypes` when the variables +/// are locked), with a `variables` element of `variable` elements (`varName`, and `trait`: +/// `textcontent`, `visibility`, `fileref` or `graphdata`; another trait or none is a variable of +/// unknown kind), and a `sampleDataSets` element (`activeDataSet`, the data set shown) of +/// `sampleDataSet` elements (`dataSetName`). A `variable` bound to an object has a `docRef` attribute +/// whose value is the object's XML id (`/XMLUIDREF`); a variable bound to several objects is +/// declared once for each, with the same name and trait. In a data set, the element named after a +/// variable holds its value: `p` elements of text, one paragraph each; a `/Bool` text, whether its +/// objects show; a linked file's URL (`file://`) or path. Graph values aren't read. What is +/// malformed, repeated or past the caps (a declaration, a data set, a value, a setting, a second +/// `variableSet`) is left out and counted; a library past [`MAX_LIBRARY_NODES`] isn't read. +fn variable_library(o: &Obj) -> VariableRead { + find_variable_sets(o, 0).map_or_else(VariableRead::default, read_variable_sets) +} + +/// The `variableSets` XML node in `o` or the dictionaries it holds. +fn find_variable_sets(o: &Obj, depth: usize) -> Option<&Obj> { + if depth > MAX_DEPTH { + return None; + } + if o.ty == "XMLNode" && element_name(o).as_deref() == Some("variableSets") { + return Some(o); + } + o.items().find_map(|c| find_variable_sets(c, depth + 1)) +} + +/// A value of an XML node's entry, by the type the editing data gives it. +#[derive(Clone, Debug, PartialEq)] +enum XmlValue { + /// A `/String` or `/UnicodeString`: its strings joined (a long one is written across lines). + Text(String), + /// A `/Bool`. + Bool(bool), +} + +/// The value of entry `key` of the XML node `o`; `None` without it, when it is of another type, or +/// when its text is longer than [`MAX_LIBRARY_BYTES`]. +fn xml_value(o: &Obj, key: &str) -> Option { + let (V::Name(ty), rest) = o.get(key)?.split_last()? else { return None }; + match ty.as_str() { + "String" | "UnicodeString" => { + let len = rest.iter().map(|v| if let V::Str(s) = v { s.len() } else { 0 }).fold(0usize, usize::saturating_add); + if len > MAX_LIBRARY_BYTES { + return None; + } + let mut bytes = Vec::with_capacity(len); + for v in rest { + let V::Str(s) = v else { return None }; + bytes.extend_from_slice(s); + } + Some(XmlValue::Text(obj::text(&bytes))) + } + "Bool" => match rest { + [V::Num(n)] if *n == 0.0 => Some(XmlValue::Bool(false)), + [V::Num(n)] if *n == 1.0 => Some(XmlValue::Bool(true)), + _ => None, + }, + _ => None, + } +} + +/// Whether `o` is an XML node of type `ty` (1 an element, 2 an attribute, 3 text). +fn is_node(o: &Obj, ty: f64) -> bool { + o.ty == "XMLNode" && o.nums("xmlnode-nodetype") == [ty] +} + +/// The name of the XML node `o` as the file writes it, prefix and all. +fn node_name(o: &Obj) -> Option { + match xml_value(o, "xmlnode-nodename")? { + XmlValue::Text(name) => Some(name), + XmlValue::Bool(_) => None, + } +} + +/// Whether `o` is an element whose name without its prefix is `name`. +fn is_element(o: &Obj, name: &str) -> bool { + is_node(o, 1.0) && node_name(o).is_some_and(|n| n.rsplit(':').next() == Some(name)) +} + +/// The text of the attribute `name` (without its prefix) of the element `o`. +fn xml_attribute(o: &Obj, name: &str) -> Option { + let attributes = o.obj("xmlnode-attributes").filter(|a| a.ty == "Dictionary")?; + let node = attributes.items().find(|a| is_node(a, 2.0) && node_name(a).is_some_and(|n| n.rsplit(':').next() == Some(name)))?; + match xml_value(node, "xmlnode-nodevalue")? { + XmlValue::Text(text) => Some(text), + XmlValue::Bool(_) => None, + } +} + +/// A name of the library (a variable's or a data set's): trimmed, not empty and at most +/// [`MAX_LIBRARY_NAME`] characters. +fn library_name(name: Option) -> Option { + let name = name?.trim().to_string(); + (!name.is_empty() && name.chars().count() <= MAX_LIBRARY_NAME).then_some(name) +} + +/// The file path of a linked file's value: a `file://` URL (`file:////Users/…`) as its path, its +/// `%XX` escapes decoded (a URL that names a host other than `localhost` as a network path, +/// `//host/…`), or an absolute path as it is. White space around it isn't part of it. +fn linked_path(text: &str) -> Option { + let text = text.trim_matches([' ', '\t', '\n', '\r']); + let drive = |p: &str| matches!(p.as_bytes(), [l, b':', ..] if l.is_ascii_alphabetic()); + let path = match text.strip_prefix("file://") { + Some(rest) => { + let rest = rest.strip_prefix("localhost").filter(|r| r.starts_with('/')).unwrap_or(rest); + if rest.starts_with('/') { + let p = percent_decoded(rest.trim_start_matches('/')); + if drive(&p) { p } else { format!("/{p}") } + } else { + // A host: the share it names. + format!("//{}", percent_decoded(rest)) + } + } + None => text.to_string(), + }; + (path.len() > 1 && (path.starts_with('/') || path.starts_with("\\\\") || drive(&path))).then_some(path) +} + +/// `s` with `%XX` escapes decoded (a file URL's path); as it is when the decoded bytes aren't UTF-8. +fn percent_decoded(s: &str) -> String { + if !s.contains('%') { + return s.to_string(); + } + let mut out = Vec::with_capacity(s.len()); + let mut rest = s.as_bytes(); + while let Some((&b, tail)) = rest.split_first() { + let hex = tail + .get(..2) + .filter(|h| h.iter().all(u8::is_ascii_hexdigit)) + .and_then(|h| std::str::from_utf8(h).ok()) + .and_then(|h| u8::from_str_radix(h, 16).ok()); + match hex { + Some(v) if b == b'%' => { + out.push(v); + rest = tail.get(2..).unwrap_or_default(); + } + _ => { + out.push(b); + rest = tail; + } + } + } + String::from_utf8(out).unwrap_or_else(|_| s.to_string()) +} + +/// The object an element's `docRef` attribute names: `None` without one, `Some(None)` when its +/// value isn't an XML id (`/XMLUIDREF`) of at most [`MAX_LIBRARY_NAME`] characters. +fn doc_ref(o: &Obj) -> Option> { + let attributes = o.obj("xmlnode-attributes").filter(|a| a.ty == "Dictionary")?; + let node = attributes.items().find(|a| is_node(a, 2.0) && node_name(a).is_some_and(|n| n.rsplit(':').next() == Some("docRef")))?; + let id = node.obj("xmlnode-nodevalue").filter(|v| v.ty == "XMLUIDREF").and_then(Obj::content_text); + Some(id.filter(|id| !id.is_empty() && id.chars().count() <= MAX_LIBRARY_NAME)) +} + +/// The walk through a variable library: the nodes read, the bytes kept, the bindings, and what was +/// left out. +#[derive(Default)] +struct LibraryWalk { + nodes: usize, + bytes: usize, + bindings: Vec, + bindings_skipped: usize, + skipped: usize, +} + +impl LibraryWalk { + /// The child nodes of the XML node `o`, in order. `None` when they aren't an array, or when the + /// library has more nodes than [`MAX_LIBRARY_NODES`]. + fn children<'o>(&mut self, o: &'o Obj) -> Option> { + let list = o.obj("xmlnode-children").filter(|c| c.ty == "Array")?; + let children: Vec<&Obj> = list.items().collect(); + self.nodes = self.nodes.saturating_add(children.len()); + (self.nodes <= MAX_LIBRARY_NODES).then_some(children) + } + + /// Whether `len` more bytes of names and values fit in [`MAX_LIBRARY_BYTES`] (they are then counted). + fn keep(&mut self, len: usize) -> bool { + let fits = self.bytes.saturating_add(len) <= MAX_LIBRARY_BYTES; + if fits { + self.bytes += len; + } + fits + } + + /// Whether a value of `len` bytes would still fit in [`MAX_LIBRARY_BYTES`] (nothing is counted). + fn room(&self, len: usize) -> bool { + self.bytes.saturating_add(len) <= MAX_LIBRARY_BYTES + } + + /// The `variableSet` `set`, into `vars`. + fn variable_set(&mut self, set: &Obj, vars: &mut Variables) { + vars.locked = match xml_attribute(set, "locked").as_deref() { + None | Some("none") => false, + Some("variableAndTypes") => true, + Some(_) => { + self.skipped += 1; + false + } + }; + let Some(children) = self.children(set) else { + self.skipped += 1; + return; + }; + for list in children.iter().filter(|c| is_element(c, "variables")) { + self.declarations(list, vars); + } + for list in children.iter().filter(|c| is_element(c, "sampleDataSets")) { + self.data_sets(list, vars); + } + } + + /// The `variable` elements of the `variables` element `list`, into `vars`, and the objects they + /// bind. A second declaration of a variable binds one more object to it. + fn declarations(&mut self, list: &Obj, vars: &mut Variables) { + let Some(children) = self.children(list) else { + self.skipped += 1; + return; + }; + for v in children.into_iter().filter(|c| !is_node(c, 3.0)) { + let name = is_element(v, "variable").then(|| library_name(xml_attribute(v, "varName"))).flatten(); + let kind = match xml_attribute(v, "trait").as_deref() { + Some("textcontent") => VariableKind::Text, + Some("visibility") => VariableKind::Visibility, + Some("fileref") => VariableKind::Image, + Some("graphdata") => VariableKind::Graph, + _ => VariableKind::Unknown, + }; + let target = doc_ref(v); + // A declaration left out, and the object it binds. + let left_out = |walk: &mut Self| { + walk.skipped += 1; + walk.bindings_skipped += usize::from(target.is_some()); + }; + let Some(name) = name else { + left_out(self); + continue; + }; + match vars.variable(&name) { + // Another object bound to the variable. + Some(declared) if declared.kind == kind => {} + // A second variable of that name, of another kind. + Some(_) => { + left_out(self); + continue; + } + None if vars.variables.len() < MAX_LIBRARY_VARIABLES && self.keep(name.len()) => { + vars.variables.push(Variable { name: name.clone(), kind }); + } + None => { + left_out(self); + continue; + } + } + if let Some(target) = target { + // The binding keeps its own copy of the name, and its target. + let len = name.len().saturating_add(target.as_ref().map_or(0, String::len)); + if self.bindings.len() < MAX_LIBRARY_BINDINGS && self.keep(len) { + self.bindings.push(BindingRef { variable: name, target }); + } else { + self.bindings_skipped += 1; + } + } + } + } + + /// The `sampleDataSet` elements of the `sampleDataSets` element `list`, into `vars`, and the + /// data set it shows. + fn data_sets(&mut self, list: &Obj, vars: &mut Variables) { + let Some(children) = self.children(list) else { + self.skipped += 1; + return; + }; + for row in children.into_iter().filter(|c| !is_node(c, 3.0)) { + let name = is_element(row, "sampleDataSet").then(|| library_name(xml_attribute(row, "dataSetName"))).flatten(); + let Some(name) = name.filter(|n| vars.dataset(n).is_none() && vars.datasets.len() < MAX_LIBRARY_DATASETS && self.keep(n.len())) else { + self.skipped += 1; + continue; + }; + let values = self.values(row, vars); + vars.datasets.push(DataSet { name, values }); + } + if let Some(active) = xml_attribute(list, "activeDataSet").and_then(|a| library_name(Some(a))) { + vars.active_dataset = vars.dataset(&active).map(|_| active); + } + } + + /// The values of the `sampleDataSet` element `row`, for the variables of `vars`. + fn values(&mut self, row: &Obj, vars: &Variables) -> std::collections::BTreeMap { + let mut values = std::collections::BTreeMap::new(); + let Some(children) = self.children(row) else { + self.skipped += 1; + return values; + }; + for el in children.into_iter().filter(|c| !is_node(c, 3.0)) { + let variable = is_node(el, 1.0).then(|| node_name(el)).flatten().and_then(|n| vars.variable(n.rsplit(':').next().unwrap_or(&n))); + let Some(variable) = variable.filter(|v| !values.contains_key(&v.name)) else { + self.skipped += 1; + continue; + }; + match self.value(el, variable.kind) { + Ok(Some(value)) => { + values.insert(variable.name.clone(), value); + } + Ok(None) => {} + Err(()) => self.skipped += 1, + } + } + values + } + + /// The value of a variable of `kind` that the element `el` holds: `Ok(None)` when it holds none, + /// `Err` when it can't be read (graph values aren't read). + fn value(&mut self, el: &Obj, kind: VariableKind) -> Result, ()> { + let children = self.children(el).ok_or(())?; + if children.is_empty() { + return Ok(None); + } + let value = match kind { + VariableKind::Text => { + let (mut paragraphs, mut total) = (Vec::new(), 0usize); + // Text between the paragraphs is white space the XML had. + for p in children.into_iter().filter(|c| !is_node(c, 3.0)) { + if !is_element(p, "p") { + return Err(()); + } + let mut paragraph = String::new(); + for t in self.children(p).ok_or(())? { + match (is_node(t, 3.0), xml_value(t, "xmlnode-nodevalue")) { + (true, Some(XmlValue::Text(text))) if self.room(total.saturating_add(text.len())) => { + total += text.len(); + paragraph.push_str(&text); + } + _ => return Err(()), + } + } + // The line break that joins it to the next one. + total = total.saturating_add(1); + paragraphs.push(paragraph); + } + if paragraphs.is_empty() { + return Ok(None); + } + DataValue::Text(paragraphs.join("\n")) + } + VariableKind::Visibility => match children.as_slice() { + [t] if is_node(t, 3.0) => match xml_value(t, "xmlnode-nodevalue") { + Some(XmlValue::Bool(show)) => DataValue::Visible(show), + _ => return Err(()), + }, + _ => return Err(()), + }, + VariableKind::Image => { + let mut text = String::new(); + for t in children { + match (is_node(t, 3.0), xml_value(t, "xmlnode-nodevalue")) { + (true, Some(XmlValue::Text(s))) if self.room(text.len().saturating_add(s.len())) => text.push_str(&s), + _ => return Err(()), + } + } + if text.trim_matches([' ', '\t', '\n', '\r']).is_empty() { + return Ok(None); + } + DataValue::Image(linked_path(&text).ok_or(())?) + } + VariableKind::Graph | VariableKind::Unknown => return Err(()), + }; + let len = match &value { + DataValue::Text(s) | DataValue::Image(s) | DataValue::Graph(s) => s.len(), + DataValue::Visible(_) => 1, + }; + if self.keep(len) { Ok(Some(value)) } else { Err(()) } + } +} + +/// The library of the `variableSets` element `sets` (see [`variable_library`]). +fn read_variable_sets(sets: &Obj) -> VariableRead { + let mut walk = LibraryWalk::default(); + let mut vars = Variables::default(); + match walk.children(sets) { + Some(children) => { + let (sets, other): (Vec<&Obj>, Vec<&Obj>) = children.into_iter().filter(|c| !is_node(c, 3.0)).partition(|c| is_element(c, "variableSet")); + // A node that isn't a variable set, and a second set (VectorCraft keeps one set of + // variables), are left out. + walk.skipped += other.len() + sets.len().saturating_sub(1); + if let Some(first) = sets.first() { + walk.variable_set(first, &mut vars); + } + } + None => walk.skipped += 1, + } + if walk.nodes > MAX_LIBRARY_NODES { + return VariableRead { variables: Variables::default(), bindings: vec![], bindings_skipped: 0, skipped: 1, present: true }; + } + VariableRead { variables: vars, bindings: walk.bindings, bindings_skipped: walk.bindings_skipped, skipped: walk.skipped, present: true } +} diff --git a/crates/eps/src/import/ai/read/masks.rs b/crates/eps/src/import/ai/read/masks.rs new file mode 100644 index 0000000000..a7e8356bd4 --- /dev/null +++ b/crates/eps/src/import/ai/read/masks.rs @@ -0,0 +1,202 @@ +//! Multi-layer masks in the legacy format (version 7 specification §10): `Mb`, the mask's path +//! painted with `W`, `Md`, the masked objects (in that layer and, past its `LB`, in the layers +//! after it), `MB`. The objects of each layer the mask covers become one clipping group in that +//! layer, its clipping path a copy of the mask's. + +use super::types::{Frame, Kind, MAX_NODES}; +use super::{Arc, Node, NodeKind, Reader}; + +/// The note for a file with a multi-layer mask. +pub(crate) const PER_LAYER: &str = "a mask that covers several layers comes in as a clipping group in each layer it covers"; + +/// A multi-layer mask being read. +#[derive(Debug)] +pub(super) struct MultiMask { + /// The mask's clipping path, once `Md` has defined it. + mask: Option, + /// What each copy of the mask adds to the objects read: its objects and their points. + weight: usize, + /// How many frames were open when the masked objects started in the frame they go in; 0 + /// outside the layers, until a layer starts. + depth: usize, + /// Where the masked objects start among that frame's children. + start: usize, +} + +impl Reader<'_> { + /// A multi-layer mask's operator `w`: `Mb` (or `Mv`) starts the mask, `Md` (or `ME`) defines + /// it, `MB` ends it, and `Mi` changes nothing here. + pub(super) fn multi_mask_op(&mut self, w: &str) -> Result<(), String> { + match w { + "Mb" | "Mv" => self.begin_multi_mask(), + "Md" | "ME" => self.define_multi_mask(), + "MB" => self.end_multi_mask(), + _ => Ok(()), + } + } + + /// `LB`: the layer ends, and a multi-layer mask goes on in the frame around it. + pub(super) fn end_layer_in_mask(&mut self) -> Result<(), String> { + self.multi_mask_layer_ends()?; + self.end_layer()?; + self.multi_mask_go_on(); + Ok(()) + } + + /// `Mb`: a multi-layer mask starts. + fn begin_multi_mask(&mut self) -> Result<(), String> { + if self.multi_mask.is_some() { + return Err("a multi-layer mask's operators are out of order".into()); + } + self.end_path_quietly(); + let start = self.frames.last().map_or(0, |f| f.children.len()); + self.multi_mask = Some(MultiMask { mask: None, weight: 0, depth: self.frames.len(), start }); + Ok(()) + } + + /// `Md`: the clipping path painted last since `Mb`, in the same group or layer, is the mask. + fn define_multi_mask(&mut self) -> Result<(), String> { + let depth = self.frames.len(); + let Some(m) = self.multi_mask.as_ref() else { return Err("a multi-layer mask's operators are out of order".into()) }; + if m.mask.is_some() || depth == 0 { + return Err("a multi-layer mask's operators are out of order".into()); + } + if m.depth != depth { + return Err("a group crosses a multi-layer mask".into()); + } + let start = m.start; + let Some(f) = self.frames.last_mut() else { return Err("a multi-layer mask's operators are out of order".into()) }; + let Some(at) = f.clips.iter().copied().filter(|i| *i >= start && *i < f.children.len()).max() else { + return Err("a multi-layer mask needs one clipping path".into()); + }; + let mut mask = f.children.remove(at); + f.clips.retain(|i| *i != at); + for i in &mut f.clips { + if *i > at { + *i -= 1; + } + } + // The mask's fill paints once, where its path is, under the objects masked after it: it stays a path of its own + // among them, and the copies of the mask in each layer it covers have no fill. + if let Some(fill) = self.fill_apart(&mut mask) { + if self.nodes > MAX_NODES { + return Err(format!("it has more than {MAX_NODES} objects")); + } + let Some(f) = self.frames.last_mut() else { return Err("a multi-layer mask's operators are out of order".into()) }; + f.children.insert(at, fill); + for i in &mut f.clips { + if *i >= at { + *i += 1; + } + } + } + let mut weight = mask.count_with_masks(); + mask.walk(&mut |n| { + if let NodeKind::Path { path, .. } = &n.kind { + weight = weight.saturating_add(path.anchor_count()); + } + }); + if let Some(m) = self.multi_mask.as_mut() { + m.weight = weight; + m.mask = Some(mask); + } + self.after_object = false; + Ok(()) + } + + /// `MB`: the masked objects end. + fn end_multi_mask(&mut self) -> Result<(), String> { + if !self.multi_mask.as_ref().is_some_and(|m| m.mask.is_some()) { + return Err("a multi-layer mask's operators are out of order".into()); + } + self.wrap_masked()?; + self.multi_mask = None; + Ok(()) + } + + /// `%AI5_BeginLayer` in a multi-layer mask, before the layer opens: the objects masked so far + /// in the frame around it are grouped, and the mask goes on in the new layer. + pub(super) fn multi_mask_layer_starts(&mut self) -> Result<(), String> { + let Some(m) = self.multi_mask.as_ref() else { return Ok(()) }; + if m.depth != 0 { + if m.mask.is_none() { + return Err("a multi-layer mask's operators are out of order".into()); + } + self.wrap_masked()?; + } + Ok(()) + } + + /// A layer opened or closed in a multi-layer mask: the masked objects go on in the frame now + /// innermost. + pub(super) fn multi_mask_go_on(&mut self) { + let (depth, start) = (self.frames.len(), self.frames.last().map_or(0, |f| f.children.len())); + if let Some(m) = self.multi_mask.as_mut() { + (m.depth, m.start) = (depth, start); + } + } + + /// `LB` in a multi-layer mask, before the layer closes: its masked objects are grouped. + fn multi_mask_layer_ends(&mut self) -> Result<(), String> { + let Some(m) = self.multi_mask.as_ref() else { return Ok(()) }; + if m.mask.is_none() { + return Err("a multi-layer mask's operators are out of order".into()); + } + if !matches!(self.frames.last(), Some(Frame { kind: Kind::Layer(_), .. })) { + return Err("a group crosses a multi-layer mask".into()); + } + self.wrap_masked() + } + + /// A group, compound path or clipping group closing: it must have opened inside the mask. + pub(super) fn multi_mask_container_ends(&self) -> Result<(), String> { + match &self.multi_mask { + Some(m) if m.depth == self.frames.len() => Err("a group crosses a multi-layer mask".into()), + _ => Ok(()), + } + } + + /// The masked objects in the innermost frame become a clipping group, a copy of the mask first. + fn wrap_masked(&mut self) -> Result<(), String> { + let Some(m) = self.multi_mask.as_ref() else { return Ok(()) }; + if m.depth == 0 { + return Ok(()); + } + if m.depth != self.frames.len() { + return Err("a group crosses a multi-layer mask".into()); + } + let Some(mut mask) = m.mask.clone() else { return Err("a multi-layer mask's operators are out of order".into()) }; + let (start, weight) = (m.start, m.weight); + let Some(f) = self.frames.last_mut() else { return Ok(()) }; + if start >= f.children.len() { + return Ok(()); + } + // A clipping path painted among the masked objects clips the whole layer or group, as + // outside a mask: it stays in the frame, outside the masked objects' group. + let painted: std::collections::HashSet = f.clips.iter().filter_map(|i| i.checked_sub(start)).collect(); + let (clips, kids): (Vec<_>, Vec<_>) = f.children.split_off(start).into_iter().enumerate().partition(|(i, _)| painted.contains(i)); + let (clips, kids): (Vec, Vec) = (clips.into_iter().map(|(_, k)| k).collect(), kids.into_iter().map(|(_, k)| k).collect()); + f.clips.retain(|i| *i < start); + if !kids.is_empty() { + self.nodes = self.nodes.saturating_add(weight).saturating_add(1); + if self.nodes > MAX_NODES { + return Err(format!("it has more than {MAX_NODES} objects")); + } + self.reid(&mut mask); + let children = std::iter::once(mask).chain(kids).map(Arc::new).collect(); + let group = Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: true }); + if let Some(f) = self.frames.last_mut() { + f.children.push(group); + } + self.warn(PER_LAYER); + } + if let Some(f) = self.frames.last_mut() { + for c in clips { + f.clips.push(f.children.len()); + f.children.push(c); + } + } + self.after_object = false; + Ok(()) + } +} diff --git a/crates/eps/src/import/ai/read/on_path.rs b/crates/eps/src/import/ai/read/on_path.rs new file mode 100644 index 0000000000..1e33e09a1b --- /dev/null +++ b/crates/eps/src/import/ai/read/on_path.rs @@ -0,0 +1,188 @@ +//! Objects on Path groups: a `u` … `U` group whose children's dictionaries carry a `Persistent ID` +//! (the path's with `KeyPath` 1, each object's with its `ConstraintArtOrderId` and the angle of its +//! frame, `BBAccumRotation`: radians, counterclockwise in art space), and a dictionary of the +//! `/Document` dictionary's `Constraint Data` array naming them: `Constraint Name`, `Constraint +//! Verison` 1, `Constraint IDs` (the path's id, then the objects' in their order along the path) +//! and `Constraint Dict` with the options (`PivotPosition` 0 to 8, `Rotation` in radians, +//! `IsEquiSpaced`, `StartRangeFraction`, `ObjectsOrder`, `ConstraintArtData`). The group opens +//! with its [`ObjectsOnPath`] record and its art where it is drawn. A record with options the +//! record can't hold (a `Spacing`, uneven spacing, a start other than 0, keys this reader doesn't +//! know), or one that doesn't match one group exactly, leaves the group a plain group. + +use std::collections::{HashMap, HashSet}; + +use vectorcraft_doc::objects_on_path::{Member, ObjectsOnPath, attachable_path}; + +use super::{Affine, Document, NodeId, NodeKind, Obj, Reader, V}; + +/// The constraint name of an Objects on Path record. +const NAME: &str = "Adobe Align On Path"; // brand-ok: the record's name in the files +/// Most records read from one file. +const MAX_RECORDS: usize = 1000; +/// Most objects one record names. +const MAX_IDS: usize = 10_000; +/// Most objects whose ids are kept. +const MAX_TAGGED: usize = 100_000; +/// The keys of `Constraint Dict` this reader reads; any other one leaves the group plain. +const KNOWN: [&str; 6] = ["StartRangeFraction", "ConstraintArtData", "ObjectsOrder", "PivotPosition", "IsEquiSpaced", "Rotation"]; + +/// An Objects on Path record of the `/Document` dictionary. +#[derive(Debug)] +pub(super) struct Record { + /// The path's id, then the objects' in their order along the path. + ids: Vec, + pivot: u8, + /// Degrees, counterclockwise. + rotate: f64, +} + +/// What an object's dictionary says of its part in an Objects on Path group. +#[derive(Clone, Copy, Debug, Default)] +struct Tag { + key_path: bool, + order: Option, + /// `BBAccumRotation`: radians, counterclockwise in art space. + angle: Option, +} + +/// The records and object ids read, for [`apply`]. +#[derive(Debug, Default)] +pub(super) struct OnPath { + records: Vec, + /// The objects with each `Persistent ID`. + ids: HashMap>, + tags: HashMap, +} + +/// The first number of entry `key`. +fn num(o: &Obj, key: &str) -> Option { + o.nums(key).first().copied() +} + +/// An Objects on Path record from a dictionary of the `Constraint Data` array: `None` for another +/// constraint, another version, or options the record can't hold. +fn record(o: &Obj) -> Option { + if o.text("Constraint Name").as_deref() != Some(NAME) || num(o, "Constraint Verison") != Some(1.0) { + return None; + } + let list = o.obj("Constraint IDs")?; + if list.entries.len() > MAX_IDS || !list.content.is_empty() { + return None; + } + let ids = list.entries.iter().map(|(_, v)| v.iter().find(|v| matches!(v, V::Str(_))).and_then(V::text)).collect::>>()?; + let members = ids.len().checked_sub(1).filter(|n| *n > 0)?; + let options = o.obj("Constraint Dict")?; + if options.entries.iter().any(|(k, _)| !k.as_deref().is_some_and(|k| KNOWN.contains(&k))) || !options.content.is_empty() { + return None; + } + if num(options, "IsEquiSpaced") != Some(1.0) + || !matches!(options.get("StartRangeFraction").map(|_| num(options, "StartRangeFraction")), None | Some(Some(0.0))) + { + return None; + } + let pivot = num(options, "PivotPosition").filter(|p| p.fract() == 0.0 && (0.0..=8.0).contains(p))? as u8; + let rotate = num(options, "Rotation").map(f64::to_degrees).filter(|r| r.is_finite())?; + let order = options.obj("ObjectsOrder")?; + let order: Vec = order.entries.iter().flat_map(|(_, v)| v.iter().filter_map(V::num)).collect(); + if order.len() != members || order.iter().enumerate().any(|(i, n)| *n != i as f64) { + return None; + } + let data = options.obj("ConstraintArtData")?; + if data.entries.len() != members || data.items().count() != members || data.items().any(|d| !d.entries.is_empty() || !d.content.is_empty()) { + return None; + } + Some(Record { ids, pivot, rotate }) +} + +impl Reader<'_> { + /// The Objects on Path records of a `Constraint Data` array in the `/Document` dictionary `o`. + pub(super) fn constraint_data(&mut self, o: &Obj) { + let Some(list) = super::document::find_entry(o, "Constraint Data", 0) else { return }; + for d in list.items().take(MAX_RECORDS) { + if self.on_path.records.len() >= MAX_RECORDS { + return; + } + if let Some(r) = record(d) { + self.on_path.records.push(r); + } + } + } + + /// The `Persistent ID` an object's dictionary `o` gives the last object, with its part in an + /// Objects on Path group. + pub(super) fn constraint_art(&mut self, o: &Obj) { + let Some(uuid) = o.text("Persistent ID") else { return }; + let Some(id) = self.last_object().filter(|n| !matches!(n.kind, NodeKind::Layer { .. })).map(|n| n.id) else { return }; + if self.on_path.tags.len() >= MAX_TAGGED { + return; + } + let angle = o.text("BBAccumRotation").and_then(|s| s.trim().parse::().ok()).filter(|a| a.is_finite()); + let tag = Tag { key_path: num(o, "KeyPath") == Some(1.0), order: num(o, "ConstraintArtOrderId"), angle }; + self.on_path.tags.insert(id, tag); + self.on_path.ids.entry(uuid).or_default().push(id); + } +} + +/// Give each group that a record of `found` names exactly its [`ObjectsOnPath`] record. +pub(super) fn apply(doc: &mut Document, found: &OnPath) { + if found.records.is_empty() { + return; + } + // Where every object with an id is, found in one walk of the tree (setting a record doesn't + // move anything). + let at = doc.index_paths(found.tags.keys().copied()); + // The groups whose path and objects have been measured. + let mut tried = HashSet::new(); + for r in &found.records { + // A record that doesn't match leaves the group as it was read. + let _ = apply_one(doc, found, &at, &mut tried, r); + } +} + +fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap>, tried: &mut HashSet, r: &Record) -> Option<()> { + // The one object still in the document with the id `uuid` (a commented copy may have gone). + let resolve = |uuid: &str| -> Option<(NodeId, &Vec)> { + let mut live = found.ids.get(uuid)?.iter().filter_map(|id| at.get(id).map(|p| (*id, p))); + let one = live.next()?; + live.next().is_none().then_some(one) + }; + let (first, rest) = r.ids.split_first()?; + let (path, path_at) = resolve(first)?; + if !found.tags.get(&path)?.key_path { + return None; + } + let (_, group_at) = path_at.split_last()?; + let g = doc.node_at(group_at)?; + let NodeKind::Group { children, clip: false } = &g.kind else { return None }; + if g.extras().objects_on_path.is_some() || children.len() != r.ids.len() { + return None; + } + let mut seen = HashSet::from([path]); + let mut placed = Vec::with_capacity(rest.len()); + for (i, uuid) in rest.iter().enumerate() { + let (id, place) = resolve(uuid)?; + let tag = found.tags.get(&id)?; + if !seen.insert(id) || place.split_last().map(|(_, up)| up) != Some(group_at) || tag.key_path || tag.order != Some(i as f64) { + return None; + } + placed.push((id, place, -tag.angle?)); + } + if children.iter().any(|c| !seen.contains(&c.id)) { + return None; + } + // What is left depends on the group's objects alone, so each group is measured once. + if !tried.insert(g.id) { + return None; + } + attachable_path(children.iter().find(|c| c.id == path)?)?; + let mut members = Vec::with_capacity(placed.len()); + for (id, place, angle) in placed { + // The frame the object is drawn in: turned by its angle (the document's y points down) + // about the center of its bounds. + let center = doc.node_at(place)?.geometric_bounds()?.center(); + members.push(Member { id, frame: Affine::rotate_about(angle, center), angle }); + } + let on_path = ObjectsOnPath { path, members, pivot: r.pivot, rotate: r.rotate, spacing: None, start: 0.0 }; + doc.node_mut_at(group_at)?.extras_mut().objects_on_path = Some(Box::new(on_path)); + Some(()) +} diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 9431061fe9..3051b4a287 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1,9 +1,12 @@ use super::containers::close; use super::document::slot_of; -use super::types::{BLENDS, FLIP, Frame, IGNORED, Kind, MAX_DEPTH}; +use super::types::{ + BLENDS, FLIP, Frame, GRAPH_OPS, GRAPH_PLAIN, GRAPH_UNENDED, IGNORED, Kind, MAX_DEPTH, MAX_NODES, MAX_TAG_TEXT, MAX_TAGS, Place, URL_TAG, + line_width, +}; use super::{ - Affine, Appearance, AppearanceItem, Arc, BlendMode, Dash, FillLayer, FillRule, Gradient, GradientDef, HashMap, HashSet, Instance, Knockout, - LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, StrokeLayer, V, obj, paint, + Affine, Appearance, AppearanceItem, Arc, BlendMode, BrushesKept, Dash, FillLayer, FillRule, Global, Gradient, GradientDef, Graph, HashMap, + HashSet, Instance, Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, ShownNames, StrokeLayer, V, obj, paint, }; impl<'a> Reader<'a> { @@ -31,23 +34,93 @@ impl<'a> Reader<'a> { // of it may start with `%_` and read as hidden tokens: a `(` there would open // a string that swallows the rest of the layer. let key = o.entries.last().and_then(|(k, _)| k.as_deref()); - if o.ty == "Binary" && key == Some("ASCII85Decode") { - self.lex.skip_past(b"~>"); - } else if o.ty == "ForeignObject" && key == Some("Data") { - self.foreign_data = Some(self.lex.skip_past(b"~>").to_vec()); + if ascii85_follows(&o.ty, key) { + let data = self.lex.skip_past(b"~>"); + if o.ty == "ForeignObject" { + self.foreign_data = Some(data.to_vec()); + } } } } + /// `X=` in a `/Mask` dictionary: the opacity mask's art starts, read until its `X+` + /// ([`Self::end_mask`]). fn open_mask_object(&mut self, hidden: bool) -> Result<(), String> { if !matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(o), .. }) if o.ty == "Mask") { // `X=` also introduces legacy text frame art, read by `text_frames`. return Ok(()); } self.end_path_quietly(); + // The art goes on from the paint before the dictionaries it is in, which `begin_obj` set + // aside: the writer leaves out paint that doesn't change, so a mask rectangle with no color + // of its own takes the white of the art before it, not a fresh state's black, which hides + // what it masks. Lock, visibility and transparency start afresh, as a dictionary's art does. + if let Some(f) = self.frames.iter().rev().take_while(|f| matches!(f.kind, Kind::Obj(_))).last() { + let before = &f.gs; + let gs = &mut self.gs; + (gs.fill, gs.stroke, gs.dash) = (before.fill.clone(), before.stroke.clone(), before.dash.clone()); + (gs.width, gs.cap, gs.join, gs.miter, gs.rule) = (before.width, before.cap, before.join, before.miter, before.rule); + (gs.overprint_fill, gs.overprint_stroke) = (before.overprint_fill, before.overprint_stroke); + (self.pending_unread_fill, self.pending_unread_stroke) = (f.pending_unread_fill, f.pending_unread_stroke); + } self.open(Kind::Mask, hidden) } + /// `LB`: a graph started in this layer that hasn't ended doesn't go on past it; the layer ends. + fn layer_end(&mut self) -> Result<(), String> { + if self.graph.as_ref().is_some_and(|g| g.frames >= self.frames.len()) { + self.graph = None; + self.warn(GRAPH_UNENDED); + } + self.end_layer_in_mask() + } + + /// A placed file's `` ` ``: its matrix, box and path; a second one, or operands of another + /// shape, leave it unreadable. + fn place_tick(&mut self, vals: &[V], hidden: bool) { + let unseen = hidden || self.gs.hidden || !self.shown(); + let p = self.place.get_or_insert_with(|| Place { hidden: unseen, ..Place::default() }); + if p.ticked { + p.broken = true; + } else { + p.ticked = true; + match tick(vals) { + Some((m, b, path)) => (p.matrix, p.bounds, p.path) = (Some(m), Some(b), path), + None => p.broken = true, + } + } + } + + /// `/identifier (string) XT` (version 7 specification §7): a tag on the object before it. The + /// `AdobeURL` tag sets the object's URL, and every other tag is added to the object's data in + /// order, up to [`MAX_TAGS`]. A tag with no object before it, with an empty identifier, or with + /// an identifier or string longer than [`MAX_TAG_TEXT`] bytes is ignored, and so are tags in a + /// pattern's or brush's art, which is not an object of the document. A compound clipping path's tags are its own, + /// not those of the compound path that paints its fill apart from it. + fn object_tag(&mut self, vals: &[V], hidden: bool) { + let [.., V::Name(id), V::Str(value)] = vals else { + self.note_unknown("XT", hidden); + return; + }; + if id.is_empty() || id.len() > MAX_TAG_TEXT || value.len() > MAX_TAG_TEXT || !self.after_object || self.pattern.is_some() { + return; + } + let (id, value) = (id.clone(), obj::text(value)); + let Some(kids) = self.frames.last_mut().map(|f| &mut f.children) else { return }; + let Some(mut at) = kids.len().checked_sub(1) else { return }; + if at > 0 && kids.get(at).is_some_and(|n| self.clip_fills.contains(&n.id)) { + at -= 1; + } + let Some(n) = kids.get_mut(at) else { return }; + n.edit_attrs(|a| { + if id == URL_TAG { + a.url = value; + } else if a.data.len() < MAX_TAGS { + a.data.push((id, value)); + } + }); + } + pub(super) fn op(&mut self, w: &str, hidden: bool) -> Result<(), String> { if self.blend_record.is_some() { self.end_blend(); @@ -57,6 +130,14 @@ impl<'a> Reader<'a> { // highlight `-- -- angle length Bh`): a NaN keeps the other operands where they are. "--" => return self.push(V::Num(f64::NAN)), "[" => { + // Drop marks that operators have taken off, so `marks` is the open nesting. + while self.marks.last().is_some_and(|&m| !matches!(self.stack.get(m), Some(V::Mark))) { + self.marks.pop(); + } + // Arrays nest as deep as their `[`s; dropping a deeper one would overflow the stack. + if self.marks.len() >= MAX_DEPTH { + return Err("its objects are nested too deeply".into()); + } self.marks.push(self.stack.len()); return self.push(V::Mark); } @@ -72,19 +153,18 @@ impl<'a> Reader<'a> { "X+" => return Ok(()), _ => {} } - // What follows an object (its name, transparency and style) ends with anything else. The - // state block of a layer whose art ended (`Xy`, `Xd`, `XW`, then `LB`) is read at the `LB`. - if !matches!(w, "Xy" | "Xd" | "XW" | "BB" | "LB") { - self.after_object = false; - self.layer_state = None; - } + self.state_block_continues(w); let group_ended = std::mem::take(&mut self.group_ended); + let mesh_ended = std::mem::take(&mut self.mesh_ended); let vals = self.operands(); let vals = self.take_head(vals); + if self.graph_record(w, hidden) { + return Ok(()); + } // Only `Bh` reads an undefined number. Anywhere else it would reach a point or a size, so // the operator is one the reader doesn't know, as before. if w != "Bh" && !self.frames.is_empty() && vals.iter().any(|v| matches!(v, V::Num(n) if n.is_nan())) { - self.note_unknown("--"); + self.note_unknown("--", hidden); return Ok(()); } if let Some(d) = self.gradient_def.as_mut() { @@ -92,6 +172,7 @@ impl<'a> Reader<'a> { "Bs" => d.stop(&vals, &mut self.stop_spots), "BD" => { if let Some((name, g)) = self.gradient_def.take().and_then(GradientDef::finish) { + self.global_names.define(Global::Gradient, &name); self.gradients.insert(name, g); } } @@ -129,24 +210,34 @@ impl<'a> Reader<'a> { self.end_path_quietly(); self.open(Kind::Compound, hidden)? } + // A wraparound group takes no operands and isn't an element of a compound path. + "*w" | "*W" if !vals.is_empty() => return Err(format!("`{w}` takes no operands")), + "*w" if self.frames.iter().any(|f| matches!(f.kind, Kind::Compound)) => { + return Err("a wraparound group is inside a compound path".into()); + } + "*w" => { + self.end_path_quietly(); + self.open(Kind::Wrap, hidden)? + } "q" => { self.end_path_quietly(); self.open(Kind::Clip, hidden)? } - "U" | "*U" | "Q" => self.end_container(w, hidden)?, + "U" | "*U" | "*W" | "Q" => self.end_container(w, hidden)?, "Lb" => self.layer_attrs(&vals), "Ln" => { if let Some(Frame { kind: Kind::Layer(a), .. }) = self.frames.last_mut() { a.name = vals.iter().rev().find_map(V::text).unwrap_or_default(); } } - "LB" => self.end_layer()?, + "LB" => self.layer_end()?, // Paths. "m" | "l" | "L" | "c" | "C" | "v" | "V" | "y" | "Y" => self.path_op(w, &vals)?, "h" => close(&mut self.path), // Ends a path that stays open. "H" => {} "W" => self.clip_next = true, + "Mb" | "Mv" | "Md" | "ME" | "MB" | "Mi" => self.multi_mask_op(w)?, // A text object's frame or path. "N" | "n" | "F" | "f" | "S" | "s" | "B" | "b" if self.in_text_path() => self.text_path(), "N" | "n" | "F" | "f" | "S" | "s" | "B" | "b" => self.paint(w, hidden, false)?, @@ -162,6 +253,19 @@ impl<'a> Reader<'a> { "O" => self.gs.overprint_fill = Self::nums(&vals).last() == Some(&1.0), "R" => self.gs.overprint_stroke = Self::nums(&vals).last() == Some(&1.0), "XR" => self.gs.rule = if Self::nums(&vals).last() == Some(&1.0) { FillRule::EvenOdd } else { FillRule::NonZero }, + // Show Center (§12): 1 shows the center point of the paths that follow, and 0 leaves + // them at their default, which hides it on an imported path. + "Ap" => match Self::nums(&vals).last().copied() { + Some(1.0) => self.gs.show_center = Some(true), + Some(0.0) => self.gs.show_center = None, + _ => {} + }, + // Object tags (§7): `/identifier (string) XT` after the object it tags. The state written + // after a group or a mesh is still theirs after its tags. + "XT" => { + self.object_tag(&vals, hidden); + (self.group_ended, self.mesh_ended) = (group_ended, mesh_ended); + } "w" => { if let Some(v) = Self::nums(&vals).last().filter(|v| v.is_finite() && **v >= 0.0) { self.gs.width = *v; @@ -201,18 +305,19 @@ impl<'a> Reader<'a> { } } // Transparency and state. - "Xy" => self.transparency(&vals), + "Xy" => self.transparency(&vals, mesh_ended), // A group's own state (`Xd`, `6 () XW`) without an `Xy` keeps the current transparency, as // the file's PDF part draws it. A look's group (`9 () XW`) has no state of its own. "Xd" if group_ended => { let gs = self.gs.clone(); if let Some(n) = self.last_object().filter(|n| matches!(n.kind, NodeKind::Group { .. })) { - (n.opacity, n.blend, n.isolate, n.knockout) = (gs.opacity, gs.blend, gs.isolate, gs.knockout); + (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = + (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); } } "Xw" => self.gs.hidden = Self::nums(&vals).last() == Some(&1.0), "A" => self.gs.locked = Self::nums(&vals).last() == Some(&1.0), - "XW" => self.style_marker(&vals, hidden), + "XW" => self.state_marker(&vals, hidden), // Gradients. "Bd" => self.gradient_def = GradientDef::begin(&vals), "Bs" | "BD" => {} @@ -257,57 +362,93 @@ impl<'a> Reader<'a> { } } // Placed files. - "`" if self.place.is_some() => { - let matrix = vals.iter().find_map(|v| if let V::Arr(a) = v { Some(Self::nums(a)) } else { None }); - let path = vals.iter().rev().find_map(V::text).unwrap_or_default(); - if let Some(p) = self.place.as_mut() { - p.matrix = matrix.and_then(|m| <[f64; 6]>::try_from(m).ok()).map(Affine::new); - p.bounds = - Self::nums(&vals).get(..4).and_then(|b| <[f64; 4]>::try_from(b).ok()).map(|[x0, y0, x1, y1]| Rect::new(x0, y0, x1, y1)); - p.path = path; - } - } + // `[a b c d tx ty] llx lly urx ury (path) `` ` ``, three more numbers before the path in + // newer files: the version 7 form has no `%AI5_BeginPlace` before it. Before the art, + // the setup's procedures run. + "`" if self.place.is_some() || !self.frames.is_empty() => self.place_tick(&vals, hidden), "~" if self.place.is_some() => self.end_place(hidden)?, // Type in the legacy format. "To" => self.begin_text(&vals, hidden), "Tp" => self.begin_text_path(&vals), "TP" => self.end_text_path(), "TO" => self.end_text(hidden)?, - "Tx" | "Tj" | "TX" => self.text_body(w, &vals), - "Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" => self.text_attr(w, &vals), - // Attributes the reader doesn't keep (kerning pairs, spacing, hanging punctuation, - // Far-Eastern type) and final-form positions (§15.3). - "Tk" | "TK" | "TC" | "TW" | "Tq" | "Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" | "T+" | "T-" | "TV" | "Tv" | "Ty" | "TY" | "TG" | "Tg" - | "Tu" | "Xu" => {} - // Hyphenation and tab-ruler attributes the reader doesn't keep either (§22): `Th` - // hyphen control, `XL` hyphenation language, `Xb`/`XB` a tab definition (and the `Xe` - // tab descriptions between them). - "Th" | "XL" | "Xb" | "XB" | "Xe" => {} + // `(text) justified TS`, special characters (§22.6): the reader adds its characters like `Tx`. + "Tx" | "Tj" | "TX" | "TS" => self.text_body(w, &vals), + "Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" | "TC" | "TW" | "Tq" | "Th" | "TV" | "Tv" | "Ty" | "TY" | "Tg" | "Xb" + | "Xe" | "XB" => { + self.text_attr(w, &vals); + } + // Attributes the reader doesn't keep (kerning pairs, line breaking and Japanese layout + // rules) and final-form positions (§15.3). + "Tk" | "TK" | "Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" | "T+" | "T-" | "TG" | "Tu" | "Xu" => {} + // `TM` (pop text matrix) and `Te` (end render), listed in §22.6, keep nothing either; the + // reader takes `Te` with any number of operands. + "TM" | "Te" => {} + // The hyphenation language (`XL`), which the reader doesn't keep either (§22). + "XL" => {} "TE" => self.te(&vals), + "TZ" => self.tz(&vals), // An image whose samples follow in comment lines (read at `%AI5_EndRaster`). "XI" if self.raster.is_some() => { + let max = self.sample_bytes(&vals); if let Some(r) = self.raster.as_mut() { r.operands = Some(vals); + r.max = max; } } + // A linked image (§8.2, §8.3): `(path) modified XG` names the file of the `XF` image after + // it, which has `XI`'s operands and no samples. + "XG" | "XF" => self.image_link_op(w, vals, hidden)?, // A plugin group ends; a blend's record follows on `%` lines. "XP" => { let name = vals.iter().find_map(V::text).unwrap_or_default(); let len = Self::nums(&vals).last().copied().unwrap_or(0.0); if name == crate::import::ai::blend::PLUGIN && len.is_finite() && len > 0.0 && len <= crate::import::ai::blend::MAX_RECORD as f64 { self.blend_record = Some((len as usize, vec![])); + } else if name == crate::import::ai::envelope::PLUGIN { + self.end_envelope(); } } _ if IGNORED.contains(&w) => {} // Before the art, the setup runs procedures of the printing format. _ if self.frames.is_empty() => {} - _ => self.note_unknown(w), + _ => self.note_unknown(w, hidden), } Ok(()) } - /// `… Lb`: a layer's options. The legacy format's has ten operands, its colour index one place - /// earlier (`visible preview unlocked printing dimmed masks colorIndex r g b`). + /// A graph's records (version 7 specification §17 and appendix A): `%_Gs` starts the graph on + /// a layer, `GS` ends it, and its data and settings (the operators in [`GRAPH_OPS`], and any + /// operator on a `%_` line between `Gt` and `GT`) are left out with their operands. Its drawn + /// art, and anything else, is read as usual. `true` when `w` was one of them. + fn graph_record(&mut self, w: &str, hidden: bool) -> bool { + let Some(g) = self.graph.as_mut() else { + // Outside a graph, its operators stay ones the reader doesn't know. + if w == "Gs" && hidden && !self.frames.is_empty() { + self.graph = Some(Graph { settings: false, frames: self.frames.len() }); + self.warn(GRAPH_PLAIN); + return true; + } + return false; + }; + match w { + // A graph doesn't start inside another: the one being read goes on. + "Gs" => self.warn(GRAPH_UNENDED), + "GS" => self.graph = None, + "Gt" => g.settings = true, + "GT" => g.settings = false, + _ if GRAPH_OPS.contains(&w) => {} + _ if hidden && g.settings => {} + _ => return false, + } + true + } + + /// `… Lb`: a layer's options, `visible preview unlocked printing dimmed`, then the colour index + /// and its RGB. The colour index is at 5 with fewer than ten operands, 6 with ten to twelve + /// (`masks` before it) and 7 with thirteen or more (one more flag before it). Four places after + /// the colour index comes the template flag (eleven operands or more), then the dimming + /// percentage (twelve or more, else 50). A fourteenth operand changes nothing here. fn layer_attrs(&mut self, vals: &[V]) { let n = Self::nums(vals); let Some(Frame { kind: Kind::Layer(a), .. }) = self.frames.last_mut() else { return }; @@ -316,9 +457,10 @@ impl<'a> Reader<'a> { a.preview = flag(1, true); a.locked = !flag(2, true); a.printable = flag(3, true); - let dim_pct = n.get(12).copied().filter(|v| v.is_finite()).unwrap_or(50.0).clamp(0.0, 100.0); + let at = 5 + usize::from(n.len() >= 10) + usize::from(n.len() >= 13); + a.template = flag(at + 4, false); + let dim_pct = n.get(at + 5).copied().filter(|v| v.is_finite()).unwrap_or(50.0).clamp(0.0, 100.0); a.dim = flag(4, false).then_some(dim_pct.round() as u8); - let at = if n.len() <= 10 { 6 } else { 7 }; let index = n.get(at).copied().unwrap_or(0.0); let rgb = |i: usize| n.get(at + i).map_or(0, |v| v.clamp(0.0, 255.0) as u8); a.color = Some(if (0.0..vectorcraft_doc::LAYER_COLORS.len() as f64).contains(&index) && index.fract() == 0.0 { @@ -330,7 +472,8 @@ impl<'a> Reader<'a> { /// `(name) x y scaleX scaleY angle reflect axis shear shearAxis [matrix] p` (`P`: the stroke's): /// the pattern swatch `name`, its space taken to art space by the matrix. A pattern this hasn't - /// read can't be drawn. + /// read can't be drawn. For a pattern defined in the version 7 form, the other operands are + /// applied in order before the initial matrix ([`pattern_controls`]). fn pattern_paint(&mut self, w: &str, vals: &[V]) { // In the setup it paints nothing (and the art's space isn't fixed yet). if self.frames.is_empty() { @@ -338,26 +481,51 @@ impl<'a> Reader<'a> { } let name = vals.iter().find_map(|v| if let V::Str(_) = v { v.text() } else { None }); let Some(tile) = name.as_deref().and_then(|n| self.pattern_tiles.get(n)).copied() else { - self.unreadable("pattern fills"); + self.unread_pattern(w); return; }; - let matrix = vals.iter().rev().find_map(|v| if let V::Arr(a) = v { paint::affine(&Self::nums(a)) } else { None }); + let mut matrix = vals.iter().rev().find_map(|v| if let V::Arr(a) = v { paint::affine(&Self::nums(a)) } else { None }); + if name.as_ref().is_some_and(|n| self.v7_patterns.contains(n)) { + let controls: Vec = + vals.iter().skip_while(|v| !matches!(v, V::Str(_))).skip(1).take_while(|v| !matches!(v, V::Arr(_))).filter_map(V::num).collect(); + let Some(controls) = pattern_controls(&controls) else { + self.unread_pattern(w); + return; + }; + matrix = Some(matrix.unwrap_or(Affine::IDENTITY) * controls); + } let Some(xf) = pattern_xf(self.space(), matrix, tile) else { - self.unreadable("pattern fills"); + self.unread_pattern(w); return; }; - let p = Paint::Pattern { pattern: name.unwrap_or_default(), xf }; + let p = Paint::Pattern { pattern: name.as_deref().map(|n| self.global_names.get(Global::Pattern, n).to_string()).unwrap_or_default(), xf }; if w == "p" { + self.pending_unread_fill = false; self.gs.fill = p; } else { + self.pending_unread_stroke = false; self.gs.stroke = p; } } + fn unread_pattern(&mut self, w: &str) { + if self.shown() { + if w == "p" { + self.pending_unread_fill = true; + } else { + self.pending_unread_stroke = true; + } + } + // In a pattern's definition, only art painted with it makes the tile unreadable (see `paint`). + if self.pattern.is_none() && (!self.shown() || self.gs.hidden) { + self.hidden_unread.insert("pattern fills".into()); + } + } + fn color(&mut self, w: &str, vals: &[V]) { let Some((p, named)) = paint::color_op(w, vals) else { return }; // Registration (`Xs`, `Xz`) says nothing of the document's colour model. - let registration = matches!(w, "Xs" | "XS" | "Xz" | "XZ"); + let registration = matches!(w, "Xs" | "XS" | "Xz" | "XZ") || p.is_registration(); match p.color().filter(|_| !registration) { Some(vectorcraft_color::Color::Rgb { .. }) => self.rgb_colors += 1, Some(vectorcraft_color::Color::Cmyk { .. }) => self.cmyk_colors += 1, @@ -371,9 +539,17 @@ impl<'a> Reader<'a> { if w.ends_with(|c: char| c.is_ascii_lowercase()) { self.gs.fill = p; self.pending_fill = None; + self.pending_unread_fill = false; + if let Some(head) = self.symbol.as_mut() { + head.missing_fill = false; + } } else { self.gs.stroke = p; self.pending_stroke = None; + self.pending_unread_stroke = false; + if let Some(head) = self.symbol.as_mut() { + head.missing_stroke = false; + } } } @@ -388,8 +564,66 @@ impl<'a> Reader<'a> { }); } - /// `mode opacity isolate knockout shape Xy`; after a group's end, the group's too. - fn transparency(&mut self, vals: &[V]) { + /// Operator `w` ends what follows an object (its name, transparency and style) unless it is part + /// of a state block. + /// The state block of a layer whose art ended (`Xy`, `Xd`, `XW`, then `LB`) is read at the + /// `LB`, and can have the stroke style between its `Xy` and `Xd`: that keeps the layer's state, + /// and what a mesh or blend before it had (`mesh_undo`). + /// After an image, the operators that end its raster (`XH`, `Xr` and the `N` after + /// `%AI5_EndRaster`) keep it the object its name and opacity mask go to. + fn state_block_continues(&mut self, w: &str) { + if self.image_tail && matches!(w, "XH" | "XT" | "Xr" | "N") { + return; + } + self.image_tail = false; + // An object's tags (`XT`) follow it one after another, and an image's follow the `XH` that + // ends its data. + if matches!(w, "Xy" | "Xd" | "XW" | "BB" | "LB" | "XT" | "XH") { + return; + } + self.after_object = false; + if !matches!(w, "J" | "j" | "w" | "M" | "d" | "XR") { + self.layer_state = None; + self.mesh_undo = None; + self.container_undo = None; + } + } + + /// `n (style) XW`: the end of a state block, or a style marker ([`Self::style_marker`]). + fn state_marker(&mut self, vals: &[V], hidden: bool) { + let code = Self::nums(vals).last().copied(); + // An object's own state block ends `6 () XW`: an `Xy` after a mesh's end was the mesh's. + if code == Some(6.0) && self.mesh_undo.take().is_some() { + self.layer_state = None; + } + match code { + Some(6.0) => self.container_undo = None, + Some(7.0) => self.layer_state_block(), + _ => {} + } + self.style_marker(vals, hidden) + } + + /// `7 () XW` ends a layer's own state block (after its art, before `LB`): an `Xy` that went to + /// the layer's last group or compound path, right after its end, was the layer's. + fn layer_state_block(&mut self) { + let Some(before) = self.container_undo.take() else { return }; + let gs = &self.gs; + let state = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); + let Some(Frame { kind: Kind::Layer(_), children, .. }) = self.frames.last_mut() else { return }; + let Some(n) = + children.last_mut().filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. } | NodeKind::SymbolInstance { .. })) + else { + return; + }; + (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = before; + self.layer_state = Some(state); + } + + /// `mode opacity isolate knockout shape Xy`; after a group's end or a symbol instance, theirs + /// too, and right after a gradient mesh's `/End X!` or a blend's record (before their `Xd` and + /// `6 () XW`), theirs, unless the layer's `LB` follows: then it is the layer's (see `end_layer`). + fn transparency(&mut self, vals: &[V], mesh_ended: bool) { let n = Self::nums(vals); let [mode, opacity, rest @ ..] = n.as_slice() else { return }; let gs = &mut self.gs; @@ -403,20 +637,67 @@ impl<'a> Reader<'a> { }; gs.knockout_shape = rest.get(2).is_some_and(|v| *v != 0.0); let gs = self.gs.clone(); - if self.last_object().is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. })) { - if let Some(n) = self.last_object() { - n.opacity = gs.opacity; - n.blend = gs.blend; - n.isolate = gs.isolate; - n.knockout = gs.knockout; - } + let in_layer = matches!(self.frames.last(), Some(Frame { kind: Kind::Layer(_), .. })); + if let Some(n) = + self.last_object().filter(|n| (mesh_ended && matches!(n.kind, NodeKind::Mesh(_))) || matches!(n.kind, NodeKind::Blend { .. })) + { + // The mesh's or blend's, or the layer's when it is the layer's last object: kept for either. + let before = (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape); + (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); + self.mesh_undo = Some(before); + self.layer_state = in_layer.then_some((gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape)); + } else if let Some(n) = self.last_object().filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. })) { + let before = (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape); + (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); + // The layer's instead when the layer's `7 () XW` follows (`layer_state_block`). + self.container_undo = in_layer.then_some(before); + self.layer_state = None; + } else if let Some(n) = self.last_object().filter(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) { + // A symbol instance's, as a group's. + let before = (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape); + (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); + self.container_undo = in_layer.then_some(before); self.layer_state = None; } else { // After a layer's art and before its `LB`: the layer's own state (#2003). Kept until // an operator that isn't part of the state block (or the `LB` that takes it) says the // art moves on, so a path's state before its paint isn't read as its layer's. - self.layer_state = - matches!(self.frames.last(), Some(Frame { kind: Kind::Layer(_), .. })).then_some((gs.opacity, gs.blend, gs.isolate, gs.knockout)); + self.layer_state = in_layer.then_some((gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape)); + } + self.note_state(); + } + + /// Inside a dictionary in the art (a text's frame, a mask's art), the transparency just set + /// stays after the dictionary: the writer goes on from it, so the objects after an area text + /// whose frame sets one have no `Xy` of their own. + fn note_state(&mut self) { + let gs = &self.gs; + let state = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); + if self.frames.iter().any(|f| matches!(f.kind, Kind::Layer(_))) + && let Some(f) = self.frames.iter_mut().rev().find(|f| matches!(f.kind, Kind::Obj(_))) + { + f.state = Some(state); + } + } + + /// A dictionary's art set transparency `state` (see [`Self::note_state`]): it is the current + /// one now, and the enclosing dictionary's. + pub(super) fn keep_state(&mut self, state: (f32, BlendMode, bool, Knockout, bool)) { + let gs = &mut self.gs; + (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape) = state; + self.note_state(); + } + + /// Brings [`Reader::brushes_kept`] up to date with the brushes and brush art read so far. + fn note_brushes_kept(&mut self) { + use super::super::brush; + let read = (self.brush_drafts.len(), self.brush_art_sections); + if self.brushes_kept.read != read { + self.brushes_kept = BrushesKept { + read, + kept: brush::kept(&self.brush_drafts, &self.brush_art), + bending: brush::bending_art(&self.brush_drafts, &self.brush_art), + }; } } @@ -427,6 +708,10 @@ impl<'a> Reader<'a> { let code = Self::nums(vals).last().copied().unwrap_or(0.0); let style = vals.iter().rev().find_map(V::text).unwrap_or_default(); let after = std::mem::take(&mut self.after_object); + // An object's own state block ends `6 () XW` (a layer's `7 () XW`): an `Xy` before it isn't the layer's. + if code == 6.0 { + self.layer_state = None; + } if code == 9.0 && let Some(look) = self .frames @@ -436,10 +721,24 @@ impl<'a> Reader<'a> { { self.looks.insert(look.id); } + // The type that a text object's look draws is the object's own, whatever comes of its style. + let mut look_drew_type = false; + if after + && let Some(f) = self.frames.last_mut() + && let [.., look, object] = f.children.as_mut_slice() + && slot_of(object.name.as_deref()).is_some() + && !super::is_look_slot(object.name.as_deref()) + && self.hidden_ids.contains(&object.id) + && self.hidden_ids.contains(&look.id) == hidden + && matches!(look.kind, NodeKind::Group { clip: false, .. }) + { + look_drew_type = strip_look_type(look); + } if code != 1.0 || style.is_empty() || !after { return; } let space = self.space(); + self.note_brushes_kept(); let Some(f) = self.frames.last_mut() else { return }; let n = f.children.len(); let (Some(object), Some(look)) = (n.checked_sub(1).and_then(|i| f.children.get(i)), n.checked_sub(2).and_then(|i| f.children.get(i))) else { @@ -454,21 +753,60 @@ impl<'a> Reader<'a> { return; } // A style read here: the object, painted as it says. - if let Some(appearance) = self - .styles - .get(&style) - .and_then(|st| styled(object, look, st, &StylePaints { gradients: &self.gradients, patterns: &self.pattern_tiles, space })) - { + if let Some(mut appearance) = self.styles.get(&style).and_then(|st| { + styled( + object, + look, + st, + &StylePaints { + gradients: &self.gradients, + patterns: &self.pattern_tiles, + names: &self.global_names, + v7_patterns: &self.v7_patterns, + brushes: &self.brush_drafts, + kept: &self.brushes_kept.kept, + bending: &self.brushes_kept.bending, + space, + }, + ) + }) { + // Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up). + let k = space.determinant().abs().sqrt(); + if k.is_finite() && k > 0.0 && (k - 1.0).abs() > 1e-9 { + appearance.scale_strokes(k); + appearance.scale_effects(k, vectorcraft_effects::scale_effect); + } let Some(mut object) = f.children.pop() else { return }; let Some(look) = f.children.pop() else { return }; - if let Some(b) = look.visual_bounds().filter(|_| !hidden && object.visible && look.visible) { + let left_out = look.visual_bounds().filter(|_| !hidden && object.visible && look.visible); + if let Some(b) = left_out { self.restyled.push(b); } + // Warped type is checked against its look once it is laid out. The look stands in for + // the type only when it holds all that the object draws: not when it draws nothing or + // draws type of its own. + if slot_of(object.name.as_deref()).is_some() && crate::import::ai::envelope::warps(&appearance) && self.warped_type.len() < MAX_NODES { + let mut saved = look.clone(); + // When the object itself is on `%_` lines, every child of its look is too, so the + // look's own copies can't be told apart from the rest. + if !hidden { + strip(&mut saved, &self.hidden_ids); + } + if !look_drew_type && !holds_type(&saved) && saved.visual_bounds().is_some() && draws_art(&saved, 0) { + take_attributes(&mut saved, &object); + self.warped_type.push(crate::import::ai::envelope::WarpedLook { slot: object.id, look: saved, left_out }); + } + } object.appearance = appearance.into(); // The object's transparency is written on its look, after the look's group ends. - (object.opacity, object.blend, object.isolate, object.knockout) = (look.opacity, look.blend, look.isolate, look.knockout); + (object.opacity, object.blend, object.isolate, object.knockout, object.knockout_shape) = + (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape); // Now the object itself, not a copy an enclosing look's `strip` would remove. self.hidden_ids.remove(&object.id); + // Linked to the style when the style list has its name ([`Reader::finish`]). + if self.style_links.len() < MAX_NODES { + self.style_links.push((object.id, style.clone())); + } f.children.push(object); return; } @@ -483,8 +821,9 @@ impl<'a> Reader<'a> { // A text object stays the type it is: over what else its look draws, or in place of a // look that was only its type. Its transparency is written on its look. let empty = look.children().is_some_and(|c| c.is_empty()); - if empty || (look.opacity >= 1.0 && look.blend == BlendMode::Normal && !look.isolate) { - (object.opacity, object.blend, object.isolate, object.knockout) = (look.opacity, look.blend, look.isolate, look.knockout); + if empty || (look.opacity >= 1.0 && look.blend == BlendMode::Normal && !look.isolate && !look.knockout_shape) { + (object.opacity, object.blend, object.isolate, object.knockout, object.knockout_shape) = + (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape); if empty { *look = object; } else { @@ -494,11 +833,11 @@ impl<'a> Reader<'a> { } // The look and the type go into a group that has the transparency. let Some(mut look) = f.children.pop() else { return }; - let state = (look.opacity, look.blend, look.isolate, look.knockout); - (look.opacity, look.blend, look.isolate, look.knockout) = (1.0, BlendMode::Normal, false, Knockout::Neutral); - (object.opacity, object.blend, object.isolate) = (1.0, BlendMode::Normal, false); + let state = (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape); + (look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) = (1.0, BlendMode::Normal, false, Knockout::Neutral, false); + (object.opacity, object.blend, object.isolate, object.knockout_shape) = (1.0, BlendMode::Normal, false, false); let mut group = Node::group(self.doc.alloc_id(), vec![Arc::new(look), Arc::new(object)]); - (group.opacity, group.blend, group.isolate, group.knockout) = state; + (group.opacity, group.blend, group.isolate, group.knockout, group.knockout_shape) = state; self.text_looks.insert(group.id); if let Some(f) = self.frames.last_mut() { f.children.push(group); @@ -508,12 +847,47 @@ impl<'a> Reader<'a> { look.name = object.name.clone().or(look.name.take()); look.visible = object.visible; look.locked = object.locked; + take_attributes(look, &object); if !hidden { self.drawn_looks += 1; } } } +/// Does `n` or anything shown in it (to [`MAX_DEPTH`]) paint? Any object other than a path, a +/// compound path or a group counts: it draws more than its fills and strokes. +fn draws_art(n: &Node, depth: usize) -> bool { + depth > MAX_DEPTH + || !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Group { .. }) + || n.appearance.items.iter().any(|i| i.visible() && !i.paint().is_none()) + || n.children().into_iter().flatten().any(|c| c.visible && draws_art(c, depth + 1)) +} + +/// Is `n` or anything in it a text slot? +fn holds_type(n: &Node) -> bool { + slot_of(n.name.as_deref()).is_some() || n.children().into_iter().flatten().any(|c| holds_type(c)) +} + +/// The note, Show Center, URL and data (object tags) of `object` stay with the `look` that stands +/// for it, in place of the look's own where the object has them. +fn take_attributes(look: &mut Node, object: &Node) { + if let Some(a) = object.extras().attrs.as_deref().cloned() { + look.edit_attrs(|l| { + if a.show_center.is_some() { + l.show_center = a.show_center; + } + if !a.url.is_empty() { + l.url = a.url; + } + if !a.note.is_empty() { + l.note = a.note; + } + let room = MAX_TAGS.saturating_sub(l.data.len()); + l.data.extend(a.data.into_iter().take(room)); + }); + } +} + /// Whether `look`'s paths don't all paint the same. pub(super) fn paints_apart(look: &Node) -> bool { fn leaves<'a>(n: &'a Node, out: &mut Vec<&'a Node>) { @@ -542,13 +916,57 @@ fn pattern_xf(space: Affine, matrix: Option, tile: Rect) -> Option= 1e-12 && xf.as_coeffs().iter().all(|v| v.is_finite())).then_some(xf) } -/// What a style's fills paint with: the file's gradients and pattern tiles, and art space → the document. +/// A pattern fill's `x y scaleX scaleY angle reflect axis shear shearAxis` as one transform of the +/// pattern's space, applied before its initial matrix: the shear (by `shear` degrees along the line +/// at `shearAxis` degrees), the reflection about the line at `axis` degrees when `reflect` isn't +/// 0, the counterclockwise rotation by `angle` degrees, the scale, then the move to `x y`. `None` +/// unless there are nine finite numbers. +fn pattern_controls(n: &[f64]) -> Option { + let &[x, y, sx, sy, angle, reflect, axis, shear, shear_axis] = n else { return None }; + if !n.iter().all(|v| v.is_finite()) { + return None; + } + let turn = |deg: f64| Affine::rotate(deg.to_radians()); + let reflection = if reflect != 0.0 { turn(axis) * Affine::scale_non_uniform(1.0, -1.0) * turn(-axis) } else { Affine::IDENTITY }; + let shearing = if shear != 0.0 { + turn(shear_axis) * Affine::new([1.0, 0.0, shear.to_radians().tan(), 1.0, 0.0, 0.0]) * turn(-shear_axis) + } else { + Affine::IDENTITY + }; + let xf = Affine::translate((x, y)) * Affine::scale_non_uniform(sx, sy) * turn(angle) * reflection * shearing; + xf.as_coeffs().iter().all(|v| v.is_finite()).then_some(xf) +} + +/// What a style's fills paint with: the file's gradients and pattern tiles with the names they get +/// in the document, the patterns defined in the version 7 form, and art space → the document. struct StylePaints<'a> { gradients: &'a HashMap, patterns: &'a HashMap, + names: &'a ShownNames, + v7_patterns: &'a HashSet, + /// The brushes the file defines, which a brushed stroke names. + brushes: &'a [super::super::brush::BrushDraft], + /// Which of [`Self::brushes`] are kept as brushes ([`super::super::brush::kept`]). + kept: &'a [bool], + /// The art an Art brush draws as the file does ([`super::super::brush::bending_art`]). + bending: &'a HashSet, space: Affine, } +/// A placed file's `` ` `` operands → its matrix, its box and its path: an array of six numbers, four +/// numbers, three more or none, and a string. `None` for any other shape or a number that isn't +/// finite. +fn tick(vals: &[V]) -> Option<(Affine, Rect, String)> { + let [V::Arr(m), rest @ .., V::Str(path)] = vals else { return None }; + let m = <[f64; 6]>::try_from(m.iter().map(V::num).collect::>>()?).ok()?; + let nums: Vec = rest.iter().map(V::num).collect::>()?; + let [x0, y0, x1, y1] = match nums.as_slice() { + [x0, y0, x1, y1] | [x0, y0, x1, y1, _, _, _] => [*x0, *y0, *x1, *y1], + _ => return None, + }; + m.iter().chain(&nums).all(|v| v.is_finite()).then(|| (Affine::new(m), Rect::new(x0, y0, x1, y1), obj::text(path))) +} + /// The gradients and patterns `look` paints with, placed as it draws them, by their swatch's name /// (the first of each; a pattern's name after `PATTERN_KEY`). fn placed_paints(look: &Node, out: &mut HashMap, depth: usize) { @@ -570,18 +988,88 @@ fn placed_paints(look: &Node, out: &mut HashMap, depth: usize) { } } +/// Is `n` a path, a compound path or a group without a clip, with no opacity mask, the objects +/// whose outline the effects that move it (Transform, Twist, Free Distort) are read on? Images, +/// type (and a text object's slot, filled with type placed where the page has it) and live objects +/// draw more than their outline, and a mask stays where it is. +fn outlines_only(n: &Node) -> bool { + matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Group { clip: false, .. }) + && n.extras().mask.is_none() + && slot_of(n.name.as_deref()).is_none() +} + +/// Does `n`, inside an object whose outline an effect moves, move with it: is it and everything in +/// it [`outlines_only`], painting with no gradient or pattern (which stay where they are placed) +/// and with no effects of its own (drawn after the outer effect, not before)? Deeper than +/// [`MAX_DEPTH`] counts as no. +fn moves_alike(n: &Node, depth: usize) -> bool { + depth <= MAX_DEPTH + && outlines_only(n) + && n.appearance.effects.is_empty() + && n.appearance.items.iter().all(|i| i.effects().is_empty() && !matches!(i.paint(), Paint::Gradient(_) | Paint::Pattern { .. })) + && n.children().into_iter().flatten().all(|c| moves_alike(c, depth + 1)) +} + +/// Does `n` or anything in it (to [`MAX_DEPTH`]) have a stroke that paints? +fn strokes(n: &Node, depth: usize) -> bool { + depth > MAX_DEPTH + || n.appearance.items.iter().any(|i| !i.is_fill() && !i.paint().is_none()) + || n.children().into_iter().flatten().any(|c| strokes(c, depth + 1)) +} + +/// Are all of path or compound path `n`'s segments straight, each anchor's handles on it? +fn straight(n: &Node) -> bool { + match &n.kind { + NodeKind::Path { path, .. } => path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.h_in == a.p && a.h_out == a.p), + NodeKind::Compound { children, .. } => children.iter().all(|c| matches!(c.kind, NodeKind::Path { .. }) && straight(c)), + _ => false, + } +} + +/// Is `object` one that style `st`, whose effect moves the outline, is read on? It and everything +/// in it [`moves_alike`], and the style paints no gradient. Twist is read only on an unstroked path +/// or compound path with straight segments, and Transform that scales, turns or reflects only when +/// nothing is stroked (its reference point lies on the bounds without strokes). +fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { + use crate::import::ai::style::StyleItem; + let stroked = st.items.iter().any(|i| matches!(i, StyleItem::Stroke { paint, .. } if !paint.is_none())) + || object.children().into_iter().flatten().any(|c| strokes(c, 1)); + !st.items.iter().any(|i| matches!(i, StyleItem::Gradient { .. })) + && outlines_only(object) + && object.children().into_iter().flatten().all(|c| moves_alike(c, 1)) + && st.effects.iter().all(|e| match e.id.as_str() { + "distort.twist" => !stroked && matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && straight(object), + "distort.transform" => { + let p = &e.params; + !stroked + || (p["scaleH"].as_f64() == Some(100.0) + && p["scaleV"].as_f64() == Some(100.0) + && p["rotate"].as_f64() == Some(0.0) + && p["reflectX"].as_bool() == Some(false) + && p["reflectY"].as_bool() == Some(false)) + } + _ => true, + }) +} + /// What [`placed_paints`] keys a pattern's name with, apart from the gradients' names. const PATTERN_KEY: &str = "\u{1}pattern "; /// `object`'s appearance with style `st`, its drawn look `look`: `None` when the style isn't one -/// this reads, or asks a group for fills or strokes. +/// this reads, asks a group for fills or strokes, has Pathfinder effects on anything but a group +/// with no fills or strokes, or moves the outline of an object it isn't read on ([`moves_with`]). fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, paints: &StylePaints) -> Option { use crate::import::ai::style::StyleItem; // A text object's slot (an empty group standing for it) takes the style as the type will. let slot = slot_of(object.name.as_deref()).is_some(); + // A symbol instance draws its symbol's art: it keeps its drawn look. if !st.plain + || matches!(object.kind, NodeKind::SymbolInstance { .. }) || (!slot && !st.simple) || (object.is_container() && !slot && !matches!(object.kind, NodeKind::Compound { .. }) && !st.items.is_empty()) + || (st.pathfinder + && (slot || !st.items.is_empty() || object.is_compound_shape() || !matches!(object.kind, NodeKind::Group { clip: false, .. }))) + || (!slot && st.moves_outline() && !moves_with(object, st)) { return None; } @@ -597,7 +1085,8 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p let mut layer = match item { StyleItem::Fill(paint) => AppearanceItem::Fill(FillLayer::new(paint.clone())), StyleItem::Gradient { name, angle } => { - let paint = match (name.as_ref().and_then(|n| placed.get(n)), gradients, own_gradient) { + // The drawn look's gradients are keyed by the names they got in the document. + let paint = match (name.as_ref().and_then(|n| placed.get(paints.names.get(Global::Gradient, n))), gradients, own_gradient) { // Other objects than type: the object's own, as they always were. (_, 1, Some(own)) if !slot => own.paint.clone(), (Some(p), ..) => p.clone(), @@ -612,29 +1101,42 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p }; AppearanceItem::Fill(FillLayer::new(paint)) } - StyleItem::Pattern { name, matrix } => match placed.get(&format!("{PATTERN_KEY}{name}")) { + StyleItem::Pattern { name, matrix, controls } => match placed.get(&format!("{PATTERN_KEY}{}", paints.names.get(Global::Pattern, name))) { Some(p) => AppearanceItem::Fill(FillLayer::new(p.clone())), None => { let tile = paints.patterns.get(name).copied()?; - let xf = pattern_xf(paints.space, matrix.and_then(|m| paint::affine(&m)), tile)?; - AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: name.clone(), xf })) + let mut matrix = matrix.and_then(|m| paint::affine(&m)); + if paints.v7_patterns.contains(name) { + matrix = Some(matrix.unwrap_or(Affine::IDENTITY) * pattern_controls(controls)?); + } + let xf = pattern_xf(paints.space, matrix, tile)?; + AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: paints.names.get(Global::Pattern, name).to_string(), xf })) } }, - StyleItem::Stroke { paint, width, cap, join, miter, dash, profile } => { - let mut layer = StrokeLayer::new(paint.clone(), *width); - (layer.cap, layer.join, layer.miter_limit, layer.dash, layer.profile) = (*cap, *join, *miter, dash.clone(), profile.clone()); - AppearanceItem::Stroke(layer) + StyleItem::Stroke { brush, .. } => { + // A brushed stroke draws as its look only with the brush the Brushes panel keeps + // under its name, at the object's settings, on a path, a compound path or type (an + // image draws no stroke). An Art brush is read on a path or a compound path with + // no effects. + if let Some((name, settings)) = brush { + let (draft, _) = paints.brushes.iter().zip(paints.kept).find(|(d, kept)| **kept && &d.name == name)?; + if !super::super::brush::draws_as(draft, settings, paints.bending) { + return None; + } + let art = matches!(settings, super::super::brush::PathBrush::Art); + let on_a_path = matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); + if !on_a_path && (art || !slot) { + return None; + } + if art && !st.effects.is_empty() { + return None; + } + } + stroke_layer(item)? } }; if let Some(look) = st.looks.get(n) { - match &mut layer { - AppearanceItem::Fill(f) => { - (f.visible, f.opacity, f.blend, f.effects) = (look.visible, look.opacity, look.blend, look.effects.clone()) - } - AppearanceItem::Stroke(s) => { - (s.visible, s.opacity, s.blend, s.effects) = (look.visible, look.opacity, look.blend, look.effects.clone()) - } - } + with_look(&mut layer, look); } items.push(layer); } @@ -646,6 +1148,107 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p Some(Appearance { items, effects: st.effects.clone(), contents_index }) } +/// A graphic style's appearance from art style `st`, on no object: `None` when the style isn't one +/// this reads, or paints with a gradient or a pattern (placed on each object as its drawn look has them). +pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle) -> Option { + use crate::import::ai::style::StyleItem; + if !st.plain { + return None; + } + let mut items = vec![]; + for (n, item) in st.items.iter().enumerate() { + let mut layer = match item { + StyleItem::Fill(paint) => AppearanceItem::Fill(FillLayer::new(paint.clone())), + // A graphic style's brush isn't checked against the file's brushes: it is left out. + StyleItem::Stroke { brush: Some(_), .. } => return None, + StyleItem::Stroke { .. } => stroke_layer(item)?, + StyleItem::Gradient { .. } | StyleItem::Pattern { .. } => return None, + }; + if let Some(look) = st.looks.get(n) { + with_look(&mut layer, look); + } + items.push(layer); + } + Some(Appearance { items, effects: st.effects.clone(), contents_index: st.contents_index }) +} + +/// What the reader makes of art style `name` in `section` (the text between `%AI9_BeginArtStyles` +/// and its end), for writers that check a style before they write it. +#[derive(Clone, Debug)] +pub(crate) struct StyleRead { + /// The style's appearance: a gradient fill is the object's own gradient. + pub appearance: Appearance, + /// An object other than type is read with it ([`crate::import::ai::style::ArtStyle::simple`]). + pub simple: bool, + /// It has Effect › Pathfinder effects, which only a group with no fills or strokes is read with. + pub pathfinder: bool, + /// The opacity, blending mode, isolation and knockout its blend filter gives. + pub transparency: Option<(f32, BlendMode, bool, Knockout)>, +} + +/// The names a style list section gives graphic styles, as the reader reads them. +pub(crate) fn read_style_list(section: &[u8]) -> Vec { + crate::import::ai::style::art_style_list(section).iter().map(|raw| obj::text(raw)).filter(|name| !name.is_empty()).collect() +} + +/// Art style `name` of `section` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], +/// with a style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads +/// it on objects other than type. `None` when the section doesn't define it, the reader doesn't read +/// it, or it paints with a pattern, a brush or a gradient that isn't the object's own. +pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&Paint>) -> Option { + use crate::import::ai::style::StyleItem; + let mut st = crate::import::ai::style::art_styles(section).remove(name)?; + if st.items.iter().filter(|i| matches!(i, StyleItem::Gradient { .. })).count() == 1 { + let own = own_gradient?; + for item in &mut st.items { + if matches!(item, StyleItem::Gradient { .. }) { + *item = StyleItem::Fill(own.clone()); + } + } + } + let appearance = appearance_from_art_style(&st)?; + Some(StyleRead { appearance, simple: st.simple, pathfinder: st.pathfinder, transparency: st.transparency }) +} + +/// Is art style `name` of `section` read on `object` as far as an effect that moves the outline +/// goes: the style has none, or `object` is one [`moves_with`] reads it on, as [`styled`] checks? +/// `false` when the section doesn't define it. +pub(crate) fn style_moves_with(section: &[u8], name: &str, object: &Node) -> bool { + crate::import::ai::style::art_styles(section).remove(name).is_some_and(|st| !st.moves_outline() || moves_with(object, &st)) +} + +/// A style's stroke as an appearance item (`None` for a fill). +fn stroke_layer(item: &crate::import::ai::style::StyleItem) -> Option { + let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile, align, brush } = item else { return None }; + let mut layer = StrokeLayer::new(paint.clone(), line_width(*width)); + (layer.cap, layer.join, layer.miter_limit, layer.dash, layer.profile, layer.align) = (*cap, *join, *miter, dash.clone(), profile.clone(), *align); + layer.brush = brush.as_ref().map(|(name, _)| name.clone()); + Some(AppearanceItem::Stroke(layer)) +} + +/// Give `layer` a fill's or stroke's own visibility, transparency and effects. +fn with_look(layer: &mut AppearanceItem, look: &crate::import::ai::style::ItemLook) { + match layer { + AppearanceItem::Fill(f) => (f.visible, f.opacity, f.blend, f.effects) = (look.visible, look.opacity, look.blend, look.effects.clone()), + AppearanceItem::Stroke(s) => (s.visible, s.opacity, s.blend, s.effects) = (look.visible, look.opacity, look.blend, look.effects.clone()), + } +} + +/// Remove from `n` the text slots of the type its look draws ([`super::is_look_slot`]), in its groups +/// too. Returns whether there were any. +fn strip_look_type(n: &mut Node) -> bool { + let mut any = false; + if let Some(children) = n.children_mut() { + let before = children.len(); + children.retain(|c| !super::is_look_slot(c.name.as_deref())); + any = children.len() != before; + for c in children.iter_mut().filter(|c| c.children().is_some_and(|k| !k.is_empty())) { + any |= strip_look_type(Arc::make_mut(c)); + } + } + any +} + /// Remove from `n` the children read from `%_` lines (`hidden`: the object itself, not its look). fn strip(n: &mut Node, hidden: &HashSet) { if let Some(children) = n.children_mut() { @@ -655,3 +1258,217 @@ fn strip(n: &mut Node, hidden: &HashSet) { } } } + +/// Whether ASCII85 data in comment lines, up to its `~>`, follows the entry keyed `key` of a +/// dictionary of type `ty`: the `/ASCII85Decode` of a `/Binary` dictionary or a text document, or a +/// non-native art object's (`/ForeignObject`'s) `/Data`. +pub(super) fn ascii85_follows(ty: &str, key: Option<&str>) -> bool { + matches!((ty, key), ("Binary" | "AI11TextDocument" | "AI11UndoFreeTextDocument", Some("ASCII85Decode")) | ("ForeignObject", Some("Data"))) +} + +/// The dictionaries (`/Type :` … `;`) a scan of tokens passes that the reader doesn't read, kept to +/// tell where an entry's ASCII85 data follows ([`ascii85_follows`]), so the scan can skip past it +/// as the reader does: a `(` on a `%_` line of the data would otherwise open a string. +#[derive(Clone, Default)] +pub(super) struct Dictionaries<'s> { + /// The open dictionaries' types, innermost last, up to [`MAX_DEPTH`]. + types: Vec<&'s [u8]>, + /// How many more are open inside the last of `types`. + deeper: usize, + /// The name just before the token taken. + name: Option<&'s [u8]>, + /// Whether the string just before the token taken is a key that ASCII85 data follows. + string_key: bool, + /// The end markers of the sections being scanned (`None`: no section) where the rest of the data + /// had no `~>` or marker to stop at, so they aren't searched for again in those sections. + no_end: Vec>, +} + +/// Where the ASCII85 data at the start of `rest` stops: just past its `~>`, or at the comment that +/// comes first with a marker of `section`, the begin and end markers of the section being scanned +/// (no begin marker when it's empty). A line of the data that reads as one of them counts as the +/// marker. `None` when `rest` has neither. +fn data_end(rest: &[u8], section: Option<(&str, &str)>) -> Option { + let mut at = 0; + for line in rest.split(|b| matches!(b, b'\r' | b'\n')) { + // The first line is what is left of the key's line, where a `%` starts no marker. + if at > 0 + && let Some((comment, (begin, end))) = line.strip_prefix(b"%").zip(section) + { + let comment = String::from_utf8_lossy(comment); + let marker = super::marker(&comment); + if marker == end || (!begin.is_empty() && marker == begin) { + return Some(at); + } + } + if let Some(i) = line.windows(2).position(|w| w == b"~>") { + return Some(at + i + 2); + } + at += line.len() + 1; + } + None +} + +impl<'s> Dictionaries<'s> { + /// Take `tok`, the token `lex` just gave, and skip the ASCII85 data that follows it, up to where + /// [`data_end`] stops for `section`, so the scan still finds that section's markers. + pub(super) fn pass(&mut self, tok: &super::Tok<'s>, lex: &mut super::Lexer<'s>, section: Option<(&str, &str)>) { + let end = section.map(|(_, end)| end); + if self.data_follows(tok) && !self.no_end.iter().any(|e| e.as_deref() == end) { + match data_end(lex.rest(), section) { + Some(stop) => lex.seek(lex.offset() + stop), + None => self.no_end.push(end.map(str::to_owned)), + } + } + } + + /// Take the next token → whether ASCII85 data follows it. + fn data_follows(&mut self, tok: &super::Tok<'s>) -> bool { + // Comments between a name and what follows it are passed over, as the reader passes them. + if matches!(tok, super::Tok::Comment(_)) { + return false; + } + let name = self.name.take(); + let string_key = std::mem::take(&mut self.string_key); + match tok { + super::Tok::Name(n) => self.name = Some(n), + // A string keys an entry as a name does, but gives a dictionary no type. + super::Tok::Str(s) | super::Tok::Hex(s) => self.string_key = self.keys_data(s), + super::Tok::Word(b":") if self.types.len() < MAX_DEPTH => self.types.push(name.unwrap_or_default()), + super::Tok::Word(b":") => self.deeper = self.deeper.saturating_add(1), + super::Tok::Word(b";") if self.deeper > 0 => self.deeper -= 1, + super::Tok::Word(b";") => { + self.types.pop(); + } + super::Tok::Word(b",") => return string_key || name.is_some_and(|key| self.keys_data(key)), + _ => {} + } + false + } + + /// Whether ASCII85 data follows an entry keyed `key` of the innermost dictionary. + fn keys_data(&self, key: &[u8]) -> bool { + let Some(ty) = self.types.last().filter(|_| self.deeper == 0) else { return false }; + let (Ok(ty), Ok(key)) = (std::str::from_utf8(ty), std::str::from_utf8(key)) else { return false }; + ascii85_follows(ty, Some(key)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::ImageObject; + use vectorcraft_geom::shapes; + + fn square(id: u64, fill: Paint) -> Arc { + Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, Paint::None, 0.0))) + } + + /// An image draws no stroke, so an image with a brush in its art style keeps its drawn look. + #[test] + fn an_image_with_a_brush_keeps_its_drawn_look() { + use super::super::super::brush::{Tool, parse_tool_object}; + let tool = "Adobe Calligraphic Brush Tool"; // brand-ok: the filter's name in the files + let text = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Inked) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n({tool}) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /StrokeStyle : 0 R\n0 1 1 0 1 0 0 XA\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n\ + 6 /Real (Diameter) ,\n2 /Real (DiameterVariation) ,\n2 /Int (DiameterDependsOn) ,\n\ + 40 /Real (Roundness) ,\n10 /Real (RoundnessVariation) ,\n5 /Int (RoundnessDependsOn) ,\n\ + 30 /Real (Angle) ,\n180 /Real (AngleVariation) ,\n6 /Int (AngleDependsOn) ,\n0 /Int (AngleRelativeTo) ,\n\ + /GObjRef : (N) ({tool}) /PluginObject ; (Brush) ,\n; /Dict ;\n /Part ,\n;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ); + let styles = crate::import::ai::style::art_styles(text.as_bytes()); + let st = &styles["Inked"]; + let brushes = [parse_tool_object(Tool::Calligraphic, "N", "1 4 8 30 50 -150 210 2 5 6 0").unwrap()]; + let (gradients, patterns, names, v7_patterns, bending) = + (HashMap::new(), HashMap::new(), ShownNames::default(), HashSet::new(), HashSet::new()); + let paints = StylePaints { + gradients: &gradients, + patterns: &patterns, + names: &names, + v7_patterns: &v7_patterns, + brushes: &brushes, + kept: &[true], + bending: &bending, + space: Affine::IDENTITY, + }; + let look = Node::group(NodeId(1), vec![square(2, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))]); + assert!(styled(&square(3, Paint::None), &look, st, &paints).is_some(), "a path takes the style"); + let image = + ImageObject { key: "a".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + assert!(styled(&Node::new(NodeId(4), NodeKind::Image(Box::new(image))), &look, st, &paints).is_none()); + } + + #[test] + fn data_stops_at_its_end_or_a_marker_of_the_section() { + let section = Some(("BeginTextDocument", "EndTextDocument")); + assert_eq!(data_end(b"\n%_(a~>\n%AI11_EndTextDocument\n", section), Some(7)); + assert_eq!(data_end(b"\n%_(a\n%AI11_EndTextDocument\n", section), Some(6)); + assert_eq!(data_end(b"\n%_(a\n%AI11_BeginTextDocument\n", section), Some(6)); + // Bytes that aren't UTF-8 after the marker, as the scan reads a comment. + assert_eq!(data_end(b"\n%_(a\n%AI11_EndTextDocument \xff\n", section), Some(6)); + // Right after the key a `%` starts no marker, and an empty begin marker matches no comment. + assert_eq!(data_end(b"%AI11_EndTextDocument\n%_(a\n", section), None); + assert_eq!(data_end(b"\n%\n", Some(("", "EndPalette"))), None); + assert_eq!(data_end(b"\n%AI11_EndTextDocument\n", None), None); + } + + #[test] + fn only_outlines_without_gradients_move_alike() { + // GUARDS: an image's pixels and a placed gradient stay behind when an effect moves the outline. + let solid = || square(2, Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))); + assert!(moves_alike(&Node::group(NodeId(1), vec![solid(), solid()]), 1)); + let gradient = square(3, Paint::Gradient(Box::new(vectorcraft_color::gradient::GradientPaint::new(Gradient::default())))); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), gradient]), 1)); + let image = + ImageObject { key: "a".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let image = Arc::new(Node::new(NodeId(4), NodeKind::Image(Box::new(image)))); + assert!(!moves_alike(&Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(5), vec![image.clone()]))]), 1)); + assert!(!outlines_only(&image)); + // A text object's slot, and a member with an opacity mask. + let mut slot = Node::group(NodeId(6), vec![]); + slot.name = Some(format!("{}0", super::super::document::TEXT_SLOT)); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), Arc::new(slot)]), 1)); + let mut masked = Node::clone(&solid()); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(7), vec![]), true))); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), Arc::new(masked)]), 1)); + // A member with an effect of its own. + let mut turned = Node::clone(&solid()); + turned.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.twist".into(), + params: serde_json::json!({"angle": 30.0}), + visible: true, + }); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), Arc::new(turned)]), 1)); + // A member painting a pattern, whose tiles stay where they are, and a clipping group. + let tiled = square(8, Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), tiled]), 1)); + let mut clipped = Node::group(NodeId(9), vec![solid(), solid()]); + if let NodeKind::Group { clip, .. } = &mut clipped.kind { + *clip = true; + } + assert!(!moves_alike(&Node::group(NodeId(1), vec![Arc::new(clipped)]), 1)); + } + + #[test] + fn an_outline_moves_with_its_effect_only_on_outlines() { + // GUARDS: a top-level image or masked path took an effect that moves the outline. + use crate::import::ai::style::ArtStyle; + let effect = |id: &str, params| vectorcraft_doc::Effect { id: id.into(), params, visible: true }; + let style = |e| ArtStyle { effects: vec![e], ..ArtStyle::default() }; + let twist = style(effect("distort.twist", serde_json::json!({"angle": 30.0}))); + let path = square(2, Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))); + assert!(moves_with(&path, &twist)); + let mut masked = Node::clone(&path); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(7), vec![]), true))); + assert!(!moves_with(&masked, &twist)); + let image = + ImageObject { key: "a".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let image = Node::new(NodeId(4), NodeKind::Image(Box::new(image))); + let distort = style(effect("distort.freeDistort", serde_json::json!({"corners": [[0.1, 0.0], [1.1, 0.0], [1.0, 1.0], [0.0, 1.0]]}))); + assert!(!moves_with(&image, &distort)); + assert!(moves_with(&path, &distort)); + } +} diff --git a/crates/eps/src/import/ai/read/raster.rs b/crates/eps/src/import/ai/read/raster.rs new file mode 100644 index 0000000000..da88fd1448 --- /dev/null +++ b/crates/eps/src/import/ai/read/raster.rs @@ -0,0 +1,268 @@ +//! The size of an embedded image (`XI`), checked before its samples are decoded: read at full size +//! up to a target number of pixels, averaged down in whole steps past it, and not read at all past +//! the hard limits ([`Limits`]). + +use std::io::Write as _; + +/// Images up to this many pixels read as they always have: an RGBA PNG, or a CMYK TIFF. +pub(super) const SMALL: u64 = 1 << 25; +/// Most bytes of one image's samples, its alpha channel included. +pub(super) const MAX_BYTES: u64 = 512 << 20; +/// Most pixels of one image. +pub(super) const MAX_PIXELS: u64 = 1 << 31; +/// Longest side of an image as it comes in (pixels). +const MAX_SIDE: u64 = 65_535; + +/// How large an image is read. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Limits { + /// Most pixels of an image as it comes in; larger ones are reduced. + pub(super) target: u64, + /// Most pixels of an image read at all. + pub(super) pixels: u64, + /// Most bytes of an image's samples, its alpha channel included. + pub(super) bytes: u64, +} + +#[cfg(test)] +thread_local! { + static TEST_LIMITS: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +impl Limits { + /// The limits on this machine: [`target`] pixels, [`MAX_PIXELS`] and [`MAX_BYTES`]. + pub(super) fn get() -> Self { + #[cfg(test)] + if let Some(l) = TEST_LIMITS.with(std::cell::Cell::get) { + return l; + } + static TARGET: std::sync::OnceLock = std::sync::OnceLock::new(); + let target = *TARGET.get_or_init(|| target(vectorcraft_render::installed_memory())); + Self { target, pixels: MAX_PIXELS, bytes: MAX_BYTES } + } + + /// The limits for an image of `channels` colour channels: a CMYK image comes in at most as + /// large as a CMYK TIFF holds ([`vectorcraft_doc::cmyk::MAX_CMYK_PIXELS`]). + pub(super) fn for_channels(channels: usize) -> Self { + let mut l = Self::get(); + if channels == 4 { + l.target = l.target.min(vectorcraft_doc::cmyk::MAX_CMYK_PIXELS); + } + l + } +} + +/// `f` run with images read under `target` pixels, `pixels` and `bytes` in place of this machine's +/// limits. +#[cfg(test)] +pub(crate) fn with_image_limits(target: u64, pixels: u64, bytes: u64, f: impl FnOnce() -> T) -> T { + TEST_LIMITS.with(|l| l.set(Some(Limits { target, pixels, bytes }))); + let out = f(); + TEST_LIMITS.with(|l| l.set(None)); + out +} + +/// Most pixels of an image as it comes in, on a machine with `memory` bytes installed (`None`: not +/// known): a thirty-second of it, from 2^26 to 2^28 pixels (an RGBA decode of at most 1 GiB); on the +/// web, a quarter of the largest image the renderer decodes, at most 2^27. +fn target(memory: Option) -> u64 { + if cfg!(target_arch = "wasm32") { + (1u64 << 27).min(vectorcraft_doc::MAX_RASTER_ALLOC / 4) + } else { + memory.map_or(1 << 26, |m| (m / 32).clamp(1 << 26, 1 << 28)) + } +} + +/// An image's layout from its `XI` operands. +#[derive(Clone, Copy, Debug)] +pub(super) struct Shape { + pub(super) w: u64, + pub(super) h: u64, + /// Colour channels a pixel: 1, 3 or 4. + pub(super) channels: u64, + /// Bits a channel: 1 or 8. + pub(super) bits: u64, + /// An alpha channel, a byte a pixel, follows the colour samples. + pub(super) alpha: bool, +} + +impl Shape { + /// Bytes in a row of colour samples (a 1-bit row is padded to a whole byte). + pub(super) fn row(&self) -> Option { + Some(self.w.checked_mul(self.channels)?.checked_mul(self.bits)?.div_ceil(8)) + } + + /// Bytes of colour samples, and of the alpha channel. + pub(super) fn lens(&self) -> Option<(u64, u64)> { + let colour = self.row()?.checked_mul(self.h)?; + let alpha = if self.alpha { self.w.checked_mul(self.h)? } else { 0 }; + colour.checked_add(alpha)?; + Some((colour, alpha)) + } + + /// The step `k` the image is reduced by (1: full size): the smallest that brings it within + /// `limits.target` pixels and [`MAX_SIDE`] a side. `None` past `limits.pixels` or + /// `limits.bytes`. + pub(super) fn step(&self, limits: &Limits) -> Option { + let pixels = self.w.checked_mul(self.h)?; + let (colour, alpha) = self.lens()?; + if pixels > limits.pixels || colour + alpha > limits.bytes { + return None; + } + let fits = |k: u64| { + let (w, h) = (self.w.div_ceil(k), self.h.div_ceil(k)); + w <= MAX_SIDE && h <= MAX_SIDE && w.saturating_mul(h) <= limits.target.max(1) + }; + // No step below these brings it within the limits. + let mut k = ((pixels as f64 / limits.target.max(1) as f64).sqrt().floor() as u64) + .max(self.w.div_ceil(MAX_SIDE)) + .max(self.h.div_ceil(MAX_SIDE)) + .max(1); + while !fits(k) { + k += 1; + } + Some(k) + } +} + +/// The samples of the image `s` (rows of [`Shape::row`] bytes; a set bit is the channel at full +/// strength) and its `alpha` channel averaged over blocks of `k` × `k` pixels into a byte a channel, +/// each block at the right and bottom edges over the pixels it has. With `inline`, the alpha follows +/// each pixel's channels; otherwise it comes back on its own. +pub(super) fn reduce(samples: &[u8], alpha: Option<&[u8]>, s: Shape, k: u64, inline: bool) -> (Vec, Option>) { + let (w, h, k) = (s.w as usize, s.h as usize, k.max(1) as usize); + let (ch, row) = (s.channels as usize, s.row().unwrap_or(0) as usize); + let (ow, oh) = (w.div_ceil(k), h.div_ceil(k)); + let n = ch + usize::from(alpha.is_some()); + let mut out = Vec::with_capacity(ow * oh * if inline { n } else { ch }); + let mut alpha_out = (alpha.is_some() && !inline).then(|| Vec::with_capacity(ow * oh)); + let mut sums = vec![0u64; ow * n]; + for oy in 0..oh { + sums.fill(0); + let rows = oy * k..((oy + 1) * k).min(h); + let tall = rows.len() as u64; + for y in rows { + let line = samples.get(y * row..(y + 1) * row).unwrap_or_default(); + let opacity = alpha.and_then(|a| a.get(y * w..(y + 1) * w)); + for x in 0..w { + let at = x / k * n; + for c in 0..ch { + let i = x * ch + c; + let v = + if s.bits == 1 { line.get(i / 8).map_or(0, |b| ((b >> (7 - i % 8)) & 1) * 255) } else { line.get(i).copied().unwrap_or(0) }; + sums[at + c] += u64::from(v); + } + if alpha.is_some() { + sums[at + ch] += u64::from(opacity.and_then(|o| o.get(x)).copied().unwrap_or(255)); + } + } + } + for ox in 0..ow { + let count = ((((ox + 1) * k).min(w) - ox * k) as u64 * tall).max(1); + let avg = |sum: u64| ((sum + count / 2) / count) as u8; + out.extend(sums[ox * n..ox * n + ch].iter().map(|v| avg(*v))); + if alpha.is_some() { + let a = avg(sums[ox * n + ch]); + match alpha_out.as_mut() { + Some(o) => o.push(a), + None => out.push(a), + } + } + } + } + (out, alpha_out) +} + +/// A grayscale PNG of 1-bit rows as they are (`row` bytes each, a set bit white): `w` × `h` +/// pixels without expanding them. +pub(super) fn gray1_png(samples: &[u8], w: u32, h: u32, row: usize) -> Option> { + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + for y in 0..h as usize { + // Filter type 0 (none), then the row. + z.write_all(&[0]).ok()?; + z.write_all(samples.get(y * row..(y + 1) * row)?).ok()?; + } + let data = z.finish().ok()?; + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + // Bit depth 1, colour type 0 (gray), deflate, filter method 0, no interlacing. + let ihdr = [&w.to_be_bytes()[..], &h.to_be_bytes(), &[1, 0, 0, 0, 0]].concat(); + for (ty, body) in [(b"IHDR", ihdr.as_slice()), (b"IDAT", data.as_slice()), (b"IEND", &[])] { + png.extend_from_slice(&u32::try_from(body.len()).ok()?.to_be_bytes()); + png.extend_from_slice(ty); + png.extend_from_slice(body); + let mut crc = flate2::Crc::new(); + crc.update(ty); + crc.update(body); + png.extend_from_slice(&crc.sum().to_be_bytes()); + } + Some(png) +} + +/// Decode the hex digits in `text` onto `out`, `half` holding a digit that waits for its pair, up +/// to `max` bytes; other characters are skipped. +pub(super) fn push_hex(out: &mut Vec, half: &mut Option, text: &[u8], max: usize) { + for &b in text { + if out.len() >= max { + return; + } + let Some(v) = char::from(b).to_digit(16) else { continue }; + match half.take() { + Some(high) => out.push(high << 4 | v as u8), + None => *half = Some(v as u8), + } + } +} + +/// The last digit of [`push_hex`]'s, without its pair, as the byte it starts. +pub(super) fn end_hex(out: &mut Vec, half: Option, max: usize) { + if let Some(high) = half + && out.len() < max + { + out.push(high << 4); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A CMYK image is reduced to the size a CMYK TIFF holds, whatever the target. + #[test] + fn cmyk_images_come_in_at_most_as_large_as_a_cmyk_tiff() { + let shape = |channels| Shape { w: 9000, h: 9000, channels, bits: 8, alpha: false }; + let (rgb, cmyk) = with_image_limits(1 << 28, MAX_PIXELS, MAX_BYTES * 4, || { + (shape(3).step(&Limits::for_channels(3)), shape(4).step(&Limits::for_channels(4))) + }); + assert_eq!(rgb, Some(1)); + let k = cmyk.unwrap(); + assert_eq!(k, 2); + assert!(9000u64.div_ceil(k).pow(2) <= vectorcraft_doc::cmyk::MAX_CMYK_PIXELS); + } + + /// The step keeps each side within 65,535 pixels, and sizes past the limits or overflowing + /// aren't read. + #[test] + fn steps_keep_sides_within_the_limit() { + let limits = Limits { target: 1 << 28, pixels: MAX_PIXELS, bytes: MAX_BYTES }; + let long = Shape { w: 200_000, h: 1, channels: 1, bits: 1, alpha: false }; + assert_eq!(long.step(&limits), Some(4)); + let huge = Shape { w: u64::MAX, h: 2, channels: 3, bits: 8, alpha: true }; + assert_eq!(huge.step(&limits), None); + let many = Shape { w: 1 << 16, h: 1 << 16, channels: 1, bits: 1, alpha: false }; + assert_eq!(many.step(&limits), None); + } + + /// Hex digits are decoded across calls, other characters skipped, up to the bytes asked for. + #[test] + fn hex_is_decoded_up_to_the_bytes_asked_for() { + let (mut out, mut half) = (vec![], None); + push_hex(&mut out, &mut half, b"F f0 1", 8); + push_hex(&mut out, &mut half, b"2a", 8); + end_hex(&mut out, half, 8); + assert_eq!(out, [0xff, 0x01, 0x2a]); + let (mut out, mut half) = (vec![], None); + push_hex(&mut out, &mut half, b"0102030", 2); + end_hex(&mut out, half, 2); + assert_eq!(out, [1, 2]); + } +} diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index 309061f3ce..5d34e248e3 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -1,8 +1,13 @@ -use super::{Affine, BlendMode, Dash, FillRule, Knockout, LayerColor, LineCap, LineJoin, Node, Obj, Paint, Rect, V}; +use super::{ + Affine, BlendMode, Dash, FillRule, HAIRLINE, Knockout, LayerColor, LineCap, LineJoin, Named, Node, NodeId, Obj, PageBox, Paint, Rect, V, +}; /// Deepest nesting of layers, groups and dictionaries. pub(super) const MAX_DEPTH: usize = 256; +/// Most nested pattern and symbol readers on one call stack. +pub(super) const MAX_SUBREADERS: usize = 32; + /// Most operands on the stack. pub(super) const MAX_STACK: usize = 1 << 20; @@ -16,15 +21,18 @@ pub(super) const BLEND_BUDGET: usize = 50_000; /// Most points in one path. pub(super) const MAX_POINTS: usize = 4_000_000; -/// Largest image read (pixels). +/// Largest placed file's preview read (pixels). pub(super) const MAX_PIXELS: u64 = 1 << 25; +/// Most placed files whose other placement ([`super::Structure::placed_elsewhere`]) is kept. +pub(super) const MAX_PLACED_ELSEWHERE: usize = 4096; -/// The note for an image past [`MAX_PIXELS`]: the file then opens from its PDF part, which reads -/// larger images (#1479). -pub const IMAGE_TOO_LARGE: &str = "an image too large to read from the editing data was left out"; +/// The note for an image past the hard limits ([`super::raster::Limits`]) in a file without page +/// art to replace it. +pub(super) const IMAGE_TOO_LARGE: &str = "an image too large to read from the editing data was left out"; -/// Most hex digits of an image's samples read from comment lines (CMYK and alpha at the largest size). -pub(super) const MAX_HEX: usize = (MAX_PIXELS as usize) * 10; +/// What an image past the hard limits is, as the notes name it: with page art, its box becomes +/// that art (#1479). +pub(super) const LARGE_IMAGES: &str = "very large images"; /// Largest side of the document and its artboards (points). pub(super) const MAX_SIDE: f64 = 1e6; @@ -35,6 +43,26 @@ pub(crate) const FLIP: Affine = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]); /// Most patterns read (others can't fill art). pub(super) const MAX_PATTERNS: usize = 4096; +/// Most symbol definitions read (instances of others come in as the page draws them). +pub(crate) const MAX_SYMBOLS: usize = 4096; + +/// Most names a symbol list orders. +pub(super) const MAX_LISTED: usize = 4 * MAX_SYMBOLS; + +/// Most characters of a path's note read (the version 7 specification allows 254, §5.3.1). +pub(super) const MAX_NOTE: usize = 1024; + +/// Most object tags (`XT`) kept in one object's data. SVG import keeps the same number of `data-*` +/// attributes per element. +pub(super) const MAX_TAGS: usize = 64; + +/// The longest identifier or string an object tag (`XT`) may have, in bytes: SVG import keeps +/// another application's attribute values up to the same length. +pub(super) const MAX_TAG_TEXT: usize = 64 * 1024; + +/// The object tag that holds the object's URL (version 7 specification §7). +pub(super) const URL_TAG: &str = "AdobeURL"; + #[derive(Clone, Debug)] pub(crate) struct GState { pub(crate) fill: Paint, @@ -54,6 +82,11 @@ pub(crate) struct GState { pub(crate) overprint_stroke: bool, pub(super) locked: bool, pub(super) hidden: bool, + /// The note (`%AI3_Note:`) the paths that follow get, until another replaces it (`None`: no + /// note comment yet; empty: none). + pub(super) note: Option, + /// Show Center (`1 Ap`) for the paths that follow (`None`: the path's default). + pub(super) show_center: Option, } impl Default for GState { @@ -77,10 +110,24 @@ impl Default for GState { overprint_stroke: false, locked: false, hidden: false, + note: None, + show_center: None, } } } +impl GState { + /// The width its stroke draws at (see [`line_width`]). + pub(crate) fn line_width(&self) -> f64 { + line_width(self.width) + } +} + +/// The width a stroke of `w w` draws at: `0 w` is the thinnest line a device draws, a [`HAIRLINE`]. +pub(super) fn line_width(w: f64) -> f64 { + if w > 0.0 { w } else { HAIRLINE } +} + /// The blend modes by their number in `Xy`. pub(super) const BLENDS: [BlendMode; 16] = [ BlendMode::Normal, @@ -118,6 +165,7 @@ pub(super) struct LayerAttrs { pub(super) preview: bool, pub(super) locked: bool, pub(super) printable: bool, + pub(super) template: bool, pub(super) dim: Option, pub(super) color: Option, } @@ -126,6 +174,9 @@ pub(super) struct LayerAttrs { pub(super) enum Kind { Layer(Box), Group, + /// Wraparound text (`*w` … `*W`, version 7 specification §15.4.2): a group whose objects other + /// than its type are wrap objects. + Wrap, Compound, Clip, Mask, @@ -140,15 +191,39 @@ pub(super) struct Frame { pub(super) hidden: bool, /// [`Reader::after_object`] when it opened. pub(super) after: bool, + /// [`Reader::mesh_ended`] when it opened. + pub(super) mesh_ended: bool, /// The state when it opened (a container's lock and visibility; a dictionary's state to go /// back to). pub(super) gs: GState, + /// Unresolved pattern paint saved by `q`, which restores graphics state at `Q`. + pub(super) pending_unread_fill: bool, + pub(super) pending_unread_stroke: bool, /// The operand stack's height when it opened. pub(super) base: usize, /// The clipping paths' indexes among the children. pub(super) clips: Vec, /// A compound member group explicitly declares its subpaths' winding with `D`. pub(super) compound_members: bool, + /// Unread kinds belonging to this top-level object. + pub(super) unread: Vec, + /// A dictionary in the art: the transparency (`Xy`) its art set last, which stays after it. + pub(super) state: Option<(f32, BlendMode, bool, Knockout, bool)>, +} + +/// An envelope whose dictionary was read, waiting for its drawn art and its plugin's `XP` (see +/// [`super::super::envelope`]). +#[derive(Debug)] +pub(super) struct PendingEnvelope { + pub(super) obj: Obj, + /// The group on `%_` lines before the dictionary. + pub(super) before: Option, + /// The art in the dictionary's `AIDeformArtKey` block. + pub(super) inner: Vec, + /// How many frames were open when the dictionary closed, and how many children the innermost + /// had: its drawn art is the one child after them. + pub(super) depth: usize, + pub(super) siblings: usize, } /// What a reader of a pattern's definition has of its head, `(name) llx lly urx ury`: the operands @@ -161,6 +236,45 @@ pub(super) struct PatternHead { pub(super) tile: Option, } +/// What a reader of a symbol's definition has read of the symbol besides its art. +#[derive(Debug, Default)] +pub(super) struct SymbolHead { + /// `AI13PatternRegistrationType` in the dictionary after the art. + pub(super) registration: Option, + /// Art the reader left out (type, a placed file, non-native art, an image it can't read or + /// place, a gradient it can't read): the symbol isn't kept, and its instances come in as the + /// page draws them, within the box of the rest. + pub(super) left_out: bool, + /// A gradient instance the reader can't make a paint of (a gradient the file doesn't define, + /// or one it can't place) is the next path's fill or stroke: the art is left out when that + /// path paints it. + pub(super) missing_fill: bool, + pub(super) missing_stroke: bool, +} + +/// The colors a brush's art uses, counted as the page's are once a brush that is kept uses the art. +#[derive(Debug, Default)] +pub(super) struct BrushArtColors { + /// The named colors its color operators define. + pub(super) spots: Vec, + /// The named colors its gradient stops name. + pub(super) stop_spots: Vec, + /// Its colors set in each model. + pub(super) cmyk: usize, + pub(super) rgb: usize, +} + +impl BrushArtColors { + /// Keep each name's first definition only, its color operators' before its gradient stops', + /// and at most `limit` names in all. The process-color counts stay as they are. + pub(super) fn keep_first(&mut self, limit: usize) { + let mut seen = std::collections::HashSet::new(); + let mut keep = |n: &Named| seen.len() < limit && seen.insert(n.name.clone()); + self.spots.retain(|n| keep(n)); + self.stop_spots.retain(|n| keep(n)); + } +} + /// An image's operands, from `XN` and before `XI`. #[derive(Debug, Default)] pub(super) struct Raster { @@ -168,8 +282,12 @@ pub(super) struct Raster { /// `XI`'s operands when its samples follow as hex in comment lines (`%FF00…`) up to /// `%AI5_EndRaster`, the form the version 7 specification documents (§8). pub(super) operands: Option>, - /// Those hex digits. - pub(super) hex: Vec, + /// The bytes of those hex digits, up to `max`. + pub(super) samples: Vec, + /// The bytes of samples the image reads (0 when it isn't read). + pub(super) max: usize, + /// A digit waiting for its pair. + pub(super) half: Option, } /// A placed file's operands, from `` ` `` and its preview, until `~`. @@ -182,26 +300,80 @@ pub(super) struct Place { pub(super) path: String, /// The preview as a PNG, and its size in pixels. pub(super) preview: Option<(Vec, u32, u32)>, + /// The file's folder relative to the document's (`src/`), from the string between + /// `%AI28_BeginPlacedRelativePath` and its end. + pub(super) folder: Option, + /// The operand stack's height at `%AI28_BeginPlacedRelativePath`, until its end. + pub(super) folder_at: Option, + /// Its `` ` `` was read. + pub(super) ticked: bool, + /// It began on a `%_` line, in a hidden object or on a layer that doesn't show. + pub(super) hidden: bool, + /// What it holds can't be read: operands of another shape, a second `` ` ``, or a document + /// included in it that doesn't end. + pub(super) broken: bool, +} + +/// The longest relative folder of a placed file read (bytes). +pub(super) const MAX_PLACED_FOLDER: usize = 4096; + +/// The dictionary entry after a placed PDF or `.ai` file that holds the page shown (1-based). +pub(super) const PLACED_PAGE: &str = "AI11 PlacedPDFPageIndex"; +/// The dictionary entry after a placed PDF or `.ai` file that holds the box it is cropped to. +pub(super) const PLACED_CROP: &str = "AI11 PlacedPDFCropTo"; + +/// The placed file just read, until the dictionary after it: it may say the file is a page of a +/// PDF or `.ai` file. +#[derive(Debug)] +pub(super) struct PlacedTail { + /// Its linked image. + pub(super) id: NodeId, + /// Its image's key in the document's images. + pub(super) key: String, + /// The size of its box. + pub(super) size: (f64, f64), + /// Its image's blob was stored for it, not shared with an earlier image. + pub(super) fresh: bool, + /// The frames open when it was read: its dictionary closes at the same depth. + pub(super) depth: usize, +} + +/// A placed file the dictionary after it says is a page of a PDF or `.ai` file. Its linked image +/// becomes a placed document once the layers have been compared with the page. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PlacedPage { + /// The linked image. + pub id: NodeId, + /// The page shown (1-based). + pub page: u32, + /// The art's bounds are shown, not `page_box`. + pub bounding: bool, + /// The box of the page shown. + pub page_box: PageBox, + /// The size of the placed file's box. + pub size: (f64, f64), } /// What the open result says of placed files: they show the preview the file keeps of them. pub(super) const LINKED_PREVIEWS: &str = "linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel"; +/// What the open result says of linked images the data keeps no pixels of (`XF`): they show a +/// placeholder. +pub const LINKED_PLACEHOLDERS: &str = + "linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel"; + /// Operators that change nothing the reader keeps. pub(super) const IGNORED: &[&str] = &[ "Ae", "AE", - "Ap", "As", "Xd", "Xr", - "XG", // `/DeviceGray XC` after a linked image's file name (`XG`): its colour space. "XC", "Xh", "XH", - "XF", "Bc", "XP", "Np", @@ -209,14 +381,12 @@ pub(super) const IGNORED: &[&str] = &[ "i", // Path resolution (`Ar`, §12): how finely curves print. "Ar", - "TZ", "Xs", "Xt", - // A brushed path's width at each anchor (`(…) Xt n XD`), on its hidden source path. + // Five indexed curves of samples along a brushed path (`(…) Xt n XD`), on its hidden source path. "XD", "Xi", "XI", - "`", "LB2", "Lc", "Xv", @@ -233,6 +403,8 @@ pub(super) const IGNORED: &[&str] = &[ ]; /// Sections skipped whole, by their markers without the `AI_` prefix: begin → end. +/// Patterns, symbols and the symbol list are read before this list is looked at; their markers +/// stay here for sections of the same kind nested in them to be skipped. pub(super) const SKIPPED: &[(&str, &str)] = &[ ("BeginPattern", "EndPattern"), ("BeginBrushPattern", "EndBrushPattern"), @@ -244,12 +416,43 @@ pub(super) const SKIPPED: &[(&str, &str)] = &[ ("BeginSymbolList", "EndSymbolList"), ("BeginTextDocument", "EndTextDocument"), ("BeginEncoding", "EndEncoding"), - ("Alternate_Content", "End_Versioned_Content"), + // The printer's crop marks, drawn after the layers (`userdict /AI3_noCropMarks known not { + // … } if`); the crop area they mark is `%AI3_Cropmarks`. + ("BeginCrops", "EndCrops"), ]; +/// The note for versioned content whose `%AI17_End_Versioned_Content` is missing: every +/// alternative after the first is read too, so some art may come in twice. +pub const VERSIONED_UNENDED: &str = "versioned content that doesn't end was read whole: some art may come in twice"; + /// The note for a `/ForeignObject` (non-native art, the content of a placed PDF, which the editor /// shows but doesn't edit) whose PDF can't be read. pub const NON_NATIVE_ART_UNREAD: &str = "non-native art (a placed PDF's content) that VectorCraft can't read is left out"; /// The name of the group a `/ForeignObject`'s art comes in as. pub const NON_NATIVE_ART: &str = "Non-native art"; + +/// The note for a file with a graph (`%_Gs` … `%_GS`): its drawn art comes in, its data and +/// settings don't. +pub const GRAPH_PLAIN: &str = "graphs come in as plain art, without their data or settings"; + +/// The note for a graph that starts inside another or doesn't end before its layer does: the art +/// read so far is kept, and what follows the layer is read as usual. +pub const GRAPH_UNENDED: &str = "a graph's records don't end where they should: its art was read as it is"; + +/// A graph's records (the version 7 specification's chapter 17 and appendix A): two-letter +/// operators starting with `G`, read and left out with their operands. +pub(super) const GRAPH_OPS: &[&str] = &[ + "G1", "G+", "Ga", "GA", "Gb", "Gc", "GC", "Gd", "GD", "Ge", "Gf", "Gg", "Gi", "Gj", "Gl", "Gm", "Go", "Gp", "Gr", "Gs", "GS", "Gt", "GT", "Gv", + "Gw", "GX", "Gx", "Gy", "Gz", +]; + +/// A graph being read (`%_Gs` … `%_GS`). +#[derive(Debug)] +pub(super) struct Graph { + /// Between `Gt` and `GT`, where the graph's settings may use paint and type operators on `%_` + /// lines too. + pub(super) settings: bool, + /// How many frames were open at its `Gs`: a layer that ends with fewer ends the graph. + pub(super) frames: usize, +} diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 57d7842f23..0ee91f8622 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -32,29 +32,63 @@ //! gradient (`Bb` … `flag (name) x y angle length … Bg` … `BB`); `stroke fill Xd` says whether it //! paints at all. A blend filter's `mode opacity isolate knockout shape Xy` is its transparency. //! +//! A stroke with a Calligraphic or Art brush is its own basic filter, `(Adobe Calligraphic Brush +//! Tool)` or `(Adobe ArtOnPath Brush Tool)`, with its stroke's style and the brush's settings for +//! the object as entries (see [`super::brush`]). +//! +//! A stroke aligned inside or outside its path (Stroke panel › Align Stroke, +//! https://helpx.adobe.com/illustrator/desktop/draw-and-paint/use-strokes/stroke-panel-options.html) +//! is its own basic filter too, `(Adobe Stroke Offset)`, with its stroke's style and +//! `StrokeOffsetInside` (1: inside, 0: outside, as its `DisplayString` names it) as entries. +//! Without that entry, or with it as anything but a `/Bool` 0 or 1, which side it paints isn't +//! known and the style isn't plain (its objects keep their drawn look). +//! //! A style is *plain* when every filter in it is one read here: fills and strokes (in a colour; fills -//! with a pattern or gradient too), each with its own transparency and effects, and the effects of +//! with a pattern or gradient too; strokes with a Calligraphic or Art brush or aligned inside or outside too), each with its own +//! transparency and effects, and the effects of //! [`effect`]. Such objects are read as themselves with an appearance of those fills, strokes and -//! effects; others keep their drawn look. +//! effects; others keep their drawn look. Effect › Pathfinder effects (`(Adobe Pathfinder)` in the +//! object's chain) are read on a group with no fills or strokes of its own, which keeps its members. use std::collections::HashMap; use serde_json::json; use vectorcraft_color::{BlendMode, Paint}; -use vectorcraft_doc::{Dash, Effect, LineCap, LineJoin, WidthProfile}; +use vectorcraft_doc::{Dash, Effect, Knockout, LineCap, LineJoin, StrokeAlign, WidthProfile}; +use vectorcraft_effects::is_pathfinder; +use super::brush::PathBrush; use super::lex::{Lexer, Tok}; -use super::obj::V; +use super::obj::{self, V}; use super::paint; const GLOW: &str = "Adobe Outer Glow"; // brand-ok: the filter's name in the files -const FEATHER: &str = "Adobe Feather"; // brand-ok: the filter's name in the files +const INNER_GLOW: &str = "Adobe Inner Glow"; // brand-ok: the filter's name in the files +const FEATHER: &str = "Adobe Fuzzy Mask"; // brand-ok: the filter's name in the files const SHADOW: &str = "Adobe Drop Shadow"; // brand-ok: the filter's name in the files +const ROUND_CORNERS: &str = "Adobe Round Corners"; // brand-ok: the filter's name in the files +const SCRIBBLE: &str = "Adobe Scribble Fill"; // brand-ok: the filter's name in the files +const EXPAND_VERSION: &str = "Adobe Effect Expand Before Version"; // brand-ok: the key's name in the files const DEFORM: &str = "Adobe Deform"; // brand-ok: the filter's name in the files const OFFSET: &str = "Adobe Offset Path"; // brand-ok: the filter's name in the files +/// Effect › Path › Outline Object. +const OUTLINE_TYPE: &str = "Adobe Outline Type"; // brand-ok: the filter's name in the files +const OUTLINE_STROKE: &str = "Adobe Outline Stroke"; // brand-ok: the filter's name in the files const TRANSFORM: &str = "Adobe Transform"; // brand-ok: the filter's name in the files +const FREE_DISTORT: &str = "Adobe Free Distort"; // brand-ok: the filter's name in the files +const PUCKER_BLOAT: &str = "Adobe Punk and Bloat"; // brand-ok: the filter's name in the files +const TWEAK: &str = "Adobe Scribble and Tweak"; // brand-ok: the filter's name in the files +const TWIST: &str = "Adobe Twirl"; // brand-ok: the filter's name in the files +const ZIG_ZAG: &str = "Adobe Zigzag"; // brand-ok: the filter's name in the files const GAUSSIAN: &str = "Adobe PSL Gaussian Blur"; // brand-ok: the filter's name in the files const BAS_RELIEF: &str = "PSAdapter_plugin_BsRl"; +const SHAPE_EFFECTS: &str = "Adobe Shape Effects"; // brand-ok: the filter's name in the files +const PATHFINDER: &str = "Adobe Pathfinder"; // brand-ok: the filter's name in the files + +/// A stroke aligned inside or outside its path (Stroke panel › Align Stroke). +const STROKE_OFFSET: &str = "Adobe Stroke Offset"; // brand-ok: the filter's name in the files +const CALLIGRAPHIC: &str = "Adobe Calligraphic Brush Tool"; // brand-ok: the filter's and plug-in's name in the files +const ART_BRUSH: &str = "Adobe ArtOnPath Brush Tool"; // brand-ok: the filter's and plug-in's name in the files const CHAIN: &str = "Chain Style Filter"; const STACK: &str = "Stack Style Filter"; @@ -82,14 +116,68 @@ const WARPS: [&str; 15] = [ "warp.twist", ]; +/// The warp style (`arc`, `arcLower`, …) numbered `n` in `DeformStyle`. +pub(super) fn warp_style(n: i64) -> Option<&'static str> { + let id = WARPS.get(usize::try_from(n.checked_sub(1)?).ok()?)?; + id.strip_prefix("warp.") +} + +/// The number `DeformStyle` gives warp style `style` (`arc`, `arcLower`, …), from 1. +pub(crate) fn warp_number(style: &str) -> Option { + let at = WARPS.iter().position(|id| id.strip_prefix("warp.") == Some(style))?; + i64::try_from(at + 1).ok() +} + +/// The Effect › Pathfinder effects by the `Command` number of their filter. `Command` 0 is Add +/// (https://community.adobe.com/questions-652/liveeffect-xml-effect-is-added-under-the-object-795137); +/// the numbers 1 to 11 are VectorCraft's own reader rules, learned from saved files. Trap (12) isn't +/// read. +const PATHFINDER_COMMANDS: [&str; 12] = [ + "pathfinder.add", + "pathfinder.intersect", + "pathfinder.exclude", + "pathfinder.subtract", + "pathfinder.minusBack", + "pathfinder.divide", + "pathfinder.outline", + "pathfinder.trim", + "pathfinder.merge", + "pathfinder.crop", + "pathfinder.hardMix", + "pathfinder.softMix", +]; + +/// The keys of an Effect › Pathfinder filter's dictionary besides `Command` and `DisplayString`, +/// each with the kind and the one value read: its Pathfinder Options, Soft Mix's mix and the Trap +/// settings. Every operation needs each of them at this value, even where the operation doesn't use +/// it, except that Soft Mix reads a `Mix` from 0.01 to 1 as its Mixing Rate (VectorCraft's own +/// reader rule, learned from saved files: the rate is `Mix` times 100, within the effect's 1 to 100; +/// a saved `Mix` outside that range keeps the drawn look). +const PATHFINDER_OPTIONS: [(&str, Kind, f64); 12] = [ + ("ConvertCustom", Kind::Bool, 1.0), + ("ExtractUnpainted", Kind::Bool, 1.0), + ("Mix", Kind::Real, 0.5), + ("Precision", Kind::Real, 10.0), + ("RemovePoints", Kind::Bool, 0.0), + ("TrapAspect", Kind::Real, 1.0), + ("TrapConvertCustom", Kind::Bool, 0.0), + ("TrapMaxTint", Kind::Real, 1.0), + ("TrapReverse", Kind::Bool, 0.0), + ("TrapThickness", Kind::Real, 0.25), + ("TrapTint", Kind::Real, 0.4), + ("TrapTintTolerance", Kind::Real, 0.05), +]; + /// A plain style's paint, as the object comes in. #[derive(Clone, Debug, Default, PartialEq)] pub(super) struct ArtStyle { /// The style reads as [`Self::items`] and [`Self::effects`]. pub plain: bool, /// It is one fill and one stroke at most, in solid colours or the object's own gradient, with - /// no transparency or effects of their own, and only Outer Glow, Feather and Drop Shadow on the - /// object: what any object is read with. Type takes the other plain styles too (its drawn look + /// no transparency or effects of their own, and only Drop Shadow, Inner Glow, Outer Glow, + /// Feather, Round Corners, Scribble, Convert to Shape, the Path effects (Offset Path, Outline Object, Outline Stroke), + /// Bas Relief read from its settings block and some Distort & Transform effects ([`any_object_takes`]) on the object + /// (and Pathfinder effects when it has no fills or strokes): what any object is read with. Type takes the other plain styles too (its drawn look /// can't be retyped); other objects keep their drawn look, which is the app's own rendering. pub simple: bool, /// Its fills and strokes, bottom first. @@ -100,6 +188,18 @@ pub(super) struct ArtStyle { pub effects: Vec, /// How many of [`Self::items`] paint below the object's contents (`None`: none do). pub contents_index: Option, + /// The object's own opacity, blend mode, isolation and knockout (its blend filter), when the + /// style has them. + pub transparency: Option<(f32, BlendMode, bool, Knockout)>, + /// [`Self::effects`] holds Effect › Pathfinder effects, which only a group is read with. + pub pathfinder: bool, +} + +impl ArtStyle { + /// Do its effects move the object's outline (Transform, Twist, Free Distort)? + pub fn moves_outline(&self) -> bool { + self.effects.iter().any(|e| matches!(e.id.as_str(), "distort.transform" | "distort.twist" | "distort.freeDistort")) + } } #[derive(Clone, Debug, PartialEq)] @@ -111,10 +211,12 @@ pub(super) enum StyleItem { name: Option, angle: f64, }, - /// A fill with pattern swatch `name`, its space taken to art space by `matrix`. + /// A fill with pattern swatch `name`, its space taken to art space by `matrix`; `controls`, the + /// numbers before the matrix, apply first when the pattern was defined in the version 7 form. Pattern { name: String, matrix: Option<[f64; 6]>, + controls: Vec, }, Stroke { paint: Paint, @@ -124,6 +226,10 @@ pub(super) enum StyleItem { miter: f64, dash: Option, profile: Option, + /// Which side of the path it paints (centred, or inside or outside a closed path). + align: StrokeAlign, + /// A brush: its name, and its settings for this object. + brush: Option<(String, PathBrush)>, }, } @@ -142,6 +248,17 @@ impl Default for ItemLook { } } +/// How a filter's dictionary writes an entry: `value /Int (key) ,`, `/Real`, `/Bool`, a fill's +/// style (`/FillStyle : … /Def ; (key) ,`), or anything else. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Int, + Real, + Bool, + Fill, + Other, +} + #[derive(Debug)] struct Filter { name: String, @@ -150,6 +267,10 @@ struct Filter { parent: Option, compound: bool, params: HashMap, + /// How each key of its dictionary is written. + kinds: HashMap, + /// A key of its dictionary is written more than once. + repeated: bool, /// Its dictionary's arrays (`/Array : v /Real , … ; (key) ,`), by key. arrays: HashMap>, fill: Option, @@ -164,10 +285,17 @@ struct Filter { gradient: bool, /// The gradient's swatch and angle (`Bg`). gradient_of: Option<(Option, f64)>, - /// `(name) … [matrix] p`. - pattern: Option<(String, Option<[f64; 6]>)>, + /// `(name) … [matrix] p`, and the numbers between the name and the matrix. + pattern: Option<(String, Option<[f64; 6]>, Vec)>, + /// The plug-in object it refers to (`/GObjRef : (name) (plug-in) /PluginObject`): its name and + /// plug-in name. + plugin_object: Option<(String, String)>, /// `mode opacity … Xy`. xy: Option<(usize, f32)>, + /// `… isolate knockout … Xy`. + xy_group: Option<(bool, Knockout)>, + /// Its settings block's bytes (`/Binary : /ASCII85Decode ,`), `Err` when it isn't read. + data: Option, ()>>, } impl Default for Filter { @@ -178,6 +306,8 @@ impl Default for Filter { parent: None, compound: false, params: HashMap::new(), + kinds: HashMap::new(), + repeated: false, arrays: HashMap::new(), fill: None, stroke: None, @@ -190,7 +320,10 @@ impl Default for Filter { gradient: false, gradient_of: None, pattern: None, + plugin_object: None, xy: None, + xy_group: None, + data: None, } } } @@ -198,6 +331,55 @@ impl Default for Filter { /// Most filters read in one style. const MAX_FILTERS: usize = 4096; +/// Most entries read from a style list. +pub(crate) const MAX_LISTED: usize = 4096; +/// The longest style name read from a style list, in bytes. +pub(crate) const MAX_LISTED_NAME: usize = 1024; + +/// The style list (`%AI9_BeginArtStyleList`, between its markers): one literal string per style, +/// the Graphic Styles panel's order. Each name is its string's bytes, escapes undone; other tokens, +/// a string the data ends inside and names past [`MAX_LISTED_NAME`] are left out. +pub(super) fn art_style_list(data: &[u8]) -> Vec> { + let mut names = vec![]; + let mut lex = Lexer::new(data); + loop { + let before = lex.offset(); + if names.len() >= MAX_LISTED { + break; + } + let Some(t) = lex.next_token() else { break }; + // The lexer stops a string at its closing `)` or at the end of the data. + let closed = lex.offset() < data.len() || data.get(before..).is_some_and(closes); + if let Tok::Str(s) = t.tok + && closed + && s.len() <= MAX_LISTED_NAME + { + names.push(s); + } + } + names +} + +/// Does the first literal string in `data` end with its own `)` (not an escaped one or one that +/// closes a nested pair)? +fn closes(data: &[u8]) -> bool { + let Some(start) = data.iter().position(|b| *b == b'(') else { return false }; + let mut depth = 0usize; + let mut bytes = data.iter().skip(start + 1); + while let Some(b) = bytes.next() { + match b { + b'\\' => { + bytes.next(); + } + b'(' => depth += 1, + b')' if depth == 0 => return true, + b')' => depth -= 1, + _ => {} + } + } + false +} + /// The styles of the section `data` (between its markers), by name. pub(super) fn art_styles(data: &[u8]) -> HashMap { let mut styles = HashMap::new(); @@ -217,23 +399,46 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { }; let mut array: Option> = None; let mut dict_array: Option> = None; + // A paint style being read as a dictionary entry: its key follows its `/Def ;`. + let mut style_entry: Option = None; + // A name of a basic filter's that may be an entry's type, with the string that follows it. + let mut other_entry: Option> = None; + // The last name was `/Binary`. + let mut binary = false; let mut lex = Lexer::new(data); while let Some(t) = lex.next_token() { if let (Some(a), Tok::Num(v)) = (array.as_mut(), &t.tok) { a.push(V::Num(*v)); continue; } + let after_binary = binary; + if let Tok::Name(n) = &t.tok { + binary = *n == b"Binary"; + } match t.tok { Tok::Num(v) => operands.push(V::Num(v)), - Tok::Str(s) | Tok::Hex(s) => operands.push(V::Str(s)), + Tok::Str(s) | Tok::Hex(s) => { + if let Some(key @ None) = other_entry.as_mut() { + *key = Some(String::from_utf8_lossy(&s).into_owned()); + } + operands.push(V::Str(s)); + } + // A basic filter's settings block: its bytes are on the comment lines the lexer skips. + Tok::Name(b"ASCII85Decode") if after_binary && in_basic => { + keep_block(&mut lex, data.len(), filters.last_mut()); + operands.clear(); + } Tok::Name(n) => match n { b"KnownStyle" => { finish(name.take(), &mut filters); operands.clear(); open.clear(); - (pending, in_basic) = (None, false); + (pending, in_basic, style_entry, other_entry) = (None, false, None, None); } + b"FillStyle" => style_entry = Some(Kind::Fill), + b"StrokeStyle" | b"BlendStyle" => style_entry = Some(Kind::Other), b"Name" if name.is_none() && filters.is_empty() => name = operands.iter().rev().find_map(V::text), + b"All" | b"[Registration]" | b"Registration" => operands.push(V::Name(obj::text(n))), b"CompoundFilter" => pending = Some(true), b"BasicFilter" => pending = Some(false), b"Part" => in_basic = false, @@ -258,24 +463,46 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { } } b"Array" => dict_array = Some(vec![]), + b"PluginObject" if in_basic => { + let mut texts = operands.iter().rev().filter_map(V::text); + if let (Some(plugin), Some(name), Some(f)) = (texts.next(), texts.next(), filters.last_mut()) { + f.plugin_object = Some((name, plugin)); + } + other_entry = Some(None); + } b"Int" | b"Real" | b"Bool" => { - let value = operands.iter().rev().find_map(V::num); + // The number right before the type: an earlier one isn't this value. + let value = operands.last().and_then(V::num); operands.clear(); if let Some(a) = dict_array.as_mut() { a.extend(value); continue; } + let kind = match n { + b"Int" => Kind::Int, + b"Real" => Kind::Real, + _ => Kind::Bool, + }; // The key follows: `value /Real (key) ,`. - if let (Some(value), Some(Tok::Str(key))) = (value, lex.next_token().map(|t| t.tok)) + if let Some(Tok::Str(key)) = lex.next_token().map(|t| t.tok) && let Some(f) = filters.last_mut() { - f.params.insert(String::from_utf8_lossy(&key).into_owned(), value); + let key = String::from_utf8_lossy(&key).into_owned(); + match value { + Some(value) => f.params.insert(key.clone(), value), + None => f.params.remove(&key), + }; + f.repeated |= f.kinds.insert(key, kind).is_some(); } continue; } + // Perhaps an entry of another type (`(text) /String (key) ,`): its key, if any, is + // the string before the `,`. + _ if in_basic => other_entry = Some(None), _ => {} }, Tok::Word(w) => { + let entry = other_entry.take().flatten(); let op = std::str::from_utf8(w).unwrap_or_default(); if op == "[" { array = Some(vec![]); @@ -298,6 +525,15 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { if op == ";" && !in_basic { open.pop(); } + if op == "," { + let key = match style_entry.take() { + Some(kind) => operands.iter().rev().find_map(V::text).map(|k| (k, kind)), + None => entry.map(|k| (k, Kind::Other)), + }; + if let (Some((key, kind)), Some(f)) = (key, filters.last_mut()) { + f.repeated |= f.kinds.insert(key, kind).is_some(); + } + } if let Some(f) = filters.last_mut() { paint_op(f, op, &operands); } @@ -306,7 +542,7 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { } continue; } - Tok::Comment(_) | Tok::Data(_) | Tok::Preview(_) => {} + Tok::Comment(_) | Tok::Data(_) | Tok::Preview(_) | Tok::Document(_) => {} } if operands.len() > 64 { operands.clear(); @@ -316,11 +552,68 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { styles } +/// Reads the settings block that `lex` (over `data_len` bytes) has just reached into `filter`'s +/// `data`; a second block on one filter, or a block that isn't read, leaves it `Err`. +fn keep_block(lex: &mut Lexer, data_len: usize, filter: Option<&mut Filter>) { + let block = binary_block(lex, data_len).ok_or(()); + if let Some(f) = filter { + f.data = Some(if f.data.is_some() { Err(()) } else { block }); + } +} + +/// The bytes of the settings block whose `/Binary : /ASCII85Decode` `lex` (over `data_len` bytes) +/// has just read: the rest of that line is its `,`, each line after it holds ASCII85 after a `%` +/// until `~>`, and `; (data) ,` follows. `lex` is moved past the `~>` when the lines up to it are +/// the block's and fit in [`adapter::MAX_ENCODED`] bytes, and past `; (data)` when they follow. +/// `None` when the block is malformed or decodes to more than [`adapter::MAX_DECODED`] bytes. +fn binary_block(lex: &mut Lexer, data_len: usize) -> Option> { + let from = lex.offset(); + let text = lex.slice(from, from.saturating_add(adapter::MAX_ENCODED).min(data_len)); + let mut lines = text.split(|b| matches!(b, b'\r' | b'\n')); + let first = lines.next()?; + if first.trim_ascii() != b"," { + return None; + } + // Where the line being read starts in `text`. + let mut at = first.len() + 1; + let mut encoded = vec![]; + for line in lines { + let start = at; + at += line.len() + 1; + if line.is_empty() { + continue; + } + // A line that isn't the block's ends it unread, the lexer left before it. + let digits = line.strip_prefix(b"%")?; + if let Some(i) = super::super::lex::find(digits, b"~>") { + encoded.extend_from_slice(digits.get(..i + 2)?); + lex.seek(from + start + 1 + i + 2); + return block_data(lex, &encoded); + } + encoded.extend_from_slice(digits); + } + None +} + +/// The bytes of a settings block's ASCII85 `encoded`, when `; (data)` follows it in `lex`. When it +/// doesn't, `lex` is left before those tokens, so the next style's `/KnownStyle` is still read. +fn block_data(lex: &mut Lexer, encoded: &[u8]) -> Option> { + let at = lex.offset(); + let data = crate::ps::ascii85_decode_within(std::str::from_utf8(encoded).ok()?, adapter::MAX_DECODED)?; + let (close, key) = (lex.next_token().map(|t| t.tok), lex.next_token().map(|t| t.tok)); + if close == Some(Tok::Word(b";")) && key == Some(Tok::Str(b"data".to_vec())) { + return Some(data); + } + lex.seek(at); + None +} + /// A paint operator of a fill's or stroke's style. fn paint_op(f: &mut Filter, op: &str, vals: &[V]) { let last = vals.iter().rev().find_map(V::num); match op { - "Xa" | "k" | "g" | "x" | "Xk" | "XA" | "K" | "G" | "X" | "XK" => { + "Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" | "xa" | "xx" | "xk" | "xs" + | "xz" => { let Some((p, _)) = paint::color_op(op, vals) else { return }; if op.ends_with(|c: char| c.is_ascii_lowercase()) { f.fill = Some(p); @@ -364,11 +657,18 @@ fn paint_op(f: &mut Filter, op: &str, vals: &[V]) { } "Xy" => { let n: Vec = vals.iter().filter_map(V::num).collect(); - if let [mode, opacity, ..] = n.as_slice() + if let [mode, opacity, rest @ ..] = n.as_slice() && mode.is_finite() && opacity.is_finite() { f.xy = Some((mode.max(0.0) as usize, opacity.clamp(0.0, 1.0) as f32)); + // As an object's own `Xy` reads them. + let knockout = match rest.get(1).map(|v| *v as i64) { + Some(1) => Knockout::On, + Some(2) => Knockout::Neutral, + _ => Knockout::Off, + }; + f.xy_group = Some((rest.first().is_some_and(|v| *v != 0.0), knockout)); } } // `flag (name) x y angle length a b c d tx ty Bg`. @@ -389,8 +689,10 @@ fn paint_op(f: &mut Filter, op: &str, vals: &[V]) { } _ => None, }); + let controls: Vec = + vals.iter().skip_while(|v| !matches!(v, V::Str(_))).skip(1).take_while(|v| !matches!(v, V::Arr(_))).filter_map(V::num).collect(); if let Some(name) = name { - f.pattern = Some((name, matrix)); + f.pattern = Some((name, matrix, controls)); } } _ => {} @@ -422,39 +724,413 @@ fn width_profile(arrays: &HashMap>) -> Option { (!uniform).then_some(WidthProfile { points }) } -/// The live effect filter `f` is, when it is one read here. -fn effect(f: &Filter) -> Option { +/// Entry `key` of `f`'s dictionary, written as `kind`: `Ok(None)` when the dictionary doesn't hold +/// it, `Err` when it holds it as another kind, without a finite number, or as an `/Int` that isn't +/// whole or a `/Bool` other than 0 and 1. +fn entry(f: &Filter, key: &str, kind: Kind) -> Result, ()> { + let Some(k) = f.kinds.get(key) else { return Ok(None) }; + match f.params.get(key) { + Some(v) + if *k == kind + && v.is_finite() + && match kind { + Kind::Real => true, + Kind::Int => v.fract() == 0.0, + Kind::Bool => *v == 0.0 || *v == 1.0, + Kind::Fill | Kind::Other => false, + } => + { + Ok(Some(*v)) + } + _ => Err(()), + } +} + +/// Entry `key` as a switch, 0 or 1 written as `kind`: `Ok(None)` when it is missing. +fn switch(f: &Filter, key: &str, kind: Kind) -> Result, ()> { + match entry(f, key, kind)? { + None => Ok(None), + Some(0.0) => Ok(Some(false)), + Some(1.0) => Ok(Some(true)), + Some(_) => Err(()), + } +} + +/// Real entry `key` within `range`, `missing` when the dictionary doesn't hold it. +fn real(f: &Filter, key: &str, missing: f64, range: std::ops::RangeInclusive) -> Option { + entry(f, key, Kind::Real).ok()?.map_or(Some(missing), |v| range.contains(&v).then_some(v)) +} + +/// What an effect in a style could change the paint of, for the Transform options whose value, +/// when the dictionary leaves it out, comes from the app's settings rather than the file. +#[derive(Clone, Copy, Debug)] +struct Under { + /// A stroke, or other effects with distances that Scale Strokes & Effects would scale. + strokes: bool, + /// A pattern. + patterns: bool, +} + +/// Anything: an effect on the whole object, whose contents can paint in any way. +const ANYTHING: Under = Under { strokes: true, patterns: true }; + +/// The Transform effect `f` (the factor and radian entries; the percent and degree ones are what +/// its dialog shows). `None` keeps the drawn look: an entry not read, Random (the file holds no +/// seed), or a missing Scale Strokes & Effects or Transform Patterns that would change `under`. +fn transform(f: &Filter, under: Under) -> Option { + for key in ["scaleH_Percent", "scaleV_Percent", "rotate_Degrees"] { + entry(f, key, Kind::Real).ok()?; + } + // The renderer's limits on scales and moves (`vectorcraft_effects`' `MAX_SCALE` and `MAX_MOVE`). + let scale = |key: &str| real(f, key, 1.0, -1000.0..=1000.0).map(|v| v * 100.0); + let (h, v) = (scale("scaleH_Factor")?, scale("scaleV_Factor")?); + let (move_h, move_v) = (real(f, "moveH_Pts", 0.0, -1e7..=1e7)?, real(f, "moveV_Pts", 0.0, -1e7..=1e7)?); + let rotate = Some(entry(f, "rotate_Radians", Kind::Real).ok()?.unwrap_or(0.0).to_degrees()).filter(|d| d.is_finite())?; + let copies = entry(f, "numCopies", Kind::Int).ok()?.unwrap_or(0.0); + let reference = entry(f, "pinPoint", Kind::Int).ok()?.unwrap_or(4.0); + if !(0.0..=1000.0).contains(&copies) || !(0.0..=8.0).contains(&reference) { + return None; + } + let on = |key: &str| switch(f, key, Kind::Bool); + let (reflect_x, reflect_y) = (on("reflectX").ok()?.unwrap_or(false), on("reflectY").ok()?.unwrap_or(false)); + let objects = on("transformObjects").ok()?.unwrap_or(true); + let (strokes, patterns) = (on("scaleLines").ok()?, on("transformPatterns").ok()?); + if on("randomize").ok()?.unwrap_or(false) { + return None; + } + let moves = h != 100.0 || v != 100.0 || move_h != 0.0 || move_v != 0.0 || rotate != 0.0 || reflect_x || reflect_y; + let scales = ((h * v).abs().sqrt() - 100.0).abs() > 1e-9; + if (strokes.is_none() && scales && under.strokes) || (patterns.is_none() && moves && under.patterns) { + return None; + } + // Art space has y up: a move up is a negative `moveV` in the document. + Some(json!({ + "scaleH": h, + "scaleV": v, + "moveH": move_h, + "moveV": 0.0 - move_v, + "rotate": rotate, + "copies": copies as i64, + "reflectX": reflect_x, + "reflectY": reflect_y, + "reference": reference as i64, + "objects": objects, + "patterns": patterns.unwrap_or(false), + "strokes": strokes.unwrap_or(false), + })) +} + +/// Free Distort's corners: the destination corners `dst0h`… measured in the source frame `src0h`… +/// (top left, top right, bottom left, bottom right, y up), as the catalog's unit-box corners (top +/// left, top right, bottom right, bottom left, y down). The source frame is only the unit the +/// corners are measured in: the distorted box is laid over the object's own bounds, as the catalog +/// effect lays it, also when the frame is another size (a unit square, or bounds with the stroke). +/// No corners is no change; some but not all, or a frame that isn't an upright rectangle, isn't read. +fn free_distort(f: &Filter) -> Option { + let mut corners = [[[0.0; 2]; 4]; 2]; + let mut held = 0; + for (which, c) in ["src", "dst"].into_iter().zip(&mut corners) { + for (i, corner) in c.iter_mut().enumerate() { + for (axis, v) in ["h", "v"].into_iter().zip(corner.iter_mut()) { + if let Some(x) = entry(f, &format!("{which}{i}{axis}"), Kind::Real).ok()? { + *v = x; + held += 1; + } + } + } + } + if held == 0 { + return Some(json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]})); + } + let [[tl, tr, bl, br], dst] = corners; + let (left, top) = (tl[0], tl[1]); + let (width, height) = (tr[0] - left, top - bl[1]); + let tolerance = 1e-5 * width.abs().max(height.abs()); + let upright = (tr[1] - top).abs() <= tolerance + && (br[1] - bl[1]).abs() <= tolerance + && (bl[0] - left).abs() <= tolerance + && (br[0] - tr[0]).abs() <= tolerance; + let extent = |d: f64| d.is_finite() && d > 0.0; + if held < 16 || !upright || !extent(width) || !extent(height) { + return None; + } + let mut out = vec![]; + for i in [0, 1, 3, 2] { + let [h, v] = *dst.get(i)?; + let (x, y) = ((h - left) / width, (top - v) / height); + if !(x.is_finite() && y.is_finite() && x.abs() <= 1e4 && y.abs() <= 1e4) { + return None; + } + out.push([x, y]); + } + Some(json!({ "corners": out })) +} + +/// A `0` relative, `1` absolute switch (`absoluteness`), `absolute` when it is missing, and the size +/// it picks: `relative_key` in percent or `absolute_key` in points, 0 when missing. +fn sized(f: &Filter, absolute: bool, relative_key: &str, absolute_key: &str) -> Option<(bool, f64)> { + let absolute = switch(f, "absoluteness", Kind::Real).ok()?.unwrap_or(absolute); + let relative = real(f, relative_key, 0.0, 0.0..=1e4)?; + let points = real(f, absolute_key, 0.0, 0.0..=1e4)?; + Some((absolute, if absolute { points } else { relative })) +} + +/// Corner (`roundness` 0, or missing) or Smooth (1). +fn points(f: &Filter) -> Option<&'static str> { + Some(if switch(f, "roundness", Kind::Real).ok()?.unwrap_or(false) { "smooth" } else { "corner" }) +} + +/// The Tweak effect `f` (`Adobe Scribble and Tweak`): relative unless `absoluteness` says otherwise, +/// moving anchors and both handles unless the dictionary turns them off. +fn tweak(f: &Filter) -> Option { + let (absolute, h) = sized(f, false, "horz", "ahor")?; + let (_, v) = sized(f, false, "vert", "aver")?; + let on = |key: &str| switch(f, key, Kind::Bool).map(|v| v.unwrap_or(true)); + let (anchors, ins, outs) = (on("anch").ok()?, on("in").ok()?, on("out").ok()?); + Some(json!({"h": h, "v": v, "relative": !absolute, "anchors": anchors, "in": ins, "out": outs})) +} + +/// The Zig Zag effect `f`: absolute unless `absoluteness` says otherwise, 4 ridges and Corner points +/// when they are missing. +fn zig_zag(f: &Filter) -> Option { + let (absolute, size) = sized(f, true, "relAmount", "amount")?; + let ridges = real(f, "ridges", 4.0, 0.0..=100.0).filter(|r| r.fract() == 0.0)?; + Some(json!({"size": size, "relative": !absolute, "ridges": ridges as i64, "points": points(f)?})) +} + +/// Whether Tweak params `p` leave the outline as it is: its random outline isn't in the file, so any +/// other keeps the drawn look. +fn still(p: &serde_json::Value) -> bool { + (p["h"].as_f64() == Some(0.0) && p["v"].as_f64() == Some(0.0)) || ["anchors", "in", "out"].iter().all(|k| p[k] == json!(false)) +} + +/// A Stylize effect's dictionary, read only as it is written: each setting a key of the kind it +/// names, with a finite value in the effect's range. +struct Settings<'a>(&'a Filter); + +impl Settings<'_> { + /// Every key is one of `known`, or one of `fixed` holding the value it names. + /// The choices (`blnd`, `csrc`, `gtyp`) are written as `/Int`, the colors as fill styles and + /// the other settings as `/Real`. + fn only(&self, known: &[&str], fixed: &[(&str, Kind, f64)]) -> bool { + let f = self.0; + let kind_of = |key: &str| match key { + "blnd" | "csrc" | "gtyp" => Kind::Int, + "sclr" | "gclr" => Kind::Fill, + _ => Kind::Real, + }; + f.arrays.is_empty() + && f.kinds.iter().all(|(key, kind)| { + (known.contains(&key.as_str()) && kind_of(key) == *kind) + || fixed.iter().any(|(k, want, v)| k == key && want == kind && f.params.get(key.as_str()) == Some(v)) + }) + } + + fn real(&self, key: &str, range: std::ops::RangeInclusive) -> Option { + (self.0.kinds.get(key) == Some(&Kind::Real)).then_some(())?; + self.0.params.get(key).copied().filter(|v| v.is_finite() && range.contains(v)) + } + + /// A choice numbered from 0 to `max`. + fn choice(&self, key: &str, max: u8) -> Option { + (self.0.kinds.get(key) == Some(&Kind::Int)).then_some(())?; + let v = self.0.params.get(key).copied().filter(|v| v.is_finite() && v.fract() == 0.0 && (0.0..=f64::from(max)).contains(v))?; + Some(v as usize) + } + + /// The blend mode in `blnd`, numbered as transparency's (`Xy`). + fn mode(&self) -> Option { + Some(super::read::blend_name(self.choice("blnd", 15)?)) + } + + /// The color of the fill style written as `key`: a solid color, in Normal at full opacity. + fn color(&self, key: &str) -> Option { + let f = self.0; + let normal = f.xy.is_none_or(|(mode, opacity)| mode == 0 && opacity >= 1.0); + (f.kinds.get(key) == Some(&Kind::Fill) && !f.gradient && f.pattern.is_none() && normal).then_some(())?; + f.fill.as_ref()?.color() + } +} + +/// Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners and Scribble (`None`: another +/// filter). `Some(None)` is one whose settings aren't all read: an unknown key, a key of another +/// kind, a value out of range or a missing setting keeps the drawn look. The keys are LiveEffect +/// XML's +/// (https://community.adobe.com/questions-652/pageitem-applyeffect-liveeffectxml-769450). +fn stylize(f: &Filter) -> Option> { + let s = Settings(f); + let opacity = || Some(s.real("opac", 0.0..=1.0)? * 100.0); + Some(match f.name.as_str() { + // `horz` and `vert` are the X and Y Offset, right and down + // (https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/create-drop-shadows.html); + // `csrc` 0 is Color (`sclr`), 1 Darkness (`dark`, a percent). `blur` is half the catalog's. + SHADOW => (|| { + let fixed = [("pair", Kind::Bool, 1.0), ("usePSLBlur", Kind::Bool, 1.0), (EXPAND_VERSION, Kind::Int, 16.0)]; + s.only(&["blnd", "opac", "horz", "vert", "blur", "csrc", "dark", "sclr"], &fixed).then_some(())?; + let mut params = json!({ + "mode": s.mode()?, + "opacity": opacity()?, + "blur": 2.0 * s.real("blur", 0.0..=500.0)?, + "x": s.real("horz", -1e4..=1e4)?, + "y": s.real("vert", -1e4..=1e4)?, + }); + if s.choice("csrc", 1)? == 0 { + params["color"] = json!(s.color("sclr")?); + } else { + params["shade"] = json!("darkness"); + params["darkness"] = json!(s.real("dark", 0.0..=100.0)?); + if let Some(c) = s.color("sclr") { + params["color"] = json!(c); + } + } + Some(("stylize.dropShadow", params)) + })(), + // `gtyp` 0 is Center, 1 Edge (https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/create-an-inner-or-outer-glow.html); + // `blur` is the catalog's. + INNER_GLOW => (|| { + s.only(&["blnd", "opac", "blur", "gtyp", "gclr"], &[]).then_some(())?; + let source = if s.choice("gtyp", 1)? == 0 { "center" } else { "edge" }; + let params = json!({ + "mode": s.mode()?, + "opacity": opacity()?, + "blur": s.real("blur", 0.0..=1000.0)?, + "color": s.color("gclr")?, + "source": source, + }); + Some(("stylize.innerGlow", params)) + })(), + // `blur` is half the catalog's. + GLOW => (|| { + s.only(&["blnd", "opac", "blur", "sclr"], &[("usePSLBlur", Kind::Bool, 1.0), (EXPAND_VERSION, Kind::Int, 16.0)]).then_some(())?; + let params = json!({"mode": s.mode()?, "opacity": opacity()?, "blur": 2.0 * s.real("blur", 0.0..=500.0)?, "color": s.color("sclr")?}); + Some(("stylize.outerGlow", params)) + })(), + // https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/feather-object-edges.html + FEATHER => s.only(&["Radius"], &[]).then(|| s.real("Radius", 0.0..=1000.0)).flatten().map(|r| ("stylize.feather", json!({"radius": r}))), + ROUND_CORNERS => { + s.only(&["radius"], &[]).then(|| s.real("radius", 0.0..=1e4)).flatten().map(|r| ("stylize.roundCorners", json!({"radius": r}))) + } + // `Angle` in degrees; widths, spacings and overlaps in points; `Scribbliness` (Curviness) + // and `ScribbleVariation` as fractions. The catalog's Scribble has no color, so a Scribble + // with `sclr` keeps the drawn look. + SCRIBBLE => (|| { + let keys = + ["Angle", "EdgeOverlap", "EdgeOverlapVariation", "StrokeWidth", "Scribbliness", "ScribbleVariation", "Spacing", "SpacingVariation"]; + s.only(&keys, &[]).then_some(())?; + let params = json!({ + "angle": s.real("Angle", -360.0..=360.0)?, + "overlap": s.real("EdgeOverlap", -1000.0..=1000.0)?, + "overlapVariation": s.real("EdgeOverlapVariation", 0.0..=100.0)?, + "strokeWidth": s.real("StrokeWidth", 0.01..=1000.0)?, + "curviness": s.real("Scribbliness", 0.0..=1.0)? * 100.0, + "curvinessVariation": s.real("ScribbleVariation", 0.0..=1.0)? * 100.0, + "spacing": s.real("Spacing", 0.1..=1000.0)?, + "spacingVariation": s.real("SpacingVariation", 0.0..=100.0)?, + }); + Some(("stylize.scribble", params)) + })(), + _ => return None, + }) +} + +/// The largest size or radius Convert to Shape reads, in points. +const MAX_SHAPE_SIZE: f64 = 1e5; + +/// Convert to Shape: Rectangle, Rounded Rectangle or Ellipse, with an absolute size or one relative +/// to the object, and a corner radius +/// (https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). +/// The keys are LiveEffect XML's: `Shape` 0 Rectangle, 1 Rounded Rectangle, 2 Ellipse +/// (https://community.adobe.com/questions-652/effect-convert-to-shape-ellipse-in-javascript-761645), +/// `Absolute` 1 for an absolute `AbsWidth` × `AbsHeight`, else `RelWidth` and `RelHeight` added to +/// each side, and `CornerRadius`; a missing size is 18 pt a side or 36 pt, and a missing radius +/// 9 pt. `None`: a key, a kind or a value that isn't read, which keeps the drawn look. +fn shape_effect(f: &Filter) -> Option { + const SIZES: [&str; 5] = ["AbsWidth", "AbsHeight", "RelWidth", "RelHeight", "CornerRadius"]; + let known = f.kinds.iter().all(|(key, kind)| match key.as_str() { + "DisplayString" => *kind == Kind::Other, + "Shape" => *kind == Kind::Int, + key => (key == "Absolute" || SIZES.contains(&key)) && *kind == Kind::Real, + }); + if !known || !f.arrays.is_empty() || f.fill.is_some() || f.stroke.is_some() || f.gradient || f.pattern.is_some() { + return None; + } + // A written size is a finite number from `min`; a missing one is `default`. + let size = |key: &str, min: f64, default: f64| match f.kinds.get(key) { + None => Some(default), + Some(_) => f.params.get(key).copied().filter(|v| v.is_finite() && (min..=MAX_SHAPE_SIZE).contains(v)), + }; + let shape = f.params.get("Shape").copied().filter(|_| f.kinds.get("Shape") == Some(&Kind::Int))?; + let absolute = match f.params.get("Absolute").copied() { + Some(0.0) => false, + Some(1.0) => true, + _ => return None, + }; + let (rel_w, rel_h) = (size("RelWidth", -MAX_SHAPE_SIZE, 18.0)?, size("RelHeight", -MAX_SHAPE_SIZE, 18.0)?); + let (abs_w, abs_h, radius) = (size("AbsWidth", 0.0, 36.0)?, size("AbsHeight", 0.0, 36.0)?, size("CornerRadius", 0.0, 9.0)?); + let id = match shape { + 0.0 => "convertToShape.rectangle", + 1.0 => "convertToShape.roundedRectangle", + // A relative Ellipse in the file is drawn round the enlarged box, and VectorCraft's inside + // it: it keeps its drawn look. + 2.0 if absolute => "convertToShape.ellipse", + _ => return None, + }; + let mut params = json!({"relative": !absolute, "extraW": 2.0 * rel_w, "extraH": 2.0 * rel_h, "width": abs_w, "height": abs_h}); + if id == "convertToShape.roundedRectangle" { + params["radius"] = json!(radius); + } + Some(Effect { id: id.into(), params, visible: f.visible }) +} + +/// The largest offset Offset Path reads, in points (the effect's own limit). +const MAX_OFFSET: f64 = 1e5; + +/// Effect › Path: Offset Path with its Offset, Joins and Miter Limit +/// (https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/offset-duplicate-objects.html), +/// Outline Object and Outline Stroke, which have no settings. Offset Path's keys are LiveEffect +/// XML's: `ofst` in points, `jntp` 0 round, 1 bevel or 2 miter, and `mlim` +/// (https://community.adobe.com/questions-652/illustrator-javascript-count-area-with-offset-782386). +/// `None`: a missing, unknown or out-of-range setting, or one of another kind, which keeps the +/// drawn look; there is no default to stand in for a missing one. +fn path_effect(f: &Filter) -> Option { + if !f.arrays.is_empty() || f.fill.is_some() || f.stroke.is_some() || f.gradient || f.pattern.is_some() { + return None; + } + let (id, params) = match f.name.as_str() { + OFFSET => { + const KEYS: [(&str, Kind); 3] = [("ofst", Kind::Real), ("jntp", Kind::Int), ("mlim", Kind::Real)]; + if f.kinds.len() != KEYS.len() || KEYS.iter().any(|(key, kind)| f.kinds.get(*key) != Some(kind)) { + return None; + } + let value = |key: &str| f.params.get(key).copied().filter(|v| v.is_finite()); + let offset = value("ofst").filter(|v| v.abs() <= MAX_OFFSET)?; + let miter = value("mlim").filter(|v| (1.0..=500.0).contains(v))?; + let joins = match value("jntp")? { + 0.0 => "round", + 1.0 => "bevel", + 2.0 => "miter", + _ => return None, + }; + ("path.offsetPath", json!({"offset": offset, "joins": joins, "miterLimit": miter})) + } + // Outline Stroke without a `width`: the stroke it is on, or the object's, gives it. + OUTLINE_STROKE if f.kinds.is_empty() => ("path.outlineStroke", json!({})), + OUTLINE_TYPE if f.kinds.is_empty() => ("path.outlineObject", json!({})), + _ => return None, + }; + Some(Effect { id: id.into(), params, visible: f.visible }) +} + +/// The live effect filter `f` is, when it is one read here; `under` is what it could change the +/// paint of. +fn effect(f: &Filter, under: Under) -> Option { + if let Some(stylized) = stylize(f) { + let (id, params) = stylized?; + return Some(Effect { id: id.into(), params, visible: f.visible }); + } let param = |k: &str| f.params.get(k).copied().filter(|v| v.is_finite()); let flag = |k: &str| param(k).is_some_and(|v| v != 0.0); - let mode = |default: usize| super::read::blend_name(param("blnd").map_or(default, |v| v.max(0.0) as usize)); - let color = f.fill.as_ref().and_then(Paint::color).unwrap_or(vectorcraft_color::Color::BLACK); let (id, params) = match f.name.as_str() { - // `blur`'s scale isn't publicly documented: read as the Gaussian's σ, an effect's blur being 2σ. - GLOW => ( - "stylize.outerGlow", - json!({"mode": mode(2), "opacity": param("opac").unwrap_or(0.75) * 100.0, "blur": 2.0 * param("blur").unwrap_or(5.0), "color": color}), - ), - // LiveEffect XML uses `radius`; art styles abbreviate it `rad` (public scripting posts on applyEffect). - FEATHER => ("stylize.feather", json!({"radius": param("rad").or_else(|| param("radius")).unwrap_or(5.0)})), - SHADOW => { - let mut params = json!({ - "mode": mode(1), - "opacity": param("opac").unwrap_or(0.75) * 100.0, - "blur": 2.0 * param("blur").unwrap_or(5.0), - // Undocumented; read as the dialog's offsets, not flipped like art-space y: its default 7/7 pt is - // right and down (https://helpx.adobe.com/illustrator/using/drop-shadows-glows-feathering.html). - "x": param("horz").unwrap_or(7.0), - "y": param("vert").unwrap_or(7.0), - "color": color, - }); - // A `csrc` of 1 is Darkness, the object's own colors with black added; any value other than 0 is read as - // Darkness. `dark` is the percent of black (0 to 100, where `opac` is a fraction), and 100 when it is missing or not finite. - if param("csrc").unwrap_or(0.0) != 0.0 { - params["shade"] = json!("darkness"); - params["darkness"] = json!(param("dark").map_or(100.0, |v| v.clamp(0.0, 100.0))); - } - ("stylize.dropShadow", params) - } // Effect › Warp: `DeformStyle` numbers the styles from 1 as the dialog lists them, `Rotate` // is Vertical, and the bend and distortions are fractions. DEFORM => { @@ -471,71 +1147,243 @@ fn effect(f: &Filter) -> Option { }), ) } - // `jntp`: 0 round, 1 bevel, 2 miter (the joins LiveEffect XML writes in public scripts). - OFFSET => ( - "path.offsetPath", - json!({ - "offset": param("ofst").unwrap_or(10.0).clamp(-1e5, 1e5), - "joins": match param("jntp").map(|v| v as i64) { Some(0) => "round", Some(1) => "bevel", _ => "miter" }, - "miterLimit": param("mlim").unwrap_or(4.0).clamp(1.0, 500.0), - }), - ), - // Art space has y up: a move up is a negative `moveV` in the document. - TRANSFORM => ( - "distort.transform", - json!({ - "scaleH": param("scaleH_Percent").unwrap_or(100.0), - "scaleV": param("scaleV_Percent").unwrap_or(100.0), - "moveH": param("moveH_Pts").unwrap_or(0.0), - "moveV": -param("moveV_Pts").unwrap_or(0.0), - "rotate": param("rotate_Degrees").unwrap_or(0.0), - "copies": param("numCopies").unwrap_or(0.0).clamp(0.0, 1000.0) as i64, - "reflectX": flag("reflectX"), - "reflectY": flag("reflectY"), - "reference": param("pinPoint").unwrap_or(4.0).clamp(0.0, 8.0) as i64, - "random": flag("randomize"), - }), - ), + OFFSET | OUTLINE_TYPE | OUTLINE_STROKE => return path_effect(f), + TRANSFORM => ("distort.transform", transform(f, under)?), + FREE_DISTORT => ("distort.freeDistort", free_distort(f)?), + // Negative puckers (https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). + PUCKER_BLOAT => ("distort.puckerBloat", json!({"amount": real(f, "d_factor", 0.0, -200.0..=200.0)?})), + TWEAK => ("distort.tweak", tweak(f).filter(still)?), + // A positive angle turns clockwise in both. + TWIST => ("distort.twist", json!({"angle": real(f, "angle", 0.0, -3600.0..=3600.0)?})), + ZIG_ZAG => ("distort.zigZag", zig_zag(f)?), GAUSSIAN => ("blur.gaussian", json!({"radius": param("blur").unwrap_or(5.0).clamp(0.0, 1000.0)})), - // Its settings are in a Photoshop plug-in's binary block: the effect's defaults stand in. - BAS_RELIEF => ("sketch.basRelief", json!({"detail": 13.0, "smoothness": 3.0, "lightDirection": "bottom"})), + BAS_RELIEF => ( + "sketch.basRelief", + match &f.data { + // Without a settings block, the effect's defaults stand in. + None => json!({"detail": 13.0, "smoothness": 3.0, "lightDirection": "bottom"}), + Some(data) => adapter::bas_relief(&descriptor(f, data)?)?, + }, + ), + SHAPE_EFFECTS => return shape_effect(f), + PATHFINDER => return pathfinder_effect(f), _ => return None, }; Some(Effect { id: id.into(), params, visible: f.visible }) } +/// The fields of filter `f`'s settings block `data`, when it was read and its `dataSize`, written +/// as `/Int`, is its length. +fn descriptor(f: &Filter, data: &Result, ()>) -> Option> { + let data = data.as_ref().ok()?; + (f.kinds.get("dataSize") == Some(&Kind::Int)).then_some(())?; + let size = f.params.get("dataSize").copied()?; + if size != data.len() as f64 { + return None; + } + adapter::decode(data) +} + +/// The Effect › Pathfinder effect of [`PATHFINDER_COMMANDS`] that an integer `Command` names, when +/// every key of [`PATHFINDER_OPTIONS`] is there with its kind and value (Soft Mix's `Mix` from 0.01 +/// to 1, as its Mixing Rate in percent) and the only other key is the `DisplayString` text, each +/// written once. `None` for anything else, which keeps the drawn look. +fn pathfinder_effect(f: &Filter) -> Option { + let known = f + .kinds + .iter() + .all(|(key, kind)| (key == "DisplayString" && *kind == Kind::Other) || key == "Command" || PATHFINDER_OPTIONS.iter().any(|(k, ..)| k == key)); + if !known || f.repeated || !f.arrays.is_empty() || f.fill.is_some() || f.stroke.is_some() || f.gradient || f.pattern.is_some() { + return None; + } + if f.kinds.get("Command") != Some(&Kind::Int) { + return None; + } + let command = f.params.get("Command").copied().filter(|c| c.is_finite() && c.fract() == 0.0 && *c >= 0.0)?; + let id = *PATHFINDER_COMMANDS.get(usize::try_from(command as i64).ok()?)?; + let soft_mix = id == "pathfinder.softMix"; + let options = PATHFINDER_OPTIONS + .iter() + .all(|(key, kind, value)| f.kinds.get(*key) == Some(kind) && ((soft_mix && *key == "Mix") || f.params.get(*key) == Some(value))); + if !options { + return None; + } + let params = if soft_mix { + let mix = f.params.get("Mix").copied().filter(|m| (0.01..=1.0).contains(m))?; + // Rounded to six decimals: a `Mix` of 0.3 is a rate of 30. + json!({"mixingRate": (mix * 100.0 * 1e6).round() / 1e6}) + } else { + json!({}) + }; + Some(Effect { id: id.into(), params, visible: f.visible }) +} + /// The fill or stroke basic filter `f` paints, `Ok(None)` when it paints nothing, `Err` when it /// paints in a way this doesn't read. fn paint_item(f: &Filter) -> Result, ()> { match f.name.as_str() { FILL if !f.paints.1 => Ok(None), FILL => match (&f.pattern, &f.gradient_of, &f.fill) { - (Some((name, matrix)), ..) => Ok(Some(StyleItem::Pattern { name: name.clone(), matrix: *matrix })), + (Some((name, matrix, controls)), ..) => Ok(Some(StyleItem::Pattern { name: name.clone(), matrix: *matrix, controls: controls.clone() })), (None, Some((name, angle)), _) => Ok(Some(StyleItem::Gradient { name: name.clone(), angle: *angle })), (None, None, _) if f.gradient => Ok(Some(StyleItem::Gradient { name: None, angle: 0.0 })), (None, None, Some(p)) => Ok(Some(StyleItem::Fill(p.clone()))), (None, None, None) => Err(()), }, - STROKE if !f.paints.0 => Ok(None), - // Dashes aligned to corners and path ends draw as the look's pieces: a solid end at each end - // and the pattern, fitted, between them. - STROKE if f.params.get("BSDashAdj").is_some_and(|v| *v != 0.0) => Err(()), - STROKE => match &f.stroke { - Some(p) if !f.gradient && f.pattern.is_none() => Ok(Some(StyleItem::Stroke { - paint: p.clone(), - width: f.width, - cap: f.cap, - join: f.join, - miter: f.miter, - dash: f.dash.clone(), - profile: width_profile(&f.arrays), - })), - _ => Err(()), - }, + STROKE => stroke_item(f, StrokeAlign::Center), + CALLIGRAPHIC => calligraphic_stroke(f).map(Some).ok_or(()), + STROKE_OFFSET => offset_stroke(f), + ART_BRUSH => art_stroke(f).map(Some).ok_or(()), _ => Err(()), } } +/// A stroke filter `f`'s stroke, painting on side `align` of its path: `Ok(None)` when it paints +/// nothing, `Err` when it paints in a way this doesn't read. +fn stroke_item(f: &Filter, align: StrokeAlign) -> Result, ()> { + if !f.paints.0 { + return Ok(None); + } + // Dashes aligned to corners and path ends draw as the look's pieces: a solid end at each end + // and the pattern, fitted, between them. + if f.params.get("BSDashAdj").is_some_and(|v| *v != 0.0) { + return Err(()); + } + match &f.stroke { + Some(p) if !f.gradient && f.pattern.is_none() => Ok(Some(StyleItem::Stroke { + paint: p.clone(), + width: f.width, + cap: f.cap, + join: f.join, + miter: f.miter, + dash: f.dash.clone(), + profile: width_profile(&f.arrays), + align, + brush: None, + })), + _ => Err(()), + } +} + +/// A Stroke Offset filter `f`: a stroke whose own style is in its dictionary, aligned inside its +/// path when `StrokeOffsetInside` is 1 and outside when it is 0 (its `DisplayString` says which). +/// `Err` when that switch is missing or not a switch, or for a stroke [`paint_item`] doesn't read. +fn offset_stroke(f: &Filter) -> Result, ()> { + let inside = switch(f, "StrokeOffsetInside", Kind::Bool)?.ok_or(())?; + stroke_item(f, if inside { StrokeAlign::Inside } else { StrokeAlign::Outside }) +} + +/// A Calligraphic brush's filter `f` as the stroke it paints: `None` when it isn't a stroke in a +/// colour, names no Calligraphic brush, or its settings aren't all there as numbers. An angle +/// relative to the path isn't read. +fn calligraphic_stroke(f: &Filter) -> Option { + let real = |key: &str| entry(f, key, Kind::Real).ok().flatten(); + let code = |key: &str| entry(f, key, Kind::Int).ok().flatten(); + if !f.paints.0 || f.gradient || f.pattern.is_some() || f.repeated { + return None; + } + if entry(f, "AngleRelativeTo", Kind::Int).ok()?.unwrap_or(0.0) != 0.0 { + return None; + } + let (name, plugin) = f.plugin_object.as_ref()?; + if plugin != CALLIGRAPHIC { + return None; + } + let values = [real("Angle")?, real("Roundness")?, real("Diameter")?]; + let variation = [real("AngleVariation")?, real("RoundnessVariation")?, real("DiameterVariation")?].map(f64::abs); + let codes = [code("AngleDependsOn")?, code("RoundnessDependsOn")?, code("DiameterDependsOn")?]; + Some(StyleItem::Stroke { + paint: f.stroke.clone()?, + width: f.width, + cap: f.cap, + join: f.join, + miter: f.miter, + dash: None, + profile: None, + align: StrokeAlign::Center, + brush: Some((name.clone(), PathBrush::Calligraphic(super::brush::calligraphic(values, variation, codes)))), + }) +} + +/// The entries an Art brush's filter may hold, with the settings [`art_stroke`] reads. Any other +/// entry keeps the drawn look, a variable width's among them. +const ART_ENTRIES: [&str; 18] = [ + "StrokeStyle", + "DisplayString", + "Brush", + "Proportional", + "Segmented", + "UpsideDown", + "Counterclockwise", + "ScaleYDependsOn", + "Spacing", + "StartSegmentLength", + "EndSegmentLength", + "Adjustment", + "FoldAdjustment", + "Scaling", + "MinScaling", + "MaxScaling", + "Colorization", + "Adobe Effect Expand Before Version", // brand-ok: the entry's name in the files +]; + +/// An Art brush's filter `f` as the stroke it paints: `None` when it isn't a stroke in a color, names +/// no Art brush, holds an entry that isn't read, or its settings aren't those of art that stretches +/// along the path, unflipped, at the brush's own width (`Scaling` 1), in Tints (`Colorization` 1), +/// with `FoldAdjustment` 1, which is [`vectorcraft_brush::ArtBrush`]'s `overlap: false`: its drawn +/// look stays. +fn art_stroke(f: &Filter) -> Option { + if !f.paints.0 + || f.gradient + || f.pattern.is_some() + || f.repeated + || !f.arrays.is_empty() + || !f.kinds.keys().all(|k| ART_ENTRIES.contains(&k.as_str())) + { + return None; + } + let (name, plugin) = f.plugin_object.as_ref()?; + if plugin != ART_BRUSH { + return None; + } + let off = |key: &str, kind: Kind| matches!(entry(f, key, kind), Ok(None | Some(0.0))); + let plain = off("Proportional", Kind::Bool) + && off("Segmented", Kind::Bool) + && off("UpsideDown", Kind::Int) + && off("Counterclockwise", Kind::Int) + && off("ScaleYDependsOn", Kind::Int) + && off("Spacing", Kind::Real) + && off("StartSegmentLength", Kind::Real) + && off("EndSegmentLength", Kind::Real); + if !plain || entry(f, "Adjustment", Kind::Int).ok()?.unwrap_or(1.0) != 1.0 || entry(f, "FoldAdjustment", Kind::Bool).ok()?.unwrap_or(1.0) != 1.0 { + return None; + } + let one = |key: &str| entry(f, key, Kind::Real).is_ok_and(|v| v.unwrap_or(1.0) == 1.0); + if entry(f, "Scaling", Kind::Real).ok()?? != 1.0 || !one("MinScaling") || !one("MaxScaling") { + return None; + } + if entry(f, "Colorization", Kind::Int).ok()?? != 1.0 { + return None; + } + let paint = f.stroke.clone()?; + // The tinted pieces are process colors, so a swatch's ink would be lost. + if matches!(paint, Paint::Solid { swatch: Some(_), .. }) { + return None; + } + Some(StyleItem::Stroke { + paint, + width: f.width, + cap: f.cap, + join: f.join, + miter: f.miter, + dash: None, + profile: None, + align: StrokeAlign::Center, + brush: Some((name.clone(), PathBrush::Art)), + }) +} + /// Builds an [`ArtStyle`] from a style's filter tree. struct Builder<'a> { filters: &'a [Filter], @@ -568,11 +1416,29 @@ impl Builder<'_> { let mut look = ItemLook { visible: f.visible, ..ItemLook::default() }; let mut painted: Option = None; let mut paints = 0; - for k in self.children(id) { + let kids = self.children(id); + // What this item's effects could change: its own paint, and its other effects' distances. + let mut under = Under { strokes: false, patterns: false }; + let mut effects = 0; + for &k in &kids { + let c = &filters[k]; + match c.name.as_str() { + _ if c.compound => {} + FILL | STROKE | STROKE_OFFSET | CALLIGRAPHIC | ART_BRUSH => match paint_item(c) { + Ok(Some(StyleItem::Stroke { .. })) => under.strokes = true, + Ok(Some(StyleItem::Pattern { .. })) => under.patterns = true, + _ => {} + }, + BLEND => {} + _ => effects += 1, + } + } + under.strokes |= effects > 1; + for k in kids { let c = &filters[k]; match c.name.as_str() { _ if c.compound => self.plain = false, - FILL | STROKE => { + FILL | STROKE | STROKE_OFFSET | CALLIGRAPHIC | ART_BRUSH => { paints += 1; look.visible &= c.visible; match paint_item(c) { @@ -585,9 +1451,11 @@ impl Builder<'_> { (look.blend, look.opacity) = (super::read::blend_mode(mode), opacity); } } - _ => match effect(c) { - Some(e) => look.effects.push(e), - None => self.plain = false, + // Convert to Shape on one fill or stroke isn't read yet: what it draws there is + // the drawn look's. A fill's or stroke's own Pathfinder effect isn't read either. + _ => match effect(c, under) { + Some(e) if !e.id.starts_with("convertToShape.") && !is_pathfinder(&e.id) => look.effects.push(e), + _ => self.plain = false, }, } } @@ -620,16 +1488,78 @@ impl Builder<'_> { } } +/// Is `e`, on the whole object, an effect any object is read with? Of the Distort & Transform +/// effects: Transform without copies (Random is never read), Twist, a Tweak that moves nothing, +/// Pucker & Bloat at 0, and Free Distort when its corners make a parallelogram (an affine map). +/// Zig Zag is left to type. Which objects Transform, Twist and Free Distort are read on is +/// `read::ops`' `moves_with`. +fn any_object_takes(e: &Effect) -> bool { + match e.id.as_str() { + "stylize.dropShadow" + | "stylize.innerGlow" + | "stylize.outerGlow" + | "stylize.feather" + | "stylize.roundCorners" + | "stylize.scribble" + | "convertToShape.rectangle" + | "convertToShape.roundedRectangle" + | "convertToShape.ellipse" + | "path.offsetPath" + | "path.outlineObject" + | "path.outlineStroke" + | "distort.twist" + | "distort.tweak" => true, + // Copies are drawn as one path, its fills under all its strokes, where the file paints each + // copy's fill and stroke in turn. + "distort.transform" => e.params["copies"].as_i64() == Some(0), + "distort.puckerBloat" => e.params["amount"].as_f64() == Some(0.0), + "distort.freeDistort" => affine(&e.params), + id => is_pathfinder(id), + } +} + +/// Does every Bas Relief filter in `filters` have a settings block, so that it reads from its +/// settings and not from its defaults standing in? +fn bas_relief_read(filters: &[Filter]) -> bool { + filters.iter().all(|f| f.name != BAS_RELIEF || f.data.is_some()) +} + +/// Is `e` read on the whole object: Bas Relief when `bas_relief` says its settings were read, and +/// otherwise what [`any_object_takes`] says? +fn object_takes(e: &Effect, bas_relief: bool) -> bool { + if e.id == "sketch.basRelief" { + return bas_relief; + } + any_object_takes(e) +} + +/// Do Free Distort params `p`'s corners (top left, top right, bottom right, bottom left) make a +/// parallelogram, so that the bilinear map is affine? +fn affine(p: &serde_json::Value) -> bool { + let Some(c) = p["corners"].as_array() else { return false }; + let at = |i: usize, axis: usize| c.get(i).and_then(|c| c.get(axis)).and_then(serde_json::Value::as_f64); + (0..2).all(|axis| match (at(0, axis), at(1, axis), at(2, axis), at(3, axis)) { + (Some(tl), Some(tr), Some(br), Some(bl)) => { + // The corners are fractions of the object's box, divided out of the file's rounded + // decimals; the tolerance is relative to how far apart they lie, not where. + let (lo, hi) = [tl, tr, br, bl].iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + ((tl + br) - (tr + bl)).abs() <= 1e-5 * (hi - lo).max(1.0) + } + _ => false, + }) +} + fn style(filters: &[Filter]) -> ArtStyle { let mut st = ArtStyle { plain: true, ..ArtStyle::default() }; let Some(root) = filters.iter().position(|f| f.parent.is_none()) else { return st }; let mut b = Builder { filters, plain: true }; + let chained = filters[root].compound && filters[root].name == CHAIN; let top = if filters[root].compound { b.children(root) } else { vec![root] }; for id in top { let f = &filters[id]; match f.name.as_str() { STACK if f.compound => b.stack(id, &mut st), - FILL | STROKE | CHAIN => { + FILL | STROKE | STROKE_OFFSET | CALLIGRAPHIC | ART_BRUSH | CHAIN => { if let Some((item, look)) = b.item(id) { st.items.push(item); st.looks.push(look); @@ -637,23 +1567,42 @@ fn style(filters: &[Filter]) -> ArtStyle { } CONDUIT => {} // The object's own transparency, which its look carries too. - BLEND => {} - _ => match effect(f) { - Some(e) => st.effects.push(e), - None => b.plain = false, + BLEND => { + if let Some((mode, opacity)) = f.xy { + let (isolate, knockout) = f.xy_group.unwrap_or((false, Knockout::Off)); + st.transparency = Some((opacity, super::read::blend_mode(mode), isolate, knockout)); + } + } + // The object's Pathfinder effects are read only in its own chain. + _ => match effect(f, ANYTHING) { + Some(e) if chained || !is_pathfinder(&e.id) => st.effects.push(e), + _ => b.plain = false, }, } } + st.pathfinder = st.effects.iter().any(|e| is_pathfinder(&e.id)); + // A group's Pathfinder effects are drawn before its other effects: one listed after another + // effect keeps the drawn look. + if st.effects.iter().skip_while(|e| is_pathfinder(&e.id)).any(|e| is_pathfinder(&e.id)) { + b.plain = false; + } st.plain = b.plain; + let bas_relief = bas_relief_read(filters); let count = |stroke: bool| st.items.iter().filter(|i| matches!(i, StyleItem::Stroke { .. }) == stroke).count(); st.simple = st.plain && count(true) <= 1 && count(false) <= 1 && st.items.iter().all(|i| matches!(i, StyleItem::Fill(_) | StyleItem::Stroke { .. } | StyleItem::Gradient { .. })) && st.looks.iter().all(|l| l.visible && l.opacity >= 1.0 && l.blend == BlendMode::Normal && l.effects.is_empty()) - && st.effects.iter().all(|e| matches!(e.id.as_str(), "stylize.outerGlow" | "stylize.feather" | "stylize.dropShadow")); + && st.effects.iter().all(|e| object_takes(e, bas_relief)) + // An effect that moves the outline is drawn on its own: with others, their order and what + // scales with it aren't kept. + && (!st.moves_outline() || st.effects.len() == 1) + // Pathfinder effects on a group with no fills or strokes of its own (`styled` checks the group). + && (!st.pathfinder || st.items.is_empty()); st } +mod adapter; #[cfg(test)] mod tests; diff --git a/crates/eps/src/import/ai/style/adapter.rs b/crates/eps/src/import/ai/style/adapter.rs new file mode 100644 index 0000000000..c06122e566 --- /dev/null +++ b/crates/eps/src/import/ai/style/adapter.rs @@ -0,0 +1,179 @@ +//! The settings of a filter-gallery effect in an art style: a basic filter's `/Binary : +//! /ASCII85Decode ,` block, whose comment lines hold the bytes until `~>`, then `; (data) ,` and the +//! byte count `n /Int (dataSize) ,`. The bytes are a descriptor, all numbers big-endian: +//! +//! ```text +//! version (u32, 1) +//! field* key (4 chars) marker (u32) … +//! marker 0: type (4 chars: long, doub, bool) value (i32, f64 or one byte) +//! marker 0x2000: an enumeration: type (4 chars) value (4 chars) +//! marker 0x80000000: an object: class (4 chars) length (u32) and that many bytes, a descriptor +//! ``` +//! +//! A filter-gallery effect's first field is `GEfk`, an enumeration of type `GEft` whose value is the +//! effect's four-character code. The keys and the enumerations' values are the ones the Photoshop +//! Actions Event Guide lists for Bas Relief, and `GEfk` and `GEft` are the filter gallery's in +//! published scripting examples. Anything else (another marker or type, a field past the end, bytes after the last field, more +//! than [`MAX_FIELDS`] fields or objects nested more than [`MAX_DEPTH`] deep) isn't read. + +use serde_json::{Value as Json, json}; + +/// Most bytes a block's text is read from (its comment lines and `~>`). +pub(super) const MAX_ENCODED: usize = 6 * 1024; +/// Most bytes a block decodes to. +pub(super) const MAX_DECODED: usize = 4 * 1024; +/// Most fields read in one descriptor, nested ones included. +const MAX_FIELDS: usize = 32; +/// Most levels of objects in objects. +const MAX_DEPTH: usize = 2; + +/// A field's value. +#[derive(Clone, Debug, PartialEq)] +pub(super) enum Value { + Long(i32), + Doub(f64), + Bool(bool), + /// An enumeration's type and value. + Enum([u8; 4], [u8; 4]), + /// An object's class and fields. + Object([u8; 4], Vec<(Key, Value)>), +} + +/// A field's key. +pub(super) type Key = [u8; 4]; + +/// The fields of descriptor `data`; `None` when it isn't one read here. +pub(super) fn decode(data: &[u8]) -> Option> { + let mut count = 0; + fields(data, 0, &mut count) +} + +fn fields(data: &[u8], depth: usize, count: &mut usize) -> Option> { + let mut r = Reader { data, at: 0 }; + if r.u32()? != 1 { + return None; + } + let mut out = vec![]; + while r.at < data.len() { + *count += 1; + if *count > MAX_FIELDS { + return None; + } + let key = r.four()?; + let value = match r.u32()? { + 0 => match &r.four()? { + b"long" => Value::Long(i32::from_be_bytes(r.four()?)), + b"doub" => Value::Doub(f64::from_be_bytes(r.eight()?)).finite()?, + b"bool" => match r.take(1)? { + [0] => Value::Bool(false), + [1] => Value::Bool(true), + _ => return None, + }, + _ => return None, + }, + 0x2000 => Value::Enum(r.four()?, r.four()?), + 0x8000_0000 if depth < MAX_DEPTH => { + let class = r.four()?; + let n = usize::try_from(r.u32()?).ok()?; + Value::Object(class, fields(r.take(n)?, depth + 1, count)?) + } + _ => return None, + }; + out.push((key, value)); + } + Some(out) +} + +impl Value { + fn finite(self) -> Option { + match self { + Value::Doub(v) if !v.is_finite() => None, + v => Some(v), + } + } +} + +struct Reader<'a> { + data: &'a [u8], + at: usize, +} + +impl<'a> Reader<'a> { + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let end = self.at.checked_add(n)?; + let bytes = self.data.get(self.at..end)?; + self.at = end; + Some(bytes) + } + + fn four(&mut self) -> Option<[u8; 4]> { + self.take(4)?.try_into().ok() + } + + fn eight(&mut self) -> Option<[u8; 8]> { + self.take(8)?.try_into().ok() + } + + fn u32(&mut self) -> Option { + Some(u32::from_be_bytes(self.four()?)) + } +} + +/// The fields of a filter-gallery effect `code`, its `GEfk` field taken off; `None` when that field +/// names another effect. +fn gallery<'a>(fields: &'a [(Key, Value)], code: &[u8; 4]) -> Option<&'a [(Key, Value)]> { + match fields.split_first() { + Some((([b'G', b'E', b'f', b'k'], Value::Enum(kind, value)), rest)) => (kind == b"GEft" && value == code).then_some(rest), + _ => Some(fields), + } +} + +/// A whole number in `range`. +fn long(v: &Value, range: std::ops::RangeInclusive) -> Option { + match v { + Value::Long(n) if range.contains(n) => Some(f64::from(*n)), + _ => None, + } +} + +/// Sketch › Bas Relief's params (`sketch.basRelief`) from its fields: `Dtl ` (detail), `Smth` +/// (smoothness) and `LghD` (the light's direction), each once; `None` when one is missing, out of +/// range or not read here, or another field is there. +pub(super) fn bas_relief(fields: &[(Key, Value)]) -> Option { + let (mut detail, mut smoothness, mut light) = (None, None, None); + for (key, value) in gallery(fields, b"BsRl")? { + let slot = match key { + b"Dtl " => &mut detail, + b"Smth" => &mut smoothness, + b"LghD" => &mut light, + _ => return None, + }; + if slot.is_some() { + return None; + } + *slot = Some(match key { + b"LghD" => json!(light_direction(value)?), + _ => json!(long(value, 1..=15)?), + }); + } + Some(json!({"detail": detail?, "smoothness": smoothness?, "lightDirection": light?})) +} + +/// The light direction of a `LghD` enumeration's value (`typeLightDirection`). +fn light_direction(v: &Value) -> Option<&'static str> { + let Value::Enum(kind, value) = v else { return None }; + if kind != b"LghD" { + return None; + } + Some(match value { + b"LDBt" => "bottom", + b"LDBL" => "bottomLeft", + b"LDLf" => "left", + b"LDTL" => "topLeft", + b"LDTp" => "top", + b"LDTR" => "topRight", + b"LDRg" => "right", + b"LDBR" => "bottomRight", + _ => return None, + }) +} diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 964b74f10b..929006856c 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -1,4 +1,5 @@ use super::*; +use vectorcraft_color::Color; #[test] fn a_variable_width_stroke_keeps_its_profile() { @@ -26,94 +27,236 @@ fn dashes_aligned_to_corners_keep_the_drawn_look() { assert!(!art_styles(data)["Stitches"].plain); } -#[test] -fn a_drop_shadow_offset_down_points_down() { - // GUARDS: the document has y down; flipping `vert` like an art-space y would turn the dialog's - // default shadow (7 pt right, 7 pt down) upwards. - let data = b"/KnownStyle :\n(Shade) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n7 /Real (horz) ,\n7 /Real (vert) ,\n; /Dict ;\n /Part ,\n;\n"; - let styles = art_styles(data); - let [shadow] = styles["Shade"].effects.as_slice() else { panic!("{:?}", styles["Shade"]) }; - assert_eq!((shadow.params["x"].as_f64(), shadow.params["y"].as_f64()), (Some(7.0), Some(7.0))); -} - /// The style `Shade`: a Drop Shadow whose dictionary holds `keys`. fn shadow_style(keys: &str) -> ArtStyle { + effect_style("Adobe Drop Shadow", keys) +} + +/// The style `Fx`: an effect `name` on the whole object, its dictionary holding `keys`. +fn effect_style(name: &str, keys: &str) -> ArtStyle { let data = format!( - "/KnownStyle :\n(Shade) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{keys}; /Dict ;\n /Part ,\n;\n" + "/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n({name}) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{keys}; /Dict ;\n /Part ,\n;\n" ); - art_styles(data.as_bytes()).remove("Shade").unwrap_or_default() + art_styles(data.as_bytes()).remove("Fx").unwrap_or_default() +} + +/// A colour entry `key`: a fill style in RGB `r g b`. +fn color_entry(key: &str, rgb: &str) -> String { + format!("/FillStyle : 0 O\n0 0 0 0 {rgb} Xa\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 1 Xd\n/Def ;\n ({key}) ,\n") +} + +/// A Drop Shadow's dictionary: every setting, with Color or Darkness set by `shade`. +fn shadow_keys(shade: &str) -> String { + format!( + "2 /Int (blnd) ,\n0.43 /Real (opac) ,\n37 /Real (dark) ,\n-13 /Real (vert) ,\n11 /Real (horz) ,\n17 /Real (blur) ,\n{}{shade}", + color_entry("sclr", "0 1 0") + ) +} + +/// `style`'s one effect on the whole object. +fn only_effect(style: &ArtStyle) -> &Effect { + assert!(style.plain, "{style:?}"); + let [e] = style.effects.as_slice() else { panic!("{style:?}") }; + e +} + +/// `params[key]`, a number within rounding of `want`. +fn near(params: &serde_json::Value, key: &str, want: f64) { + let got = params[key].as_f64(); + assert!(got.is_some_and(|v| (v - want).abs() < 1e-9), "{key}: {got:?}, not {want}: {params}"); +} + +#[test] +fn a_drop_shadow_reads_its_settings() { + // GUARDS: `vert` read as an art-space y would flip a shadow offset down to up. + let style = shadow_style(&shadow_keys("0 /Int (csrc) ,\n")); + let shadow = only_effect(&style); + let p = &shadow.params; + assert_eq!( + (shadow.id.as_str(), &p["mode"], &p["color"]), + ("stylize.dropShadow", &json!("Screen"), &json!(vectorcraft_color::Color::rgb(0.0, 1.0, 0.0))) + ); + for (key, want) in [("x", 11.0), ("y", -13.0), ("blur", 34.0), ("opacity", 43.0)] { + near(p, key, want); + } + assert_eq!((p.get("shade"), p.get("darkness")), (None, None)); } #[test] fn a_drop_shadow_with_darkness_reads_its_darkness() { - // GUARDS: a `csrc` other than 0 made the style not plain, and the object came in as its drawn look. - let style = shadow_style("1 /Int (blnd) ,\n0.75 /Real (opac) ,\n5 /Real (blur) ,\n1 /Int (csrc) ,\n50 /Real (dark) ,\n"); - assert!(style.plain, "{style:?}"); - let [shadow] = style.effects.as_slice() else { panic!("{style:?}") }; - let p = &shadow.params; + let shadow = only_effect(&shadow_style(&shadow_keys("1 /Int (csrc) ,\n"))).clone(); + assert_eq!((&shadow.params["shade"], &shadow.params["darkness"]), (&json!("darkness"), &json!(37.0))); +} + +#[test] +fn a_drop_shadow_with_settings_not_read_keeps_the_drawn_look() { + // GUARDS: an unknown `csrc` was read as Darkness, `blnd` was cast to a mode, a missing setting + // took a default and an unknown key was skipped: each became an editable shadow the file doesn't draw. + let full = shadow_keys("0 /Int (csrc) ,\n"); + let cases = [ + full.replace("0 /Int (csrc)", "99 /Int (csrc)"), + full.replace("2 /Int (blnd)", "99 /Int (blnd)"), + full.replace("2 /Int (blnd)", "2.5 /Int (blnd)"), + full.replace("0 /Int (csrc)", "0.5 /Int (csrc)"), + full.replace("11 /Real (horz)", "11 /Int (horz)"), + full.replace("37 /Real (dark)", "37 /Int (dark)"), + full.replace("2 /Int (blnd)", "2 /Real (blnd)"), + full.replace("0.43 /Real (opac)", "1.5 /Real (opac)"), + full.replace("11 /Real (horz) ,\n", ""), + full.replace(&color_entry("sclr", "0 1 0"), ""), + full.replace("0 1 0 0 0 Xy", "2 0.5 0 0 0 Xy"), + format!("{full}1 /Real (spread) ,\n"), + format!("{full}0 /Bool (pair) ,\n"), + format!("{full}(x) /String (note) ,\n"), + format!("{full}3 4 /RealPointRelToROrigin (spot) ,\n"), + shadow_keys("1 /Int (csrc) ,\n").replace("37 /Real (dark)", "250 /Real (dark)"), + shadow_keys("1 /Int (csrc) ,\n").replace("37 /Real (dark)", "(fifty) /Real (dark)"), + ]; + for keys in cases { + assert!(!shadow_style(&keys).plain, "{keys}"); + } + let observed = format!("{full}1 /Bool (pair) ,\n1 /Bool (usePSLBlur) ,\n16 /Int (Adobe Effect Expand Before Version) ,\n"); + assert!(shadow_style(&observed).plain); +} + +#[test] +fn an_inner_glow_reads_its_settings() { + let keys = + |gtyp: &str| format!("10 /Int (blnd) ,\n0.41 /Real (opac) ,\n13 /Real (blur) ,\n{}{gtyp} /Int (gtyp) ,\n", color_entry("gclr", "1 0 0")); + let style = effect_style("Adobe Inner Glow", &keys("0")); + let glow = only_effect(&style); + let p = &glow.params; assert_eq!( - (shadow.id.as_str(), &p["shade"], &p["darkness"], &p["opacity"], &p["blur"]), - ("stylize.dropShadow", &json!("darkness"), &json!(50.0), &json!(75.0), &json!(10.0)) + (glow.id.as_str(), &p["mode"], &p["source"], &p["color"]), + ("stylize.innerGlow", &json!("Difference"), &json!("center"), &json!(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0))) ); + near(p, "opacity", 41.0); + near(p, "blur", 13.0); + assert!(style.simple); + assert_eq!(only_effect(&effect_style("Adobe Inner Glow", &keys("1"))).params["source"], json!("edge")); + assert!(!effect_style("Adobe Inner Glow", &keys("2")).plain); } #[test] -fn a_drop_shadow_darkness_is_100_percent_when_missing_and_kept_within_0_to_100() { - for (dark, want) in [("", 100.0), ("(fifty) /Real (dark) ,\n", 100.0), ("250 /Real (dark) ,\n", 100.0), ("-5 /Real (dark) ,\n", 0.0)] { - let style = shadow_style(&format!("1 /Int (csrc) ,\n{dark}")); - assert!(style.plain, "{dark:?}: {style:?}"); - let [shadow] = style.effects.as_slice() else { panic!("{dark:?}: {style:?}") }; - assert_eq!((&shadow.params["shade"], &shadow.params["darkness"]), (&json!("darkness"), &json!(want)), "{dark:?}"); +fn an_outer_glow_reads_its_settings_and_keeps_the_drawn_look_for_others() { + let keys = format!( + "16 /Int (Adobe Effect Expand Before Version) ,\n10 /Int (blnd) ,\n0.42 /Real (opac) ,\n19 /Real (blur) ,\n{}1 /Bool (usePSLBlur) ,\n", + color_entry("sclr", "0 0 1") + ); + let glow = only_effect(&effect_style("Adobe Outer Glow", &keys)).clone(); + assert_eq!((glow.id.as_str(), &glow.params["mode"]), ("stylize.outerGlow", &json!("Difference"))); + near(&glow.params, "opacity", 42.0); + near(&glow.params, "blur", 38.0); + for other in [ + format!("{keys}1 /Real (spread) ,\n"), + keys.replace("19 /Real (blur)", "19 /Int (blur)"), + keys.replace("1 /Bool (usePSLBlur)", "0 /Bool (usePSLBlur)"), + ] { + assert!(!effect_style("Adobe Outer Glow", &other).plain, "{other}"); } } #[test] -fn a_drop_shadow_with_color_keeps_its_params() { - // GUARDS: a `csrc` of 0, or none, is Color; its shadow has neither `shade` nor `darkness`. - for csrc in ["", "0 /Int (csrc) ,\n50 /Real (dark) ,\n"] { - let style = shadow_style(&format!("2 /Int (blnd) ,\n0.5 /Real (opac) ,\n{csrc}")); - assert!(style.plain, "{csrc:?}: {style:?}"); - let [shadow] = style.effects.as_slice() else { panic!("{csrc:?}: {style:?}") }; - let want = json!({"mode": "Screen", "opacity": 50.0, "blur": 10.0, "x": 7.0, "y": 7.0, "color": vectorcraft_color::Color::BLACK}); - assert_eq!(shadow.params, want, "{csrc:?}"); +fn a_feather_reads_its_radius() { + // GUARDS: Feather was looked for under another name and key, so the files' Feather kept the drawn look. + let style = effect_style("Adobe Fuzzy Mask", "14 /Real (Radius) ,\n"); + let feather = only_effect(&style); + assert_eq!((feather.id.as_str(), feather.params["radius"].as_f64()), ("stylize.feather", Some(14.0))); + assert!(style.simple); + for other in ["14 /Real (radius) ,\n", "", "-1 /Real (Radius) ,\n"] { + assert!(!effect_style("Adobe Fuzzy Mask", other).plain, "{other}"); } } #[test] -fn a_feather_reads_its_radius_from_rad() { - let data = b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n12 /Real (rad) ,\n; /Dict ;\n /Part ,\n;\n"; - let styles = art_styles(data); - let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; - assert_eq!((feather.id.as_str(), feather.params["radius"].as_f64()), ("stylize.feather", Some(12.0))); +fn round_corners_read_their_radius() { + let style = effect_style("Adobe Round Corners", "21 /Real (radius) ,\n"); + let round = only_effect(&style); + assert_eq!((round.id.as_str(), round.params["radius"].as_f64()), ("stylize.roundCorners", Some(21.0))); + assert!(style.simple); + for other in ["21 /Real (Radius) ,\n", "21 /Int (radius) ,\n", "-1 /Real (radius) ,\n"] { + assert!(!effect_style("Adobe Round Corners", other).plain, "{other}"); + } +} + +/// A Scribble's dictionary with every setting. +const SCRIBBLE_KEYS: &str = "0.8 /Real (SpacingVariation) ,\n0.23 /Real (ScribbleVariation) ,\n4 /Real (EdgeOverlapVariation) ,\n67 /Real (Angle) ,\n\ + 2.3 /Real (StrokeWidth) ,\n-7 /Real (EdgeOverlap) ,\n0.17 /Real (Scribbliness) ,\n13 /Real (Spacing) ,\n"; + +#[test] +fn a_scribble_reads_its_settings() { + let style = effect_style("Adobe Scribble Fill", SCRIBBLE_KEYS); + let scribble = only_effect(&style); + assert_eq!(scribble.id, "stylize.scribble"); + let want = [ + ("angle", 67.0), + ("overlap", -7.0), + ("overlapVariation", 4.0), + ("strokeWidth", 2.3), + ("curviness", 17.0), + ("curvinessVariation", 23.0), + ("spacing", 13.0), + ("spacingVariation", 0.8), + ]; + for (key, v) in want { + near(&scribble.params, key, v); + } + assert!(style.simple); } #[test] -fn a_feather_falls_back_to_radius_and_defaults_to_five_points() { - let with_name = b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n3 /Real (radius) ,\n; /Dict ;\n /Part ,\n;\n"; - let styles = art_styles(with_name); - let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; - assert_eq!(feather.params["radius"].as_f64(), Some(3.0)); +fn a_scribble_with_a_colour_or_settings_not_read_keeps_the_drawn_look() { + let cases = [ + format!("{SCRIBBLE_KEYS}{}", color_entry("sclr", "0 1 0")), + format!("{SCRIBBLE_KEYS}0.5 /Real (MinDensity) ,\n"), + SCRIBBLE_KEYS.replace("13 /Real (Spacing) ,\n", ""), + SCRIBBLE_KEYS.replace("0.17 /Real (Scribbliness)", "17 /Real (Scribbliness)"), + ]; + for keys in cases { + assert!(!effect_style("Adobe Scribble Fill", &keys).plain, "{keys}"); + } +} - let bare = b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n;\n"; - let styles = art_styles(bare); - let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; - assert_eq!(feather.params["radius"].as_f64(), Some(5.0)); +#[test] +fn effects_on_the_object_keep_their_order() { + let data = format!( + "/KnownStyle :\n(Two) /Name ,\n/ActiveStyle :\n{}", + compound( + "Chain Style Filter", + &[basic("Adobe Round Corners", "10 /Real (radius) ,\n"), basic("Adobe Drop Shadow", &shadow_keys("0 /Int (csrc) ,\n"))] + ) + ); + let st = &art_styles(data.as_bytes())["Two"]; + assert!(st.plain && st.simple, "{st:?}"); + assert_eq!(st.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.roundCorners", "stylize.dropShadow"]); +} + +#[test] +fn a_glow_on_one_fill_stays_on_that_fill() { + // An ordinary object keeps the drawn look (`simple` is false); type takes the fill's glow. + let glow = basic( + "Adobe Inner Glow", + &format!("2 /Int (blnd) ,\n0.75 /Real (opac) ,\n5 /Real (blur) ,\n{}1 /Int (gtyp) ,\n", color_entry("gclr", "1 1 1")), + ); + let item = compound("Chain Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), glow]); + let data = + format!("/KnownStyle :\n(Lit) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])])); + let st = &art_styles(data.as_bytes())["Lit"]; + assert!(st.plain && !st.simple, "{st:?}"); + assert!(st.effects.is_empty()); + assert_eq!(st.looks[0].effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.innerGlow"]); } #[test] fn art_styles_clear_operands_beyond_the_cap() { let mut data = Vec::from( - b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n", + b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Adobe Fuzzy Mask) 1 0 /Filter ,\n1 /Visible ,\n", ); for _ in 0..80 { data.extend_from_slice(b"1 "); } - data.extend_from_slice(b"/Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n;\n"); + data.extend_from_slice(b"/Dictionary : /NotRecorded ,\n5 /Real (Radius) ,\n; /Dict ;\n /Part ,\n;\n"); let styles = art_styles(&data); let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; assert_eq!(feather.params["radius"].as_f64(), Some(5.0)); @@ -121,7 +264,8 @@ fn art_styles_clear_operands_beyond_the_cap() { #[test] fn art_styles_ignore_filters_beyond_the_cap() { - const UNIT: &[u8] = b"/BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n"; + const UNIT: &[u8] = + b"/BasicFilter :\n(Adobe Fuzzy Mask) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n1 /Real (Radius) ,\n; /Dict ;\n /Part ,\n"; let mut data = Vec::from(b"/KnownStyle :\n(Capped) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n"); for _ in 0..MAX_FILTERS + 16 { @@ -132,6 +276,19 @@ fn art_styles_ignore_filters_beyond_the_cap() { assert!(style.effects.len() <= MAX_FILTERS); } +#[test] +fn a_style_list_keeps_its_strings_in_order() { + let list = art_style_list(b"(A)\n(B\\)C)\n(D(E))\n/Name 3 x\n(Caf\\303\\251)\n(F"); + let want: [&[u8]; 4] = [b"A", b"B)C", b"D(E)", "Caf\u{e9}".as_bytes()]; + assert_eq!(list, want, "the string the data ends inside is left out"); + assert!(art_style_list(b"").is_empty()); + let unended: [&[u8]; 1] = [b"A"]; + assert_eq!(art_style_list(b"(A)\n(B\\)"), unended, "an escaped `)` doesn't end the string"); + assert_eq!(art_style_list(b"(A)\n(B(C)"), unended, "nor does one that closes a nested pair"); + assert_eq!(art_style_list(format!("({})", "x".repeat(MAX_LISTED_NAME + 1)).as_bytes()), Vec::>::new()); + assert_eq!(art_style_list("(x)\n".repeat(MAX_LISTED + 5).as_bytes()).len(), MAX_LISTED); +} + #[test] fn hostile_dash_offsets_and_width_profiles_are_tamed() { let mut f = Filter::default(); @@ -309,12 +466,580 @@ fn contents_above_some_items_count_them() { #[test] fn an_effect_not_read_here_keeps_the_drawn_look() { - let item = compound("Chain Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), basic("Adobe Scribble Fill", "")]); + let item = compound("Chain Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), basic("Adobe Zig Zag", "")]); let data = format!("/KnownStyle :\n(Odd) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])])); assert!(!art_styles(data.as_bytes())["Odd"].plain); } +/// The dictionary of an Effect › Pathfinder filter with `Command` `command` and `Mix` `mix`, and +/// the other options at the values the effect reads. +fn pathfinder_keys(command: &str, mix: &str) -> String { + format!( + "0 /Bool (RemovePoints) ,\n{mix} /Real (Mix) ,\n1 /Bool (ConvertCustom) ,\n{command} /Int (Command) ,\n1 /Real (TrapMaxTint) ,\n\ + 1 /Real (TrapAspect) ,\n0.4 /Real (TrapTint) ,\n0.25 /Real (TrapThickness) ,\n0 /Bool (TrapReverse) ,\n10 /Real (Precision) ,\n\ + (Op) /UnicodeString (DisplayString) ,\n0 /Bool (TrapConvertCustom) ,\n0.05 /Real (TrapTintTolerance) ,\n1 /Bool (ExtractUnpainted) ,\n" + ) +} + +/// The style `Group`: the object's chain holding `effects`, a stack whose fill and stroke paint +/// nothing, and the object's transparency. +fn group_style(effects: &[String]) -> ArtStyle { + let stack = compound( + "Stack Style Filter", + &[ + basic("Stroke Style Filter", "/StrokeStyle : 0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n"), + basic("Conduit Filter", ""), + basic( + "Fill Style Filter", + "/FillStyle : 0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 0 Xd\n/Def ;\n (FillStyle) ,\n0 /Bool (UseEvenOdd) ,\n", + ), + ], + ); + let mut kids = effects.to_vec(); + kids.extend([stack, blend(0, 1.0)]); + let data = format!("/KnownStyle :\n(Group) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &kids)); + art_styles(data.as_bytes()).remove("Group").unwrap_or_default() +} + +fn pathfinder(keys: &str) -> String { + basic("Adobe Pathfinder", keys) +} + +#[test] +fn pathfinder_add_is_read_as_its_effect() { + // GUARDS: an `Adobe Pathfinder` filter made the style not plain, so a group with it came in as its drawn look. + let st = group_style(&[pathfinder(&pathfinder_keys("0", "0.5"))]); + assert!(st.plain && st.simple && st.pathfinder, "{st:?}"); + assert!(st.items.is_empty(), "{st:?}"); + let [e] = st.effects.as_slice() else { panic!("{st:?}") }; + assert_eq!((e.id.as_str(), &e.params, e.visible), ("pathfinder.add", &json!({}), true)); +} + +#[test] +fn each_pathfinder_command_is_read_as_its_effect() { + // GUARDS: only `Command` 0 (Add) was read; a group with any other operation came in as its drawn look. + let ids = [ + (1, "pathfinder.intersect"), + (2, "pathfinder.exclude"), + (3, "pathfinder.subtract"), + (4, "pathfinder.minusBack"), + (5, "pathfinder.divide"), + (6, "pathfinder.outline"), + (7, "pathfinder.trim"), + (8, "pathfinder.merge"), + (9, "pathfinder.crop"), + (10, "pathfinder.hardMix"), + ]; + for (command, id) in ids { + let st = group_style(&[pathfinder(&pathfinder_keys(&command.to_string(), "0.5"))]); + assert!(st.plain && st.simple && st.pathfinder, "{command}: {st:?}"); + let [e] = st.effects.as_slice() else { panic!("{command}: {st:?}") }; + assert_eq!((e.id.as_str(), &e.params, e.visible), (id, &json!({}), true), "{command}"); + } +} + +#[test] +fn soft_mix_is_read_with_its_mixing_rate() { + for (mix, rate) in [("0.5", 50.0), ("0.3", 30.0), ("0.01", 1.0), ("1", 100.0)] { + let st = group_style(&[pathfinder(&pathfinder_keys("11", mix))]); + assert!(st.plain && st.simple && st.pathfinder, "{mix}: {st:?}"); + let [e] = st.effects.as_slice() else { panic!("{mix}: {st:?}") }; + assert_eq!((e.id.as_str(), &e.params), ("pathfinder.softMix", &json!({"mixingRate": rate})), "{mix}"); + } + // A rate the effect doesn't take keeps the drawn look. + for mix in ["0", "0.005", "1.5", "-0.5", "1e999"] { + let st = group_style(&[pathfinder(&pathfinder_keys("11", mix))]); + assert!(!st.plain && !st.pathfinder && st.effects.is_empty(), "{mix}: {st:?}"); + } +} + +#[test] +fn trap_and_unknown_pathfinder_commands_keep_the_drawn_look() { + for command in [12, 13, 40] { + let st = group_style(&[pathfinder(&pathfinder_keys(&command.to_string(), "0.5"))]); + assert!(!st.plain && !st.pathfinder && st.effects.is_empty(), "{command}: {st:?}"); + } +} + +fn stroke(paint: &str) -> String { + basic("Stroke Style Filter", &format!("/StrokeStyle : 0 1 0 0 0 Xy\n0 J 0 j 2 w 10 M []0 d0 XR\n{paint}\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n")) +} + +fn offset(ofst: f64, jntp: i64, mlim: f64) -> String { + basic("Adobe Offset Path", &format!("{ofst} /Real (ofst) ,\n{mlim} /Real (mlim) ,\n{jntp} /Int (jntp) ,\n")) +} + +/// Style `Fx`: `effects` on the whole object over a stack of a fill (with `on_fill` before its +/// fill style, `after_fill` after it) and a stroke (with `on_stroke` and `after_stroke`). +fn path_style(effects: &[String], on_fill: &[String], after_fill: &[String], on_stroke: &[String], after_stroke: &[String]) -> ArtStyle { + let item = |before: &[String], paint: String, after: &[String]| { + if before.is_empty() && after.is_empty() { + return paint; + } + compound("Chain Style Filter", &[before.concat(), paint, after.concat()]) + }; + let stack = compound( + "Stack Style Filter", + &[ + item(on_stroke, stroke("0 0 0 1 0 0 0 XA"), after_stroke), + item(on_fill, fill("0 0 0 0 1 0 0 Xa"), after_fill), + basic("Conduit Filter", ""), + ], + ); + let root = compound("Chain Style Filter", &[effects.concat(), stack]); + let data = format!("/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{root}"); + art_styles(data.as_bytes()).remove("Fx").unwrap() +} + +fn ids(effects: &[Effect]) -> Vec<&str> { + effects.iter().map(|e| e.id.as_str()).collect() +} + +#[test] +fn offset_path_on_the_object_is_read_with_its_settings() { + // GUARDS: an object with Offset Path kept its drawn look, and the effect was read only on type. + let st = path_style(&[offset(4.0, 1, 6.0)], &[], &[], &[], &[]); + assert!(st.plain && st.simple, "{st:?}"); + let [e] = st.effects.as_slice() else { panic!("{:?}", st.effects) }; + assert_eq!((e.id.as_str(), &e.params), ("path.offsetPath", &json!({"offset": 4.0, "joins": "bevel", "miterLimit": 6.0}))); + assert!(e.visible); + for (jntp, joins) in [(0, "round"), (2, "miter")] { + let st = path_style(&[offset(-5.0, jntp, 7.0)], &[], &[], &[], &[]); + assert_eq!((&st.effects[0].params["joins"], &st.effects[0].params["offset"]), (&json!(joins), &json!(-5.0))); + } +} + +#[test] +fn a_hidden_pathfinder_effect_comes_in_hidden() { + let st = group_style(&[pathfinder(&pathfinder_keys("0", "0.5")).replacen("1 /Visible", "0 /Visible", 1)]); + assert!(st.simple, "{st:?}"); + let [e] = st.effects.as_slice() else { panic!("{st:?}") }; + assert_eq!((e.id.as_str(), e.visible), ("pathfinder.add", false)); +} + +#[test] +fn pathfinder_effects_keep_their_order_among_the_objects_effects() { + let offset = basic("Adobe Offset Path", "3 /Real (ofst) ,\n0 /Int (jntp) ,\n4 /Real (mlim) ,\n"); + let st = group_style(&[pathfinder(&pathfinder_keys("0", "0.5")), offset.clone()]); + assert!(st.plain, "{st:?}"); + assert_eq!(ids(&st.effects), ["pathfinder.add", "path.offsetPath"]); + // GUARDS: an effect before the Pathfinder effect was read too, and the group drew the Pathfinder + // effect first, which isn't what the file draws. + let st = group_style(&[offset, pathfinder(&pathfinder_keys("0", "0.5"))]); + assert!(!st.plain, "{st:?}"); +} + +#[test] +fn pathfinder_settings_this_does_not_read_keep_the_drawn_look() { + let add = pathfinder_keys("0", "0.5"); + let cases = [ + ("no Command", add.replace("0 /Int (Command) ,\n", "")), + ("Trap", add.replace("0 /Int (Command)", "12 /Int (Command)")), + ("unknown Command", add.replace("0 /Int (Command)", "40 /Int (Command)")), + ("negative Command", add.replace("0 /Int (Command)", "-1 /Int (Command)")), + ("fractional Command", add.replace("0 /Int (Command)", "2.5 /Int (Command)")), + ("huge Command", add.replace("0 /Int (Command)", "1e999 /Int (Command)")), + ("Command as a real", add.replace("0 /Int (Command)", "0 /Real (Command)")), + ("Command without a number", add.replace("0 /Int (Command)", "(zero) /Int (Command)")), + // A number before the string isn't its value. + ("Command with a string after a number", add.replace("0 /Int (Command)", "3 (zero) /Int (Command)")), + ("Command twice", add.clone() + "1 /Int (Command) ,\n"), + // GUARDS: the last of a repeated key was read, so a Trap command followed by Add was read as Add. + ("Command twice, Add last", add.replace("0 /Int (Command)", "12 /Int (Command) ,\n0 /Int (Command)")), + ("Command twice, both Add", add.replace("0 /Int (Command)", "0 /Int (Command) ,\n0 /Int (Command)")), + ("an option twice, the read value last", add.replace("10 /Real (Precision)", "5 /Real (Precision) ,\n10 /Real (Precision)")), + ("unknown key", add.clone() + "1 /Int (Extra) ,\n"), + ("unknown string", add.clone() + "(x) /String (Extra) ,\n"), + ("an array", add.clone() + "/Array :\n1 /Real ,\n; (Extra) ,\n"), + ("many strings", add.clone() + &(0..40).map(|i| format!("(x) /String (DisplayString{i}) ,\n")).collect::()), + ("missing option", add.replace("0.25 /Real (TrapThickness) ,\n", "")), + ("missing Mix", add.replace("0.5 /Real (Mix) ,\n", "")), + ("option of the wrong type", add.replace("10 /Real (Precision)", "10 /Int (Precision)")), + ("other Precision", add.replace("10 /Real (Precision)", "5 /Real (Precision)")), + ("huge Precision", add.replace("10 /Real (Precision)", "1e999 /Real (Precision)")), + ("Remove Redundant Points", add.replace("0 /Bool (RemovePoints)", "1 /Bool (RemovePoints)")), + ("unpainted art kept", add.replace("1 /Bool (ExtractUnpainted)", "0 /Bool (ExtractUnpainted)")), + ("other trap tint", add.replace("0.4 /Real (TrapTint)", "0.25 /Real (TrapTint)")), + ("Mix on Add", add.replace("0.5 /Real (Mix)", "0.3 /Real (Mix)")), + ("Mix on Intersect", pathfinder_keys("1", "0.3")), + ("Mix on Hard Mix", pathfinder_keys("10", "0.3")), + ("Mix as a bool", add.replace("0.5 /Real (Mix)", "1 /Bool (Mix)")), + ("Soft Mix with Mix as an int", pathfinder_keys("11", "0.5").replace("0.5 /Real (Mix)", "1 /Int (Mix)")), + ("Soft Mix without Mix", pathfinder_keys("11", "0.5").replace("0.5 /Real (Mix) ,\n", "")), + ("Soft Mix with other Precision", pathfinder_keys("11", "0.3").replace("10 /Real (Precision)", "5 /Real (Precision)")), + ("Intersect with other Precision", pathfinder_keys("1", "0.5").replace("10 /Real (Precision)", "5 /Real (Precision)")), + ("Divide keeping unpainted art", pathfinder_keys("5", "0.5").replace("1 /Bool (ExtractUnpainted)", "0 /Bool (ExtractUnpainted)")), + ("Command twice, Intersect then Add", add.replace("0 /Int (Command)", "1 /Int (Command) ,\n0 /Int (Command)")), + ]; + for (case, keys) in cases { + let st = group_style(&[pathfinder(&keys)]); + assert!(!st.plain && !st.pathfinder && st.effects.is_empty(), "{case}: {st:?}"); + } +} + +#[test] +fn a_pathfinder_effect_outside_the_objects_chain_keeps_the_drawn_look() { + let pf = pathfinder(&pathfinder_keys("0", "0.5")); + // On a fill of its own. + let item = compound("Chain Style Filter", &[pf.clone(), fill("0 0 0 1 0 0 0 Xa")]); + let data = + format!("/KnownStyle :\n(Item) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])])); + let st = &art_styles(data.as_bytes())["Item"]; + assert!(!st.plain, "{st:?}"); + // In a style that isn't an object's chain. + let data = format!("/KnownStyle :\n(Bare) /Name ,\n/ActiveStyle :\n{pf}"); + let st = &art_styles(data.as_bytes())["Bare"]; + assert!(!st.plain && st.effects.is_empty(), "{st:?}"); +} + +#[test] +fn a_pathfinder_effect_with_fills_of_its_own_keeps_the_drawn_look() { + let stack = compound("Stack Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), basic("Conduit Filter", "")]); + let data = format!( + "/KnownStyle :\n(Filled) /Name ,\n/ActiveStyle :\n{}", + compound("Chain Style Filter", &[pathfinder(&pathfinder_keys("0", "0.5")), stack]) + ); + let st = &art_styles(data.as_bytes())["Filled"]; + assert!(st.pathfinder && !st.simple, "{st:?}"); +} + +#[test] +fn outline_object_and_outline_stroke_are_read_with_no_settings() { + // GUARDS: `Adobe Outline Type` and `Adobe Outline Stroke` weren't read, so the style kept its drawn look. + let outline = basic("Adobe Outline Type", ""); + let outline_stroke = basic("Adobe Outline Stroke", ""); + let st = path_style(&[outline.clone(), outline_stroke.clone()], &[], &[], &[], &[]); + assert!(st.plain && st.simple, "{st:?}"); + assert_eq!(ids(&st.effects), ["path.outlineObject", "path.outlineStroke"]); + // No `width`: the stroke gives it. + assert!(st.effects.iter().all(|e| e.params == json!({})), "{:?}", st.effects); + // On a fill and on a stroke: Outline Object before the item's own style, Outline Stroke after it. + let (before, after) = (std::slice::from_ref(&outline), std::slice::from_ref(&outline_stroke)); + let st = path_style(&[], before, after, before, after); + assert!(st.plain && !st.simple, "{st:?}"); + // Bottom first: the fill, then the stroke. + assert!(matches!(st.items.as_slice(), [StyleItem::Fill(_), StyleItem::Stroke { .. }]), "{:?}", st.items); + for look in &st.looks { + assert_eq!(ids(&look.effects), ["path.outlineObject", "path.outlineStroke"]); + } +} + +#[test] +fn path_effects_keep_their_order_and_visibility() { + let hidden = offset(3.0, 0, 4.0).replacen("1 /Visible", "0 /Visible", 1); + let st = path_style(&[hidden, offset(6.0, 1, 4.0)], &[], &[], &[], &[]); + assert!(st.plain && st.simple, "{st:?}"); + let offsets: Vec<_> = st.effects.iter().map(|e| (e.params["offset"].as_f64(), e.visible)).collect(); + assert_eq!(offsets, [(Some(3.0), false), (Some(6.0), true)]); + // On a fill and a stroke, with another effect after it. + let transform = basic("Adobe Transform", "2 /Int (numCopies) ,\n"); + let after = std::slice::from_ref(&transform); + let st = path_style(&[], &[offset(2.0, 2, 4.0)], after, &[offset(-1.0, 0, 4.0)], after); + assert!(st.plain, "{st:?}"); + assert_eq!(ids(&st.looks[0].effects), ["path.offsetPath", "distort.transform"]); + assert_eq!(ids(&st.looks[1].effects), ["path.offsetPath", "distort.transform"]); + assert_eq!((st.looks[0].effects[0].params["offset"].as_f64(), st.looks[1].effects[0].params["offset"].as_f64()), (Some(2.0), Some(-1.0))); +} + +#[test] +fn offset_path_with_settings_not_read_keeps_the_drawn_look() { + // GUARDS: a missing setting was read as 10 pt, miter or 4, and an out-of-range one was clamped. + let complete = "4 /Real (ofst) ,\n1 /Int (jntp) ,\n6 /Real (mlim) ,\n"; + let bodies = [ + String::new(), + "4 /Real (ofst) ,\n".into(), + "1 /Int (jntp) ,\n".into(), + "4 /Real (ofst) ,\n1 /Int (jntp) ,\n".into(), + format!("{complete}1 /Int (later) ,\n"), + format!("{complete}(x) /UnicodeString (DisplayString) ,\n"), + complete.replace("/Int (jntp)", "/Real (jntp)"), + complete.replace("4 /Real (ofst)", "(4) /Real (ofst)"), + complete.replace("4 /Real (ofst)", "1e999 /Real (ofst)"), + complete.replace("4 /Real (ofst)", "100001 /Real (ofst)"), + complete.replace("6 /Real (mlim)", "0.5 /Real (mlim)"), + complete.replace("6 /Real (mlim)", "501 /Real (mlim)"), + complete.replace("1 /Int (jntp)", "3 /Int (jntp)"), + complete.replace("1 /Int (jntp)", "-1 /Int (jntp)"), + complete.replace("1 /Int (jntp)", "0.5 /Int (jntp)"), + ]; + for body in &bodies { + let filter = basic("Adobe Offset Path", body); + let one = std::slice::from_ref(&filter); + for st in [path_style(one, &[], &[], &[], &[]), path_style(&[], one, &[], &[], &[])] { + assert!(!st.plain, "{body:?}: {st:?}"); + } + } + assert!(path_style(&[basic("Adobe Offset Path", complete)], &[], &[], &[], &[]).plain); + // The outline effects have no settings. + for name in ["Adobe Outline Type", "Adobe Outline Stroke"] { + assert!(!path_style(&[basic(name, "1 /Real (width) ,\n")], &[], &[], &[], &[]).plain, "{name}"); + assert!(!path_style(&[basic(name, "/Array : 1 /Real , ; (width) ,\n")], &[], &[], &[], &[]).plain, "{name}"); + } +} + +/// The style `Fx`: effect `name` on the whole object, its dictionary holding `keys`. +fn distort_effect_style(name: &str, keys: &str) -> ArtStyle { + let data = format!("/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[basic(name, keys)])); + art_styles(data.as_bytes()).remove("Fx").unwrap_or_default() +} + +/// The params of effect `name` with `keys`, `None` when the style keeps the drawn look. +fn read_effect(name: &str, keys: &str) -> Option { + let st = distort_effect_style(name, keys); + if !st.plain { + return None; + } + let [e] = st.effects.as_slice() else { panic!("{st:?}") }; + Some(e.params.clone()) +} + +/// A filter named `name` whose dictionary holds `entries`. +fn dict(name: &str, entries: &[(&str, Kind, f64)]) -> Filter { + let kinds = entries.iter().map(|(k, kind, _)| (k.to_string(), *kind)).collect(); + let params = entries.iter().map(|(k, _, v)| (k.to_string(), *v)).collect(); + Filter { name: name.into(), kinds, params, ..Filter::default() } +} + +fn close(a: &serde_json::Value, want: f64) -> bool { + a.as_f64().is_some_and(|a| (a - want).abs() < 1e-6) +} + +/// Every switch of the Transform effect, as files write them. +const SWITCHES: &str = "0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"; + +#[test] +fn a_transform_reads_its_factors_and_radians() { + // GUARDS: the percent and degree entries (what the dialog shows) were read, and the options were not. + let p = read_effect( + "Adobe Transform", + "150 /Real (scaleH_Percent) ,\n1.4 /Real (scaleH_Factor) ,\n80 /Real (scaleV_Percent) ,\n1.2 /Real (scaleV_Factor) ,\n\ + 30 /Real (rotate_Degrees) ,\n0.471238898 /Real (rotate_Radians) ,\n-8 /Real (moveV_Pts) ,\n3 /Real (moveH_Pts) ,\n\ + 2 /Int (numCopies) ,\n0 /Int (pinPoint) ,\n1 /Bool (reflectX) ,\n0 /Bool (transformObjects) ,\n1 /Bool (transformPatterns) ,\n\ + 1 /Bool (scaleLines) ,\n0 /Bool (randomize) ,\n", + ) + .unwrap(); + assert!(close(&p["scaleH"], 140.0) && close(&p["scaleV"], 120.0) && close(&p["rotate"], 27.0), "{p}"); + assert_eq!((&p["moveH"], &p["moveV"], &p["copies"], &p["reference"]), (&json!(3.0), &json!(8.0), &json!(2), &json!(0))); + assert_eq!((&p["reflectX"], &p["reflectY"]), (&json!(true), &json!(false))); + assert_eq!((&p["objects"], &p["patterns"], &p["strokes"]), (&json!(false), &json!(true), &json!(true))); +} + +#[test] +fn a_transforms_percent_and_degrees_alone_change_nothing() { + let p = read_effect("Adobe Transform", &format!("150 /Real (scaleH_Percent) ,\n30 /Real (rotate_Degrees) ,\n{SWITCHES}")).unwrap(); + assert_eq!((&p["scaleH"], &p["scaleV"], &p["rotate"]), (&json!(100.0), &json!(100.0), &json!(0.0))); +} + +#[test] +fn a_transforms_reference_point_and_move_up() { + for pin in 0..9 { + let p = read_effect("Adobe Transform", &format!("0.5 /Real (scaleH_Factor) ,\n{pin} /Int (pinPoint) ,\n{SWITCHES}")).unwrap(); + assert_eq!(p["reference"], json!(pin)); + } + // A move up the page in the file is a move up in the document, whose y runs down. + let p = read_effect("Adobe Transform", &format!("10 /Real (moveV_Pts) ,\n{SWITCHES}")).unwrap(); + assert_eq!(p["moveV"], json!(-10.0)); + let p = read_effect("Adobe Transform", &format!("4 /Int (pinPoint) ,\n{SWITCHES}")).unwrap(); + assert_eq!((&p["objects"], &p["copies"], &p["scaleH"]), (&json!(true), &json!(0), &json!(100.0))); +} + +#[test] +fn a_transform_without_the_options_its_change_depends_on_keeps_the_drawn_look() { + // Missing Scale Strokes & Effects or Transform Patterns are the app's settings, not the file's. + let half = "0.5 /Real (scaleH_Factor) ,\n0.5 /Real (scaleV_Factor) ,\n"; + assert_eq!(read_effect("Adobe Transform", &format!("{half}0 /Bool (transformPatterns) ,\n")), None); + assert_eq!(read_effect("Adobe Transform", &format!("{half}0 /Bool (scaleLines) ,\n")), None); + // A move scales nothing; with Transform Patterns given, it reads. + let p = read_effect("Adobe Transform", "5 /Real (moveH_Pts) ,\n0 /Bool (transformPatterns) ,\n").unwrap(); + assert_eq!(p["strokes"], json!(false)); + // On a fill's own Transform, only that fill's paint counts: a solid fill moves the same either way. + let moved = basic("Adobe Transform", "5 /Real (moveH_Pts) ,\n"); + let item = |paint: &str| { + let item = compound("Chain Style Filter", &[fill(paint), moved.clone()]); + let data = + format!("/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])])); + art_styles(data.as_bytes()).remove("Fx").unwrap_or_default().plain + }; + assert!(item("0 0 0 1 0 0 0 Xa")); + assert!(!item("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p")); +} + +#[test] +fn a_random_transform_keeps_the_drawn_look() { + // The file holds no seed for its random share. + assert_eq!(read_effect("Adobe Transform", &format!("1 /Bool (randomize) ,\n{SWITCHES}")), None); +} + +/// Free Distort's dictionary: the source corners `src` and the destination `dst`, top left, top +/// right, bottom left, bottom right, y up. +fn corners(src: [[f64; 2]; 4], dst: [[f64; 2]; 4]) -> String { + let mut out = String::new(); + for (which, c) in [("src", src), ("dst", dst)] { + for (i, [h, v]) in c.into_iter().enumerate() { + out += &format!("{h} /Real ({which}{i}h) ,\n{v} /Real ({which}{i}v) ,\n"); + } + } + out +} + +fn unit_corners(p: &serde_json::Value) -> Vec<[f64; 2]> { + p["corners"].as_array().unwrap().iter().map(|c| [c[0].as_f64().unwrap(), c[1].as_f64().unwrap()]).collect() +} + +fn corners_near(a: &[[f64; 2]], b: &[[f64; 2]]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(a, b)| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9) +} + +#[test] +fn free_distort_measures_its_corners_in_its_own_frame() { + // GUARDS: Free Distort wasn't read, and type with it came in as its drawn look. + let dst = [[180.0, 310.0], [320.0, 300.0], [210.0, 240.0], [250.0, 260.0]]; + // A frame wider than the object (its stroke's): the corners are fractions of that frame. + let p = read_effect("Adobe Free Distort", &corners([[195.0, 305.0], [305.0, 305.0], [195.0, 245.0], [305.0, 245.0]], dst)).unwrap(); + let want = [[-15.0 / 110.0, -5.0 / 60.0], [125.0 / 110.0, 5.0 / 60.0], [0.5, 0.75], [15.0 / 110.0, 65.0 / 60.0]]; + assert!(corners_near(&unit_corners(&p), &want), "{p}"); + // A unit frame: the same corners measured in it, far outside the unit box. + let p = read_effect("Adobe Free Distort", &corners([[0.0, 0.0], [1.0, 0.0], [0.0, -1.0], [1.0, -1.0]], dst)).unwrap(); + assert!(corners_near(&unit_corners(&p), &[[180.0, -310.0], [320.0, -300.0], [250.0, -260.0], [210.0, -240.0]]), "{p}"); + // No corners: no change. + let p = read_effect("Adobe Free Distort", "").unwrap(); + assert!(corners_near(&unit_corners(&p), &[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]), "{p}"); +} + +#[test] +fn free_distort_without_every_corner_or_an_upright_frame_keeps_the_drawn_look() { + let src = [[0.0, 0.0], [1.0, 0.0], [0.0, -1.0], [1.0, -1.0]]; + let dst = [[0.1, 0.0], [1.0, 0.1], [0.0, -1.0], [1.0, -1.2]]; + let all = corners(src, dst); + // The destination alone, one entry missing, a frame that is turned or of no height. + let dst_only: String = all.lines().filter(|l| l.contains("(dst")).map(|l| format!("{l}\n")).collect(); + let short = all.replace("-1.2 /Real (dst3v) ,\n", ""); + for keys in [ + dst_only, + short, + corners([[0.0, 0.0], [1.0, 0.5], [0.0, -1.0], [1.0, -1.0]], dst), + corners([[0.0, 0.0], [1.0, 0.0], [0.0, 0.0], [1.0, 0.0]], dst), + // A frame too wide for a number. + corners([[-1e308, 0.0], [1e308, 0.0], [-1e308, -1.0], [1e308, -1.0]], dst), + ] { + assert_eq!(read_effect("Adobe Free Distort", &keys), None, "{keys}"); + } +} + +#[test] +fn pucker_and_twist_keep_their_sense() { + // Negative is Pucker; a positive angle turns clockwise in the file and in the catalog. + assert_eq!(read_effect("Adobe Punk and Bloat", "-35 /Real (d_factor) ,\n"), Some(json!({"amount": -35.0}))); + assert_eq!(read_effect("Adobe Punk and Bloat", ""), Some(json!({"amount": 0.0}))); + assert_eq!(read_effect("Adobe Twirl", "45 /Real (angle) ,\n"), Some(json!({"angle": 45.0}))); + assert_eq!(read_effect("Adobe Twirl", ""), Some(json!({"angle": 0.0}))); + assert_eq!(read_effect("Adobe Punk and Bloat", "250 /Real (d_factor) ,\n"), None); + assert_eq!(read_effect("Adobe Twirl", "4000 /Real (angle) ,\n"), None); +} + +#[test] +fn any_object_takes_the_distort_effects_that_draw_as_its_drawn_look() { + // GUARDS: `simple` left out every Distort & Transform effect, so only type took them. + let simple = |name: &str, keys: &str| { + let st = distort_effect_style(name, keys); + assert!(st.plain, "{name}: {st:?}"); + st.simple + }; + assert!(simple("Adobe Twirl", "45 /Real (angle) ,\n")); + assert!(simple("Adobe Transform", &format!("0.5 /Real (scaleH_Factor) ,\n{SWITCHES}"))); + assert!(simple("Adobe Scribble and Tweak", "")); + assert!(simple("Adobe Punk and Bloat", "")); + assert!(simple("Adobe Free Distort", "")); + // A slant: the bottom edge moved as far as the top one. + let src = [[0.0, 0.0], [1.0, 0.0], [0.0, -1.0], [1.0, -1.0]]; + assert!(simple("Adobe Free Distort", &corners(src, [[0.2, 0.0], [1.2, 0.0], [0.0, -1.0], [1.0, -1.0]]))); + assert!(!simple("Adobe Free Distort", &corners(src, [[0.2, 0.0], [1.2, 0.1], [0.0, -1.0], [1.0, -1.0]]))); + assert!(!simple("Adobe Punk and Bloat", "-35 /Real (d_factor) ,\n")); + assert!(!simple("Adobe Zigzag", "")); + assert!(!simple("Adobe Transform", &format!("1 /Int (numCopies) ,\n{SWITCHES}"))); + // With another effect, only type takes it. + let chain = [basic("Adobe Twirl", "45 /Real (angle) ,\n"), basic("Adobe Offset Path", "4 /Real (ofst) ,\n0 /Int (jntp) ,\n4 /Real (mlim) ,\n")]; + let data = format!("/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &chain)); + let st = art_styles(data.as_bytes()).remove("Fx").unwrap_or_default(); + assert!(st.plain && !st.simple, "{st:?}"); +} + +#[test] +fn affine_corners_are_a_parallelogram_however_far_they_reach() { + assert!(affine(&json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}))); + assert!(affine(&json!({"corners": [[180.0, -310.0], [320.0, -300.0], [330.0, -250.0], [190.0, -260.0]]}))); + assert!(!affine(&json!({"corners": [[180.0, -310.0], [320.0, -300.0], [330.0, -250.01], [190.0, -260.0]]}))); + // Far from the box, a small shape is held to its own size. + assert!(!affine(&json!({"corners": [[9999.0, 0.0], [10000.0, 0.0], [10000.05, 1.0], [9999.0, 1.0]]}))); + // GUARDS: a slant written in rounded decimals, in a frame of 33.333 pt, missed by a hair. + let src = [[0.0, 0.0], [33.333, 0.0], [0.0, -33.333], [33.333, -33.333]]; + let slant = distort_effect_style("Adobe Free Distort", &corners(src, [[6.6667, 0.0], [40.0, 0.0], [0.0, -33.333], [33.333, -33.333]])); + assert!(slant.plain && slant.simple, "{slant:?}"); + assert!(!affine(&json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]]}))); + assert!(!affine(&json!({}))); +} + +#[test] +fn roughen_keeps_the_drawn_look() { + // Its outline is random and the file holds no seed; at a size of 0 the effect still redraws the + // path's segments. + assert_eq!(read_effect("Adobe Roughen", "30 /Real (size) ,\n"), None); + assert_eq!(read_effect("Adobe Roughen", ""), None); +} + +#[test] +fn tweak_picks_its_amounts_by_its_mode_and_moves_every_point_unless_told() { + let amounts = [("horz", Kind::Real, 30.0), ("vert", Kind::Real, 20.0), ("ahor", Kind::Real, 2.0), ("aver", Kind::Real, 3.0)]; + let mut absolute = amounts.to_vec(); + absolute.push(("absoluteness", Kind::Real, 1.0)); + let want = |h: f64, v: f64, relative: bool| json!({"h": h, "v": v, "relative": relative, "anchors": true, "in": true, "out": true}); + assert_eq!(tweak(&dict("Adobe Scribble and Tweak", &amounts)), Some(want(30.0, 20.0, true))); + assert_eq!(tweak(&dict("Adobe Scribble and Tweak", &absolute)), Some(want(2.0, 3.0, false))); + let off = tweak(&dict("Adobe Scribble and Tweak", &[("in", Kind::Bool, 0.0)])).unwrap(); + assert_eq!((&off["anchors"], &off["in"], &off["out"]), (&json!(true), &json!(false), &json!(true))); + // Random too: it reads only when it moves nothing. + assert_eq!(read_effect("Adobe Scribble and Tweak", "30 /Real (horz) ,\n"), None); + assert!(read_effect("Adobe Scribble and Tweak", "").is_some()); + let still = "30 /Real (horz) ,\n0 /Bool (anch) ,\n0 /Bool (in) ,\n0 /Bool (out) ,\n"; + assert!(read_effect("Adobe Scribble and Tweak", still).is_some()); +} + +#[test] +fn zig_zag_is_absolute_with_four_ridges_and_corners_unless_told() { + let p = read_effect("Adobe Zigzag", "30 /Real (relAmount) ,\n2 /Real (amount) ,\n").unwrap(); + assert_eq!(p, json!({"size": 2.0, "relative": false, "ridges": 4, "points": "corner"})); + let p = read_effect( + "Adobe Zigzag", + "30 /Real (relAmount) ,\n2 /Real (amount) ,\n0 /Real (absoluteness) ,\n6 /Real (ridges) ,\n1 /Real (roundness) ,\n", + ) + .unwrap(); + assert_eq!(p, json!({"size": 30.0, "relative": true, "ridges": 6, "points": "smooth"})); + assert_eq!(read_effect("Adobe Zigzag", "2.5 /Real (ridges) ,\n"), None); +} + +#[test] +fn a_distort_entry_this_cant_read_keeps_the_drawn_look_and_unknown_ones_are_ignored() { + // Not a number, the wrong kind, a switch other than 0 or 1, a whole number that isn't. + for (name, keys) in [ + ("Adobe Twirl", "NaN /Real (angle) ,\n"), + ("Adobe Twirl", "45 /Int (angle) ,\n"), + ("Adobe Zigzag", "2 /Real (absoluteness) ,\n"), + ("Adobe Transform", "4 /Real (pinPoint) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"), + ("Adobe Transform", "2 /Bool (reflectX) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"), + ("Adobe Transform", "1e999 /Real (scaleH_Percent) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"), + ("Adobe Transform", "1001 /Int (numCopies) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"), + // In degrees, too large for a number. + ("Adobe Transform", "1e308 /Real (rotate_Radians) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"), + ("Adobe Free Distort", "(x) /Real (src0h) ,\n"), + ] { + assert_eq!(read_effect(name, keys), None, "{name}: {keys}"); + } + assert_eq!(read_effect("Adobe Twirl", "37 /Real (angle) ,\n9 /Real (futureKey) ,\n"), Some(json!({"angle": 37.0}))); + // The last of a repeated entry stands. + assert_eq!(read_effect("Adobe Twirl", "37 /Real (angle) ,\n12 /Real (angle) ,\n"), Some(json!({"angle": 12.0}))); +} + #[test] fn a_hidden_fill_comes_in_hidden() { let hidden = fill("0 0 0 1 0 0 0 Xa").replacen("1 /Visible", "0 /Visible", 1); @@ -326,3 +1051,405 @@ fn a_hidden_fill_comes_in_hidden() { assert!(st.plain, "{st:?}"); assert_eq!(st.looks.iter().map(|l| l.visible).collect::>(), [false, true]); } + +/// A descriptor (version 1) of `fields`. +fn descriptor(fields: &[Vec]) -> Vec { + [vec![0, 0, 0, 1], fields.concat()].concat() +} + +fn long_field(key: &[u8; 4], v: i32) -> Vec { + [&key[..], &[0; 4], b"long", &v.to_be_bytes()].concat() +} + +fn enum_field(key: &[u8; 4], kind: &[u8; 4], v: &[u8; 4]) -> Vec { + [&key[..], &0x2000u32.to_be_bytes(), kind, v].concat() +} + +/// Bas Relief's fields: the filter-gallery code, `detail`, `smoothness` and the light direction `light`. +fn relief_fields(detail: i32, smoothness: i32, light: &[u8; 4]) -> Vec> { + vec![enum_field(b"GEfk", b"GEft", b"BsRl"), long_field(b"Dtl ", detail), long_field(b"Smth", smoothness), enum_field(b"LghD", b"LghD", light)] +} + +/// A settings block of `data`: the ASCII85 on comment lines, then `; (data) ,`. +fn block(data: &[u8]) -> String { + let lines: String = crate::ps::ascii85(data).lines().map(|l| format!("%{l}\n")).collect(); + format!("/Binary : /ASCII85Decode ,\n{lines}; (data) ,\n") +} + +/// The style `name`: a black fill and Bas Relief on the object, whose dictionary holds `body`. +fn relief_text(name: &str, body: &str) -> String { + let stack = compound("Stack Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), basic("Conduit Filter", "")]); + let relief = basic("PSAdapter_plugin_BsRl", body); + format!("/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[stack, relief])) +} + +/// The style of [`relief_text`]. +fn relief_style(body: &str) -> ArtStyle { + art_styles(relief_text("Relief", body).as_bytes()).remove("Relief").unwrap_or_default() +} + +#[test] +fn a_settings_block_without_its_end_leaves_the_next_style_alone() { + // GUARDS: the block's `~>` was looked for past its own lines, in the next style's block, which was skipped. + let data = descriptor(&relief_fields(8, 1, b"LDBt")); + let cut = format!("{}{} /Int (dataSize) ,\n", block(&data).replace("~>", ""), data.len()); + let whole = format!("{}{} /Int (dataSize) ,\n", block(&data), data.len()); + let styles = art_styles(format!("{}{}", relief_text("Cut", &cut), relief_text("Whole", &whole)).as_bytes()); + assert!(styles["Cut"].effects.is_empty(), "{:?}", styles["Cut"]); + assert!(styles["Whole"].simple, "{:?}", styles["Whole"]); + assert_eq!(styles["Whole"].effects[0].params["detail"], json!(8.0)); +} + +#[test] +fn a_settings_block_without_its_data_key_leaves_the_next_style_alone() { + // GUARDS: the tokens after the block's `;` were taken as its `(data)` key, the closing of its + // dictionary or the next style's `/KnownStyle` among them, and the next style was lost. + let data = descriptor(&relief_fields(8, 1, b"LDBt")); + let whole = format!("{}{} /Int (dataSize) ,\n", block(&data), data.len()); + let keyless = block(&data).replace("(data) ,\n", ""); + let next = relief_text("Whole", &whole); + // A style cut short right after its block's `;`, the next style's `/KnownStyle` following. + let short = relief_text("Cut", &keyless); + let short = short.get(..short.find("~>\n;").unwrap_or_default() + 4).unwrap_or_default(); + for text in [ + format!("{short}\n{next}"), + format!("{}{next}", relief_text("Cut", &keyless)), + format!("{}{next}", relief_text("Cut", &format!("{keyless}{} /Int (dataSize) ,\n", data.len()))), + ] { + let styles = art_styles(text.as_bytes()); + assert!(styles.get("Whole").is_some_and(|s| s.simple), "{styles:?}"); + assert_eq!(styles["Whole"].effects[0].params["detail"], json!(8.0)); + assert!(!styles.get("Cut").is_some_and(|s| s.simple), "{styles:?}"); + } +} + +/// [`relief_style`] with the settings block of `data` and a `dataSize` of its length. +fn relief_with(data: &[u8]) -> ArtStyle { + relief_style(&format!("{}300 /Int (PrevDres) ,\n{} /Int (dataSize) ,\n1 /Bool (go) ,\n", block(data), data.len())) +} + +#[test] +fn bas_relief_reads_its_settings_block() { + // GUARDS: the effect's defaults stood in for the settings, and an object other than type with it + // came in as its drawn look. + for (code, light) in [ + (b"LDBt", "bottom"), + (b"LDBL", "bottomLeft"), + (b"LDLf", "left"), + (b"LDTL", "topLeft"), + (b"LDTp", "top"), + (b"LDTR", "topRight"), + (b"LDRg", "right"), + (b"LDBR", "bottomRight"), + ] { + let st = relief_with(&descriptor(&relief_fields(8, 1, code))); + assert!(st.plain && st.simple, "{st:?}"); + let [e] = st.effects.as_slice() else { panic!("{st:?}") }; + assert_eq!((e.id.as_str(), &e.params), ("sketch.basRelief", &json!({"detail": 8.0, "smoothness": 1.0, "lightDirection": light}))); + } + // Without the filter-gallery code, and with the fields in another order. + let [_, detail, smoothness, light] = <[Vec; 4]>::try_from(relief_fields(15, 15, b"LDTp")).unwrap(); + let st = relief_with(&descriptor(&[light, smoothness, detail])); + assert!(st.simple, "{st:?}"); + assert_eq!(st.effects[0].params, json!({"detail": 15.0, "smoothness": 15.0, "lightDirection": "top"})); +} + +#[test] +fn bas_relief_without_a_settings_block_keeps_the_effects_defaults_on_type_only() { + let st = relief_style("300 /Int (PrevDres) ,\n"); + assert!(st.plain && !st.simple, "{st:?}"); + assert_eq!(st.effects[0].params, json!({"detail": 13.0, "smoothness": 3.0, "lightDirection": "bottom"})); +} + +#[test] +fn bas_relief_with_settings_not_read_here_keeps_the_drawn_look() { + let good = || relief_fields(8, 1, b"LDBt"); + let with = |i: usize, field: Vec| { + let mut f = good(); + f[i] = field; + descriptor(&f) + }; + let cases: Vec<(&str, Vec)> = vec![ + ("detail 0", with(1, long_field(b"Dtl ", 0))), + ("detail 16", with(1, long_field(b"Dtl ", 16))), + ("smoothness -1", with(2, long_field(b"Smth", -1))), + ("an unknown direction", with(3, enum_field(b"LghD", b"LghD", b"LDXx"))), + ("a direction of another type", with(3, enum_field(b"LghD", b"Dirc", b"LDBt"))), + ("a detail that isn't a whole number", with(1, [&b"Dtl "[..], &[0; 4], b"doub", &8.0f64.to_be_bytes()].concat())), + ("another effect's code", with(0, enum_field(b"GEfk", b"GEft", b"Crst"))), + ("an unknown key", [descriptor(&good()), long_field(b"Xtra", 1)].concat()), + ("a key twice", [descriptor(&good()), long_field(b"Dtl ", 8)].concat()), + ("a missing key", descriptor(&good()[..3])), + ("a byte after the last field", [descriptor(&good()), vec![0]].concat()), + ("a cut field", descriptor(&good()).split_last().unwrap().1.to_vec()), + ("version 2", [vec![0, 0, 0, 2], good().concat()].concat()), + ]; + for (what, data) in cases { + let st = relief_with(&data); + assert!(!st.plain && !st.simple && st.effects.is_empty(), "{what}: {st:?}"); + } + let data = descriptor(&good()); + let encoded = block(&data); + for (what, body) in [ + ("a wrong dataSize", format!("{encoded}{} /Int (dataSize) ,\n", data.len() + 1)), + ("no dataSize", encoded.clone()), + ("a dataSize of another kind", format!("{encoded}{} /Real (dataSize) ,\n", data.len())), + ("no ~>", format!("{}{} /Int (dataSize) ,\n", encoded.replace("~>", ""), data.len())), + ("a digit past u", format!("{}{} /Int (dataSize) ,\n", encoded.replacen("%", "%v", 2), data.len())), + ("a line without %", format!("{}{} /Int (dataSize) ,\n", encoded.replacen("\n%", "\n", 1), data.len())), + ("no (data) key", format!("{}{} /Int (dataSize) ,\n", encoded.replace("(data)", "(other)"), data.len())), + ("two blocks", format!("{encoded}{encoded}{} /Int (dataSize) ,\n", data.len())), + ] { + let st = relief_style(&body); + assert!(!st.plain && st.effects.is_empty(), "{what}: {st:?}"); + } +} + +#[test] +fn settings_blocks_are_bounded() { + // More than the decoded limit, though its text is short (`z` is four zero bytes). + let zeros = format!("/Binary : /ASCII85Decode ,\n%{}~>\n; (data) ,\n4100 /Int (dataSize) ,\n", "z".repeat(1025)); + assert!(relief_style(&zeros).effects.is_empty()); + // An end further than the encoded limit. + let far = format!("/Binary : /ASCII85Decode ,\n{}%~>\n; (data) ,\n0 /Int (dataSize) ,\n", "%!!!!!\n".repeat(1000)); + assert!(relief_style(&far).effects.is_empty()); + // Objects nest two deep at most, and a descriptor holds 32 fields at most. + let object = |inner: Vec| [&b"Objc"[..], &0x8000_0000u32.to_be_bytes(), b"Clss", &(inner.len() as u32).to_be_bytes(), &inner].concat(); + let two = descriptor(&[object(descriptor(&[object(descriptor(&[long_field(b"Valu", 1)]))]))]); + assert!(adapter::decode(&two).is_some()); + let three = descriptor(&[object(descriptor(&[object(descriptor(&[object(descriptor(&[]))]))]))]); + assert!(adapter::decode(&three).is_none()); + assert!(adapter::decode(&descriptor(&vec![long_field(b"Valu", 1); 32])).is_some()); + assert!(adapter::decode(&descriptor(&vec![long_field(b"Valu", 1); 33])).is_none()); + let long_object = [&b"Objc"[..], &0x8000_0000u32.to_be_bytes(), b"Clss", &u32::MAX.to_be_bytes()].concat(); + assert!(adapter::decode(&descriptor(&[long_object])).is_none()); + let nan = [&b"Valu"[..], &[0; 4], b"doub", &f64::NAN.to_be_bytes()].concat(); + assert!(adapter::decode(&descriptor(&[nan])).is_none()); + let flag = |b: u8| [&b"Valu"[..], &[0; 4], b"bool", &[b]].concat(); + assert!(adapter::decode(&descriptor(&[flag(1)])).is_some()); + assert!(adapter::decode(&descriptor(&[flag(2)])).is_none()); +} + +/// A Convert to Shape filter whose dictionary holds `keys`. +fn shape(keys: &str) -> String { + basic("Adobe Shape Effects", &format!("(Shape) /UnicodeString (DisplayString) ,\n{keys}")) +} + +/// The style `Boxed`: a fill and a stroke, and `effects` on the whole object after them. +fn shape_style(effects: &[String]) -> ArtStyle { + let stack = compound( + "Stack Style Filter", + &[ + basic("Stroke Style Filter", "/StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j 2 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n"), + fill("0 0 0 0 1 1 1 Xa"), + ], + ); + let mut kids = vec![stack]; + kids.extend_from_slice(effects); + let data = format!("/KnownStyle :\n(Boxed) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &kids)); + art_styles(data.as_bytes()).remove("Boxed").unwrap_or_default() +} + +/// Every setting of a Relative or Absolute size, with a corner radius. +const SIZES: &str = "150 /Real (AbsWidth) ,\n40 /Real (AbsHeight) ,\n20 /Real (RelWidth) ,\n6 /Real (RelHeight) ,\n15 /Real (CornerRadius) ,\n"; + +#[test] +fn convert_to_shape_comes_in_live_with_its_settings() { + // GUARDS: `Adobe Shape Effects` wasn't read, so an object with it kept its drawn look. + for (keys, id, want) in [ + ( + format!("0 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}"), + "convertToShape.rectangle", + json!({"relative": true, "extraW": 40.0, "extraH": 12.0, "width": 150.0, "height": 40.0}), + ), + ( + format!("1 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}"), + "convertToShape.roundedRectangle", + json!({"relative": true, "extraW": 40.0, "extraH": 12.0, "width": 150.0, "height": 40.0, "radius": 15.0}), + ), + ( + format!("2 /Int (Shape) ,\n1 /Real (Absolute) ,\n{SIZES}"), + "convertToShape.ellipse", + json!({"relative": false, "extraW": 40.0, "extraH": 12.0, "width": 150.0, "height": 40.0}), + ), + ( + format!("0 /Int (Shape) ,\n1 /Real (Absolute) ,\n{SIZES}"), + "convertToShape.rectangle", + json!({"relative": false, "extraW": 40.0, "extraH": 12.0, "width": 150.0, "height": 40.0}), + ), + // A relative size alone, and one that shrinks the shape: each is added to every side. + ( + "0 /Int (Shape) ,\n0 /Real (Absolute) ,\n20 /Real (RelWidth) ,\n6 /Real (RelHeight) ,\n".to_string(), + "convertToShape.rectangle", + json!({"relative": true, "extraW": 40.0, "extraH": 12.0, "width": 36.0, "height": 36.0}), + ), + ( + "0 /Int (Shape) ,\n0 /Real (Absolute) ,\n-10 /Real (RelWidth) ,\n-4 /Real (RelHeight) ,\n".to_string(), + "convertToShape.rectangle", + json!({"relative": true, "extraW": -20.0, "extraH": -8.0, "width": 36.0, "height": 36.0}), + ), + // Missing sizes: 18 pt a side, 36 pt, and a 9 pt radius. + ( + "0 /Int (Shape) ,\n0 /Real (Absolute) ,\n20 /Real (RelWidth) ,\n".to_string(), + "convertToShape.rectangle", + json!({"relative": true, "extraW": 40.0, "extraH": 36.0, "width": 36.0, "height": 36.0}), + ), + ( + "1 /Int (Shape) ,\n1 /Real (Absolute) ,\n".to_string(), + "convertToShape.roundedRectangle", + json!({"relative": false, "extraW": 36.0, "extraH": 36.0, "width": 36.0, "height": 36.0, "radius": 9.0}), + ), + ] { + let st = shape_style(&[shape(&keys)]); + assert!(st.plain && st.simple, "{keys}: {st:?}"); + let [e] = st.effects.as_slice() else { panic!("{keys}: {:?}", st.effects) }; + assert_eq!((e.id.as_str(), &e.params, e.visible), (id, &want, true), "{keys}"); + assert_eq!(st.items.len(), 2, "{keys}"); + } +} + +#[test] +fn convert_to_shape_keeps_its_place_among_effects_and_its_visibility() { + let offset = basic("Adobe Offset Path", "2 /Int (jntp) ,\n4 /Real (mlim) ,\n4 /Real (ofst) ,\n"); + let st = shape_style(&[shape(&format!("0 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}")), offset.clone()]); + assert!(st.plain, "{st:?}"); + let ids: Vec<_> = st.effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, ["convertToShape.rectangle", "path.offsetPath"]); + // Offset Path is read on any object too. + assert!(st.simple); + // A hidden one stays, hidden, with its settings. + let hidden = shape(&format!("1 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}")).replacen("1 /Visible", "0 /Visible", 1); + let st = shape_style(&[hidden]); + assert!(st.plain && st.simple, "{st:?}"); + let [e] = st.effects.as_slice() else { panic!("{:?}", st.effects) }; + assert_eq!( + (e.id.as_str(), e.visible, &e.params["radius"], &e.params["extraW"]), + ("convertToShape.roundedRectangle", false, &json!(15.0), &json!(40.0)) + ); +} + +#[test] +fn convert_to_shape_settings_that_arent_read_keep_the_drawn_look() { + let valid = format!("0 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}"); + assert!(shape_style(&[shape(&valid)]).plain); + for keys in [ + // Another shape, a shape that isn't a whole number or an /Int, and a missing one. + valid.replace("0 /Int (Shape)", "3 /Int (Shape)"), + valid.replace("0 /Int (Shape)", "0.5 /Int (Shape)"), + valid.replace("0 /Int (Shape)", "0 /Real (Shape)"), + valid.replace("0 /Int (Shape) ,\n", ""), + // A mode other than 0 and 1, or a missing one. + valid.replace("0 /Real (Absolute)", "2 /Real (Absolute)"), + valid.replace("0 /Real (Absolute) ,\n", ""), + valid.replace("0 /Real (Absolute)", "0 /Int (Absolute)"), + // Sizes that aren't finite numbers, negative absolute sizes and radii, and huge ones. + valid.replace("20 /Real (RelWidth)", "NaN /Real (RelWidth)"), + valid.replace("6 /Real (RelHeight)", "1e999 /Real (RelHeight)"), + valid.replace("6 /Real (RelHeight)", "(x) /Real (RelHeight)"), + valid.replace("150 /Real (AbsWidth)", "-150 /Real (AbsWidth)"), + valid.replace("15 /Real (CornerRadius)", "-1 /Real (CornerRadius)"), + valid.replace("20 /Real (RelWidth)", "1e6 /Real (RelWidth)"), + valid.replace("40 /Real (AbsHeight)", "40 /Int (AbsHeight)"), + // A key that isn't read. + format!("{valid}1 /Real (Future) ,\n"), + format!("{valid}(x) /String (Future) ,\n"), + // A relative Ellipse. + valid.replace("0 /Int (Shape)", "2 /Int (Shape)"), + ] { + let st = shape_style(&[shape(&keys)]); + assert!(!st.plain, "{keys}: {st:?}"); + } + // On one fill: the drawn look, for type too. + let item = compound("Chain Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), shape(&valid)]); + let data = + format!("/KnownStyle :\n(Odd) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])])); + assert!(!art_styles(data.as_bytes())["Odd"].plain); +} + +#[test] +fn warp_numbers_are_the_dialogs_order() { + for n in 1..=15 { + let style = warp_style(n).unwrap(); + assert_eq!(warp_number(style), Some(n), "{style}"); + } + assert_eq!((warp_style(0), warp_style(16), warp_number("arcs"), warp_number("")), (None, None, None, None)); +} + +/// A style as a writer checks it: the reader's appearance, with a gradient fill as the object's own, +/// and nothing for styles it doesn't read. +#[test] +fn a_style_is_read_as_a_writer_checks_it() { + let read = |data: &str, own: Option<&Paint>| crate::import::read_art_style(data.as_bytes(), "Odd", own); + let style = |kids: &[String]| format!("/KnownStyle :\n(Odd) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", kids)); + let gradient = fill("Bb\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB"); + let stack = compound("Stack Style Filter", std::slice::from_ref(&gradient)); + let data = style(&[stack, blend(1, 0.5)]); + let own = Paint::solid(vectorcraft_color::Color::WHITE); + let got = read(&data, Some(&own)).unwrap(); + assert_eq!(got.appearance.items.len(), 1); + assert_eq!(got.appearance.items[0].paint(), &own); + assert_eq!(got.transparency.map(|t| (t.0, t.1)), Some((0.5, BlendMode::Multiply))); + assert!(got.simple && !got.pathfinder); + // A gradient that isn't the object's own, a pattern, another name, two gradients: nothing. + assert!(read(&data, None).is_none()); + let pattern = style(&[compound("Stack Style Filter", &[fill("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p")])]); + assert!(read(&pattern, None).is_none()); + assert!(crate::import::read_art_style(data.as_bytes(), "Even", Some(&own)).is_none()); + assert!(read(&style(&[compound("Stack Style Filter", &[gradient.clone(), gradient])]), Some(&own)).is_none()); + // Damaged text: every cut of the style, and stray bytes, without a panic. + for cut in 0..data.len() { + let _ = read(data.get(..cut).unwrap_or_default(), Some(&own)); + } + for junk in ["(", ")", ";", "/KnownStyle :\n(Odd) /Name ,\n;;;;", "/KnownStyle :\n(Odd) /Name ,\n/Array : 1 /Real , ; (x) ,"] { + let _ = read(junk, Some(&own)); + } +} + +#[test] +fn art_styles_read_registration_and_named_colors() { + let reg_0 = fill("1 1 1 1 ([Registration]) 1 Xs"); + let reg_100 = fill("1 1 1 1 ([Registration]) 0 Xs"); + let reg_name = fill("1 1 1 1 /All 1 Xs"); + let named_spot = fill("0 0.5 1 0 (Shemen) 0 0 Xx"); + let stroke_reg = basic( + "Stroke Style Filter", + "/StrokeStyle : 0 R\n1 1 1 1 ([Registration]) 1 XS\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n", + ); + let data = format!( + "/KnownStyle :\n(Reg0) /Name ,\n/ActiveStyle :\n{}\n\ + /KnownStyle :\n(Reg100) /Name ,\n/ActiveStyle :\n{}\n\ + /KnownStyle :\n(RegName) /Name ,\n/ActiveStyle :\n{}\n\ + /KnownStyle :\n(Shemen) /Name ,\n/ActiveStyle :\n{}\n\ + /KnownStyle :\n(StrokeReg) /Name ,\n/ActiveStyle :\n{}\n", + compound("Chain Style Filter", &[compound("Stack Style Filter", &[reg_0])]), + compound("Chain Style Filter", &[compound("Stack Style Filter", &[reg_100])]), + compound("Chain Style Filter", &[compound("Stack Style Filter", &[reg_name])]), + compound("Chain Style Filter", &[compound("Stack Style Filter", &[named_spot])]), + compound("Chain Style Filter", &[compound("Stack Style Filter", &[stroke_reg])]), + ); + let styles = art_styles(data.as_bytes()); + let st0 = &styles["Reg0"]; + assert!(st0.plain); + let [StyleItem::Fill(Paint::Solid { swatch, tint, color })] = st0.items.as_slice() else { panic!("{st0:?}") }; + assert_eq!((swatch.as_deref(), *tint, *color), (Some(vectorcraft_color::swatch::REGISTRATION), 0.0, Color::cmyk(1.0, 1.0, 1.0, 1.0).tinted(0.0))); + + let st100 = &styles["Reg100"]; + assert!(st100.plain); + let [StyleItem::Fill(Paint::Solid { swatch, tint, color })] = st100.items.as_slice() else { panic!("{st100:?}") }; + assert_eq!((swatch.as_deref(), *tint, *color), (Some(vectorcraft_color::swatch::REGISTRATION), 1.0, Color::cmyk(1.0, 1.0, 1.0, 1.0))); + + let st_name = &styles["RegName"]; + assert!(st_name.plain); + let [StyleItem::Fill(Paint::Solid { swatch, tint, .. })] = st_name.items.as_slice() else { panic!("{st_name:?}") }; + assert_eq!((swatch.as_deref(), *tint), (Some(vectorcraft_color::swatch::REGISTRATION), 0.0)); + + let st_spot = &styles["Shemen"]; + assert!(st_spot.plain); + let [StyleItem::Fill(Paint::Solid { swatch, tint, color })] = st_spot.items.as_slice() else { panic!("{st_spot:?}") }; + assert_eq!((swatch.as_deref(), *tint, *color), (Some("Shemen"), 1.0, Color::cmyk(0.0, 0.5, 1.0, 0.0))); + + let st_stroke = &styles["StrokeReg"]; + assert!(st_stroke.plain); + let [StyleItem::Stroke { paint: Paint::Solid { swatch, tint, .. }, .. }] = st_stroke.items.as_slice() else { panic!("{st_stroke:?}") }; + assert_eq!((swatch.as_deref(), *tint), (Some(vectorcraft_color::swatch::REGISTRATION), 0.0)); +} diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 721365c25a..ffb950729d 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2,10 +2,10 @@ use std::sync::Arc; -use kurbo::{Point, Rect}; +use kurbo::{Affine, Point, Rect}; use vectorcraft_color::gradient::GradientKind; use vectorcraft_color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{AppearanceItem, ColorMode, Document, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind, Unit}; +use vectorcraft_doc::{AppearanceItem, ColorMode, Document, Guide, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind, Unit}; use super::*; @@ -33,6 +33,13 @@ fn read_ok(body: &str) -> Structure { } } +fn assert_unread(r: &Structure, kind: &str) { + assert_eq!(r.unread.len(), 1); + let (id, kinds) = &r.unread[0]; + assert_eq!(kinds, &[kind]); + assert!(r.doc.node(*id).is_some(), "the unread object has a placeholder"); +} + #[test] fn ruler_units_from_the_header_set_the_documents_units() { let body = layer(""); @@ -47,6 +54,14 @@ fn ruler_units_from_the_header_set_the_documents_units() { assert_eq!(read(with_px.as_bytes()).unwrap().doc.units, Unit::Pixels); } +#[test] +fn arrays_nested_past_the_depth_limit_are_refused() { + let deep = |n: usize| layer(&format!("{}{} pop", "[".repeat(n), "]".repeat(n))); + let nested = |n: usize| read(stream(&deep(n)).as_bytes()).err().is_some_and(|e| e.contains("nested too deeply")); + assert!(!nested(200)); + assert!(nested(100_000)); +} + /// The children of the first layer. fn art(doc: &Document) -> Vec> { doc.layers.first().and_then(|l| l.children()).cloned().unwrap_or_default() @@ -111,6 +126,289 @@ fn groups_names_hidden_and_locked() { assert!(!hidden.visible); } +/// A node's Attributes panel note (empty: none). +fn note(n: &Node) -> String { + n.extras().attrs.as_deref().map(|a| a.note.clone()).unwrap_or_default() +} + +/// The notes of the first layer's objects, in order. +fn notes(doc: &Document) -> Vec { + art(doc).iter().map(|n| note(n)).collect() +} + +/// A note comment names the paths after it until another one replaces it, and an empty one clears +/// it (§5.3.1: `%AI3_Note: `). +#[test] +fn a_note_comment_is_the_note_of_the_paths_after_it() { + let [a, b, c, d] = [0.0, 20.0, 40.0, 60.0].map(|x| rect_path(x, 0.0, x + 10.0, 10.0)); + let body = format!("%AI3_Note:hello\n{a}f\n{b}f\n%AI3_Note:\n{c}f\n%AI3_Note:world\n{d}f\n"); + assert_eq!(notes(&read_ok(&layer(&body)).doc), ["hello", "hello", "", "world"]); + // `%%Note:` sets it too. + assert_eq!(notes(&read_ok(&layer(&format!("%%Note:old style\n{a}f\n"))).doc), ["old style"]); + // A path without a note has no attributes. + assert!(art(&read_ok(&layer(&format!("{a}f\n"))).doc)[0].extras().attrs.is_none()); +} + +/// `%AI5_NoteMore:` adds a line to the note; the text is kept as written, and its bytes are read as +/// UTF-8, else Windows-1252. +#[test] +fn a_note_continues_on_more_lines_and_keeps_its_text() { + let a = rect_path(0.0, 0.0, 10.0, 10.0); + let body = format!("%AI3_Note: two (words) caf@ \n%AI5_NoteMore:more\n{a}f\n"); + let data = stream(&layer(&body)).replace('@', "\u{1}").into_bytes(); + let data: Vec = data.into_iter().map(|b| if b == 1 { 0xE9 } else { b }).collect(); + assert_eq!(notes(&read(&data).unwrap().doc), [" two (words) café \nmore"]); + // A continuation of an empty note is its second line; one with no note before it is ignored. + assert_eq!(notes(&read_ok(&layer(&format!("%AI3_Note:\n%AI5_NoteMore:x\n{a}f\n"))).doc), ["\nx"]); + assert_eq!(notes(&read_ok(&layer(&format!("%AI5_NoteMore:x\n{a}f\n"))).doc), [""]); + // A note too long is cut at 1,024 characters, however many lines it has. + let long = format!("%AI3_Note:{}\n{}{a}f\n", "x".repeat(5000), "%AI5_NoteMore:yy\n".repeat(3000)); + assert_eq!(notes(&read_ok(&layer(&long)).doc)[0].chars().count(), 1024); + let long = format!("%AI3_Note:x\n{}{a}f\n", "%AI5_NoteMore:yy\n".repeat(3000)); + assert_eq!(notes(&read_ok(&layer(&long)).doc)[0].chars().count(), 1024); + // A long UTF-8 line stays UTF-8 where it is cut. + let long = format!("%AI3_Note:{}\n{a}f\n", "é".repeat(3000)); + assert_eq!(notes(&read_ok(&layer(&long)).doc), ["é".repeat(1024)]); + // A note on a `%_` line is read too. + assert_eq!(notes(&read_ok(&layer(&format!("%_%AI3_Note:hidden\n{a}f\n"))).doc), ["hidden"]); +} + +/// A note before a group or a compound path isn't theirs: their paths keep their own. +#[test] +fn a_note_before_a_group_or_compound_path_is_not_theirs() { + let [a, b] = [0.0, 20.0].map(|x| rect_path(x, 0.0, x + 10.0, 10.0)); + for (open, close) in [("u", "U"), ("*u", "*U")] { + let body = format!("%AI3_Note:outer\n0 Ae\n{open}\n%AI3_Note:inner\n{a}f\n{b}f\n{close}\n"); + let doc = read_ok(&layer(&body)).doc; + let top = &art(&doc)[0]; + assert_eq!(note(top), "", "{open}"); + let kids: Vec = top.children().unwrap().iter().map(|k| note(k)).collect(); + assert_eq!(kids, ["inner", "inner"], "{open}"); + } +} + +/// A filled clipping path keeps its note, and no other object takes it. +#[test] +fn a_filled_clipping_paths_note_is_its_own() { + let body = + format!("0 Ae\nq\n{RED}%AI3_Note:clip\n{}W\nf\n%AI3_Note:\n{}f\nQ\n", rect_path(5.0, 5.0, 25.0, 25.0), rect_path(0.0, 0.0, 30.0, 30.0)); + let doc = read_ok(&layer(&body)).doc; + fn walk(nodes: &[Arc], out: &mut Vec<(bool, String)>) { + for n in nodes { + out.push((matches!(n.kind, NodeKind::Path { clipping: true, .. }), note(n))); + walk(n.children().map(Vec::as_slice).unwrap_or_default(), out); + } + } + let mut all = Vec::new(); + walk(&art(&doc), &mut all); + let noted: Vec<_> = all.iter().filter(|(_, n)| n == "clip").collect(); + assert_eq!(noted, [&(true, "clip".to_string())], "{all:?}"); + assert_eq!(all.len(), 3, "the group, its clipping path and the art: {all:?}"); +} + +/// `1 Ap` shows the center point of the paths after it until `0 Ap` (§12, showCenter), which leaves +/// them at an imported path's default: hidden. +#[test] +fn ap_shows_the_center_of_the_paths_after_it() { + let [a, b, c] = [0.0, 20.0, 40.0].map(|x| rect_path(x, 0.0, x + 10.0, 10.0)); + let ellipse = "50 0 m\n50 5.5 45.5 10 40 10 c\n34.5 10 30 5.5 30 0 c\n30 -5.5 34.5 -10 40 -10 c\n45.5 -10 50 -5.5 50 0 c\n"; + let body = format!("1 Ap\n{a}f\n{b}f\n0 Ap\n{c}f\n{ellipse}f\n2 Ap\n{a}f\n"); + let doc = read_ok(&layer(&body)).doc; + let shown: Vec<_> = art(&doc).iter().map(|n| (n.extras().attrs.as_deref().and_then(|a| a.show_center), n.shows_center())).collect(); + assert_eq!(shown, [(Some(true), true), (Some(true), true), (None, false), (None, false), (None, false)]); +} + +/// What a skipped section sets doesn't reach the art after it. +#[test] +fn a_note_or_ap_in_a_skipped_section_does_not_reach_the_art_after_it() { + let a = rect_path(0.0, 0.0, 10.0, 10.0); + let body = format!("%AI3_BeginBrushPattern\n1 Ap\n%AI3_Note:brush\n{a}f\n%AI3_EndBrushPattern\n{}", layer(&format!("{a}f\n"))); + let doc = read_ok(&body).doc; + let n = &art(&doc)[0]; + assert_eq!(note(n), ""); + assert!(!n.shows_center()); +} + +/// A node's URL and data (object tags), empty when it has no attributes. +fn tags(n: &Node) -> (String, Vec<(String, String)>) { + n.extras().attrs.as_deref().map(|a| (a.url.clone(), a.data.clone())).unwrap_or_default() +} + +fn tag(id: &str, value: &str) -> (String, String) { + (id.to_string(), value.to_string()) +} + +/// `/identifier (string) XT` tags the object before it (version 7 specification §7): `AdobeURL` +/// is its URL, and other tags go to its data in order, an empty string included. Paths, groups, +/// compound paths, text objects and images take tags. +#[test] +fn object_tags_are_kept_on_the_object_before_them() { + let [a, b, c, d] = [0.0, 20.0, 40.0, 60.0].map(|x| rect_path(x, 0.0, x + 10.0, 10.0)); + let text = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Hi) Tx\nTO\n"; + let body = format!( + "{a}N\n/part_no (A-12) XT\n/AdobeURL (https://example.com/a) XT\n/part_no (A-13) XT\n\ + u\n{b}f\nU\n/hand () XT\n*u\n{c}f\n{d}f\n*U\n/shape (two \\(parts\\)) XT\n{text}/AdobeURL (https://example.com/t) XT\n{a}f\n" + ); + let r = read(stream7(&layer7("L", &body)).as_bytes()).unwrap(); + let got: Vec<_> = art(&r.doc).iter().map(|n| tags(n)).collect(); + assert_eq!( + got, + [ + ("https://example.com/a".to_string(), vec![tag("part_no", "A-12"), tag("part_no", "A-13")]), + (String::new(), vec![tag("hand", "")]), + (String::new(), vec![tag("shape", "two (parts)")]), + ("https://example.com/t".to_string(), vec![]), + (String::new(), vec![]), + ] + ); + assert!(r.warnings.is_empty() && r.unread.is_empty(), "{:?} {:?}", r.warnings, r.unread); + // The group's and the compound path's paths keep no tags of their own. + for n in &art(&r.doc)[1..3] { + assert!(n.children().unwrap().iter().all(|k| k.extras().attrs.is_none())); + } + // A later `AdobeURL` replaces an earlier one. + let body = format!("{a}f\n/AdobeURL (https://example.com/1) XT\n/AdobeURL (https://example.com/2) XT\n"); + assert_eq!(tags(&art(&read7(&layer7("L", &body)).doc)[0]).0, "https://example.com/2"); +} + +/// A tag with no object right before it (at a layer's start, after a state change, after a group +/// opens) and a tag with an empty identifier tag nothing; one with operands of another kind is an +/// operator the reader doesn't know. +#[test] +fn object_tags_without_an_object_before_them_tag_nothing() { + let a = rect_path(0.0, 0.0, 10.0, 10.0); + for body in + [format!("/first (x) XT\n{a}f\n"), format!("{a}f\n1 w\n/late (x) XT\n"), format!("u\n/inside (x) XT\n{a}f\nU\n"), format!("{a}f\n/ (x) XT\n")] + { + let doc = read7(&layer7("L", &body)).doc; + let mut all = art(&doc); + all.extend(all.iter().flat_map(|n| n.children().cloned().unwrap_or_default()).collect::>()); + assert!(all.iter().all(|n| n.extras().attrs.is_none()), "{body}"); + } + for bad in ["(x) (y) XT\n", "/id 3 XT\n", "XT\n"] { + let err = read(stream7(&layer7("L", &format!("{a}f\n{bad}"))).as_bytes()).unwrap_err(); + assert!(err.contains("operators VectorCraft doesn't know"), "{bad}: {err}"); + } + // Outside any layer too. + let err = read(stream7(&format!("(x) (y) XT\n{}", layer7("L", &format!("{a}f\n")))).as_bytes()).unwrap_err(); + assert!(err.contains("operators VectorCraft doesn't know"), "{err}"); +} + +/// A filled clipping path's tags are its own, and a clip group's tags after `Q` are the group's. +/// One object keeps at most 64 tags in its data. +#[test] +fn object_tags_on_clipping_paths_and_the_tag_limit() { + let body = format!( + "0 Ae\nq\n{RED}{}W\nf\n/edge (clip) XT\n{}f\nQ\n/group (clipped) XT\n", + rect_path(5.0, 5.0, 25.0, 25.0), + rect_path(0.0, 0.0, 30.0, 30.0) + ); + let doc = read_ok(&layer(&body)).doc; + let top = &art(&doc); + assert_eq!(top.len(), 1); + assert_eq!(tags(&top[0]).1, [tag("group", "clipped")]); + assert_eq!(top[0].children().unwrap().len(), 2, "the clipping path and the art"); + let tagged: Vec<_> = top[0].children().unwrap().iter().filter(|k| !tags(k).1.is_empty()).map(|k| k.kind.clone()).collect(); + assert_eq!(tagged.len(), 1, "{tagged:?}"); + assert!(matches!(tagged[0], NodeKind::Path { clipping: true, .. }), "{tagged:?}"); + let many: String = (0..70).map(|i| format!("/t{i} ({i}) XT\n")).collect(); + let body = format!("{}f\n{many}/AdobeURL (https://example.com) XT\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let (url, data) = tags(&art(&read_ok(&layer(&body)).doc)[0]); + assert_eq!(data.len(), 64); + assert_eq!(data.last(), Some(&tag("t63", "63"))); + assert_eq!(url, "https://example.com", "the URL is kept past the limit"); + // A tag whose identifier or string is longer than 64 KiB is ignored. + let long = "x".repeat(64 * 1024 + 1); + let body = format!("{}f\n/{long} (a) XT\n/b ({long}) XT\n/c (ok) XT\n", rect_path(0.0, 0.0, 10.0, 10.0)); + assert_eq!(tags(&art(&read_ok(&layer(&body)).doc)[0]).1, [tag("c", "ok")]); +} + +/// An image takes the tags after it, as any other object does. +#[test] +fn object_tags_after_an_image_are_its_own() { + let mut data = image("[ 10 0 0 10 50 90 ]", (1, 1), ("DeviceRGB", 3, 0), &[255, 0, 0], 3); + let at = data.windows(6).position(|w| w == b"N\r\nLB\r").unwrap(); + data.splice(at..at, b"/AdobeURL (https://example.com/i) XT\r\n/sku (I-1) XT\r\n".iter().copied()); + let r = read(&data).unwrap(); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Image(_)), "{a:#?}"); + assert_eq!(tags(&a[0]), ("https://example.com/i".to_string(), vec![tag("sku", "I-1")])); +} + +/// The state written after a group's end or a gradient mesh's `/End X!` is still theirs when the +/// object's tags come first. +#[test] +fn object_tags_before_a_group_or_mesh_state_leave_it_theirs() { + let body = format!("{RED}0 Ae\nu\n0 0.5 0 0 0 Xy\n{}f\nU\n/hand (x) XT\n0 0 Xd\n6 () XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let doc = read_ok(&layer(&body)).doc; + assert_eq!((art(&doc)[0].opacity, tags(&art(&doc)[0]).1), (0.5, vec![tag("hand", "x")])); + let corner = + |x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| format!("%_[1 1 1 1 {x} {y} {} {} 1 {} {} 1] /N X#\n", next.0, next.1, prev.0, prev.1); + let mesh = format!( + "/Mesh X!\n%_(DeviceRGB) /CS X#\n%_[0 0] /P X#\n{}{}{}{}%_0 /E X#\n/End X!\n", + corner(0, 0, (0, 10), (10, 0)), + corner(0, 40, (10, 40), (0, 30)), + corner(40, 40, (40, 30), (30, 40)), + corner(40, 0, (30, 0), (40, 10)), + ); + let doc = read_ok(&layer(&format!("{mesh}/hand (y) XT\n1 0.35 0 0 0 Xy\n0 0 Xd\n6 () XW\n"))).doc; + let (m, l) = (&art(&doc)[0], &doc.layers[0]); + assert!(matches!(m.kind, NodeKind::Mesh(_)), "{m:#?}"); + assert_eq!((m.opacity, m.blend, tags(m).1), (0.35, BlendMode::Multiply, vec![tag("hand", "y")])); + assert_eq!((l.opacity, l.blend), (1.0, BlendMode::Normal), "not the layer's"); +} + +/// The tags of an object whose drawn look stands for it (its style not found) stay with the look. +#[test] +fn a_drawn_look_keeps_its_objects_tags() { + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + let body = format!( + "0 Ae\nu\n{RED}{}f\nU\n0 0 Xd\n6 () XW\n%_{hidden_rect}n\n%_/AdobeURL (https://example.com/n) XT\n%_/sku (N-1) XT\n1 (Gone style) XW\n", + rect_path(0.0, 0.0, 10.0, 10.0), + ); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert_eq!(tags(&a[0]), ("https://example.com/n".to_string(), vec![tag("sku", "N-1")])); + // A look with tags of its own keeps them, and takes the object's after them. + let a = art(&read_ok(&layer(&body.replace("U\n0 0 Xd", "U\n/own (L) XT\n0 0 Xd"))).doc); + assert_eq!(tags(&a[0]), ("https://example.com/n".to_string(), vec![tag("own", "L"), tag("sku", "N-1")])); +} + +/// A clipping subpath on `%_` lines in a drawn look leaves with the fill read apart from it. +#[test] +fn a_hidden_clipping_paths_fill_leaves_the_look_with_it() { + let (a, b, c) = (rect_path(0.0, 0.0, 30.0, 30.0), rect_path(5.0, 5.0, 25.0, 25.0), rect_path(0.0, 0.0, 10.0, 10.0)); + let two = rect_path(8.0, 8.0, 20.0, 20.0); + let second: String = format!("0 0 1 0 0 0 1 Xa\n{two}h\nW\nf\n").lines().map(|l| format!("%_{l}\n")).collect(); + let hidden_clip = format!("*u\n{RED}{a}h\nW\nf\n{second}*U\n"); + let body = format!("0 Ae\nu\nu\n{hidden_clip}{b}f\nU\nU\n0 0 Xd\n6 () XW\n%_{}n\n1 (Gone style) XW\n", c.replace('\n', "\n%_")); + let doc = read_ok(&layer(&body)).doc; + let mut leaves = vec![]; + doc.layers.iter().for_each(|l| { + l.walk(&mut |n| { + if let NodeKind::Path { clipping, .. } = &n.kind { + leaves.push((*clipping, fill(n).color())); + } + }) + }); + // The first subpath, its fill and the look's plain path stay; the second subpath and its fill leave. + let (red, blue) = (Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))); + assert_eq!(leaves, [(true, None), (false, red), (false, blue)]); +} + +/// Tags in a brush's art don't keep it from being read, and stay out of the art: it isn't an object +/// of the document. +#[test] +fn a_brushs_art_with_tags_is_read_without_them() { + let art_ = format!("%AI8_BeginBrushPattern\n(Dot art)\n0 A\n0 g\n{}f\n/sku (D-1) XT\n%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, 4.0, 4.0)); + let r = read_ok(&format!("{art_}{}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(""))); + let lib = vectorcraft_brush::library(&r.doc); + let vectorcraft_brush::BrushKind::Scatter(s) = brush_named(&lib, "Spray") else { panic!("scatter: {:?}", r.warnings) }; + assert_eq!(s.art.geometric_bounds().map(|b| (b.width(), b.height())), Some((4.0, 4.0))); + assert!(s.art.extras().attrs.is_none(), "{:?}", s.art.extras().attrs); +} + #[test] fn paths_colours_and_strokes() { let art_ = format!( @@ -151,6 +449,140 @@ fn paths_colours_and_strokes() { assert!(a[4].appearance.fill().is_none() && a[4].appearance.stroke().is_some()); } +/// Each subpath's anchor kinds, in order. +fn anchor_kinds(n: &Node) -> Vec> { + let Some(path) = n.path_data() else { panic!("{:?}", n.kind) }; + path.subpaths.iter().map(|s| s.anchors.iter().map(|a| a.kind).collect()).collect() +} + +/// A path's anchors at (x, y) in document space, and their handles. +fn anchor_points(n: &Node) -> Vec<[(f64, f64); 3]> { + let Some(path) = n.path_data() else { panic!("{:?}", n.kind) }; + path.subpaths.iter().flat_map(|s| s.anchors.iter()).map(|a| [(a.p.x, a.p.y), (a.h_in.x, a.h_in.y), (a.h_out.x, a.h_out.y)]).collect() +} + +/// A segment operator in lower case makes the anchor it ends on smooth, in upper case a corner +/// (§5.3.2), whether the segment is straight or curved and whatever its handles: the points and +/// handles stay where they are. +#[test] +fn a_segment_operators_case_sets_the_kind_of_the_anchor_it_ends_on() { + use vectorcraft_geom::AnchorKind::{Corner, Smooth}; + let doc = read_ok(&layer("0 0 m\n10 10 20 0 30 0 c\n40 10 50 0 60 0 C\nh\nS\n")).doc; + let a = art(&doc); + assert_eq!(anchor_kinds(&a[0]), [vec![Corner, Smooth, Corner]], "handles that aren't in line stay a smooth point's"); + assert_eq!( + anchor_points(&a[0]), + [[(0.0, 100.0), (0.0, 100.0), (10.0, 90.0)], [(30.0, 100.0), (20.0, 100.0), (40.0, 90.0)], [(60.0, 100.0), (50.0, 100.0), (60.0, 100.0)]] + ); + // `l`, `L`, `v`, `y`, `C` with handles in line (a corner all the same) and `c`, on an open path. + let doc = read_ok(&layer("0 0 m\n10 0 l\n20 0 L\n30 10 40 10 v\n50 10 60 10 y\n70 10 80 10 90 10 C\n100 10 110 0 110 0 c\nS\n")).doc; + let a = art(&doc); + assert_eq!(anchor_kinds(&a[0]), [vec![Corner, Smooth, Corner, Smooth, Smooth, Corner, Smooth]]); + assert_eq!(anchor_points(&a[0])[5], [(90.0, 90.0), (80.0, 90.0), (100.0, 90.0)]); +} + +/// A closed path's first anchor takes the kind of the segment back to it; a path closed without +/// one keeps its first anchor's kind from its handles. +#[test] +fn a_closed_paths_start_takes_the_case_of_the_segment_back_to_it() { + use vectorcraft_geom::AnchorKind::{Corner, Smooth}; + let start = |close: &str| { + let doc = read_ok(&layer(&format!("{close}s\n"))).doc; + anchor_kinds(&art(&doc)[0]) + }; + assert_eq!(start("0 0 m\n40 0 L\n40 40 L\n0 0 l\n"), [vec![Smooth, Corner, Corner]]); + assert_eq!(start("0 0 m\n40 0 l\n40 40 l\n0 0 L\n"), [vec![Corner, Smooth, Smooth]]); + // The start's handles are in line, so it would be smooth by them alone. + assert_eq!(start("0 0 m\n10 0 40 30 40 40 c\n40 50 -10 0 0 0 C\n"), [vec![Corner, Smooth]]); + assert_eq!(start("0 0 m\n10 0 40 30 40 40 C\n40 50 -10 0 0 0 c\n"), [vec![Smooth, Corner]]); + assert_eq!(start("0 0 m\n40 0 L\n40 40 l\nh\n"), [vec![Corner, Corner, Smooth]], "no segment back to the start"); + assert_eq!(start("0 0 m\n40 0 L\n40 40 l\n"), [vec![Corner, Corner, Smooth]], "`s` closes it the same way"); +} + +/// Every `m` starts a subpath of its own, in a compound path's members and within one path. +#[test] +fn each_subpath_takes_the_case_of_its_own_segments() { + use vectorcraft_geom::AnchorKind::{Corner, Smooth}; + let body = "*u\n0 0 m\n10 0 l\n10 10 L\nh\nf\n20 0 m\n30 0 L\n30 10 l\n20 0 l\nf\n*U\n\ + 0 50 m\n10 50 L\n10 60 l\nh\n20 50 m\n30 50 l\n30 60 L\n20 50 l\nf\n"; + let a = art(&read_ok(&layer(body)).doc); + let NodeKind::Compound { children, .. } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(anchor_kinds(&children[0]), [vec![Corner, Smooth, Corner]]); + assert_eq!(anchor_kinds(&children[1]), [vec![Smooth, Corner, Smooth]]); + assert_eq!(anchor_kinds(&a[1]), [vec![Corner, Corner, Smooth], vec![Smooth, Smooth, Corner]]); +} + +/// Guide paths and clipping paths keep the case of their segments too. +#[test] +fn guide_and_clipping_paths_take_the_case_of_their_segments() { + use vectorcraft_geom::AnchorKind::{Corner, Smooth}; + let a = art(&read_ok(&layer("(N) *\n10 10 m\n50 10 l\n90 10 L\n(N) *\n")).doc); + assert!(matches!(a[0].kind, NodeKind::Path { guide: true, .. })); + assert_eq!(anchor_kinds(&a[0]), [vec![Corner, Smooth, Corner]]); + let clipped = format!("0 Ae\nq\n{}f\n0 0 m\n30 0 l\n30 30 L\n0 0 l\nh\nW\nn\nQ\n", rect_path(0.0, 0.0, 40.0, 40.0)); + let a = art(&read_ok(&layer(&clipped)).doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); + assert_eq!(anchor_kinds(&children[0]), [vec![Smooth, Smooth, Corner]]); +} + +/// Operands that don't make a segment leave no kind behind, so the kinds after them stay with +/// their own anchors. +#[test] +fn a_segment_that_isnt_read_leaves_the_kinds_in_step() { + use vectorcraft_geom::AnchorKind::{Corner, Smooth}; + let a = art(&read_ok(&layer("10 c\n0 0 m\n5 l\n10 0 L\n(x) 20 y\n20 0 l\n30 0 L\nS\n")).doc); + assert_eq!(anchor_kinds(&a[0]), [vec![Corner, Corner, Smooth, Corner]]); + // A subpath of a lone `m` is a point of its own. + let a = art(&read_ok(&layer("5 5 m\n0 0 m\n10 0 l\n20 0 L\nS\n")).doc); + assert_eq!(anchor_kinds(&a[0]), [vec![Corner], vec![Corner, Smooth, Corner]]); +} + +/// `0 w` is the thinnest line the device draws (PostScript's `setlinewidth`), so a stroke of width 0 +/// comes in as a hairline: on a path, on a gradient-filled path that `1 BB` strokes, and on type. +#[test] +fn a_line_width_of_zero_is_a_hairline() { + let red = Some(Color::rgb(1.0, 0.0, 0.0)); + let a = art(&read_ok(&layer("0 1 1 0 1 0 0 XA\n2 J\n0 w\n20 20 m\n180 80 L\nS\n")).doc); + assert_eq!(a.len(), 1); + let st = a[0].appearance.stroke().unwrap(); + assert_eq!((st.width, st.paint.color(), st.cap), (0.25, red, LineCap::Square)); + + let art_ = format!( + "0 1 1 0 1 0 0 XA\n0 w\n{}Bb\n0 0 0 0 Bh\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n50 0 0 -50 100 50 Bm\nf\n1 BB\n", + rect_path(50.0, 0.0, 150.0, 100.0) + ); + let a = art(&read_ok(&format!("{G_DEFS}{}", layer(&art_))).doc); + assert!(matches!(fill(&a[0]), Paint::Gradient(_)), "{:?}", fill(&a[0])); + let st = a[0].appearance.stroke().unwrap(); + assert_eq!((st.width, st.paint.color()), (0.25, red)); + + let text = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n1 Tr\n0 1 1 0 1 0 0 XA\n0 w\n/_Helvetica 9 Tf\n(hi) Tx\nTO\n"; + let a = art(&read_ok(&layer(text)).doc); + let Some(NodeKind::Text(t)) = a.first().map(|n| &n.kind) else { panic!("{a:#?}") }; + let style = &t.runs[0].style; + assert_eq!((style.stroke_width, style.stroke.color(), style.fill.clone()), (0.25, red, Paint::None)); +} + +/// An art style's stroke of width 0 comes in as a hairline too. +#[test] +fn an_art_style_s_line_width_of_zero_is_a_hairline() { + let styles = "%AI9_BeginArtStyles\n/KnownStyle :\n(Thin) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ + /StrokeStyle : 0 R\n0 1 1 0 1 0 0 XA\n0 J 0 j 0 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n%AI9_EndArtStyles\n"; + let line = "20 20 m\n180 80 L\n"; + let art_ = format!("0 Ae\nu\n0 1 1 0 1 0 0 XA\n0 w\n{line}S\nU\n%_0 1 1 0 1 0 0 XA\n%_0 w\n%_{}S\n1 (Thin) XW\n", line.replace('\n', "\n%_")); + let r = read_ok(&format!("{styles}{}", layer(&art_))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look: {a:#?}"); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let st = a[0].appearance.stroke().unwrap(); + assert_eq!((st.width, st.paint.color()), (0.25, Some(Color::rgb(1.0, 0.0, 0.0)))); +} + /// `Xk` and `XK` are global process colours: a name, a tint and whether the colour is RGB, as /// `Xx` has them (#1025). They come in as global swatches that aren't inks, linked at their tint. #[test] @@ -196,12 +628,82 @@ fn a_gradient_stop_naming_a_process_colour_leaves_its_swatch_process() { assert!(near(sw.paint.color()), "{sw:?}"); } +/// A gradient whose name in the file is shown as the name of a color a later gradient's stop names +/// is numbered: the color keeps its swatch. +#[test] +fn a_gradient_shown_as_a_stops_color_name_is_numbered() { + let first = "%AI5_BeginGradient: (Test Cyan\\n1)\n(Test Cyan\\n1) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let brand = "%AI5_BeginGradient: (Brand)\n(Brand) 0 2 Bd\n[\n\ + %_0.93 0.1 0 0 (Test Cyan) 0 0 5 1 6 50 0 Bs\n%_0 0 0 0 1 0 0 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let art_ = format!("Bb\n1 (Test Cyan\\n1) 0 0 0 10 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let doc = read_ok(&format!("{first}{brand}{}", layer(&art_))).doc; + let Paint::Gradient(g) = fill(&art(&doc)[0]) else { panic!("{:?}", fill(&art(&doc)[0])) }; + assert_eq!(g.swatch.as_deref(), Some("Test Cyan 2")); + let sw = doc.swatch("Test Cyan").unwrap(); + assert!(matches!(sw.paint, Paint::Solid { .. }) && sw.global, "{sw:?}"); +} + +/// A gradient whose name has no newline keeps it when a gradient shown as that name is defined +/// first: the one shown up to its newline is numbered. +#[test] +fn a_gradient_name_without_a_newline_is_kept_whichever_comes_first() { + let gradient = |name: &str| format!("%AI5_BeginGradient: ({name})\n({name}) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n"); + let filled = |name: &str| format!("Bb\n1 ({name}) 0 0 0 10 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let doc = read_ok(&format!("{}{}{}", gradient("Sky\\n1"), gradient("Sky"), layer(&format!("{}{}", filled("Sky\\n1"), filled("Sky"))))).doc; + let links: Vec<_> = art(&doc).iter().map(|n| if let Paint::Gradient(g) = fill(n) { g.swatch.clone() } else { None }).collect(); + assert_eq!(links, [Some("Sky 2".to_string()), Some("Sky".to_string())]); + // A gradient without stops isn't kept, and its name stays free. + let empty = "%AI5_BeginGradient: (Sky)\n(Sky) 0 0 Bd\n[\nBD\n%AI5_EndGradient\n"; + let doc = read_ok(&format!("{empty}{}{}", gradient("Sky\\n1"), layer(&filled("Sky\\n1")))).doc; + assert!(matches!(fill(&art(&doc)[0]), Paint::Gradient(g) if g.swatch.as_deref() == Some("Sky"))); +} + /// A pattern's definition (`%AI3_BeginPattern`): its name and tile (8 points square here, y up), /// then its art on `%_` lines (a group of the tile's unpainted box and a dot, a round-capped /// stroke of no length), `E`. const DOTS: &str = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 8 8\n%_0 A\n%_0 Xw\n%_0 Ae\n%_u\n%_0 O\n%_0 8 m\n%_8 8 L\n%_8 0 L\n%_0 0 L\n%_0 8 L\n%_n\n\ %_0 R\n%_0 0 0 1 K\n%_1 J 0 j 2 w 4 M []0 d\n%_4 4 m\n%_4 4 L\n%_S\n%_U\n%_/ArtDictionary :\n%_;\n%_\n%_9 () XW\nE\n%AI3_EndPattern\n"; +/// An unpainted box that a pattern's definition marks as its tile's box isn't art; a painted one +/// with the mark stays. +#[test] +fn a_patterns_marked_tile_box_is_not_art() { + let mark = "%_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_\n"; + let def = |paint: &str, op: &str| { + format!( + "%AI3_BeginPattern: (Box)\n(Box) 0 0 8 8\n%_0 A\n%_0 Xw\n%_{paint}0 XR\n%_0 8 m\n%_8 8 L\n%_8 0 L\n%_0 0 L\n%_0 8 L\n%_{op}\n{mark}\ + %_0 0 0 1 k\n%_2 2 m\n%_6 2 L\n%_6 6 L\n%_2 6 L\n%_f\nE\n%AI3_EndPattern\n" + ) + }; + let layer = format!( + "%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n(Box) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\nLB\n%AI5_EndLayer--\n", + rect_path(10.0, 20.0, 70.0, 80.0) + ); + let s = read_ok(&format!("{}{layer}", def("", "n"))); + let art = &s.doc.pattern("Box").unwrap().art; + assert_eq!(art.len(), 1, "the square only"); + assert_eq!(art[0].geometric_bounds(), Some(Rect::new(2.0, -6.0, 6.0, -2.0))); + let s = read_ok(&format!("{}{layer}", def("1 0 0 0 k\n%_", "f"))); + assert_eq!(s.doc.pattern("Box").unwrap().art.len(), 2, "a painted box is art"); + // The mark after a group or a compound path of an unpainted box leaves it in the art. + for (open, close, kind) in [("u", "U", "group"), ("*u", "*U", "compound path")] { + let def = format!( + "%AI3_BeginPattern: (Box)\n(Box) 0 0 8 8\n%_0 A\n%_0 Xw\n%_{open}\n%_0 8 m\n%_8 8 L\n%_8 0 L\n%_0 0 L\n%_0 8 L\n%_n\n%_{close}\n{mark}\ + %_0 0 0 1 k\n%_2 2 m\n%_6 2 L\n%_6 6 L\n%_2 6 L\n%_f\nE\n%AI3_EndPattern\n" + ); + let s = read_ok(&format!("{def}{layer}")); + assert_eq!(s.doc.pattern("Box").unwrap().art.len(), 2, "after a {kind}"); + } + // Outside a pattern's definition the mark leaves the box in the art. + let marked = format!( + "%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n0 XR\n{}n\n{mark}0 0 0 1 k\n{}f\nLB\n%AI5_EndLayer--\n", + rect_path(10.0, 20.0, 70.0, 80.0), + rect_path(20.0, 30.0, 40.0, 50.0) + ); + let s = read_ok(&marked); + assert_eq!(s.doc.layers[0].children().unwrap().len(), 2, "outside a pattern"); +} + /// Patterns are read into pattern swatches, and `p` fills with one (#1025): the art keeps its /// layers, the fill places the tiles by its matrix. #[test] @@ -239,6 +741,201 @@ fn patterns_are_pattern_swatches_and_fill_with_them() { assert!(s.warnings.is_empty(), "{:?}", s.warnings); } +/// A pattern's name in the file is shown up to its newline (AI7 spec §4): two patterns named +/// `Dots` apart from what follows the newline are "Dots" and "Dots 2", each fill paints with its +/// own, and one defined again under its name in the file replaces the first. +#[test] +fn pattern_names_are_shown_up_to_their_newline() { + let def = |name: &str, tile: u32| DOTS.replace("(Dots)", &format!("({name})")).replace("0 0 8 8\n", &format!("0 0 {tile} {tile}\n")); + let filled = |name: &str| format!("({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(10.0, 20.0, 70.0, 80.0)); + let body = format!( + "{}{}{}{}", + def("Dots\\n1", 8), + def("Dots\\n2", 8), + def("Dots\\n2", 9), + layer(&format!("{}{}", filled("Dots\\n2"), filled("Dots\\n1"))) + ); + let s = read_ok(&body); + let doc = &s.doc; + let tiles: Vec<_> = doc.patterns.iter().map(|p| (p.name.as_str(), p.tile.width())).collect(); + assert_eq!(tiles, [("Dots", 8.0), ("Dots 2", 9.0)]); + for name in ["Dots", "Dots 2"] { + assert!(matches!(&doc.swatch(name).unwrap().paint, Paint::Pattern { pattern, .. } if pattern == name), "{name}"); + } + let fills: Vec<_> = art(doc).iter().map(|n| if let Paint::Pattern { pattern, .. } = fill(n) { pattern } else { String::new() }).collect(); + assert_eq!(fills, ["Dots 2", "Dots"]); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); + // Without a palette (or with an empty one) the document keeps its default swatches, and a named + // color the art uses has its swatch: a pattern takes none of their names. + let empty = "%AI5_BeginPalette\n0 0 Pb\nPB\n%AI5_EndPalette\n"; + let ink = format!("0 1 1 0 (Ink) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0)); + for palette in ["", empty] { + let body = + format!("{}{}{palette}{}", def("Black\\n1", 8), def("Ink\\n1", 8), layer(&format!("{}{}{ink}", filled("Black\\n1"), filled("Ink\\n1")))); + let doc = read_ok(&body).doc; + for (solid, pattern) in [("Black", "Black 2"), ("Ink", "Ink 2")] { + assert!(matches!(&doc.swatch(pattern).unwrap().paint, Paint::Pattern { pattern: p, .. } if p == pattern), "{palette:?}"); + assert!(matches!(doc.swatch(solid).unwrap().paint, Paint::Solid { .. }), "{palette:?}"); + } + let fills: Vec<_> = art(&doc).iter().map(|n| fill(n)).collect(); + assert!(matches!(&fills[..2], [Paint::Pattern { pattern: a, .. }, Paint::Pattern { pattern: b, .. }] if a == "Black 2" && b == "Ink 2")); + } + // Nor the name of a custom color the program of an EPS gives, or None's. + let ps = b"%!PS-Adobe-3.0\n%%CMYKCustomColor: 0 0 1 0 (Outer Ink)\n%%EndComments\n"; + let data = stream(&format!("{}{}{}", def("Outer Ink\\n1", 8), def("[None]\\n1", 8), layer(&filled("Outer Ink\\n1")))); + let doc = super::read_beside(data.as_bytes(), true, ps, false).unwrap().doc; + assert_eq!(doc.patterns.iter().map(|p| p.name.as_str()).collect::>(), ["Outer Ink 2", "[None] 2"]); + assert!(matches!(doc.swatch("Outer Ink").unwrap().paint, Paint::Solid { .. })); + assert!(matches!(fill(&art(&doc)[0]), Paint::Pattern { pattern, .. } if pattern == "Outer Ink 2")); +} + +/// A pattern shown as the name of one of the document's other swatches is numbered: a swatch or a +/// color group of the palette the reader keeps (under any version's prefix, a swatch it names by +/// its values too), Registration, and a custom color of the editing data's own header. A pattern +/// whose name has no newline keeps it, whichever is defined first. The default swatches go when a +/// palette replaces them, and their names are free then; a palette only in versioned content that +/// isn't read replaces nothing. +#[test] +fn pattern_names_are_numbered_around_the_documents_swatches() { + let def = |name: &str| DOTS.replace("(Dots)", &format!("({name})")); + let palette = "%AI12_BeginPalette\n0 0 Pb\n0 0 0 0.5 k\n(Mist)\nPc\n1 (Greys) 1 Pg\n0 0 0 0.2 k\nPc\nPB\n%AI12_EndPalette\n"; + let header = "%%CMYKCustomColor: 0 0 1 0 (Head Ink)\n"; + let doc = |defs: &[&str], palette: &str| { + let body = format!("{}{palette}{}", defs.iter().map(|n| def(n)).collect::(), layer("")); + read(stream_with_header(header, &body).as_bytes()).unwrap().doc + }; + let names = |d: &Document| d.patterns.iter().map(|p| p.name.clone()).collect::>(); + let d = doc(&["Mist\\n1", "Greys\\n1", "[Registration]\\n1", "Head Ink\\n1", "Red\\n1", "Sky\\n1", "Sky"], palette); + let generated = d.swatch_groups[0].swatches[0].name.clone(); + let all: Vec<&str> = d.swatches_iter().map(|s| s.name.as_str()).collect(); + assert!(d.swatch("Mist").is_some() && d.swatch("Head Ink").is_some(), "{all:?}"); + assert!(matches!(&d.swatch("Red").unwrap().paint, Paint::Pattern { pattern, .. } if pattern == "Red"), "{all:?}"); + assert_eq!(names(&d), ["Mist 2", "Greys 2", "[Registration] 2", "Head Ink 2", "Red", "Sky 2", "Sky"]); + let d = doc(&[&format!("{generated}\\n1")], palette); + assert_eq!(names(&d), [format!("{generated} 2")]); + // Without a palette the default swatches stay, and so they do when the only palette is in + // versioned content that isn't read. + let versioned = format!("%AI17_Begin_Content_if_version_gt:17 1\n%AI17_Alternate_Content\n{palette}%AI17_End_Versioned_Content\n"); + for palette in ["", &versioned] { + let d = doc(&["Red\\n1"], palette); + assert!(matches!(d.swatch("Red").unwrap().paint, Paint::Solid { .. }), "{palette:?}"); + assert_eq!(names(&d), ["Red 2"], "{palette:?}"); + } + // A pattern and a color in versioned content that isn't read take no name. + let unread = format!( + "%AI17_Begin_Content_if_version_gt:17 1\n%AI17_Alternate_Content\n{}{}%AI17_End_Versioned_Content\n", + def("Sky"), + layer("0 1 1 0 (Sea) 0 x\n") + ); + let d = doc(&["Sky\\n1", "Sea\\n1"], &unread); + assert_eq!(names(&d), ["Sky", "Sea"]); + // Nor does a color of a palette that a later one replaces, or of a palette's alternate. + let replaced = "%AI5_BeginPalette\n0 0 Pb\n0 1 1 0 (Sky) 0 x\n(Sky)\nPc\nPB\n%AI5_EndPalette\n\ + %AI5_BeginPalette\n0 0 Pb\n%AI17_Begin_Content_if_version_gt:17 1\n0 0 0 1 k\n(Ink)\nPc\n\ + %AI17_Alternate_Content\n0 1 0 0 (Sea) 0 x\n(Sea)\nPc\n%AI17_End_Versioned_Content\nPB\n%AI5_EndPalette\n"; + let d = doc(&["Sky\\n1", "Sea\\n1"], replaced); + assert_eq!(names(&d), ["Sky", "Sea"]); + // Versioned content that doesn't end is read whole, its colors too. + let unended = format!("%AI17_Begin_Content_if_version_gt:17 1\n%AI17_Alternate_Content\n{}", layer("0 1 1 0 (Sea) 0 x\n")); + let d = doc(&["Sea\\n1"], &unended); + assert_eq!(names(&d), ["Sea 2"]); +} + +/// A pattern whose name has no newline keeps it, and its swatch takes the first free "Name 2" when +/// another swatch has the name: a default swatch, a named color the art uses, or a color of the +/// palette. A pattern a swatch already paints with gets no other. +#[test] +fn a_pattern_swatch_named_as_another_swatch_is_numbered() { + let def = |name: &str| DOTS.replace("(Dots)", &format!("({name})")); + let filled = |name: &str| format!("({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(10.0, 20.0, 70.0, 80.0)); + let ink = format!("0 1 1 0 (Ink) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0)); + let paints = |d: &Document, name: &str| d.swatches_iter().find(|s| s.name == name).map(|s| s.paint.clone()); + let doc = read_ok(&format!("{}{}{}", def("White"), def("Ink"), layer(&format!("{}{}{ink}", filled("White"), filled("Ink"))))).doc; + assert_eq!(doc.patterns.iter().map(|p| p.name.as_str()).collect::>(), ["White", "Ink"]); + for name in ["White", "Ink"] { + assert!(matches!(paints(&doc, name), Some(Paint::Solid { .. })), "{name}"); + let numbered = format!("{name} 2"); + assert!(matches!(paints(&doc, &numbered), Some(Paint::Pattern { pattern, .. }) if pattern == name), "{numbered}"); + } + let fills: Vec<_> = art(&doc).iter().map(|n| fill(n)).collect(); + assert!(matches!(&fills[..2], [Paint::Pattern { pattern: a, .. }, Paint::Pattern { pattern: b, .. }] if a == "White" && b == "Ink")); + // A pattern defined later under the numbered name keeps its swatch's name. + let doc = read_ok(&format!("{}{}{}", def("White"), def("White 2"), layer(&filled("White")))).doc; + assert!(matches!(paints(&doc, "White 2"), Some(Paint::Pattern { pattern, .. }) if pattern == "White 2")); + assert!(matches!(paints(&doc, "White 3"), Some(Paint::Pattern { pattern, .. }) if pattern == "White")); + // A color of the palette. + let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0.5 k\n(Mist)\nPc\nPB\n%AI5_EndPalette\n"; + let doc = read_ok(&format!("{}{palette}{}", def("Mist"), layer(&filled("Mist")))).doc; + assert!(matches!(paints(&doc, "Mist"), Some(Paint::Solid { .. }))); + assert!(matches!(paints(&doc, "Mist 2"), Some(Paint::Pattern { pattern, .. }) if pattern == "Mist")); + // A palette swatch under another name already paints with the pattern. + let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0.5 k\n(Mist)\nPc\n(Mist) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Fog)\nPc\nPB\n%AI5_EndPalette\n"; + let doc = read_ok(&format!("{}{palette}{}", def("Mist"), layer(&filled("Mist")))).doc; + let names: Vec<&str> = doc.swatches_iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["[None]", "Mist", "Fog"]); +} + +/// A named color whose name a gradient or pattern swatch of the palette has takes the first free +/// "Name 2", and the fills and gradient stops linked to it follow it. +#[test] +fn a_color_named_as_a_palette_gradient_or_pattern_is_numbered() { + let gradient = "%AI5_BeginGradient: (Brand)\n(Brand) 0 2 Bd\n[\n\ + %_0 1 1 0 (Brand) 0 0 5 1 6 50 0 Bs\n%_0 0 0 0 1 0 0 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let palette = "%AI5_BeginPalette\n0 0 Pb\nBb\n2 (Brand) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Brand)\nPc\n\ + (Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Ink)\nPc\nPB\n%AI5_EndPalette\n"; + let colored = |name: &str| format!("0 1 1 0 ({name}) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0)); + let doc = read_ok(&format!("{gradient}{DOTS}{palette}{}", layer(&format!("{}{}", colored("Brand"), colored("Ink"))))).doc; + let paints = |name: &str| doc.swatches_iter().find(|s| s.name == name).map(|s| s.paint.clone()); + assert!(matches!(paints("Brand"), Some(Paint::Gradient(_)))); + assert!(matches!(paints("Ink"), Some(Paint::Pattern { .. }))); + for name in ["Brand 2", "Ink 2"] { + let sw = doc.swatches_iter().find(|s| s.name == name).unwrap_or_else(|| panic!("{name}")); + assert!(matches!(sw.paint, Paint::Solid { .. }) && sw.global && sw.spot, "{sw:?}"); + } + let links: Vec<_> = art(&doc).iter().map(|n| if let Paint::Solid { swatch, .. } = fill(n) { swatch } else { None }).collect(); + assert_eq!(links, [Some("Brand 2".to_string()), Some("Ink 2".to_string())]); + let Some(Paint::Gradient(g)) = paints("Brand") else { panic!() }; + assert_eq!(g.gradient.stops[0].swatch.as_deref(), Some("Brand 2"), "the stop's link"); + // A color defined later under the numbered name keeps it and its links. + let later = format!("0 0 1 0 (Brand 2) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0)); + let doc = read_ok(&format!("{gradient}{DOTS}{palette}{}", layer(&format!("{}{later}", colored("Brand"))))).doc; + let color = |name: &str| doc.swatches_iter().find(|s| s.name == name).and_then(|s| s.paint.color()); + assert_eq!(color("Brand 2"), Some(Color::cmyk(0.0, 0.0, 1.0, 0.0))); + assert_eq!(color("Brand 3"), Some(Color::cmyk(0.0, 1.0, 1.0, 0.0))); + let links: Vec<_> = art(&doc).iter().map(|n| if let Paint::Solid { swatch, .. } = fill(n) { swatch } else { None }).collect(); + assert_eq!(links, [Some("Brand 3".to_string()), Some("Brand 2".to_string())]); +} + +/// A palette's gradient swatch holds its gradient without a link to a swatch, whether it is named +/// by its gradient or has a name of its own, and the art filled with the gradient links to the +/// swatch named by the gradient. +#[test] +fn a_palette_gradient_swatch_is_not_linked_to_itself() { + let gradient = "%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let palette = "%AI5_BeginPalette\n0 0 Pb\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n\ + Bb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Brand)\nPc\nPB\n%AI5_EndPalette\n"; + let filled = format!("Bb\n1 (Sky) 0 0 0 10 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let doc = read_ok(&format!("{gradient}{palette}{}", layer(&filled))).doc; + for name in ["Sky", "Brand"] { + let sw = doc.swatch(name).unwrap_or_else(|| panic!("no {name} swatch")); + let Paint::Gradient(g) = &sw.paint else { panic!("{sw:?}") }; + assert_eq!(g.swatch, None, "{name}'s own paint"); + assert_eq!(g.geom, None); + assert_eq!(g.gradient.stops.len(), 2); + } + assert!(matches!(fill(&art(&doc)[0]), Paint::Gradient(g) if g.swatch.as_deref() == Some("Sky"))); +} + +/// A palette's pattern swatch named by its pattern takes the name the pattern is shown with. +#[test] +fn a_palette_pattern_swatch_takes_its_patterns_shown_name() { + let palette = "%AI5_BeginPalette\n0 0 Pb\n(Dots\\n1) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\nPc\nPB\n%AI5_EndPalette\n"; + let doc = read_ok(&format!("{}{palette}{}", DOTS.replace("(Dots)", "(Dots\\n1)"), layer(""))).doc; + let names: Vec<&str> = doc.swatches.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["[None]", "Dots"]); + assert!(matches!(&doc.swatch("Dots").unwrap().paint, Paint::Pattern { pattern, .. } if pattern == "Dots")); +} + /// Where a definition draws its tile doesn't move the fill: the tile's lower left is the pattern's /// origin, so the same dots drawn at 30..38 × 40..48 tile as they do at 0..8 × 0..8. #[test] @@ -281,23 +978,296 @@ fn a_gradient_in_a_patterns_definition_is_placed_from_the_canvas() { /// has that isn't read, where it shows. Its definition costs nothing else. #[test] fn a_pattern_it_cant_read_is_an_error_only_where_it_fills() { - let unread = "%AI3_BeginPattern: (Old)\n(Old) 0 0 8 8 [\n(0 O 0 R 0 g) @\n(\n0 0 m 8 8 L S\n) &\n] E\n%AI3_EndPattern\n\ + let unread = "%AI3_BeginPattern: (Old)\n(Old) 0 0 8 8 [\n(0 O 0 R 0 g) @\n(\n0 0 m 8 8 L frobnicate S\n) &\n] E\n%AI3_EndPattern\n\ %AI3_BeginPattern: (Odd)\n(Odd) 0 0 8 8\n%_U\nE\n%AI3_EndPattern\n%AI3_BeginPattern: (Flat)\n(Flat) 0 0 8 0\n%_0 0 m\n%_8 0 L\n%_S\nE\n%AI3_EndPattern\n"; let s = read_ok(&format!("{unread}{}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")))); assert!(s.doc.patterns.is_empty() && s.doc.swatches.iter().all(|w| !matches!(w.paint, Paint::Pattern { .. }))); for name in ["Old", "Odd", "Flat"] { - let e = read( + let r = read( stream(&format!("{unread}{}", layer(&format!("({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(0.0, 0.0, 1.0, 1.0))))) .as_bytes(), ) - .unwrap_err(); - assert!(e.contains("pattern fills"), "{name}: {e}"); + .unwrap(); + assert_unread(&r, "pattern fills"); } // Type in a pattern isn't read either. let typed = "%AI3_BeginPattern: (Words)\n(Words) 0 0 8 8\n%_/AI11Text :\n%_0 /StoryIndex ,\n%_;\nE\n%AI3_EndPattern\n"; assert!(read_ok(&format!("{typed}{}", layer(""))).doc.patterns.is_empty()); } +/// A pattern whose definition paints with a pattern it doesn't have isn't kept, on `%_` lines or +/// not: a fill with it is something the file has that isn't read. +#[test] +fn a_pattern_painting_with_an_unread_pattern_is_not_kept() { + for prefix in ["%_", ""] { + let tile = rect_path(0.0, 0.0, 8.0, 8.0).replace('\n', &format!("\n{prefix}")); + let def = format!( + "%AI3_BeginPattern: (Nest)\n(Nest) 0 0 8 8\n{prefix}(Missing) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{prefix}{tile}f\nE\n%AI3_EndPattern\n" + ); + let s = read_ok(&format!("{def}{}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")))); + assert!(s.doc.patterns.is_empty(), "{prefix:?}: {:?}", s.doc.patterns.iter().map(|p| &p.name).collect::>()); + let r = read( + stream(&format!("{def}{}", layer(&format!("(Nest) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(0.0, 0.0, 1.0, 1.0))))).as_bytes(), + ) + .unwrap(); + assert_unread(&r, "pattern fills"); + // A color set before the tile is drawn replaces the missing pattern, and the pattern is kept. + let repainted = def.replace(&format!("{prefix}{tile}f"), &format!("{prefix}0 g\n{prefix}{tile}f")); + let s = read_ok(&format!("{repainted}{}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")))); + assert!(s.doc.pattern("Nest").is_some(), "{prefix:?}"); + } +} + +/// A pattern's definition inside another's isn't read, so the outer one isn't kept either. +#[test] +fn a_pattern_with_a_definition_inside_it_isnt_kept() { + let tile = rect_path(0.0, 0.0, 8.0, 8.0).replace('\n', "\n%_"); + let inner = "%AI3_BeginPattern: (In)\n(In) 0 0 1 1\n%_0 0 m\n%_1 1 L\n%_S\nE\n%AI3_EndPattern\n"; + let def = format!("%AI3_BeginPattern: (Out)\n(Out) 0 0 8 8\n{inner}%_{tile}f\nE\n%AI3_EndPattern\n"); + let s = read_ok(&format!("{def}{}", layer(""))); + assert!(s.doc.patterns.is_empty(), "{:?}", s.doc.patterns.iter().map(|p| &p.name).collect::>()); + // Without the definition inside it, it is kept. + let s = read_ok(&format!("{}{}", def.replace(inner, ""), layer(""))); + assert!(s.doc.pattern("Out").is_some()); +} + +/// A definition whose art follows its head as operators is still read when that art starts with a +/// dash array (`[]0 d`) off `%_` lines, which isn't a version 7 layer list. +#[test] +fn a_pattern_whose_art_starts_with_a_dash_array_is_read() { + let def = format!("%AI3_BeginPattern: (Dash)\n(Dash) 0 0 8 8 []0 d\n{}f\nE\n%AI3_EndPattern\n", rect_path(0.0, 0.0, 8.0, 8.0)); + let s = read_ok(&format!("{def}{}", layer(""))); + assert_eq!(s.doc.pattern("Dash").map(|p| p.art.len()), Some(1)); +} + +/// Editing data in the version 7 form: `%AI5_FileFormat 2.0`, the art size around the template +/// box's center (an artboard 200 by 100 from the origin), `setup` (pattern definitions), then `body`. +fn pattern_stream7(setup: &str, body: &str) -> String { + format!( + "%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 2.0\n%AI5_ArtSize: 200 100\n%AI3_TemplateBox: 100 50 100 50\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n{setup}%%EndSetup\n{body}\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n" + ) +} + +/// One layer named `name` with the version 7 form's ten operands before `Lb`, holding `art`. +fn pattern_layer7(name: &str, art: &str) -> String { + format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n({name}) Ln\n0 A\n{art}LB\n%AI5_EndLayer--\n") +} + +/// A definition of `name` in the version 7 form: its 20-point tile, then `layers`, the layer list. +fn pattern7(name: &str, layers: &str) -> String { + format!("%AI3_BeginPattern: ({name})\n({name}) 0 0 20 20 [\n%AI3_Tile\n{layers}] E\n%AI3_EndPattern\n") +} + +fn pattern_read7(setup: &str, body: &str) -> Structure { + match read(pattern_stream7(setup, body).as_bytes()) { + Ok(s) => s, + Err(e) => panic!("{e}"), + } +} + +/// A definition in the version 7 form (§3.4): each layer's colors (`@`) paint its tile's art (`&`), +/// the first layer the lowest. The operator lines in the strings end in CR, and each layer starts +/// from the definition's state, so the second layer's stroke doesn't take the first one's width. +#[test] +fn version_7_pattern_layers_paint_in_order_with_their_own_colors() { + let layers = "(0 O 0 R 1 0 0 0 k\r1 0 0 0 K) @\n(\r%AI6_BeginPatternLayer\r0 J 0 j 3 w 4 M []0 d\r2 2 m\r9 2 L\r9 9 L\r2 9 L\rf\r%AI6_EndPatternLayer\r) &\n\ + (0 O 1 R 0 0 0 1 k\r0 0 0 1 K) @\n(\r2 12 m\r18 12 L\rS\r) &\n"; + let fill_with = format!("(Grid) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(10.0, 10.0, 90.0, 90.0)); + let s = pattern_read7(&pattern7("Grid", layers), &pattern_layer7("Art", &fill_with)); + assert!(s.unread.is_empty() && s.warnings.is_empty(), "{:?} {:?}", s.unread, s.warnings); + let def = s.doc.pattern("Grid").unwrap(); + assert_eq!(def.tile, Rect::new(0.0, -20.0, 20.0, 0.0), "the tile, y down"); + assert_eq!(def.art.len(), 2, "one path for each layer"); + let (square, line) = (&def.art[0], &def.art[1]); + assert_eq!(square.geometric_bounds(), Some(Rect::new(2.0, -9.0, 9.0, -2.0))); + assert_eq!(fill(square).color(), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0))); + assert!(square.appearance.stroke().is_none()); + assert!(line.appearance.fill().is_none()); + let stroke = line.appearance.stroke().unwrap(); + assert_eq!(stroke.paint.color(), Some(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + assert_eq!(stroke.width, 1.0, "the first layer's width stays with it"); + assert!(stroke.overprint); + assert!(matches!(fill(&art(&s.doc)[0]), Paint::Pattern { pattern, .. } if pattern == "Grid")); +} + +/// `_ &` fills the tile's box with the layer's fill color, without a stroke (§3.4). +#[test] +fn a_version_7_patterns_underbar_fills_the_tile_box() { + let layers = "(0 O 0 R 0 1 0 0 k 0 0 0 1 K) @ _ &\n(0 0 0 1 k 0 0 0 1 K) @ (2 2 m 18 18 L S) &\n"; + let s = pattern_read7(&pattern7("Back", layers), &pattern_layer7("Art", "")); + let def = s.doc.pattern("Back").unwrap(); + let back = &def.art[0]; + assert_eq!(back.geometric_bounds(), Some(def.tile)); + assert_eq!(fill(back).color(), Some(Color::cmyk(0.0, 1.0, 0.0, 0.0))); + assert!(back.appearance.stroke().is_none()); + assert!(def.art[1].appearance.stroke().is_some()); +} + +/// A version 7 pattern shown as the name of a custom color its own layer strings use is numbered: +/// the color keeps its swatch. +#[test] +fn a_version_7_pattern_shown_as_its_colors_name_is_numbered() { + let layers = "(0 O 0 R 0 0 0 1 \\(Ink\\) 0 x) @ (2 2 m 9 2 L 9 9 L f) &\n"; + let s = pattern_read7(&pattern7("Ink\\n1", layers), &pattern_layer7("Art", "")); + assert_eq!(s.doc.patterns.iter().map(|p| p.name.as_str()).collect::>(), ["Ink 2"]); + assert!(matches!(&s.doc.swatch("Ink 2").unwrap().paint, Paint::Pattern { pattern, .. } if pattern == "Ink 2")); + assert!(matches!(s.doc.swatch("Ink").unwrap().paint, Paint::Solid { .. })); +} + +/// A layer's strings are read with their escapes undone: `\r`, `\n`, an octal tab, a backslash at +/// a line's end, and escaped parentheses around a custom color's name. +#[test] +fn a_version_7_patterns_strings_are_read_with_their_escapes_undone() { + let layers = "(0 O 0 R 0 0 0 1 \\(Ink \\(A\\)\\) 0 x) @\n(2 2 m\\r9 2 L\\n9 9 L\\0112 9 \\\nL f) &\n"; + let s = pattern_read7(&pattern7("Ink", layers), &pattern_layer7("Art", "")); + let def = s.doc.pattern("Ink").unwrap(); + assert_eq!(def.art.len(), 1); + assert_eq!(def.art[0].geometric_bounds(), Some(Rect::new(2.0, -9.0, 9.0, -2.0))); + assert!(s.doc.swatch("Ink (A)").is_some(), "{:?}", s.doc.swatches.iter().map(|w| &w.name).collect::>()); +} + +/// A definition in the version 7 form that can't be read whole isn't kept, and a fill with it is +/// something the file has that isn't read: an operator it doesn't know, type, a definition inside +/// it, colors with other operators, a layer without its tile or its `&`, a string longer than the +/// format allows, an `E`, a group or an array a layer doesn't end, more than 65,536 layers, a list +/// without its `]` or its `E`, anything after its `E`. +#[test] +fn a_version_7_pattern_it_cant_read_whole_isnt_kept() { + let line = "(0 0 m 8 8 L S) &\n"; + let long = format!("(0 g) @ ({}0 0 m 8 8 L S) &\n", " ".repeat(65_536)); + let open = "%AI3_BeginPattern: (P)\n(P) 0 0 20 20 [\n(0 g) @ (0 0 m 8 8 L S) &\n"; + let defs = [ + pattern7("P", "(0 g) @ (0 0 m 8 8 L frobnicate S) &\n"), + pattern7("P", "(0 g) @ (0 To 1 0 0 1 2 2 0 Tp TP (a) Tx TO) &\n"), + pattern7("P", "(0 g) @ (\r%AI3_BeginPattern: (In)\r(In) 0 0 1 1\rE\r%AI3_EndPattern\r0 0 m 8 8 L S) &\n"), + pattern7("P", &format!("%AI3_BeginPattern: (In)\n(In) 0 0 1 1 [\n] E\n%AI3_EndPattern\n(0 g) @ {line}")), + pattern7("P", &format!("(0 g 0 0 m) @ {line}")), + pattern7("P", "(0 g) @\n"), + pattern7("P", "(0 g) @ _\n"), + pattern7("P", &long), + pattern7("P", "(0 g) @ (0 0 m 8 8 L S E) &\n"), + pattern7("P", "(0 g) @ (u 0 0 m 8 8 L S) &\n"), + pattern7("P", "(0 g) @ (0 0 m 8 8 L S [) &\n"), + pattern7("P", "(0 g) @ ([ 0 0 m 8 8 L S) &\n"), + pattern7("P", &"(0 g) @ _ &\n".repeat(65_537)), + format!("{open}E\n%AI3_EndPattern\n"), + format!("{open}]\n%AI3_EndPattern\n"), + format!("{open}] E\n0 0 m 8 8 L S\n%AI3_EndPattern\n"), + ]; + let fill_with = format!("(P) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(0.0, 0.0, 1.0, 1.0)); + for (i, def) in defs.iter().enumerate() { + assert!(pattern_read7(def, &pattern_layer7("Art", "")).doc.patterns.is_empty(), "case {i}"); + assert_unread(&pattern_read7(def, &pattern_layer7("Art", &fill_with)), "pattern fills"); + } + // The same definition, whole, is kept. + let s = pattern_read7(&pattern7("P", &format!("(0 g) @ {line}")), &pattern_layer7("Art", &fill_with)); + assert!(s.doc.pattern("P").is_some() && s.unread.is_empty()); +} + +/// With a pattern defined in the version 7 form, a fill's other operands are applied in order +/// before its initial matrix (§5.4.1): the shear along its axis, the reflection about the line at +/// its angle, the rotation, the scale, then the offset. Identity ones move the tiles by the offset +/// alone. `P` places a stroke's tiles the same way. +#[test] +fn a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear() { + let def = pattern7("Grid", "(0 g) @ _ &\n"); + // The operands, and the pattern's space → art space they make (a b c d e f). + let cases = [ + ("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, 15.0]), + ("25 30 1.5 .75 30 1 45 10 0 [1 0 0 1 0 0]", [-0.75, 0.649519, 1.166793, 0.489528, 25.0, 30.0]), + ("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, -0.353553, 1.035276, 0.353553, -5.0, 7.0]), + ("3 -4 1.2 .8 20 1 30 12 25 [.8 .1 -.2 1.1 4 -6]", [-0.028557, 0.816531, 1.054026, 0.117492, 7.2, -10.1]), + ]; + // Art space → the document (the artboard is 100 high), and a tile's art (y down from its top + // left) → the pattern's space. + let space = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]); + let tile = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 20.0]); + for (ops, want) in cases { + for (op, paint) in [("p", "f"), ("P", "S")] { + let s = pattern_read7(&def, &pattern_layer7("Art", &format!("(Grid) {ops} {op}\n{}{paint}\n", rect_path(10.0, 10.0, 90.0, 90.0)))); + let node = &art(&s.doc)[0]; + let p = if op == "p" { fill(node) } else { node.appearance.stroke().unwrap().paint.clone() }; + let Paint::Pattern { xf, .. } = p else { panic!("{ops} {op}: {p:?}") }; + let got = (space.inverse() * xf * tile.inverse()).as_coeffs(); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6), "{ops} {op}: {got:?}"); + } + } + // The tiles' corners: with identity operands but the offset, the tile's top left (0, 20) is at + // (10, 35) in art space; with the last ones, its lower right (20, 0) is at (6.628860, 6.230623). + let placed = |ops: &str| { + let s = pattern_read7(&def, &pattern_layer7("Art", &format!("(Grid) {ops} p\n{}f\n", rect_path(10.0, 10.0, 90.0, 90.0)))); + let Paint::Pattern { xf, .. } = fill(&art(&s.doc)[0]) else { panic!() }; + xf + }; + assert_eq!(placed(cases[0].0) * Point::ZERO, Point::new(10.0, 65.0)); + assert!((placed(cases[3].0) * Point::new(20.0, 20.0)).distance(Point::new(6.628860, 93.769377)) < 1e-5); + // Without its nine operands, a fill with the pattern isn't read. + let r = pattern_read7(&def, &pattern_layer7("Art", &format!("(Grid) 0 0 1 1 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(10.0, 10.0, 90.0, 90.0)))); + assert_unread(&r, "pattern fills"); +} + +/// With a pattern defined in the newer form (art on `%_` lines), the matrix alone places the tiles +/// (#1025): the other operands don't move them, and a fill without all nine is still read. +#[test] +fn a_newer_pattern_fill_is_placed_by_its_matrix_alone() { + let placed = |ops: &str| { + let s = read_ok(&format!("{DOTS}{}", layer(&format!("(Dots) {ops} p\n{}f\n", rect_path(10.0, 20.0, 70.0, 80.0))))); + assert!(s.unread.is_empty() && s.warnings.is_empty(), "{ops}: {:?} {:?}", s.unread, s.warnings); + let Paint::Pattern { xf, .. } = fill(&art(&s.doc)[0]) else { panic!("{ops}: {:?}", fill(&art(&s.doc)[0])) }; + xf + }; + let plain = placed("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"); + assert_eq!(plain * Point::ZERO, Point::new(0.0, 92.0)); + assert_eq!(placed("25 30 1.5 .75 30 1 45 10 0 [1 0 0 1 0 0]"), plain); + assert_eq!(placed("0 0 1 1 0 0 0 0 [1 0 0 1 0 0]"), plain); +} + +/// An art style `Tiled` whose fill is `(name) {ops} p`. +fn tiled_style(name: &str, ops: &str) -> String { + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Tiled) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n({name}) {ops} p\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ) +} + +/// A fill set through an art style on a text object places the tiles as a `p` fill with the same +/// operands does: with the other operands before the matrix for a pattern defined in the version 7 +/// form, by the matrix alone for one defined in the newer form. +#[test] +fn a_style_pattern_fill_is_placed_as_a_direct_one() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + // The text object's drawn look (without a pattern to take the placement from), then the object. + let look = "0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\nU\n"; + let own = "%_/AI11Text :\n%_0 /FreeUndo ,\n%_0 /FrameIndex ,\n%_0 /StoryIndex ,\n%_;\n"; + let ops = "25 30 1.5 .75 30 1 45 10 0 [.8 .1 -.2 1.1 4 -6]"; + for (name, def) in [("Grid", pattern7("Grid", "(0 g) @ _ &\n")), ("Dots", DOTS.to_string())] { + let styled = read_ok(&format!("{}{def}{}", tiled_style(name, ops), layer(&format!("{look}{own}1 (Tiled) XW\n")))); + let direct = read_ok(&format!("{def}{}", layer(&format!("({name}) {ops} p\n{rect}f\n")))); + let xf = |s: &Structure| match fill(&art(&s.doc)[0]) { + Paint::Pattern { xf, .. } => xf, + p => panic!("{name}: {p:?} {:?} {:?}", s.unread, s.warnings), + }; + let (got, want) = (xf(&styled).as_coeffs(), xf(&direct).as_coeffs()); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-9), "{name}: {got:?} {want:?}"); + } +} + +/// An art style's pattern fill paints with the pattern under the name it is shown with. +#[test] +fn a_style_pattern_fill_paints_with_the_shown_name() { + let look = "0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\nU\n"; + let own = "%_/AI11Text :\n%_0 /FreeUndo ,\n%_0 /FrameIndex ,\n%_0 /StoryIndex ,\n%_;\n"; + let defs = format!("{}{}", pattern7("Grid", "(0 g) @ _ &\n"), pattern7("Grid\\n1", "(0 g) @ _ &\n")); + let s = read_ok(&format!("{}{defs}{}", tiled_style("Grid\\n1", "0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"), layer(&format!("{look}{own}1 (Tiled) XW\n")))); + let pattern = |n: &Node| match fill(n) { + Paint::Pattern { pattern, .. } => pattern, + p => panic!("{p:?} {:?} {:?}", s.unread, s.warnings), + }; + assert_eq!(pattern(&art(&s.doc)[0]), "Grid 2"); +} + #[test] fn compound_paths_and_clipping() { let art_ = format!( @@ -318,16 +1288,247 @@ fn compound_paths_and_clipping() { // The clipping path goes first. assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); assert!(matches!(children[1].kind, NodeKind::Path { clipping: false, .. })); - // A clipping path with a fill paints it too, under the art it clips; without one, nothing. + // A clipping path with a fill keeps it, and paints it under the art it clips (`Node::clip_paint`); without one, + // nothing. + let blue = Some(Color::rgb(0.0, 0.0, 1.0)); let filled = format!("0 Ae\nq\n{RED}{}f\n0 0 1 0 0 0 1 Xa\n{}W\nf\nQ\n", rect_path(0.0, 0.0, 30.0, 30.0), rect_path(5.0, 5.0, 25.0, 25.0)); let doc = read_ok(&layer(&filled)).doc; let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("a clipping group") }; let kinds: Vec<_> = children.iter().map(|c| (matches!(c.kind, NodeKind::Path { clipping: true, .. }), fill(c).color())).collect(); - assert_eq!(kinds, [(true, None), (false, Some(Color::rgb(0.0, 0.0, 1.0))), (false, Some(Color::rgb(1.0, 0.0, 0.0)))]); + assert_eq!(kinds, [(true, blue), (false, Some(Color::rgb(1.0, 0.0, 0.0)))]); + assert_eq!(children[0].clip_paint().fill.map(|f| fill(&f).color()), Some(blue)); // A clipping path in a layer clips the layer. let doc = read_ok(&layer(&format!("{}f\n{}W\nn\n", rect_path(0.0, 0.0, 9.0, 9.0), rect_path(0.0, 0.0, 5.0, 5.0)))).doc; let NodeKind::Layer { clip, children, .. } = &doc.layers[0].kind else { panic!() }; assert!(*clip && matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); + // A filled clipping path in a layer keeps its fill too. + let doc = read_ok(&layer(&format!("{RED}{}f\n0 0 1 0 0 0 1 Xa\n{}W\nf\n", rect_path(0.0, 0.0, 9.0, 9.0), rect_path(0.0, 0.0, 5.0, 5.0)))).doc; + let NodeKind::Layer { clip: true, children, .. } = &doc.layers[0].kind else { panic!("{:?}", doc.layers[0].kind) }; + let kinds: Vec<_> = children.iter().map(|c| (matches!(c.kind, NodeKind::Path { clipping: true, .. }), fill(c).color())).collect(); + assert_eq!(kinds, [(true, blue), (false, Some(Color::rgb(1.0, 0.0, 0.0)))]); + // A compound clipping path keeps its subpaths' fill. + let compound = format!( + "0 Ae\nq\n{RED}{}f\n0 0 1 0 0 0 1 Xa\n*u\n{}h\nW\nf\n{}h\nW\nf\n*U\nQ\n", + rect_path(0.0, 0.0, 30.0, 30.0), + rect_path(5.0, 5.0, 25.0, 25.0), + rect_path(10.0, 10.0, 20.0, 20.0) + ); + let doc = read_ok(&layer(&compound)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("a clipping group") }; + assert!(matches!(children[0].kind, NodeKind::Compound { .. }) && children.len() == 2, "{children:?}"); + assert_eq!((fill(&children[0]).color(), fill(&children[1]).color()), (blue, Some(Color::rgb(1.0, 0.0, 0.0)))); + // One subpath filled and a later one stroked: the compound clipping path keeps the stroke, and the filled subpath's + // fill is a compound path of its own under the art, so the stroked subpath stays unfilled. + let mixed = format!( + "0 Ae\nq\n{RED}{}f\n0 0 1 0 0 0 1 Xa\n0 1 0 0 0 1 0 XA\n3 w\n*u\n{}h\nW\nf\n{}h\nW\nS\n*U\nQ\n", + rect_path(0.0, 0.0, 30.0, 30.0), + rect_path(5.0, 5.0, 25.0, 25.0), + rect_path(10.0, 10.0, 20.0, 20.0) + ); + let doc = read_ok(&layer(&mixed)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("a clipping group") }; + assert!(matches!(children[0].kind, NodeKind::Compound { .. }) && children.len() == 3, "{children:?}"); + let stroke = children[0].appearance.stroke().map(|s| (s.paint.color(), s.width)); + assert_eq!((fill(&children[0]).color(), stroke), (None, Some((Some(Color::rgb(0.0, 1.0, 0.0)), 3.0)))); + let NodeKind::Compound { children: filled, .. } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + assert_eq!(filled.len(), 1, "only the filled subpath: {filled:?}"); + assert!(filled.iter().all(|p| matches!(p.kind, NodeKind::Path { clipping: false, .. })), "{filled:?}"); + assert_eq!((fill(&children[1]).color(), children[1].appearance.stroke().is_none()), (blue, true)); + assert_eq!(fill(&children[2]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); + // A subpath that doesn't clip keeps its fill; only the clipping subpath's fill is read apart. + let green = Some(Color::rgb(0.0, 1.0, 0.0)); + let plain = format!( + "0 Ae\nq\n{RED}{}f\n*u\n0 0 1 0 0 0 1 Xa\n{}f\n0 1 0 0 0 1 0 Xa\n{}h\nW\nf\n*U\nQ\n", + rect_path(0.0, 0.0, 30.0, 30.0), + rect_path(5.0, 5.0, 25.0, 25.0), + rect_path(10.0, 10.0, 20.0, 20.0) + ); + let doc = read_ok(&layer(&plain)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("a clipping group") }; + let NodeKind::Compound { children: subpaths, .. } = &children[0].kind else { panic!("{:?}", children[0].kind) }; + let kinds: Vec<_> = subpaths.iter().map(|c| (matches!(c.kind, NodeKind::Path { clipping: true, .. }), fill(c).color())).collect(); + assert_eq!(kinds, [(false, blue), (true, None)]); + let NodeKind::Compound { children: apart, .. } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + assert_eq!((apart.len(), fill(&children[1]).color()), (1, green), "only the clipping subpath's fill: {apart:?}"); + // A tag after the compound clipping path is its own. + let doc = read_ok(&layer(&mixed.replace("*U\n", "*U\n/edge (clip) XT\n"))).doc; + let NodeKind::Group { children, .. } = &art(&doc)[0].kind else { panic!("a clipping group") }; + assert_eq!((tags(&children[0]).1, tags(&children[1]).1), (vec![tag("edge", "clip")], vec![])); +} + +/// A stroked clipping path (`W S`, `W B`, or a gradient fill with `1 BB`) keeps its stroke and its fill on the clipping +/// path. +#[test] +fn a_clipping_paths_stroke_stays_on_the_clipping_path() { + let blue = Some(Color::rgb(0.0, 0.0, 1.0)); + let red = Some(Color::rgb(1.0, 0.0, 0.0)); + // (clipping, fill colour, a gradient fill, stroke colour and width) of each of the clipping group's children. + let children = |doc: &Document| { + let NodeKind::Group { children, clip: true } = &art(doc)[0].kind else { panic!("{:?}", art(doc)[0].kind) }; + children + .iter() + .map(|c| { + let clipping = matches!(c.kind, NodeKind::Path { clipping: true, .. }); + (clipping, fill(c).color(), matches!(fill(c), Paint::Gradient(_)), c.appearance.stroke().map(|s| (s.paint.color(), s.width))) + }) + .collect::>() + }; + let under = rect_path(0.0, 0.0, 30.0, 30.0); + let clip = rect_path(5.0, 5.0, 25.0, 25.0); + let stroked = format!("0 Ae\nq\n{RED}{under}f\n0 0 1 0 0 0 1 XA\n3 w\n{clip}W\nS\nQ\n"); + assert_eq!(children(&read_ok(&layer(&stroked)).doc), [(true, None, false, Some((blue, 3.0))), (false, red, false, None)]); + let both = format!("0 Ae\nq\n{RED}{under}f\n0 1 0 0 0 1 0 Xa\n0 0 1 0 0 0 1 XA\n3 w\n{clip}W\nB\nQ\n"); + assert_eq!(children(&read_ok(&layer(&both)).doc), [(true, Some(Color::rgb(0.0, 1.0, 0.0)), false, Some((blue, 3.0))), (false, red, false, None)]); + let defs = "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n0 0 0 0 1 0 0 2 0 6 %_BS\n%_0 0 0 0 1 0 0 2 0 6 0 0 Bs\n\ + %_0 0 0 0 0 0 1 2 1 6 100 50 Bs\nBD\n%AI5_EndGradient\n"; + let gradient = format!("0 Ae\nq\n{RED}{under}f\n0 0 1 0 0 0 1 XA\n3 w\n{clip}W\nBb\n0 0 0 0 Bh\n1 (G) 5 5 0 20 1 0 0 1 0 0 1 Bg\nf\n1 BB\nQ\n"); + assert_eq!(children(&read_ok(&format!("{defs}{}", layer(&gradient))).doc), [(true, None, true, Some((blue, 3.0))), (false, red, false, None)]); + // Several clipping paths each keep their own stroke, opacity and blend mode: the second one clips a clipping group + // inside the first one's. + let inner = rect_path(10.0, 10.0, 20.0, 20.0); + let strokes = |first: &str, second: &str| { + let body = format!("0 Ae\nq\n{RED}{under}f\n0 0 1 0 0 0 1 XA\n3 w\n{first}{clip}W\nS\n{second}{inner}W\nS\nQ\n"); + let doc = read_ok(&layer(&body)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + let NodeKind::Group { children: nested, clip: true } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + [&children[0], &nested[0]].map(|c| { + assert!(matches!(c.kind, NodeKind::Path { clipping: true, .. }), "{:?}", c.kind); + (c.appearance.stroke().map(|s| (s.paint.color(), s.width)), c.opacity, c.blend) + }) + }; + let plain = (Some((blue, 3.0)), 1.0, BlendMode::Normal); + assert_eq!(strokes("", ""), [plain, plain]); + assert_eq!(strokes("", "9 0.5 0 0 0 Xy\n"), [plain, (Some((blue, 3.0)), 0.5, BlendMode::Lighten)]); + assert_eq!(strokes("", "5 w\n"), [plain, (Some((blue, 5.0)), 1.0, BlendMode::Normal)], "strokes that differ"); +} + +/// Clipping paths in a compound path that holds a drawn look become one compound path, which keeps the knockout shape +/// flag when they all have it. +#[test] +fn the_compound_of_clipping_paths_keeps_their_knockout_shape() { + let (under, over) = (rect_path(0.0, 0.0, 30.0, 30.0), rect_path(5.0, 5.0, 25.0, 25.0)); + let (a, b) = (rect_path(0.0, 0.0, 10.0, 10.0), rect_path(5.0, 0.0, 20.0, 10.0)); + let clipping = |first: &str, second: &str| { + let look = format!("0 Ae\nu\n{RED}{under}f\n0 0 0 0 0 0 1 Xa\n{over}f\nU\n9 () XW\n"); + let doc = read_ok(&layer(&format!("0 Ae\n*u\n{look}{first}{a}h\nW\nn\n{second}{b}h\nW\nn\n*U\n"))).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Compound { .. }), "{:?}", children[0].kind); + (children[0].opacity, children[0].knockout_shape) + }; + let shape = "0 0.5 0 0 1 Xy\n"; + assert_eq!(clipping(shape, ""), (0.5, true)); + assert_eq!(clipping("", ""), (1.0, false)); + assert_eq!(clipping(shape, "0 0.5 0 0 0 Xy\n"), (0.5, false), "the flag on one of them only"); + assert_eq!(clipping(shape, "0 0.8 0 0 1 Xy\n"), (1.0, true), "opacities that differ"); +} + +/// Several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection: each `W` +/// reduces the clip set by the ones before it (AI7 spec §5.6.2). Each clipping path after the first clips a clipping +/// group inside the one before it, and the innermost one holds the art; a filled clipping path keeps its fill. +#[test] +fn several_clipping_paths_clip_to_their_intersection() { + let square = rect_path(0.0, 0.0, 80.0, 80.0); + let (a, b) = (rect_path(20.0, 20.0, 60.0, 60.0), rect_path(25.0, 25.0, 70.0, 55.0)); + // (clipping, fill color, bounds) of a clipping group's children, with a nested clipping group's children listed + // after it. + type Level = Vec<(bool, Option, Option)>; + fn levels(children: &[Arc]) -> Vec { + let mut out = vec![]; + let mut at = children; + loop { + out.push(at.iter().map(|c| (matches!(c.kind, NodeKind::Path { clipping: true, .. }), fill(c).color(), c.geometric_bounds())).collect()); + let Some(NodeKind::Group { children, clip: true }) = at.last().map(|c| &c.kind) else { return out }; + at = children; + } + } + let red = Some(Color::rgb(1.0, 0.0, 0.0)); + let blue = Some(Color::rgb(0.0, 0.0, 1.0)); + // A rectangle as written, in the document's coordinates (y down from the 100 pt high page's top). + let r = |x0, y0, x1, y1| Some(Rect::new(x0, 100.0 - y1, x1, 100.0 - y0)); + let (ra, rb) = (r(20.0, 20.0, 60.0, 60.0), r(25.0, 25.0, 70.0, 55.0)); + let group = |body: &str| { + let doc = read_ok(&layer(body)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + levels(children) + }; + // The art after both clipping paths, in a clipping group of the second inside the first's. + let two = group(&format!("0 Ae\nq\n{a}h\nW\nn\n{b}h\nW\nn\n{RED}{square}f\nQ\n")); + assert_eq!((two.len(), two[0].len()), (2, 2), "{two:?}"); + assert_eq!(two[0][0], (true, None, ra)); + assert_eq!(two[1], [(true, None, rb), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // Three clipping paths nest twice; a filled clipping path keeps its fill at its own level, so the fill is clipped + // by that path and the paths before it only. + let three = + group(&format!("0 Ae\nq\n{a}h\nW\nn\n0 0 1 0 0 0 1 Xa\n{b}h\nW\nf\n{}h\nW\nn\n{RED}{square}f\nQ\n", rect_path(30.0, 10.0, 50.0, 90.0))); + assert_eq!(three.len(), 3, "{three:?}"); + assert_eq!((three[1].len(), three[1][0]), (2, (true, blue, rb)), "{three:?}"); + assert_eq!(three[2], [(true, None, r(30.0, 10.0, 50.0, 90.0)), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // As with one clipping path, every object in the group is clipped by all of them, in the order written, wherever + // it is written. + let small = rect_path(0.0, 0.0, 10.0, 10.0); + let before = group(&format!("0 Ae\nq\n{RED}{small}f\n{a}h\nW\nn\n{b}h\nW\nn\n0 0 1 0 0 0 1 Xa\n{square}f\nQ\n")); + assert_eq!(before.len(), 2, "{before:?}"); + assert_eq!(before[1], [(true, None, rb), (false, red, r(0.0, 0.0, 10.0, 10.0)), (false, blue, r(0.0, 0.0, 80.0, 80.0))]); + let between = group(&format!("0 Ae\nq\n{RED}{small}f\n{a}h\nW\nn\n0 0 1 0 0 0 1 Xa\n{square}f\n{b}h\nW\nn\n{RED}{square}f\nQ\n")); + assert_eq!((between.len(), between[0].len()), (2, 2), "{between:?}"); + assert_eq!( + between[1], + [(true, None, rb), (false, red, r(0.0, 0.0, 10.0, 10.0)), (false, blue, r(0.0, 0.0, 80.0, 80.0)), (false, red, r(0.0, 0.0, 80.0, 80.0))] + ); + // A compound clipping path and a clipping path after it: their union, then that intersected with the second. + let c = rect_path(30.0, 10.0, 50.0, 90.0); + let mixed = format!("0 Ae\nq\n*u\n{a}h\nW\nn\n{b}h\nW\nn\n*U\n{c}h\nW\nn\n{RED}{square}f\nQ\n"); + let doc = read_ok(&layer(&mixed)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Compound { .. }) && children.len() == 2, "{children:?}"); + assert_eq!(levels(children)[1], [(true, None, r(30.0, 10.0, 50.0, 90.0)), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // Clipping paths alone in a group (`u W n W n U`) clip the clipping group around it the same way. + let grouped = group(&format!("0 Ae\nq\n{RED}{square}f\n0 Ae\nu\n{a}h\nW\nn\n{b}h\nW\nn\nU\nQ\n")); + assert_eq!(grouped.len(), 2, "{grouped:?}"); + assert_eq!(grouped[1], [(true, None, rb), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // A compound path of clipping paths is still one clipping path, their union. + let compound = format!("0 Ae\nq\n*u\n{a}h\nW\nn\n{b}h\nW\nn\n*U\n{RED}{square}f\nQ\n"); + let doc = read_ok(&layer(&compound)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Compound { .. }) && children.len() == 2, "{children:?}"); + // Two clipping paths in a layer: the layer clips by the first, a clipping group in it by the second. + let doc = read_ok(&layer(&format!("{a}h\nW\nn\n{b}h\nW\nn\n{RED}{square}f\n"))).doc; + let NodeKind::Layer { clip: true, children, .. } = &doc.layers[0].kind else { panic!("{:?}", doc.layers[0].kind) }; + let in_layer = levels(children); + assert_eq!(in_layer.len(), 2, "{in_layer:?}"); + assert_eq!(in_layer[1], [(true, None, rb), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // Two clipping paths in an opacity mask's art: the art clips by the first, a clipping group in it by the second. + let mask_art: String = format!("{a}h\nW\nn\n{b}h\nW\nn\n1 g\n{square}f\n").lines().map(|l| format!("%_{l}\n")).collect(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let doc = read_ok(&layer(&format!("{RED}{square}f\n{mask}"))).doc; + let m = art(&doc)[0].extras().mask.clone().unwrap(); + let NodeKind::Group { children, clip: true } = &m.art.kind else { panic!("{:?}", m.art.kind) }; + let in_mask = levels(children); + assert_eq!(in_mask.len(), 2, "{in_mask:?}"); + assert_eq!((in_mask[0][0].0, in_mask[0][0].2, in_mask[1][0]), (true, ra, (true, None, rb))); + assert_eq!(in_mask[1].len(), 2, "{in_mask:?}"); + // Clipping paths are nested as far as the document's depth limit allows; past it they are refused rather than + // merged away, in a clipping group, a layer and an opacity mask's art. + let fits = |text: &dyn Fn(usize) -> String| (2..400).take_while(|n| read(stream(&layer(&text(*n))).as_bytes()).is_ok()).last().unwrap(); + let deep = |n: usize, last: &str| format!("0 Ae\nq\n{}{last}{RED}{square}f\nQ\n", format!("{a}h\nW\nn\n").repeat(n)); + // The layer is 1 deep, the clipping group 2, and the art in the innermost of `n` levels `n + 2`. + let in_group = fits(&|n| deep(n, "")); + assert_eq!(in_group, vectorcraft_doc::MAX_DEPTH - 2); + let r = read_ok(&layer(&deep(in_group, ""))); + let NodeKind::Group { children, clip: true } = &art(&r.doc)[0].kind else { panic!("{:?}", art(&r.doc)[0].kind) }; + assert_eq!(levels(children).len(), in_group, "{:?}", r.warnings); + assert!(read(stream(&layer(&deep(400, ""))).as_bytes()).unwrap_err().contains("nested too deeply")); + let in_layer = fits(&|n| format!("{}{RED}{square}f\n", format!("{a}h\nW\nn\n").repeat(n))); + assert_eq!(in_layer, vectorcraft_doc::MAX_DEPTH - 1); + let in_mask = fits(&|n| { + let art: String = format!("{}1 g\n{square}f\n", format!("{a}h\nW\nn\n").repeat(n)).lines().map(|l| format!("%_{l}\n")).collect(); + format!("{RED}{square}f\n%_/ArtDictionary :\n%_/Mask :\n%_X=\n{art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n") + }); + // The masked object is 2 deep and its mask's art 3. + assert_eq!(in_mask, vectorcraft_doc::MAX_DEPTH - 3); + // A compound clipping path holds its subpaths one level down: as the innermost one, it adds a level. + let compound_last = format!("*u\n{a}h\nW\nn\n{b}h\nW\nn\n*U\n"); + assert!(read(stream(&layer(&deep(in_group - 1, &compound_last))).as_bytes()).unwrap_err().contains("nested too deeply")); } /// A clipping group's clipping path can sit alone in a group of its own, after the art it clips (`q … u W n U @@ -391,6 +1592,77 @@ fn a_layer_keeps_its_own_transparency() { let doc = read_ok(&layer(&art_)).doc; assert_eq!(doc.layers[0].opacity, 1.0, "no layer state written: the layer stays opaque"); assert_eq!(art(&doc)[0].opacity, 0.5, "the group's own state"); + // A layer whose last object is a gradient mesh: an `Xy` right after the mesh's end is the + // layer's when `LB` follows (directly or after the layer's `Xd` and `7 () XW`), and the mesh's + // when its own `6 () XW` follows. + let corner = + |x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| format!("%_[1 1 1 1 {x} {y} {} {} 1 {} {} 1] /N X#\n", next.0, next.1, prev.0, prev.1); + let mesh = format!( + "0 0.8 0 0 0 Xy\n/Mesh X!\n%_(DeviceRGB) /CS X#\n%_[0 0] /P X#\n{}{}{}{}%_0 /E X#\n/End X!\n", + corner(0, 0, (0, 10), (10, 0)), + corner(0, 40, (10, 40), (0, 30)), + corner(40, 40, (40, 30), (30, 40)), + corner(40, 0, (30, 0), (40, 10)), + ); + for (after, layer_state, mesh_state) in [ + ("1 0.35 0 0 0 Xy\n", (0.35, BlendMode::Multiply), (0.8, BlendMode::Normal)), + ("1 0.35 0 0 0 Xy\n0 0 Xd\n7 () XW\n", (0.35, BlendMode::Multiply), (0.8, BlendMode::Normal)), + ("1 0.35 0 0 0 Xy\n0 0 Xd\n6 () XW\n", (1.0, BlendMode::Normal), (0.35, BlendMode::Multiply)), + // The stroke style in the layer's state block. + ("1 0.35 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 0 Xd\n7 () XW\n", (0.35, BlendMode::Multiply), (0.8, BlendMode::Normal)), + ] { + let doc = read_ok(&layer(&format!("{mesh}{after}"))).doc; + let l = &doc.layers[0]; + assert!(matches!(art(&doc)[0].kind, NodeKind::Mesh(_)), "{after:?}"); + assert_eq!((l.opacity, l.blend), layer_state, "the layer's state after {after:?}"); + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].blend), mesh_state, "the mesh's state after {after:?}"); + } +} + +#[test] +fn a_layers_state_after_its_last_group_or_compound_path_is_the_layers() { + // GUARDS: the layer's `Xy` right after its last group or compound path, before the layer's + // `0 0 Xd` and `7 () XW`, went to that group or compound path, and the layer stayed opaque. + let a = rect_path(0.0, 0.0, 10.0, 10.0); + let b = rect_path(2.0, 2.0, 8.0, 8.0); + let layer_block = "1 0.6 1 2 1 Xy\n0 0 Xd\n7 () XW\n"; + for last in [format!("0 Ae\nu\n{RED}{a}f\nU\n"), format!("0 Ae\n*u\n{RED}{a}f\n{b}f\n*U\n")] { + let doc = read_ok(&layer(&format!("{last}{layer_block}"))).doc; + let l = &doc.layers[0]; + assert_eq!( + (l.opacity, l.blend, l.isolate, l.knockout, l.knockout_shape), + (0.6, BlendMode::Multiply, true, Knockout::Neutral, true), + "{last}" + ); + let n = &art(&doc)[0]; + assert_eq!((n.opacity, n.blend, n.isolate, n.knockout_shape), (1.0, BlendMode::Normal, false, false), "{last}"); + // The group's own state block (`6 () XW`) keeps it the group's. + let doc = read_ok(&layer(&format!("{last}1 0.6 1 2 1 Xy\n0 0 Xd\n6 () XW\n"))).doc; + assert_eq!(doc.layers[0].opacity, 1.0, "{last}"); + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].knockout_shape), (0.6, true), "{last}"); + } +} + +#[test] +fn a_layers_state_keeps_through_the_stroke_style_written_in_it() { + // GUARDS: a layer's state block can have the stroke style between its `Xy` and `Xd`; read as + // the art moving on, it lost the layer's opacity and the layer drew opaque. + let state = "0 0.25 0 2 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 0 Xd\n7 () XW\n"; + let clip_group = format!( + "q\n{}h\nW\nn\n0 Ae\nu\n{RED}{}f\nU\n9 () XW\nQ\n9 () XW\n{state}", + rect_path(10.0, 10.0, 90.0, 90.0), + rect_path(0.0, 0.0, 100.0, 100.0) + ); + let path = format!("{RED}{}f\n{state}", rect_path(0.0, 0.0, 10.0, 10.0)); + for body in [clip_group, path] { + let doc = read_ok(&layer(&body)).doc; + let l = &doc.layers[0]; + assert_eq!((l.opacity, l.knockout), (0.25, Knockout::Neutral), "{body}"); + assert_eq!(art(&doc)[0].opacity, 1.0, "{body}"); + } + // An object's own state block (`6 () XW`) isn't the layer's. + let note = format!("{RED}{}f\n{}", rect_path(0.0, 0.0, 10.0, 10.0), state.replace("7 () XW", "6 () XW")); + assert_eq!(read_ok(&layer(¬e)).doc.layers[0].opacity, 1.0); } #[test] @@ -410,6 +1682,110 @@ fn transparency_of_objects_and_groups() { assert_eq!((a[2].opacity, a[2].blend), (1.0, BlendMode::Normal), "the next object's state isn't the group's"); } +/// A mesh's opacity defines the knockout shape when an `Xy` says so before it or right after its +/// end, whether its patches make one mesh or a group of patches. An `Xy` that is the layer's leaves +/// the mesh's as it was. +#[test] +fn a_gradient_mesh_keeps_its_knockout_shape() { + let one = straight_mesh(2, 2, (10.0, 10.0)); + let patches = one.replace("[2 2] /Size X#\n", ""); + let shape = "0 0.5 0 0 1 Xy\n"; + for (mesh, is_mesh) in [(&one, true), (&patches, false)] { + let doc = read_ok(&layer(&format!("{shape}{mesh}"))).doc; + assert_eq!(matches!(art(&doc)[0].kind, NodeKind::Mesh(_)), is_mesh, "{:?}", art(&doc)[0].kind); + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].knockout_shape), (0.5, true), "{is_mesh}"); + } + let doc = read_ok(&layer(&format!("{one}{shape}0 0 Xd\n6 () XW\n"))).doc; + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].knockout_shape), (0.5, true), "written after its end"); + let doc = read_ok(&layer(&format!("{shape}{one}1 0.35 0 0 0 Xy\n0 0 Xd\n7 () XW\n"))).doc; + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].knockout_shape), (0.5, true), "the mesh's own"); + assert_eq!((doc.layers[0].opacity, doc.layers[0].knockout_shape), (0.35, false), "the layer's own"); + let doc = read_ok(&layer(&format!("{one}1 0.35 0 0 1 Xy\n0 0 Xd\n7 () XW\n"))).doc; + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].knockout_shape), (1.0, false), "the mesh's own"); + assert_eq!((doc.layers[0].opacity, doc.layers[0].knockout_shape), (0.35, true), "the layer's own"); +} + +#[test] +fn a_gradient_mesh_takes_the_transparency_written_after_it() { + // GUARDS: a mesh's own state (`Xy`) comes right after its `/End X!`, before `Xd` and `XW`, as a + // group's does after `U`; read as the next object's, a Multiply shadow mesh painted opaque. + let corner = + |x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| format!("%_[1 1 1 1 {x} {y} {} {} 1 {} {} 1] /N X#\n", next.0, next.1, prev.0, prev.1); + let mesh = |x: i32| { + format!( + "/Mesh X!\n%_(DeviceRGB) /CS X#\n%_[0 0] /P X#\n{}{}{}{}%_0 /E X#\n/End X!\n", + corner(x, 0, (x, 10), (x + 10, 0)), + corner(x, 40, (x + 10, 40), (x, 30)), + corner(x + 40, 40, (x + 40, 30), (x + 30, 40)), + corner(x + 40, 0, (x + 30, 0), (x + 40, 10)), + ) + }; + let art_ = format!( + "0 1 0 0 0 Xy\n{}1 0.8 0 0 0 Xy\n0 0 Xd\n6 () XW\n{}0 0 Xd\n6 () XW\n2 0.7 0 0 0 Xy\n{RED}{}f\n", + mesh(0), + mesh(50), + rect_path(100.0, 0.0, 110.0, 10.0) + ); + let doc = read_ok(&layer(&art_)).doc; + let a = art(&doc); + assert!(matches!(a[0].kind, NodeKind::Mesh(_)) && matches!(a[1].kind, NodeKind::Mesh(_)), "{a:#?}"); + assert_eq!((a[0].opacity, a[0].blend), (0.8, BlendMode::Multiply), "the state after the mesh is its own"); + assert_eq!((a[1].opacity, a[1].blend), (0.8, BlendMode::Multiply), "the next mesh keeps the current state"); + assert_eq!((a[2].opacity, a[2].blend), (0.7, BlendMode::Screen), "a state after the mesh's `Xd` and `XW` is the next object's"); +} + +#[test] +fn a_masked_gradient_mesh_takes_the_transparency_written_after_its_mask() { + // GUARDS: a mesh with an opacity mask has its state after the mask's dictionary, whose art (on + // `%_` lines) has operators of its own; read as the next object's, each masked mesh in a run + // drew with the blend mode of the one before it. + let corners: String = ["10 20 10 25 1 15 20 1", "10 50 15 50 1 10 45 1", "40 50 40 45 1 35 50 1", "40 20 35 20 1 40 25 1"] + .iter() + .map(|g| format!("%_[0.5 1 {g}] /N X#\n")) + .collect(); + let mesh = format!("/Mesh X!\n%_/DeviceGray /CS X#\n{corners}%_/E X#\n/End X!\n"); + let mask = "%_/ArtDictionary :\n%_/Mask :\n%_X=\n%_u\n%_1 g\n%_10 20 m\n%_10 50 L\n%_40 50 L\n%_40 20 L\n%_f\n%_U\n%_X+\n\ + %_(Art) ,\n%_1 /Bool (Clipping) ,\n%_1 /Bool (Linked) ,\n%_; (AI9_Mask) ,\n%_;\n"; + let next = format!("0 1 0 0 0 Xy\n{RED}{}f\n", rect_path(60.0, 20.0, 80.0, 40.0)); + for (state, expected) in [("1 0.5 0 0 0 Xy\n", (0.5, BlendMode::Multiply)), ("", (1.0, BlendMode::Overlay))] { + let a = art(&read_ok(&layer(&format!("3 1 0 0 0 Xy\n{mesh}{mask}{state}0 0 Xd\n6 () XW\n{next}"))).doc); + assert_eq!(a.len(), 2, "{a:?}"); + assert!(matches!(a[0].kind, NodeKind::Mesh(_)) && a[0].extras().mask.is_some(), "{:?}", a[0]); + assert_eq!((a[0].opacity, a[0].blend), expected, "{state:?}: the state after the mask is the mesh's"); + assert_eq!((a[1].opacity, a[1].blend), (1.0, BlendMode::Normal), "the next object's own state"); + } +} + +#[test] +fn a_transparency_set_in_a_dictionary_s_art_stays_after_it() { + // GUARDS: an area text's frame (its `/ConfiningPath` art) sets its own transparency; the objects + // after the text, with no `Xy` of their own, draw with it. Read as the dictionary's alone, they + // drew with the Lighten of the path before the text and vanished on a light background. + let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n/Art :\nX=\n0 Ap\n0 1 0 0 0 Xy\n0 w\n100 0 m\n100 10 L\nn\nX+\n\ + ; /ConfiningPath ,\n2 /TextAntialiasing ,\n;\n"; + let body = format!("9 0.5 0 0 0 Xy\n{RED}{}f\n{text}{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0), rect_path(20.0, 0.0, 30.0, 10.0)); + let a = art(&read_ok(&layer(&body)).doc); + let paths: Vec<_> = a.iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).collect(); + assert_eq!(paths.len(), 2, "{a:#?}"); + assert_eq!((paths[0].opacity, paths[0].blend), (0.5, BlendMode::Lighten), "the state before the text"); + assert_eq!((paths[1].opacity, paths[1].blend), (1.0, BlendMode::Normal), "the state the text's art set"); +} + +#[test] +fn a_transparency_set_in_a_clipping_group_stays_after_it() { + // GUARDS: `Q` ends a clipping group but doesn't take the transparency back to what it was at + // its `q`: the writer sets `Xy` only when the next object's state differs from the last one it + // wrote. A Screen glow, then a clipping group whose path is set back to Normal, then type with + // no `Xy`: restored at `Q`, the type drew in Screen and nearly vanished on a light background. + let clip = format!("q\n0 1 0 0 0 Xy\n{}h\nW\nn\n{RED}{}f\nQ\n", rect_path(0.0, 0.0, 200.0, 100.0), rect_path(40.0, 0.0, 50.0, 10.0)); + let body = format!("2 0.8 0 0 0 Xy\n{RED}{}f\n{clip}{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0), rect_path(20.0, 0.0, 30.0, 10.0)); + let a = art(&read_ok(&layer(&body)).doc); + assert_eq!(a.len(), 3, "{a:#?}"); + assert_eq!((a[0].opacity, a[0].blend), (0.8, BlendMode::Screen), "the glow's own state"); + assert!(matches!(a[1].kind, NodeKind::Group { clip: true, .. }), "{:?}", a[1].kind); + assert_eq!((a[2].opacity, a[2].blend), (1.0, BlendMode::Normal), "the state set inside the clipping group"); +} + #[test] fn gradients() { let defs = "%AI5_BeginGradient: (G)\n(G) 1 2 Bd\n[\n<00FF>\n0\n0 0 0 0 1 0 0 2 1 6 %_BS\n\ @@ -483,6 +1859,61 @@ fn a_compound_path_holding_its_drawn_look_paints_its_paths_apart() { assert_eq!(fills, [Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))], "{a:#?}"); } +/// Clipping paths in a compound path that holds its drawn look clip as one compound path. Each one's fill is a path of +/// its own under the art they clip, with the clipping path's opacity mask, so overlapping fills and fills that differ +/// paint as each clipping path paints them. +#[test] +fn clipping_paths_beside_a_compound_paths_look_keep_their_fills() { + let (a, b) = (rect_path(0.0, 0.0, 20.0, 20.0), rect_path(5.0, 5.0, 25.0, 25.0)); + let look = format!("0 Ae\nu\n{RED}{}f\n0 0 0 0 0 0 1 Xa\n{}f\nU\n9 () XW\n", rect_path(0.0, 0.0, 30.0, 30.0), rect_path(10.0, 10.0, 15.0, 15.0)); + let mask_art: String = + format!("0 0 0 0 (Global white) 1 0 Xk\n{}f\n", rect_path(0.0, 0.0, 10.0, 10.0)).lines().map(|l| format!("%_{l}\n")).collect(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let children = |second: &str, after_first: &str| { + let body = format!("0 Ae\n*u\n{RED}{a}h\nW\nf\n{after_first}{second}{b}h\nW\nf\n{look}*U\n"); + let doc = read_ok(&layer(&body)).doc; + // Every object, opacity masks' art included, has an id of its own. + fn ids(n: &Node, seen: &mut std::collections::HashSet) { + assert!(seen.insert(n.id), "{:?} appears twice", n.id); + if let Some(m) = &n.extras().mask { + ids(&m.art, seen); + } + for c in n.children().into_iter().flatten() { + ids(c, seen); + } + } + let mut seen = std::collections::HashSet::new(); + doc.layers.iter().for_each(|l| ids(l, &mut seen)); + let a = art(&doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{a:#?}") }; + // An opacity mask: the swatch its art's fill is linked to. + let mask = |c: &Node| { + c.extras().mask.as_ref().map(|m| { + let mut swatch = None; + m.art.walk(&mut |p| { + if let Paint::Solid { swatch: Some(s), .. } = fill(p) { + swatch = Some(s); + } + }); + swatch + }) + }; + children.iter().map(|c| (c.kind.clone(), fill(c).color(), mask(c))).collect::>() + }; + let (red, blue) = (Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))); + // A child's kind, fill color and, with an opacity mask, the swatch its art is linked to. + type Child = (NodeKind, Option, Option>); + let paths = |c: &[Child]| { + assert!(matches!(c[0].0, NodeKind::Compound { .. }) && c.len() == 4, "{c:?}"); + c[..3].iter().map(|(k, c, m)| (matches!(k, NodeKind::Path { clipping: false, .. }), *c, m.clone())).collect::>() + }; + assert_eq!(paths(&children("", "")), [(false, None, None), (true, red, None), (true, red, None)]); + assert_eq!(paths(&children("0 0 0 0 0 0 1 Xa\n", "")), [(false, None, None), (true, red, None), (true, blue, None)]); + // The fill's copy of the mask stays linked to the mask art's global swatch. + let linked = Some(Some("Global white".to_string())); + assert_eq!(paths(&children("0 0 0 0 0 0 1 Xa\n", &mask)), [(false, None, None), (true, red, linked), (true, blue, None)]); +} + #[test] fn a_compound_path_of_a_plain_group_stays_one_compound_path() { // GUARDS: #980. Files write `9 () XW` after every group, the one a compound path keeps its @@ -575,34 +2006,519 @@ fn artboards() { assert_eq!(doc.artboards[0].rect, Rect::new(0.0, 0.0, 600.0, 400.0)); } -/// A variable library in the document data isn't read: a note gives how many variables and data -/// sets it has, counting the elements of the library alone (a data set's element for a variable named -/// `variable` isn't a variable). #[test] -fn a_variable_library_is_noted_with_its_counts() { - use vectorcraft_testkit::ai::variable_library; +fn the_active_artboard_is_the_one_crop_area_active_names() { + let board = |x: i32, w: i32| { + format!( + "%_/Dictionary :\n%_{x} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n", + x + w + ) + }; let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); - let notes = |library: &str| read_ok(&format!("{library}{square}")).warnings.into_iter().filter(|w| w.contains("variables")).collect::>(); + // Four artboards in the array, the second of no width (left out); `entry` follows the array. + let opened = |entry: &str| { + let boards = [board(0, 100), board(200, 0), board(400, 100), board(600, 100)].concat(); + let data = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{boards}%_; (ArtboardArray) ,\n{entry}%_; /NotRecorded ,\n%_;\n{square}"); + let doc = read_ok(&data).doc; + doc.opened_artboard.map(|id| doc.artboards.iter().position(|a| a.id == id)) + }; + // The index counts every entry of the array, the one left out too. + assert_eq!(opened("%_3 /Int (CropAreaActive) ,\n"), Some(Some(2))); + assert_eq!(opened("%_2 /Int (CropAreaActive) ,\n"), Some(Some(1))); + // After another entry of the dictionary that holds the array. + assert_eq!(opened("%_1 /Int (Other) ,\n%_3 /Int (CropAreaActive) ,\n"), Some(Some(2))); + // The first artboard, the one left out, one past the end, a value of another type, or none. + for entry in + ["%_0 /Int (CropAreaActive) ,\n", "%_1 /Int (CropAreaActive) ,\n", "%_4 /Int (CropAreaActive) ,\n", "%_2 /Real (CropAreaActive) ,\n", ""] + { + assert_eq!(opened(entry), None, "{entry}"); + } +} + +/// The document data of artboards side by side, 100 points wide, each with the entries `extra`. +fn boards_with(extra: &[&str]) -> String { + let boards: String = extra + .iter() + .enumerate() + .map(|(i, e)| { + let x = i * 100; + format!( + "%_/Dictionary :\n{e}%_{x} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n", + x + 100 + ) + }) + .collect(); + format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{boards}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n") +} + +#[test] +fn artboards_keep_their_display_options() { + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let options = |extra: &[&str]| { + read_ok(&format!("{}{square}", boards_with(extra))) + .doc + .artboards + .iter() + .map(|a| (a.show_center_mark, a.show_cross_hairs, a.show_video_safe_areas, a.video_ruler_pixel_aspect_ratio)) + .collect::>() + }; assert_eq!( - notes(&variable_library(&["variable", "Team"], &["Home", "Away", "Third"])), - ["the file's variables and data sets weren't read (variables: 2, data sets: 3): the Variables panel doesn't list them"] + options(&["%_1 /Int (DisplayMark) ,\n%_1.33 /Real (PAR) ,\n", "%_6 /Int (DisplayMark) ,\n%_2 /Real (PAR) ,\n"]), + [(true, false, false, 1.33), (false, true, true, 2.0)], + "each artboard has its own" ); + assert_eq!(options(&["%_7 /Int (DisplayMark) ,\n%_1 /Real (PAR) ,\n"]), [(true, true, true, 1.0)]); + // Values of another type or out of range leave the defaults. + for bad in [ + "%_1 /Real (DisplayMark) ,\n%_1 /Int (PAR) ,\n", + "%_-1 /Int (DisplayMark) ,\n%_20 /Real (PAR) ,\n", + "%_1.5 /Int (DisplayMark) ,\n%_0.05 /Real (PAR) ,\n", + "%_1 2 /Int (DisplayMark) ,\n%_(2) /Real (PAR) ,\n", + ] { + assert_eq!(options(&[bad]), [(false, false, false, 1.0)], "{bad}"); + } +} + +/// The document data with the Document Raster Effects Settings `entries`. +fn raster_settings(entries: &str) -> String { + format!("%_/Document :\n%_/Dictionary :\n%_/Dictionary :\n{entries}%_; (AI Auto Rasterize) ,\n%_; /NotRecorded ,\n%_;\n") +} + +#[test] +fn document_raster_effects_settings_come_from_the_document() { + use vectorcraft_doc::{Background, RasterColorModel, RasterEffectsSettings}; + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let settings = |entries: &str| { + let doc = read_ok(&format!("{}{square}", raster_settings(entries))).doc; + (doc.raster_effects_ppi, doc.raster_effects) + }; + let all = "%_6 /Int (colr) ,\n%_0 /Bool (spot) ,\n%_150 /Int (dpi.) ,\n%_1 /Bool (mask) ,\n%_0 /Bool (alis) ,\n%_7 /Real (padd) ,\n"; assert_eq!( - notes(&variable_library(&["Team"], &["Home"])), - ["the file's variables and data sets weren't read (variables: 1, data sets: 1): the Variables panel doesn't list them"] + settings(all), + ( + 150.0, + RasterEffectsSettings { + color_model: RasterColorModel::Grayscale, + background: Background::Transparent, + anti_alias: false, + clipping_mask: true, + add_around: 7.0, + preserve_spot_colors: false, + } + ) ); - assert!(notes(&variable_library(&[], &[])).is_empty(), "an empty library gives no warning"); - assert!(notes("").is_empty()); - // When the reader can't read the layers, `variables` still counts the library, for the warning - // of the file read from its PDF part. - let unread = stream(&format!("{}{}", variable_library(&["Team"], &["Home", "Away"]), layer("1 Zz\n"))); + let (_, white) = settings("%_0 /Int (colr) ,\n"); + assert_eq!((white.color_model, white.background), (RasterColorModel::Document, Background::White)); + let (_, document) = settings("%_4 /Int (colr) ,\n"); + assert_eq!((document.color_model, document.background), (RasterColorModel::Document, Background::Transparent)); + // Values of another type, out of range or unknown leave the defaults. + let defaults = (72.0, RasterEffectsSettings::default()); + for bad in [ + "%_150 /Real (dpi.) ,\n%_1 /Int (mask) ,\n%_7 /Int (padd) ,\n%_6 /Real (colr) ,\n", + "%_5000 /Int (dpi.) ,\n%_2 /Bool (alis) ,\n%_-1 /Real (padd) ,\n%_3 /Int (colr) ,\n", + "%_0 /Int (dpi.) ,\n%_(0) /Bool (spot) ,\n%_2000 /Real (padd) ,\n%_1 /Int (colr) ,\n", + "%_150.5 /Int (dpi.) ,\n%_0.5 /Bool (mask) ,\n%_4.5 /Int (colr) ,\n", + ] { + assert_eq!(settings(bad), defaults, "{bad}"); + } +} + +/// Editing data whose header has the comments `header` before `%%EndComments`. +fn stream_with_header(header: &str, body: &str) -> String { + stream(body).replacen("%%EndComments", &format!("{header}%%EndComments"), 1) +} + +#[test] +fn the_header_gives_the_author_and_custom_colors() { + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let header = "%%For: (Ann \\(QA\\) Lee) (Studio)\n%%DocumentCustomColors: (Ink A)\n%%+ (Ink B)\n%%+ (Ink C)\n\ + %%CMYKCustomColor: 0.1 0.2 0.3 0.4 (Ink A)\n%%+ 0 1 0 0 (Ink B)\n%%RGBCustomColor: 1 0.5 0 (Ink C)\n\ + %%+ 2 0 0 (Too bright)\n%%CMYKCustomColor: 0.1 0.2 0.3 (Too few)\n%%+ 0 0 0 1 (Unended\n"; + let after = "%%CMYKCustomColor: 0 0 0 1 (After the header)\n%%For: (Someone else) ()\n"; + let r = read(stream_with_header(header, &format!("{after}{square}")).as_bytes()).unwrap(); + assert_eq!(r.doc.metadata.author, "Ann (QA) Lee"); + let ink = |name: &str| r.doc.swatches.iter().find(|s| s.name == name).map(|s| (s.paint.color(), s.global, s.spot)); + assert_eq!(ink("Ink A"), Some((Some(Color::cmyk(0.1, 0.2, 0.3, 0.4)), true, true))); + assert_eq!(ink("Ink B"), Some((Some(Color::cmyk(0.0, 1.0, 0.0, 0.0)), true, true))); + assert_eq!(ink("Ink C"), Some((Some(Color::rgb(1.0, 0.5, 0.0)), true, true))); + for name in ["Too bright", "Too few", "Unended", "After the header"] { + assert_eq!(ink(name), None, "{name}"); + } + // A color the art defines keeps its definition. + let used = layer(&format!("0.5 0 0 0 (Ink A) 0 x\n{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let r = read(stream_with_header(header, &used).as_bytes()).unwrap(); + let a: Vec<_> = r.doc.swatches.iter().filter(|s| s.name == "Ink A").map(|s| s.paint.color()).collect(); + assert_eq!(a, [Some(Color::cmyk(0.5, 0.0, 0.0, 0.0))]); + // A color with the name of a default swatch takes its place in a file without a palette, + // whether the header or the art defines it. + let red = "%%CMYKCustomColor: 0 0.5 0.5 0 (Red)\n%%+ 0 0 0 1 ([None])\n"; + let r = read(stream_with_header(red, &square).as_bytes()).unwrap(); + let reds: Vec<_> = r.doc.swatches.iter().filter(|s| s.name == "Red").map(|s| (s.paint.color(), s.spot)).collect(); + assert_eq!(reds, [(Some(Color::cmyk(0.0, 0.5, 0.5, 0.0)), true)]); + assert!(matches!(r.doc.swatch("[None]").map(|s| &s.paint), Some(Paint::None)), "a reserved name keeps its swatch"); + let art_red = layer(&format!("0 0.5 0.5 0 (Red) 0 x\n{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let r = read(stream(&art_red).as_bytes()).unwrap(); + let reds: Vec<_> = r.doc.swatches.iter().filter(|s| s.name == "Red").map(|s| (s.paint.color(), s.spot)).collect(); + assert_eq!(reds, [(Some(Color::cmyk(0.0, 0.5, 0.5, 0.0)), true)]); + // Without the comments: no author, the default swatches. + let plain = read_ok(&square).doc; + assert_eq!(plain.metadata.author, ""); + assert!(plain.swatches.iter().all(|s| !s.name.starts_with("Ink"))); +} + +#[test] +fn an_older_files_template_box_places_its_artboard() { + let old = + format!("%!PS-Adobe-3.0\n%AI5_ArtSize: 600 400\n%%TemplateBox: 300.5 199.5 300.5 199.5\n%%EndComments\n{}", layer("10 10 m\n20 20 L\nS\n")); + let r = read(old.as_bytes()).unwrap(); + assert_eq!(r.doc.artboards[0].rect, Rect::new(0.0, 0.0, 600.0, 400.0)); + assert_eq!(r.template, Some([300.5, 199.5, 300.5, 199.5])); +} + +#[test] +fn art_after_the_printers_crop_marks_reads() { + // GUARDS: the crop marks between `%AI3_BeginCrops` and `%AI3_EndCrops` are skipped, and the art + // after them is read. + let crops = format!("%AI3_BeginCrops\n{}S\n%AI3_EndCrops\n", rect_path(-20.0, -20.0, -10.0, -10.0)); + let doc = read_ok(&format!("{crops}{}", layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))))).doc; + assert_eq!(art(&doc).len(), 1); +} + +/// The document data `library` (a `variableSets` element) read with a layer holding a square: the +/// variables read and the notes about the library. +fn read_library(library: &str) -> (vectorcraft_doc::Variables, Vec) { + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let r = read_ok(&format!("{}{square}", vectorcraft_testkit::ai::variable_library_data(library))); + let notes = r.warnings.into_iter().filter(|w| w.contains("variable library")).collect(); + ((*r.doc.variables).clone(), notes) +} + +/// The note of a library read but for `n` entries. +fn partly_read(n: usize) -> String { + format!("the file's variable library was partly read (entries skipped: {n}): the Variables panel lists the rest") +} + +/// A variable library in the document data comes in with its variables in order, each of the kind +/// its trait gives (a variable without one is of unknown kind), and without bindings. A library +/// read whole gives no note. +#[test] +fn ai_variable_library_definitions() { + use vectorcraft_doc::VariableKind; + let (vars, notes) = read_library(&vectorcraft_testkit::ai::sample_variable_sets("none", &[])); + let kinds: Vec<(&str, VariableKind)> = vars.variables.iter().map(|v| (v.name.as_str(), v.kind)).collect(); + assert_eq!( + kinds, + [ + ("v_text", VariableKind::Text), + ("v_visible", VariableKind::Visibility), + ("v_file", VariableKind::Image), + ("v_graph", VariableKind::Graph), + ("v_unbound", VariableKind::Unknown) + ] + ); + assert!(vars.bindings.is_empty()); + assert!(notes.is_empty(), "{notes:?}"); + // The library of the testkit's text variables, and an empty one. + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let r = read_ok(&format!("{}{square}", vectorcraft_testkit::ai::variable_library(&["variable", "Team"], &["Home", "Away"]))); + let names: Vec<&str> = r.doc.variables.variables.iter().map(|v| v.name.as_str()).collect(); + assert_eq!(names, ["variable", "Team"], "{:?}", r.warnings); + assert_eq!(r.doc.variables.dataset("Away").and_then(|d| d.values.get("Team")), Some(&vectorcraft_doc::DataValue::Text("Away Team".into()))); + let r = read_ok(&format!("{}{square}", vectorcraft_testkit::ai::variable_library(&[], &[]))); + assert_eq!(*r.doc.variables, vectorcraft_doc::Variables::default()); + assert!(!r.warnings.iter().any(|w| w.contains("variable")), "{:?}", r.warnings); +} + +/// The objects a variable is bound to come with the library, each by the XML id its `docRef` gives, +/// in the order the library declares them: a variable bound to two objects is declared twice and +/// comes in once. A `docRef` that isn't an XML id is kept as unreadable, a declaration without one +/// binds nothing, and a second variable of the same name and another kind is left out with a note, +/// its binding counted as left out. +/// The objects read keep their XML ids; an id two objects have names neither of them. +#[test] +fn ai_variable_library_bindings() { + use vectorcraft_testkit::ai::{XmlValue, named, variable_library_data, xml_element, xml_node}; + let declare = |name: &str, t: &str, art: Option| { + let mut attributes = vec![("trait", XmlValue::Str(t)), ("varName", XmlValue::Unicode(name))]; + attributes.extend(art.map(|a| ("docRef", a))); + xml_node(1, "variable", XmlValue::Str(""), &attributes, &[]) + }; + let declared = vec![ + declare("v_shown", "visibility", Some(XmlValue::Raw("/XMLUIDREF : (one) ;"))), + declare("v_text", "textcontent", Some(XmlValue::Str("one"))), + declare("v_shown", "visibility", Some(XmlValue::Raw("/XMLUIDREF : (two) ;"))), + declare("v_shown", "textcontent", Some(XmlValue::Raw("/XMLUIDREF : (two) ;"))), + declare("v_free", "visibility", None), + ]; + let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]); + let library = variable_library_data(&xml_element("variableSets", &[], &[set])); + let square = |x: f64, id: &str| format!("{RED}{}f\n{}", rect_path(x, 0.0, x + 10.0, 10.0), named(id)); + let squares = layer(&[square(0.0, "one"), square(20.0, "two"), square(40.0, "twice"), square(60.0, "twice")].concat()); + let r = read_ok(&format!("{library}{squares}")); + let names: Vec<&str> = r.doc.variables.variables.iter().map(|v| v.name.as_str()).collect(); + assert_eq!(names, ["v_shown", "v_text", "v_free"]); + let refs: Vec<(&str, Option<&str>)> = r.bindings.iter().map(|b| (b.variable.as_str(), b.target.as_deref())).collect(); + assert_eq!(refs, [("v_shown", Some("one")), ("v_text", None), ("v_shown", Some("two"))]); + assert!(r.warnings.contains(&partly_read(1)), "{:?}", r.warnings); + // The object the declaration left out binds is counted for the bindings' note. + assert_eq!(r.bindings_skipped, 1); + // The reader doesn't bind them: the importer does, with the objects it keeps. + assert!(r.doc.variables.bindings.is_empty()); + let ids: Vec = art(&r.doc).iter().map(|n| n.id).collect(); + assert_eq!(r.xml_ids.get("one"), Some(&Some(ids[0]))); + assert_eq!(r.xml_ids.get("two"), Some(&Some(ids[1]))); + assert_eq!(r.xml_ids.get("twice"), Some(&None)); +} + +/// The bindings count against the library's 8 MB of names and values: each one keeps its +/// variable's name and its target. The declarations past that bind nothing and are counted as left +/// out. +#[test] +fn ai_variable_library_bindings_stay_within_the_byte_budget() { + use vectorcraft_testkit::ai::{XmlValue, variable_library_data, xml_element, xml_node}; + let (name, id) = ("é".repeat(255), "a".repeat(255)); + let target = format!("/XMLUIDREF : ({id}) ;"); + let declare = || { + xml_node( + 1, + "variable", + XmlValue::Str(""), + &[("trait", XmlValue::Str("visibility")), ("varName", XmlValue::Unicode(&name)), ("docRef", XmlValue::Raw(&target))], + &[], + ) + }; + let declared: Vec<_> = (0..11_500).map(|_| declare()).collect(); + let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]); + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let r = read_ok(&format!("{}{square}", variable_library_data(&xml_element("variableSets", &[], &[set])))); + assert_eq!(r.doc.variables.variables.len(), 1); + // The variable's name, then each binding's name and target. + let kept = ((8 << 20) - name.len()) / (name.len() + id.len()); + assert_eq!(r.bindings.len(), kept); + assert_eq!(r.bindings_skipped, 11_500 - kept); +} + +/// The data sets come in in order with their values: text of one paragraph per `p` element (`&`, +/// `<` and accented letters as they are), whether the objects show, and a linked file's path from +/// its URL, kept when it names no file. A variable of unknown kind has no value. +#[test] +fn ai_variable_library_dataset_values() { + use vectorcraft_doc::DataValue; + use vectorcraft_testkit::ai::{SAMPLE_MISSING_FILE, sample_variable_sets}; + let (vars, notes) = read_library(&sample_variable_sets("none", &[])); + assert!(notes.is_empty(), "{notes:?}"); + let names: Vec<&str> = vars.datasets.iter().map(|d| d.name.as_str()).collect(); + assert_eq!(names, ["ds_one", "ds_two", "ds_three"]); + let two = &vars.datasets[1].values; + assert_eq!(two.get("v_text"), Some(&DataValue::Text("line one\nline two & < é".into()))); + assert_eq!(two.get("v_visible"), Some(&DataValue::Visible(false))); + assert_eq!(two.get("v_file"), Some(&DataValue::Image(SAMPLE_MISSING_FILE.into()))); + assert!(!std::path::Path::new(SAMPLE_MISSING_FILE).exists()); + assert_eq!(two.len(), 3, "{two:?}"); + let one = &vars.datasets[0].values; + assert_eq!(one.get("v_text"), Some(&DataValue::Text("one".into()))); + assert_eq!(one.get("v_visible"), Some(&DataValue::Visible(true))); + assert_eq!(one.get("v_file"), Some(&DataValue::Image("/Users/test/Art (one)/tile-a.eps".into()))); +} + +/// A data set's value element can carry a namespace prefix. +#[test] +fn ai_variable_library_dataset_values_with_a_prefix() { + use vectorcraft_doc::DataValue; + use vectorcraft_testkit::ai::sample_variable_sets; + let library = sample_variable_sets("none", &[]).replace("%_(v_visible) /String (xmlnode-nodename)", "%_(c:v_visible) /String (xmlnode-nodename)"); + assert!(library.contains("c:v_visible")); + let (vars, notes) = read_library(&library); + assert!(notes.is_empty(), "{notes:?}"); + assert_eq!(vars.datasets[0].values.get("v_visible"), Some(&DataValue::Visible(true))); + assert_eq!(vars.datasets[1].values.get("v_visible"), Some(&DataValue::Visible(false))); +} + +/// The data set shown comes in as the active one, and the lock as it was set. +#[test] +fn ai_variable_library_state() { + use vectorcraft_testkit::ai::sample_variable_sets; + let (vars, notes) = read_library(&sample_variable_sets("variableAndTypes", &[])); + assert_eq!(vars.active_dataset.as_deref(), Some("ds_two")); + assert!(vars.locked, "{notes:?}"); + assert!(notes.is_empty(), "{notes:?}"); + let (vars, _) = read_library(&sample_variable_sets("none", &[])); + assert!(!vars.locked); + assert_eq!(vars.active_dataset.as_deref(), Some("ds_two")); + // A lock VectorCraft doesn't know reads as unlocked, with a note. + let (vars, notes) = read_library(&sample_variable_sets("everything", &[])); + assert!(!vars.locked); + assert_eq!(notes, [partly_read(1)]); + // A data set shown that isn't one of the library's leaves none active. + let library = sample_variable_sets("none", &[]).replace("%_(ds_two) /UnicodeString (xmlnode-nodevalue) ,\n%_2 /Int (xmlnode-nodetype) ,\n%_/Array :\n%_; (xmlnode-children) ,\n%_/Dictionary :\n%_; (xmlnode-attributes) ,\n%_; (i:activeDataSet)", "%_(ds_nine) /UnicodeString (xmlnode-nodevalue) ,\n%_2 /Int (xmlnode-nodetype) ,\n%_/Array :\n%_; (xmlnode-children) ,\n%_/Dictionary :\n%_; (xmlnode-attributes) ,\n%_; (i:activeDataSet)"); + assert!(library.contains("ds_nine")); + let (vars, notes) = read_library(&library); + assert_eq!(vars.active_dataset, None); + assert_eq!(vars.datasets.len(), 3, "{notes:?}"); +} + +/// A value that can't be read is left out with a note, and the values and data sets after it still +/// come in. +#[test] +fn ai_variable_library_bad_sibling() { + use vectorcraft_doc::DataValue; + use vectorcraft_testkit::ai::{XmlValue, sample_variable_sets, xml_element, xml_text}; + // A value for a variable the library doesn't declare, and a second value for `v_visible`. + let more = [xml_element("v_nope", &[], &[xml_text(XmlValue::Str("x"))]), xml_element("v_visible", &[], &[xml_text(XmlValue::Bool(true))])]; + let (vars, notes) = read_library(&sample_variable_sets("none", &more)); + assert_eq!(notes, [partly_read(2)]); + assert_eq!(vars.datasets[1].values.get("v_visible"), Some(&DataValue::Visible(false))); + assert_eq!(vars.datasets[2].values.get("v_text"), Some(&DataValue::Text("three".into()))); + assert_eq!(vars.active_dataset.as_deref(), Some("ds_two")); +} + +/// A graph variable comes in, but its values aren't read: each is left out with a note. +#[test] +fn ai_variable_library_graph_partial() { + use vectorcraft_doc::VariableKind; + use vectorcraft_testkit::ai::{XmlValue, sample_variable_sets, xml_element, xml_text}; + let graph = xml_element("v_graph", &[], &[xml_text(XmlValue::Str("a,b\n1,2"))]); + let (vars, notes) = read_library(&sample_variable_sets("none", &[graph])); + assert_eq!(notes, [partly_read(1)]); + assert_eq!(vars.variable("v_graph").map(|v| v.kind), Some(VariableKind::Graph)); + assert!(vars.datasets.iter().all(|d| !d.values.contains_key("v_graph"))); + assert_eq!(vars.datasets[1].values.len(), 3); +} + +/// Declarations, data sets and values that are malformed, repeated or past the caps are left out +/// and counted; a value is never read as one of another kind. A library nothing can be read from +/// says so. +#[test] +fn ai_variable_library_edge_cases() { + use vectorcraft_doc::{DataValue, VariableKind}; + use vectorcraft_testkit::ai::{XmlValue, xml_element, xml_node, xml_text}; + let set = |locked: &str, declared: Vec, rows: Vec| { + let sets = xml_element("v:sampleDataSets", &[], &rows); + xml_element("variableSets", &[], &[xml_element("variableSet", &[("locked", locked)], &[xml_element("variables", &[], &declared), sets])]) + }; + let var = |name: &str, t: &str| xml_element("variable", &[("varName", name), ("trait", t)], &[]); + let declared = vec![ + var("A", "textcontent"), + // The same name again, no name, an empty one, one that is too long, and an attribute node + // whose name isn't text. + var("A", "visibility"), + xml_element("variable", &[("trait", "textcontent")], &[]), + var(" ", "textcontent"), + var(&"n".repeat(256), "textcontent"), + xml_node(1, "variable", XmlValue::Str(""), &[("varName", XmlValue::Bool(true))], &[]), + // A trait VectorCraft doesn't know: unknown kind. + var("Fancy", "sparkle"), + var("Shown", "visibility"), + var("File", "fileref"), + // Something that isn't a variable. + xml_element("note", &[], &[]), + ]; + let rows = vec![ + xml_element( + "v:sampleDataSet", + &[("dataSetName", "One")], + &[ + xml_element("A", &[], &[xml_element("p", &[], &[xml_text(XmlValue::Unicode(" spaced "))]), xml_element("p", &[], &[])]), + // A value for the unknown kind, a visibility that is text, a file that is a relative + // path. + xml_element("Fancy", &[], &[xml_text(XmlValue::Str("x"))]), + xml_element("Shown", &[], &[xml_text(XmlValue::Str("true"))]), + xml_element("File", &[], &[xml_text(XmlValue::Str("art/tile.eps"))]), + ], + ), + // The same data set again, and one without a name. + xml_element("v:sampleDataSet", &[("dataSetName", "One")], &[]), + xml_element("v:sampleDataSet", &[], &[]), + xml_element( + "v:sampleDataSet", + &[("dataSetName", "Two")], + &[ + // Text whose paragraph holds an element, a file on a drive, a visibility of two texts. + xml_element("A", &[], &[xml_element("p", &[], &[xml_element("b", &[], &[])])]), + xml_element("File", &[], &[xml_text(XmlValue::Str("file:///C:/My%20Art/50%off.eps"))]), + xml_element("Shown", &[], &[xml_text(XmlValue::Bool(true)), xml_text(XmlValue::Bool(false))]), + ], + ), + ]; + let (vars, notes) = read_library(&set("none", declared, rows)); + let kinds: Vec<(&str, VariableKind)> = vars.variables.iter().map(|v| (v.name.as_str(), v.kind)).collect(); + assert_eq!( + kinds, + [("A", VariableKind::Text), ("Fancy", VariableKind::Unknown), ("Shown", VariableKind::Visibility), ("File", VariableKind::Image)] + ); + let names: Vec<&str> = vars.datasets.iter().map(|d| d.name.as_str()).collect(); + assert_eq!(names, ["One", "Two"]); + let one = &vars.datasets[0].values; + assert_eq!(one.get("A"), Some(&DataValue::Text(" spaced \n".into()))); + assert_eq!(one.len(), 1, "{one:?}"); + let two = &vars.datasets[1].values; + assert_eq!(two.get("File"), Some(&DataValue::Image("C:/My Art/50%off.eps".into()))); + assert_eq!(two.len(), 1, "{two:?}"); + // 6 declarations, 2 data sets and 5 values. + assert_eq!(notes, [partly_read(13)]); + + // Children that aren't an array: nothing can be read. + let broken = xml_element("variableSets", &[], &[xml_element("variableSet", &[], &[])]).replace( + "%_/Array :\n%_; (xmlnode-children) ,\n%_/Dictionary :\n%_; (xmlnode-attributes) ,\n%_; ,", + "%_/Dictionary :\n%_; (xmlnode-children) ,\n%_/Dictionary :\n%_; (xmlnode-attributes) ,\n%_; ,", + ); + assert!(broken.contains("%_/Dictionary :\n%_; (xmlnode-children)")); + let (vars, notes) = read_library(&broken); + assert_eq!(vars, vectorcraft_doc::Variables::default()); + assert_eq!(notes, ["the file's variable library couldn't be read: the Variables panel doesn't list it"]); + + // Past the caps: 256 variables and 1,000 data sets are kept. + let declared: Vec = (0..257).map(|i| var(&format!("v{i}"), "textcontent")).collect(); + let rows: Vec = (0..1001).map(|i| xml_element("v:sampleDataSet", &[("dataSetName", &format!("d{i}"))], &[])).collect(); + let (vars, notes) = read_library(&set("none", declared, rows)); + assert_eq!((vars.variables.len(), vars.datasets.len()), (256, 1000)); + assert_eq!(notes, [partly_read(2)]); + // A text longer than the library's 8 MiB is left out, and so is text past what is left of them. + let long = |name: &str, len: usize| { + let text = xml_element("p", &[], &[xml_text(XmlValue::Str(&"x".repeat(len)))]); + xml_element("v:sampleDataSet", &[("dataSetName", name)], &[xml_element("A", &[], &[text])]) + }; + let rows = vec![long("Big", (8 << 20) + 1), long("Half", 5 << 20), long("More", 4 << 20)]; + let (vars, notes) = read_library(&set("none", vec![var("A", "textcontent")], rows)); + let held: Vec<(&str, usize)> = vars.datasets.iter().map(|d| (d.name.as_str(), d.values.len())).collect(); + assert_eq!(held, [("Big", 0), ("Half", 1), ("More", 0)]); + assert_eq!(notes, [partly_read(2)]); + // Linked files on a network share, and on `localhost`. + let file = |name: &str, url: &str| { + xml_element("v:sampleDataSet", &[("dataSetName", name)], &[xml_element("File", &[], &[xml_text(XmlValue::Str(url))])]) + }; + let rows = vec![file("Share", "file://server/My%20Share/a.eps"), file("Local", "file://localhost/Users/test/a.eps")]; + let (vars, notes) = read_library(&set("none", vec![var("File", "fileref")], rows)); + let paths: Vec> = vars.datasets.iter().map(|d| d.values.get("File")).collect(); + assert_eq!(paths, [Some(&DataValue::Image("//server/My Share/a.eps".into())), Some(&DataValue::Image("/Users/test/a.eps".into()))]); + assert!(notes.is_empty(), "{notes:?}"); + // A library whose only node isn't a variable set. + let (_, notes) = read_library(&xml_element("variableSets", &[], &[xml_element("note", &[], &[])])); + assert_eq!(notes, ["the file's variable library couldn't be read: the Variables panel doesn't list it"]); + // A second variable set is left out. + let two_sets = xml_element("variableSets", &[], &[xml_element("variableSet", &[], &[]), xml_element("variableSet", &[], &[])]); + let (_, notes) = read_library(&two_sets); + assert_eq!(notes, ["the file's variable library couldn't be read: the Variables panel doesn't list it"]); +} + +/// When the layers can't be read, or reading stops before the library, [`variables`] still reads +/// it, for the file read from its PDF part. +#[test] +fn ai_variable_library_without_the_layers() { + use vectorcraft_testkit::ai::{sample_variable_sets, variable_library_data}; + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let library = variable_library_data(&sample_variable_sets("variableAndTypes", &[])); + let unread = stream(&format!("{library}{}", layer("1 Zz\n"))); assert!(read(unread.as_bytes()).is_err()); - assert_eq!(variables(unread.as_bytes()), read::VariableLibrary { variables: 1, data_sets: 2 }); - // The same when the reading stops before it reaches the library (at an `LB` without its layer). - let early = stream(&format!("LB\n{}{square}", variable_library(&["Team"], &["Home", "Away"]))); + let found = variables(unread.as_bytes()); + assert!(found.present && found.variables.locked && found.skipped == 0); + assert_eq!((found.variables.variables.len(), found.variables.datasets.len()), (5, 3)); + assert_eq!(found.variables.active_dataset.as_deref(), Some("ds_two")); + // The reading stops before it reaches the library (at an `LB` without its layer). + let early = stream(&format!("LB\n{library}{square}")); assert!(read(early.as_bytes()).is_err()); - assert_eq!(variables(early.as_bytes()), read::VariableLibrary { variables: 1, data_sets: 2 }); - assert_eq!(variables(stream(&square).as_bytes()), read::VariableLibrary::default()); + assert_eq!(variables(early.as_bytes()), found); + assert_eq!(variables(stream(&square).as_bytes()), read::VariableRead::default()); } #[test] @@ -628,6 +2544,44 @@ fn a_drawn_look_stands_for_its_object() { assert!(r.warnings.iter().any(|w| w.contains("drawn look (1)")), "{:?}", r.warnings); } +/// An object kept as its drawn look: the look (a group), then the object on `%_` lines and its style. +fn drawn_look_art() -> String { + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + format!( + "0 Ae\nu\n{RED}{}f\n{}S\nU\n%_{hidden_rect}n\n%_/ArtDictionary :\n%_/XMLUID : (Look) ; (AI10_ArtUID) ,\n%_;\n1 (Look style) XW\n", + rect_path(0.0, 0.0, 10.0, 10.0), + rect_path(0.0, 0.0, 10.0, 10.0), + ) +} + +/// A pattern's art holding an object kept as its drawn look counts in the note, as a symbol's does; +/// a definition the same name replaces later counts no longer. +#[test] +fn a_drawn_look_in_a_patterns_art_is_noted() { + let pattern = |art: &str| format!("%AI3_BeginPattern: (P)\n(P) 0 0 10 10\n0 A\n0 Xw\n{art}E\n%AI3_EndPattern\n"); + let looked = pattern(&drawn_look_art()); + let r = read_ok(&format!("{looked}{}", layer(""))); + assert_eq!(r.doc.patterns.len(), 1, "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("drawn look (1)")), "{:?}", r.warnings); + let plain = pattern(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let r = read_ok(&format!("{looked}{plain}{}", layer(""))); + assert_eq!(r.doc.patterns.len(), 1, "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + +/// A brush's art holding an object kept as its drawn look counts in the note once a brush that is +/// kept uses the art; art no brush uses brings no note. +#[test] +fn a_drawn_look_in_a_brushs_art_is_noted_when_a_brush_uses_it() { + let section = format!("%AI8_BeginBrushPattern\n(Dot art)\n0 A\n{}%AI8_EndBrushPattern\n", drawn_look_art()); + let r = read_ok(&format!("{section}{}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(""))); + let lib = vectorcraft_brush::library(&r.doc); + assert!(matches!(brush_named(&lib, "Spray"), vectorcraft_brush::BrushKind::Scatter(_)), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("drawn look (1)")), "{:?}", r.warnings); + let r = read_ok(&format!("{section}{}{}", plugin_object(CALLIGRAPHIC, "Nib", NIB), layer(""))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + /// Editing data with one layer holding an image: `matrix` (`[a b c d tx ty]`), its size, colour /// space, kind and alpha channels, its samples, and the size the data comment declares. fn image(matrix: &str, (w, h): (u32, u32), (space, kind, alpha): (&str, u32, u32), data: &[u8], declared: usize) -> Vec { @@ -659,6 +2613,58 @@ fn a_drawn_look_that_is_an_image_stands_for_its_object() { assert!(r.warnings.iter().any(|w| w.contains("drawn look (1)")), "{:?}", r.warnings); } +/// Samples in hex comment lines after `XI` (the version 7 specification's form) are read up to the +/// bytes the image needs; an image past the hard limits isn't read, whatever lines follow it. +#[test] +fn hex_comment_line_samples_are_read_up_to_the_image() { + let raster = |(w, h): (u32, u32), lines: &str| { + let s = format!( + "%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceRGB XN\n\ + [ 1 0 0 1 0 100 ] {w} {h} 0 Xh\n[ 1 0 0 1 0 100 ] 0 0 {w} {h} {w} {h} 8 3 0 0 0 0 XI\n{lines}%AI5_EndRaster\nN\nLB\n%AI5_EndLayer--\n" + ); + let mut out = stream("").into_bytes(); + let at = out.windows(14).position(|w| w == b"%%PageTrailer\n").unwrap(); + out.splice(at..at, s.into_bytes()); + out + }; + // 2 × 1: red, green, then digits past the image's six bytes. + let r = read(&raster((2, 1), "%FF00\n%0000FF\n%00FFFFFF\n")).unwrap(); + let img = pixels(&r.doc).0; + assert_eq!((img.get_pixel(0, 0).0, img.get_pixel(1, 0).0), ([255, 0, 0, 255], [0, 255, 0, 255])); + let r = read(&raster((70_000, 70_000), "%FF0000\n%00FF00\n")).unwrap(); + assert!(art(&r.doc).is_empty()); + assert!(r.warnings.iter().any(|w| w == "an image too large to read from the editing data was left out"), "{:?}", r.warnings); +} + +/// The name and opacity mask after an image follow the operators that end its raster: `XH`, the +/// versioned `Xr` and the `N` after `%AI5_EndRaster`. +#[test] +fn an_images_name_and_mask_follow_the_end_of_its_raster() { + let mask = "%_/ArtDictionary :\r\n%_/Mask :\r\n%_X=\r\n%_0 g\r\n%_0 0 m\r\n%_5 0 l\r\n%_5 5 l\r\n%_f\r\n%_X+\r\n%_ (Art) ,\r\n\ + %_0 /Bool (Clipping) ,\r\n%_0 /Bool (Inverted) ,\r\n%_0 /Bool (Disabled) ,\r\n%_1 /Bool (Linked) ,\r\n%_; (AI9_Mask) ,\r\n\ + %_/XMLUID : (Photo) ; (AI10_ArtUID) ,\r\n%_;\r\n%_\r\n"; + for tail in [ + "XH\r\n%AI5_EndRaster\r\nN\r\n", + "XH\r\n%AI17_Begin_Content_if_version_gt:24 17\r\n72 72 Xr\r\n%AI17_End_Versioned_Content\r\n%AI5_EndRaster\r\nN\r\n", + ] { + let mut data = image("[ 10 0 0 10 50 90 ]", (1, 1), ("DeviceRGB", 3, 0), &[255, 0, 0], 7); + let at = data.windows(6).position(|w| w == b"XH\r\n%A").unwrap(); + let end = data.windows(6).position(|w| w == b"N\r\nLB\r").unwrap() + 3; + data.splice(at..end, [tail, mask].concat().into_bytes()); + let r = read(&data).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Image(_)), "{:?}", a[0].kind); + assert_eq!(a[0].name.as_deref(), Some("Photo")); + assert!(a[0].extras().mask.is_some()); + } + // An operator of another kind in between ends the image: the name has no object. + let mut data = image("[ 10 0 0 10 50 90 ]", (1, 1), ("DeviceRGB", 3, 0), &[255, 0, 0], 7); + let end = data.windows(6).position(|w| w == b"N\r\nLB\r").unwrap() + 3; + data.splice(end..end, b"0 A\r\n%_/ArtDictionary :\r\n%_/XMLUID : (Photo) ; (AI10_ArtUID) ,\r\n%_;\r\n%_\r\n".to_vec()); + assert_eq!(art(&read(&data).unwrap().doc)[0].name, None); +} + fn pixels(doc: &Document) -> (image::RgbaImage, kurbo::Affine) { let a = art(doc); let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; @@ -693,6 +2699,61 @@ fn one_bit_images_read_each_channel() { assert_eq!((0..3).map(|x| img.get_pixel(x, 0).0[0]).collect::>(), [255, 0, 255]); } +/// A gray image `w` × 1 in hex with ImageMask `mask` and `bits` bits a pixel, after the fill `fill`. +fn masked_gray(fill: &str, bits: u32, mask: u32, w: u32, hex: &[u8]) -> Vec { + let text = String::from_utf8(image("[ 1 0 0 1 0 100 ]", (w, 1), ("DeviceGray", 1, 0), hex, hex.len())).unwrap(); + text.replacen(" 8 1 0 0 1 0 ", &format!(" {bits} 1 0 0 0 {mask} "), 1).replacen("(L) Ln\n", &format!("(L) Ln\n{fill}"), 1).into_bytes() +} + +/// ImageMask 1 on a 1-bit gray image: the image is colorized with the fill color, so its black +/// pixels take the color and its white ones are transparent. ImageMask 0 keeps the opaque image. +#[test] +fn image_masks_are_colorized_with_the_fill() { + // 4 × 1 at 1 bit: black, white, white, black (0110). + let r = read(&masked_gray("0 0 1 0 k\n", 1, 1, 4, b"60")).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let a = art(&r.doc); + let Some(Paint::Solid { color, .. }) = a[0].extras().colorize.as_deref() else { panic!("{:?}", a[0].extras().colorize) }; + assert_eq!(color.to_rgba8(1.0), Color::cmyk(0.0, 0.0, 1.0, 0.0).to_rgba8(1.0)); + let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; + let blob = &r.doc.images[&im.key]; + assert!(blob.gray_source().is_some_and(|g| !g.alpha), "an image a fill color can colorize"); + let img = pixels(&r.doc).0; + assert_eq!( + (0..4).map(|x| img.get_pixel(x, 0).0).collect::>(), + [[0, 0, 0, 255], [255, 255, 255, 255], [255, 255, 255, 255], [0, 0, 0, 255]] + ); + // How much of the color each pixel shows: the black ones only. + assert_eq!(blob.coverage().map(|c| c.2), Some(vec![255, 0, 0, 255])); + // A spot color keeps its swatch and tint. + let spot = "0 0 1 0 (Ink) 0.5 0 Xx\n"; + let a = art(&read(&masked_gray(spot, 1, 1, 4, b"60")).unwrap().doc); + assert!( + matches!(a[0].extras().colorize.as_deref(), Some(Paint::Solid { swatch: Some(s), tint, .. }) if s == "Ink" && (*tint - 0.5).abs() < 1e-6), + "{:?}", + a[0].extras().colorize + ); + // A fill that isn't a solid color (here a pattern) colorizes it black. + let patterned = String::from_utf8(masked_gray("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n", 1, 1, 4, b"60")).unwrap(); + let doc = read(patterned.replacen("%AI5_BeginLayer", &format!("{DOTS}%AI5_BeginLayer"), 1).as_bytes()).unwrap().doc; + let a = art(&doc); + let Some(Paint::Solid { color, swatch: None, .. }) = a[0].extras().colorize.as_deref() else { panic!("{:?}", a[0].extras().colorize) }; + assert_eq!(color.to_rgba8(1.0), Color::BLACK.to_rgba8(1.0)); + // An 8-bit gray image with ImageMask 1 opens as before, with no color. + let doc = read(&masked_gray("0 1 0 0 k\n", 8, 1, 2, b"00ff")).unwrap().doc; + assert!(art(&doc)[0].extras().colorize.is_none()); + assert_eq!(pixels(&doc).0.get_pixel(1, 0).0, [255, 255, 255, 255]); + // ImageMask 0: the opaque image, with no color. + let doc = read(&masked_gray("0 0 1 0 k\n", 1, 0, 4, b"60")).unwrap().doc; + assert!(art(&doc)[0].extras().colorize.is_none()); + assert_eq!(pixels(&doc).0.get_pixel(0, 0).0, [0, 0, 0, 255]); + // An RGB image can't take a color: ImageMask 1 leaves it as it is. + let text = String::from_utf8(image("[ 1 0 0 1 0 100 ]", (1, 1), ("DeviceRGB", 3, 0), b"ff0000", 6)).unwrap(); + let doc = read(text.replacen(" 8 3 0 0 1 0 ", " 8 3 0 0 0 1 ", 1).as_bytes()).unwrap().doc; + assert!(art(&doc)[0].extras().colorize.is_none()); + assert_eq!(pixels(&doc).0.get_pixel(0, 0).0, [255, 0, 0, 255]); +} + #[test] fn images_with_alpha_channels() { // RGB samples, then the alpha channel (not counted in the data's size). @@ -775,6 +2836,111 @@ fn a_rotated_image_is_placed_as_its_matrix_maps_it() { } } +/// A raster object in the version 7 form (§8): `%AI5_BeginRaster`, `head` (a link's `XG`, or +/// nothing), the operands `[matrix] 0 0 w h w h 8 3 0 0 0 0`, the operator `op` and `tail` (an +/// `XI`'s samples on `%` lines), `%AI5_EndRaster`. +fn raster7(head: &str, matrix: &str, (w, h): (u32, u32), op: &str, tail: &str) -> String { + format!("%AI5_File:\n%AI5_BeginRaster\n{head}{matrix} 0 0 {w} {h} {w} {h} 8 3 0 0 0 0 {op}\n{tail}%AI5_EndRaster\n") +} + +/// A linked 1-bit gray image with ImageMask 1 keeps the fill color as the color that colorizes it, +/// as an embedded one does. Other linked images have no color. +#[test] +fn linked_image_masks_are_colorized_with_the_fill() { + let m = "[ 1 0 0 1 0 0 ]"; + let linked = |bits_kind_mask: &str| { + let xf = raster7("(a.tif) 0 XG\n", m, (2, 2), "XF", "").replace(" 8 3 0 0 0 0 XF", &format!(" {bits_kind_mask} XF")); + let r = read(stream7(&layer7("L", &format!("0 0 1 0 (Ink) 0.5 0 Xx\n{xf}"))).as_bytes()).unwrap(); + let a = art(&r.doc); + assert!(matches!(&a[0].kind, NodeKind::Image(im) if im.link.is_some()), "{:?} {:?}", a, r.warnings); + a[0].extras().colorize.as_deref().cloned() + }; + assert!( + matches!(linked("1 1 0 0 0 1"), Some(Paint::Solid { swatch: Some(s), tint, .. }) if s == "Ink" && (tint - 0.5).abs() < 1e-6), + "a 1-bit image mask" + ); + assert_eq!(linked("1 1 0 0 0 0"), None, "ImageMask 0"); + assert_eq!(linked("8 1 0 0 0 1"), None, "8-bit gray"); + assert_eq!(linked("8 3 0 0 0 1"), None, "RGB"); +} + +/// A linked image in the version 7 form (§8.2, §8.3), `(path) modified XG` and then `XF` with no +/// samples, is a linked image of that file. The data keeps no pixels of it, so it shows a +/// placeholder over the place the matrix maps the image's pixels to, as an embedded image (`XI`) +/// of the same operands is placed. +#[test] +fn a_version_7_linked_image_shows_a_placeholder_where_the_image_is() { + let (s, c) = 30f64.to_radians().sin_cos(); + for m in [[2.0, 0.0, 0.0, 3.0, 100.0, 400.0], [3.0 * c, 3.0 * s, -2.0 * s, 2.0 * c, 40.0, 60.0]] { + let matrix = format!("[ {} ]", m.map(|v| v.to_string()).join(" ")); + let linked = raster7("(Macintosh HD:Images:photo.tif) 0 XG\n", &matrix, (10, 20), "XF", ""); + let embedded = raster7("", &matrix, (10, 20), "XI", &"%FF0000\n".repeat(200)); + let r = read(stream7(&layer7("L", &format!("{linked}{embedded}"))).as_bytes()).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 2, "{:?}", r.warnings); + let (NodeKind::Image(link), NodeKind::Image(emb)) = (&a[0].kind, &a[1].kind) else { panic!("{:?}", a) }; + assert_eq!(link.link.as_ref().map(|l| l.path.as_str()), Some("Macintosh HD:Images:photo.tif")); + assert_eq!(emb.link, None, "an image whose samples follow stays embedded"); + assert!(r.doc.images[&link.key].is_proxy(), "the placeholder is what a missing link shows"); + // The file's pixels, placed as the embedded image's are: relinking keeps that size. + assert_eq!((link.width, link.height, link.xf), (emb.width, emb.height, emb.xf)); + assert_eq!((link.width, link.height), (10, 20)); + assert_eq!(r.warnings.iter().filter(|w| *w == read::LINKED_PLACEHOLDERS).count(), 1, "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings); + } + // Images of other files keep images of their own, though each shows the same placeholder; two + // of one file share theirs. + let m = "[ 1 0 0 1 0 100 ]"; + let three = ["(a.tif) 0 XG\n", "(b.tif) 0 XG\n", "(a.tif) 0 XG\n"].map(|xg| raster7(xg, m, (2, 2), "XF", "")).concat(); + let r = read(stream7(&layer7("L", &three)).as_bytes()).unwrap(); + let keys: Vec<_> = art(&r.doc).iter().filter_map(|n| if let NodeKind::Image(im) = &n.kind { Some(im.key.clone()) } else { None }).collect(); + assert!(matches!(&keys[..], [a, b, c] if a != b && a == c), "{keys:?}"); + assert_eq!(r.doc.images.len(), 2); +} + +/// `XG` names the file of the `XF` after it only: an `XF` without a file name before it, after an +/// `XG` with operands of another shape or an empty path, or after an image that took the name, +/// is left out with a warning, as is one whose operands `XI` couldn't read. Of two `XG`s, the +/// second names the file. +#[test] +fn a_version_7_linked_image_without_its_file_name_is_left_out_with_a_warning() { + let m = "[ 1 0 0 1 0 100 ]"; + let embedded = raster7("() 1 XG\n", m, (1, 1), "XI", "%FF0000\n"); + for (what, src) in [ + ("no XG", raster7("", m, (2, 2), "XF", "")), + ("a name, not a string", raster7("/photo 0 XG\n", m, (2, 2), "XF", "")), + ("no modified flag", raster7("(a.tif) XG\n", m, (2, 2), "XF", "")), + ("an empty path", raster7("() 0 XG\n", m, (2, 2), "XF", "")), + ("taken by an embedded image", format!("{}{}", raster7("(a.tif) 0 XG\n", m, (1, 1), "XI", "%FF0000\n"), raster7("", m, (2, 2), "XF", ""))), + ("named in an earlier raster object", format!("%AI5_BeginRaster\n(a.tif) 0 XG\n%AI5_EndRaster\n{}", raster7("", m, (2, 2), "XF", ""))), + ("named outside a raster object", format!("(a.tif) 0 XG\n{}", raster7("", m, (2, 2), "XF", ""))), + ("too few operands", raster7("(a.tif) 0 XG\n", m, (2, 2), "XF", "").replace(" 8 3 0 0 0 0 XF", " 8 3 0 XF")), + ("no matrix", raster7("(a.tif) 0 XG\n", "", (2, 2), "XF", "")), + ("a matrix with no area", raster7("(a.tif) 0 XG\n", "[ 0 0 0 0 0 0 ]", (2, 2), "XF", "")), + ("no pixels", raster7("(a.tif) 0 XG\n", m, (0, 2), "XF", "")), + ("a side past the largest", raster7("(a.tif) 0 XG\n", m, (2_000_000, 2), "XF", "")), + ("samples of 7 bits", raster7("(a.tif) 0 XG\n", m, (2, 2), "XF", "").replace(" 8 3 0 0 0 0 XF", " 7 3 0 0 0 0 XF")), + ] { + let body = format!("{embedded}{src}"); + let r = read(stream7(&layer7("L", &body)).as_bytes()).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), body.matches(" XI\n").count(), "{what}: {:?}", r.warnings); + assert!(a.iter().all(|n| matches!(&n.kind, NodeKind::Image(im) if im.link.is_none())), "{what}: the embedded images only"); + let left_out = r.warnings.iter().filter(|w| *w == "an image VectorCraft can't read was left out").count(); + assert_eq!(left_out, 1, "{what}: {:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w == read::LINKED_PLACEHOLDERS), "{what}: {:?}", r.warnings); + } + // More pixels than an embedded image may have: no pixels are read, so the linked image comes in. + let r = read(stream7(&layer7("L", &raster7("(a.tif) 0 XG\n", m, (100_000, 100_000), "XF", ""))).as_bytes()).unwrap(); + let a = art(&r.doc); + assert!(matches!(&a[..], [n] if matches!(&n.kind, NodeKind::Image(im) if (im.width, im.height) == (100_000, 100_000))), "{a:?}"); + assert!(!r.warnings.iter().any(|w| w == "an image too large to read from the editing data was left out"), "{:?}", r.warnings); + let twice = raster7("(a.tif) 0 XG\n(b.tif) 0 XG\n", m, (2, 2), "XF", ""); + let r = read(stream7(&layer7("L", &twice)).as_bytes()).unwrap(); + let a = art(&r.doc); + assert!(matches!(&a[..], [n] if matches!(&n.kind, NodeKind::Image(im) if im.link.as_ref().is_some_and(|l| l.path == "b.tif"))), "{a:?}"); +} + /// CMYK images keep their ink amounts, as the file's PDF part keeps them, and an alpha channel /// becomes their opacity mask: a grayscale image over the image. #[test] @@ -833,6 +2999,543 @@ fn placed(visible: bool, matrix: &str, path: &str, preview: Option<&[u8]>, after s } +/// [`placed`]'s file with its placed file written as the copy of an object on `%_` lines (the +/// editable object whose drawn look comes before it): the lines from `%AI5_BeginPlace` to +/// `%AI5_EndPlace` start with `%_`, the versioned content's markers aside. The preview's header +/// line does too; its samples follow it raw. +fn hide_placed(data: &[u8]) -> Vec { + let find = |w: &[u8]| data.windows(w.len()).position(|x| x == w).unwrap(); + let (from, to) = (find(b"%AI5_BeginPlace"), find(b"%AI5_EndPlace\r") + 14); + let mut out = data[..from].to_vec(); + for line in data[from..to].split(|b| *b == b'\r') { + if !line.is_empty() && !line.starts_with(b"%AI17_") { + out.extend_from_slice(b"%_"); + } + out.extend_from_slice(line); + out.push(b'\r'); + } + out.pop(); + out.extend_from_slice(&data[to..]); + out +} + +#[test] +fn a_placed_file_on_commented_lines_is_read() { + // Its `%_%AI5_BeginPlace` was dropped as a comment after `%_`, so the `~` that ends it was an + // operator the reader didn't know, and the whole file came in as its PDF part; and its + // preview, whose header starts with `%_`, wasn't read. + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let data = hide_placed(&placed(true, "[5 0 0 -5 0 200]", "/pics/photo.png", Some(&preview), "")); + assert!(data.windows(18).any(|w| w == b"%_%AI5_BeginPlace\r"), "{}", String::from_utf8_lossy(&data)); + let r = read(&data).unwrap(); + let a = art(&r.doc); + let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!((im.link.as_ref().map(|l| l.path.as_str()), im.width, im.height), (Some("/pics/photo.png"), 2, 1)); + let (img, _) = pixels(&r.doc); + assert_eq!((img.get_pixel(0, 0).0, img.get_pixel(1, 0).0), ([255, 0, 0, 255], [0, 127, 0, 128]), "its preview"); +} + +/// [`placed`]'s file whose relative folder section holds `folder` (written as it is, parentheses +/// included) instead of `()`. +fn placed_in(folder: &str, path: &str, preview: &[u8]) -> Vec { + let data = placed(true, "[5 0 0 -5 0 200]", path, Some(preview), ""); + let (at, len) = (data.windows(4).position(|w| w == b"\r()\r").unwrap(), 4); + let mut out = data[..at].to_vec(); + out.extend_from_slice(format!("\r{folder}\r").as_bytes()); + out.extend_from_slice(&data[at + len..]); + out +} + +/// The relative path of the one linked image of `data`. +fn relative_of(data: &[u8]) -> Option { + let r = read(data).unwrap(); + let a = art(&r.doc); + let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some("/old/place/src/photo.png")); + im.link.as_ref().and_then(|l| l.relative.clone()) +} + +#[test] +fn a_placed_file_keeps_its_folder_relative_to_the_document() { + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let path = "/old/place/src/photo.png"; + assert_eq!(relative_of(&placed_in("(src/)", path, &preview)).as_deref(), Some("src/photo.png")); + assert_eq!(relative_of(&placed_in("(../art)", path, &preview)).as_deref(), Some("../art/photo.png")); + assert_eq!(relative_of(&placed_in(r"(..\\art\\)", path, &preview)).as_deref(), Some("../art/photo.png")); + assert_eq!(relative_of(&placed_in("( art /)", path, &preview)).as_deref(), Some(" art /photo.png"), "spaces are part of names"); + // On `%_` lines too. + assert_eq!(relative_of(&hide_placed(&placed_in("(src/)", path, &preview))).as_deref(), Some("src/photo.png")); + // An empty folder is the document's own: the file's name. + assert_eq!(relative_of(&placed_in("()", path, &preview)).as_deref(), Some("photo.png")); + // An absolute folder, one too long or not a string: the path alone, and the file still opens. + let long = format!("({})", "a/".repeat(3000)); + for folder in ["(/elsewhere/)", "(C:\\\\art\\\\)", long.as_str(), "12", "/src"] { + assert_eq!(relative_of(&placed_in(folder, path, &preview)), None, "{folder}"); + } + // A section that doesn't end leaves the folder unread. + let data = placed_in("(src/)", path, &preview); + let end = data.windows(27).position(|w| w == b"%AI28_EndPlacedRelativePath").unwrap(); + let mut cut = data[..end].to_vec(); + cut.extend_from_slice(b"%AI28_Other"); + cut.extend_from_slice(&data[end + 27..]); + assert_eq!(relative_of(&cut), None); +} + +#[test] +fn hidden_placed_file_ended_by_comment_stays_hidden() { + let mut data = hide_placed(&placed(true, "[5 0 0 -5 0 200]", "/pics/photo.png", None, "")); + let end = data.windows(4).position(|w| w == b"%_~\r").unwrap(); + data.drain(end..end + 4); + let r = read(&data).unwrap(); + assert!(art(&r.doc).is_empty()); + assert!(r.unread.is_empty(), "hidden placement has no shown placeholder"); + assert!(r.hidden_unread.contains("placed files")); +} + +#[test] +fn previewless_placement_records_box_corner_as_alternative() { + let mut data = placed(true, "[1 0 0 -1 -7970 8070]", "missing.png", None, ""); + let at = data.windows(15).position(|w| w == b"%AI5_BeginLayer").unwrap(); + data.splice(at..at, *b"%AI3_TemplateBox: 100 50 100 50\n"); + let r = read(&data).unwrap(); + assert_unread(&r, "placed files"); + assert_eq!(r.unread_elsewhere.len(), 1); + assert_eq!(r.unread_elsewhere[0].0, r.unread[0].0); + assert_ne!(r.unread_elsewhere[0].1, r.doc.node(r.unread[0].0).unwrap().visual_bounds().unwrap()); +} + +/// Editing data in the version 7 format (§2): art size 200 × 100 around the template box's centre +/// (0, 0), then `body`. +fn placed_stream7(body: &str) -> String { + format!( + "%!PS-Adobe-3.0\n%%Creator: test\n%%BoundingBox: 0 0 200 100\n%AI5_FileFormat 2.0\n%AI5_ArtSize: 200 100\n\ + %AI3_TemplateBox: 0 0 0 0\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n{body}\n\ + %%PageTrailer\nshowpage\n%%Trailer\n%%EOF\n" + ) +} + +/// One layer of the version 7 format (ten operands before `Lb`), showing or not, holding `art`. +fn placed_layer7(visible: bool, art: &str) -> String { + format!("%AI5_BeginLayer\n{} 1 1 1 0 0 1 79 128 255 Lb\n(L) Ln\n0 A\n{art}\nLB\n%AI5_EndLayer--\n", u8::from(visible)) +} + +fn placed_read7(visible: bool, art: &str) -> Result { + read(placed_stream7(&placed_layer7(visible, art)).as_bytes()) +} + +/// The placed file's box (`llx lly urx ury`) taken by `matrix` into the document: where the +/// version 7 format puts it (§16.1). +fn placed_box(r: &Structure, matrix: [f64; 6], b: [f64; 4]) -> Rect { + (r.to_doc * kurbo::Affine::new(matrix)).transform_rect_bbox(Rect::new(b[0], b[1], b[2], b[3])) +} + +/// The placeholder's bounds and the other bounds [`Structure::unread_elsewhere`] keeps for it. +fn placeholder_boxes(r: &Structure) -> Vec { + let id = r.unread[0].0; + let mut boxes = vec![r.doc.node(id).unwrap().visual_bounds().unwrap()]; + boxes.extend(r.unread_elsewhere.iter().filter(|(o, _)| *o == id).map(|(_, b)| *b)); + boxes +} + +fn near(a: Rect, b: Rect) -> bool { + [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-6) +} + +#[test] +fn version7_placed_files_are_read_without_a_begin_place() { + // `~` was an operator the reader didn't know, so the file's layers weren't read. + let matrices = [ + [1.0, 0.0, 0.0, 1.0, 10.0, 20.0], + [2.0, 0.0, 0.0, 0.5, -5.0, 3.0], + [-1.29904, 0.75, 0.375, 0.649519, 125.8461, 159.7668], + [-1.0, 0.0, 0.0, 1.0, 100.0, 0.0], + ]; + for m in matrices { + for extra in ["", " 4 4 0"] { + let [a, b, c, d, e, f] = m; + let body = format!( + "[{a} {b} {c} {d} {e} {f}] 10 20 50 50{extra} (art.eps) `\n%%IncludeFile: art.eps\n~\n{RED}{}f", + rect_path(0.0, 0.0, 5.0, 5.0) + ); + let r = placed_read7(true, &body).unwrap_or_else(|e| panic!("{m:?}{extra}: {e}")); + assert_eq!(art_kinds(&r.doc), ["path", "path"], "{m:?}{extra}: a placeholder, then the path after it"); + assert_unread(&r, "placed files"); + let want = placed_box(&r, m, [10.0, 20.0, 50.0, 50.0]); + assert!(placeholder_boxes(&r).iter().any(|b| near(*b, want)), "{m:?}{extra}: {:?} {want:?}", placeholder_boxes(&r)); + } + } +} + +/// The kinds of the first layer's objects. +fn art_kinds(doc: &Document) -> Vec<&'static str> { + art(doc) + .iter() + .map(|n| match n.kind { + NodeKind::Group { .. } => "group", + NodeKind::Path { .. } => "path", + NodeKind::Image(_) => "image", + _ => "other", + }) + .collect() +} + +#[test] +fn version7_placed_file_included_whole_is_read() { + // The included document's operators, a `~`, a nested document and counted data in it aren't + // the editing data's. + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor frobnicate ~\n\ + %%BeginDocument: inner.eps\n~\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%EOF\n"; + let body = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\n"); + let r = placed_read7(true, &body).unwrap(); + assert_eq!(art_kinds(&r.doc), ["path"]); + assert_unread(&r, "placed files"); + // One that doesn't end leaves the layer without its end. + let cut = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}~\n"); + assert!(placed_read7(true, &cut).is_err()); +} + +#[test] +fn version7_placed_file_without_a_file_is_read() { + // `` ` `` followed by `~`: a placed file whose file isn't there. + let r = placed_read7(true, "[1 0 0 1 10 20] 10 20 50 50 (gone.eps) `\n~\n").unwrap(); + assert_unread(&r, "placed files"); + // In a hidden layer it is left out, with a note. + let r = placed_read7(false, "[1 0 0 1 10 20] 10 20 50 50 (gone.eps) `\n%%IncludeFile: gone.eps\n~\n").unwrap(); + assert!(r.unread.is_empty() && art(&r.doc).is_empty()); + assert!(r.hidden_unread.contains("placed files"), "{:?}", r.hidden_unread); +} + +#[test] +fn version7_placed_file_in_a_group_keeps_its_place() { + // In a group, the group is what isn't read. + let body = format!("u\n{RED}{}f\n[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%IncludeFile: art.eps\n~\nU\n", rect_path(0.0, 0.0, 5.0, 5.0)); + let r = placed_read7(true, &body).unwrap(); + assert_eq!(art_kinds(&r.doc), ["group"]); + assert_eq!(r.unread.iter().map(|(id, kinds)| (*id, kinds.clone())).collect::>(), [(art(&r.doc)[0].id, vec!["placed files".to_string()])]); + // A locked one keeps its lock. + let r = placed_read7(true, "1 A\n[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%IncludeFile: art.eps\n~\n").unwrap(); + assert_unread(&r, "placed files"); + assert!(r.doc.node(r.unread[0].0).unwrap().locked); +} + +#[test] +fn placed_file_operands_of_another_shape_arent_read() { + for operands in [ + // Five numbers in the matrix, three box numbers, two extra numbers, no path, a name for the + // path, a number that isn't finite. + "[1 0 0 1 10] 10 20 50 50 (a.eps)", + "[1 0 0 1 10 20] 10 20 50 (a.eps)", + "[1 0 0 1 10 20] 10 20 50 50 4 4 (a.eps)", + "[1 0 0 1 10 20] 10 20 50 50", + "[1 0 0 1 10 20] 10 20 50 50 /a.eps", + "[1 0 0 1 10 20] 10 20 50 1e999 (a.eps)", + ] { + // Without a box to put a placeholder in, the file isn't read. + let e = placed_read7(true, &format!("{operands} `\n~\n")).err().unwrap_or_default(); + assert!(e.contains("placed files"), "{operands}: {e}"); + } +} + +#[test] +fn a_placed_file_with_a_zero_area_box_or_a_second_tick_isnt_read() { + for body in [ + "[1 0 0 1 10 20] 10 20 10 50 (a.eps) `\n~\n", + // The operands of a second `` ` `` before `~` don't take the first one's place. + "[1 0 0 1 10 20] 10 20 50 50 (a.eps) `\n[1 0 0 1 0 0] 0 0 5 5 (b.eps) `\n~\n", + ] { + let e = placed_read7(true, body).err().unwrap_or_default(); + assert!(e.contains("placed files"), "{body}: {e}"); + } + // A `%AI5_BeginPlace` while one is open: the open one isn't read either. + let body = "%AI5_BeginPlace\n[1 0 0 1 10 20] 10 20 50 50 (a.eps) `\n%AI5_BeginPlace\n[1 0 0 1 0 0] 0 0 5 5 (b.eps) `\n~\n%AI5_EndPlace\n"; + assert!(placed_read7(true, body).err().unwrap_or_default().contains("placed files")); + let r = placed_read7(false, body).unwrap(); + assert!(r.hidden_unread.contains("placed files") && art(&r.doc).is_empty()); + // One that no `~` ends isn't read; a hidden one, or one on a layer that doesn't show, is left + // out with a note. + let open = "[1 0 0 1 10 20] 10 20 50 50 (a.eps) `\n"; + assert!(placed_read7(true, &format!("%AI5_BeginPlace\n{open}")).err().unwrap_or_default().contains("placed files")); + assert!(placed_read7(true, open).err().unwrap_or_default().contains("placed files")); + for (visible, art) in [(true, format!("%_%AI5_BeginPlace\n%_{open}")), (true, format!("%_{open}")), (false, open.to_string())] { + let r = placed_read7(visible, &art).unwrap_or_else(|e| panic!("{art}: {e}")); + assert!(r.hidden_unread.contains("placed files"), "{art}: {:?}", r.hidden_unread); + } +} + +#[test] +fn a_tilde_without_a_placed_file_is_an_unknown_operator() { + let e = placed_read7(true, "~\n").err().unwrap_or_default(); + assert!(e.contains('~'), "{e}"); + // An apostrophe isn't the placed file's operator. + let e = placed_read7(true, "[1 0 0 1 10 20] 10 20 50 50 (a.eps) '\n~\n").err().unwrap_or_default(); + assert!(e.contains('\''), "{e}"); +} + +/// A previewless locked placement keeps its edit lock on the page-art placeholder. +#[test] +fn previewless_placement_placeholder_inherits_lock() { + let mut data = placed(true, "[5 0 0 -5 0 200]", "missing.png", None, ""); + let at = data.windows(15).position(|w| w == b"%AI5_BeginPlace").unwrap(); + data.splice(at..at, *b"1 A\n"); + let result = read(&data).unwrap(); + assert_unread(&result, "placed files"); + let node = result.doc.node(result.unread[0].0).unwrap(); + assert!(node.locked); + assert!(node.visible); +} + +/// A placed file's XML id names the linked image it comes in as, for the variable library's +/// bindings. +#[test] +fn a_placed_files_xml_id_names_its_image() { + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let name = "%_/ArtDictionary :\r%_/XMLUID : (photo_x5F_1) ; (AI10_ArtUID) ,\r%_;\r"; + let r = read(&placed(true, "[5 0 0 -5 0 200]", "/pics/photo.png", Some(&preview), name)).unwrap(); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Image(_)), "{:?}", a[0].kind); + assert_eq!(r.xml_ids.get("photo_x5F_1"), Some(&Some(a[0].id))); +} + +/// The XML ids kept stay within `MAX_XML_ID_BYTES` in all: an id that would pass it is left out, +/// and a shorter one after it still fits. +#[test] +fn xml_ids_stay_within_their_byte_budget() { + use vectorcraft_doc::NodeId; + let (mut ids, mut bytes) = (std::collections::HashMap::new(), 0); + super::read::remember_xml_id(&mut ids, &mut bytes, "a".repeat(super::read::MAX_XML_ID_BYTES - 4), NodeId(1)); + super::read::remember_xml_id(&mut ids, &mut bytes, "long_id".into(), NodeId(2)); + super::read::remember_xml_id(&mut ids, &mut bytes, "id_2".into(), NodeId(3)); + super::read::remember_xml_id(&mut ids, &mut bytes, "id_2".into(), NodeId(4)); + assert_eq!(ids.len(), 2); + assert!(!ids.contains_key("long_id")); + assert_eq!(ids.get("id_2"), Some(&None), "two objects with one id are neither of them that id's"); + assert_eq!(bytes, super::read::MAX_XML_ID_BYTES); +} + +/// Placed files of other paths keep images of their own though their previews are alike; two of +/// one path share theirs. +#[test] +fn placed_files_of_other_paths_keep_images_of_their_own() { + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let object = |path: &str| { + let data = placed(true, "[5 0 0 -5 0 200]", path, Some(&preview), ""); + let find = |s: &[u8]| data.windows(s.len()).position(|w| w == s).unwrap(); + data[find(b"%AI5_BeginPlace")..find(b"%AI5_EndPlace\r") + 14].to_vec() + }; + let mut data = placed(true, "[5 0 0 -5 0 200]", "a.png", Some(&preview), ""); + let end = data.windows(14).position(|w| w == b"%AI5_EndPlace\r").unwrap() + 14; + data.splice(end..end, [object("b.png"), object("a.png")].concat()); + let r = read(&data).unwrap(); + let keys: Vec<_> = art(&r.doc).iter().filter_map(|n| if let NodeKind::Image(im) = &n.kind { Some(im.key.clone()) } else { None }).collect(); + assert!(matches!(&keys[..], [a, b, c] if a != b && a == c), "{keys:?}"); + assert_eq!(r.doc.images.len(), 2); +} + +/// A placed file followed by the dictionary `numbers` (`value /Int (key)` lines, on `%_` lines). +fn placed_with(numbers: &[(&str, &str)]) -> Structure { + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let entries: String = numbers.iter().map(|(key, v)| format!("%_{v} /Int ({key}) ,\r")).collect(); + let dictionary = format!("%_/ArtDictionary :\r{entries}%_;\r%_\r"); + read(&placed(true, "[5 0 0 -5 0 200]", "/art/flyer.pdf", Some(&preview), &dictionary)).unwrap() +} + +#[test] +fn a_placed_files_dictionary_names_the_page_and_box_it_shows() { + use vectorcraft_doc::PageBox; + const PAGE: &str = "AI11 PlacedPDFPageIndex"; + const CROP: &str = "AI11 PlacedPDFCropTo"; + for (crop, bounding, page_box) in [ + ("0", false, PageBox::Art), + ("1", false, PageBox::Crop), + ("2", false, PageBox::Trim), + ("3", false, PageBox::Bleed), + ("4", false, PageBox::Media), + ("5", true, PageBox::Crop), + ] { + let r = placed_with(&[(PAGE, "3"), (CROP, crop)]); + let a = art(&r.doc); + let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(r.placed_pages.len(), 1, "{crop}"); + let p = r.placed_pages[0]; + assert_eq!((p.id, p.page, p.bounding, p.page_box, p.size), (a[0].id, 3, bounding, page_box, (4.0, 2.0)), "{crop}"); + assert_eq!(r.doc.images.keys().collect::>(), [&im.key], "{crop}: the preview is stored once, under the image's key"); + assert!(r.doc.images[&im.key].is_proxy(), "{crop}"); + } + // One entry alone: the first page, or the page's crop box. + let r = placed_with(&[(CROP, "4")]); + assert_eq!((r.placed_pages[0].page, r.placed_pages[0].page_box), (1, PageBox::Media)); + let r = placed_with(&[(PAGE, "2")]); + assert_eq!((r.placed_pages[0].bounding, r.placed_pages[0].page_box), (false, PageBox::Crop)); +} + +#[test] +fn a_placed_files_dictionary_it_cant_read_leaves_a_linked_image() { + const PAGE: &str = "AI11 PlacedPDFPageIndex"; + const CROP: &str = "AI11 PlacedPDFCropTo"; + let plain = placed_with(&[]); + let plain_key = { + let a = art(&plain.doc); + let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; + im.key.clone() + }; + assert!(plain.placed_pages.is_empty()); + for entries in [ + vec![(PAGE, "0"), (CROP, "4")], + vec![(PAGE, "-1"), (CROP, "4")], + vec![(PAGE, "1.5"), (CROP, "4")], + vec![(PAGE, "1e30"), (CROP, "4")], + vec![(PAGE, "2"), (CROP, "6")], + vec![(PAGE, "2"), (CROP, "-1")], + vec![(PAGE, "2"), (CROP, "0.5")], + vec![(PAGE, "(2)"), (CROP, "4")], + vec![(PAGE, "2"), (CROP, "(4)")], + vec![(PAGE, "(2)")], + ] { + let r = placed_with(&entries); + assert!(r.placed_pages.is_empty(), "{entries:?}"); + let a = art(&r.doc); + let NodeKind::Image(im) = &a[0].kind else { panic!("{entries:?}: {:?}", a[0].kind) }; + assert_eq!((im.key.as_str(), im.link.as_ref().and_then(|l| l.page)), (plain_key.as_str(), None), "{entries:?}"); + } +} + +/// The dictionaries of the art in a placed file's opacity mask, read inside its own dictionary, +/// don't speak for the placed file. +#[test] +fn a_placed_files_mask_art_leaves_its_page_to_the_placed_files_dictionary() { + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let dictionary = "%_/ArtDictionary :\r%_/Mask :\r%_X=\r%_0 g\r%_0 0 m\r%_5 0 l\r%_5 -5 l\r%_f\r\ + %_/ArtDictionary :\r%_/XMLUID : (Inner) ; (AI10_ArtUID) ,\r%_;\r%_\r%_X+\r%_ (Art) ,\r%_; (AI9_Mask) ,\r\ + %_2 /Int (AI11 PlacedPDFPageIndex) ,\r%_4 /Int (AI11 PlacedPDFCropTo) ,\r%_;\r%_\r"; + let r = read(&placed(true, "[5 0 0 -5 0 200]", "/art/flyer.pdf", Some(&preview), dictionary)).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:?}"); + assert!(a[0].extras().mask.is_some(), "the mask is read"); + assert_eq!(r.placed_pages.len(), 1); + assert_eq!((r.placed_pages[0].id, r.placed_pages[0].page_box), (a[0].id, vectorcraft_doc::PageBox::Media)); +} + +/// A placed file in a placed file's opacity mask, read before the outer file's dictionary closes, +/// leaves the outer file's page to that dictionary. +#[test] +fn a_placed_file_in_a_placed_files_mask_leaves_the_outer_files_page() { + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let mut inner = + b"%_%AI5_BeginPlace\r%_%%FileType: 1\r%_[5 0 0 -5 0 200] 10 20 14 22 4 4 0\r%_(/art/mask.pdf)`\r%_%AI26_BeginPlacedObjectPreview\r%_" + .to_vec(); + inner.extend_from_slice(&preview); + inner.extend_from_slice( + b"\r%_%AI26_EndPlacedObjectPreview\r%_~\r%_%AI5_EndPlace\r%_/ArtDictionary :\r%_5 /Int (AI11 PlacedPDFPageIndex) ,\r%_;\r%_\r", + ); + let mut dictionary = b"%_/ArtDictionary :\r%_/Mask :\r%_X=\r".to_vec(); + dictionary.extend_from_slice(&inner); + dictionary + .extend_from_slice(b"%_X+\r%_ (Art) ,\r%_; (AI9_Mask) ,\r%_2 /Int (AI11 PlacedPDFPageIndex) ,\r%_4 /Int (AI11 PlacedPDFCropTo) ,\r%_;\r%_\r"); + let data = placed(true, "[5 0 0 -5 0 200]", "/art/flyer.pdf", Some(&preview), "@@DICT@@"); + let at = data.windows(8).position(|x| x == b"@@DICT@@").unwrap(); + let data = [&data[..at], &dictionary[..], &data[at + 8..]].concat(); + let r = read(&data).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:?}"); + assert!(a[0].extras().mask.is_some(), "the mask is read"); + let outer: Vec<_> = r.placed_pages.iter().filter(|p| p.id == a[0].id).collect(); + assert_eq!(outer.len(), 1, "{:?}", r.placed_pages); + assert_eq!((outer[0].page, outer[0].page_box), (2, vectorcraft_doc::PageBox::Media)); + assert!(r.placed_pages.iter().any(|p| p.id != a[0].id && p.page == 5), "the inner one names its own page: {:?}", r.placed_pages); +} + +/// A placed file in a placed file's opacity mask that shows the same file with no page of its own +/// keeps the preview they share when the outer one's dictionary names a page. +#[test] +fn a_placed_file_in_a_placed_files_mask_keeps_the_preview_they_share() { + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let mut dictionary = + b"%_/ArtDictionary :\r%_/Mask :\r%_X=\r%_%AI5_BeginPlace\r%_%%FileType: 1\r%_[5 0 0 -5 0 200] 10 20 14 22 4 4 0\r%_(/art/flyer.pdf)`\r\ + %_%AI26_BeginPlacedObjectPreview\r%_" + .to_vec(); + dictionary.extend_from_slice(&preview); + dictionary.extend_from_slice( + b"\r%_%AI26_EndPlacedObjectPreview\r%_~\r%_%AI5_EndPlace\r%_X+\r%_ (Art) ,\r%_; (AI9_Mask) ,\r\ + %_2 /Int (AI11 PlacedPDFPageIndex) ,\r%_;\r%_\r", + ); + let data = placed(true, "[5 0 0 -5 0 200]", "/art/flyer.pdf", Some(&preview), "@@DICT@@"); + let at = data.windows(8).position(|x| x == b"@@DICT@@").unwrap(); + let data = [&data[..at], &dictionary[..], &data[at + 8..]].concat(); + let r = read(&data).unwrap(); + let a = art(&r.doc); + assert_eq!(r.placed_pages.len(), 1, "{:?}", r.placed_pages); + let mask = a[0].extras().mask.clone().expect("the mask is read"); + let mut keys = vec![]; + mask.art.walk(&mut |n| { + if let NodeKind::Image(im) = &n.kind { + keys.push(im.key.clone()); + } + }); + let [inner] = &keys[..] else { panic!("{keys:?}") }; + assert!(r.doc.images.contains_key(inner), "the mask's image keeps its preview"); + let NodeKind::Image(outer) = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert!(r.doc.images.contains_key(&outer.key) && outer.key != *inner); +} + +#[test] +fn a_placed_file_with_its_box_written_backward_stays_a_linked_image() { + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let dictionary = "%_/ArtDictionary :\r%_2 /Int (AI11 PlacedPDFPageIndex) ,\r%_4 /Int (AI11 PlacedPDFCropTo) ,\r%_;\r%_\r"; + let data = placed(true, "[5 0 0 -5 0 200]", "/art/flyer.pdf", Some(&preview), dictionary); + let at = data.windows(11).position(|x| x == b"10 20 14 22").unwrap(); + let data = [&data[..at], b"14 22 10 20", &data[at + 11..]].concat(); + let r = read(&data).unwrap(); + assert!(r.placed_pages.is_empty()); + let a = art(&r.doc); + let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(im.link.as_ref().and_then(|l| l.page), None); +} + +#[test] +fn only_the_dictionary_right_after_a_placed_file_names_its_page() { + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let dictionary = "%_/ArtDictionary :\r%_2 /Int (AI11 PlacedPDFPageIndex) ,\r%_4 /Int (AI11 PlacedPDFCropTo) ,\r%_;\r%_\r"; + // After another object: that object's dictionary. Art with such a dictionary stays art. + let after = format!("0 g\r0 0 m\r5 0 l\r5 5 l\rf\r{dictionary}"); + let r = read(&placed(true, "[5 0 0 -5 0 200]", "/art/flyer.pdf", Some(&preview), &after)).unwrap(); + assert!(r.placed_pages.is_empty()); + assert_eq!(art(&r.doc).len(), 2); + // A second dictionary after the first: the first one spoke for the placed file. + let after = format!("%_/ArtDictionary :\r%_(Photo) /String (AIArtName) ,\r%_;\r%_\r{dictionary}"); + let r = read(&placed(true, "[5 0 0 -5 0 200]", "/art/flyer.pdf", Some(&preview), &after)).unwrap(); + assert!(r.placed_pages.is_empty()); + // Without a placed file before it, nothing happens. + let r = read(stream(&layer(&format!("0 g\r0 0 m\r5 0 l\r5 5 l\rf\r{dictionary}"))).as_bytes()).ok(); + assert!(r.is_none_or(|r| r.placed_pages.is_empty())); +} + +/// Two pages of a file with the same preview don't share a key: reading one page's file in would +/// change the other's image. +#[test] +fn placed_pages_of_one_file_keep_images_of_their_own() { + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let one = + placed(true, "[5 0 0 -5 0 200]", "/art/flyer.pdf", Some(&preview), "%_/ArtDictionary :\r%_1 /Int (AI11 PlacedPDFPageIndex) ,\r%_;\r%_\r"); + let two = + placed(true, "[5 0 0 -5 0 200]", "/art/flyer.pdf", Some(&preview), "%_/ArtDictionary :\r%_2 /Int (AI11 PlacedPDFPageIndex) ,\r%_;\r%_\r"); + let find = |d: &[u8], w: &[u8]| d.windows(w.len()).position(|x| x == w).unwrap(); + let body = two[find(&two, b"%AI5_BeginPlace")..find(&two, b"LB\n%AI5_EndLayer")].to_vec(); + let mut both = one.clone(); + let at = find(&both, b"LB\n%AI5_EndLayer"); + both.splice(at..at, body); + let r = read(&both).unwrap(); + assert_eq!(r.placed_pages.len(), 2); + let keys: Vec = art(&r.doc) + .iter() + .map(|n| match &n.kind { + NodeKind::Image(im) => im.key.clone(), + k => panic!("{k:?}"), + }) + .collect(); + assert_ne!(keys[0], keys[1]); + assert!(keys.iter().all(|k| r.doc.images.contains_key(k)) && r.doc.images.len() == 2, "{keys:?}"); +} + #[test] fn placed_files_are_linked_images_showing_their_preview() { // A 2×1 preview (premultiplied ARGB, a padded row) of a file of 4×2 pixels. @@ -862,8 +3565,7 @@ fn placed_files_are_linked_images_showing_their_preview() { let xf = pixels(&r.doc).1; assert_eq!((xf * Point::ZERO, xf * Point::new(2.0, 1.0)), (Point::new(100.0, 50.0), Point::new(110.0, 30.0))); - // Without a preview it can read (none, cut short, not 32 bits, absurd sizes), without a path or - // a matrix, the file isn't read from its editing data. + // A placed file with a box but no usable preview is marked for page-art replacement. let cut = &preview[..preview.len() - 6]; let huge = b"70000 70000 280000 32 17 \0\0\0\0"; let overflow = b"1 2 18446744073709551615 32 17 \0\0\0\0\0\0\0\0"; @@ -878,8 +3580,13 @@ fn placed_files_are_linked_images_showing_their_preview() { ("[0 0 0 0 0 0]", "a.png", Some(&preview[..])), ("[1 2 3]", "a.png", Some(&preview[..])), ] { - let e = read(&placed(true, matrix, path, preview, "")).unwrap_err(); - assert!(e.contains("placed files"), "{matrix} {path} {preview:?}: {e}"); + let result = read(&placed(true, matrix, path, preview, "")); + if matrix == "[0 0 0 0 0 0]" || matrix == "[1 2 3]" { + let e = result.err().unwrap_or_else(|| panic!("expected missing bounds for {matrix} {path}")); + assert!(e.contains("placed files"), "{matrix} {path} {preview:?}: {e}"); + } else { + assert_unread(&result.unwrap(), "placed files"); + } } // On a layer that doesn't show, such a file is left out of it. let r = read(&placed(false, "[5 0 0 -5 0 200]", "a.png", None, "")).unwrap(); @@ -915,14 +3622,940 @@ fn text_objects_are_slots_named_after_their_story() { let r = read_ok(&layer(&format!("{look}{own}1 (Style) XW\n"))); let a = art(&r.doc); assert_eq!((a.len(), a[0].children().map(Vec::len), slot_of(a[1].name.as_deref())), (2, Some(1), Some(Some(7)))); + // The type of the look in a group of it is the object's too. + let nested = look.replacen("u\n", "u\nu\n", 1).replacen("U\n", "U\nU\n", 1); + let r = read_ok(&layer(&format!("{nested}{own}1 (Style) XW\n"))); + let mut slots = vec![]; + r.doc.walk(|n| { + if let Some(story) = slot_of(n.name.as_deref()) { + slots.push(story); + } + }); + assert_eq!(slots, [Some(7)]); + // Whatever comes of the object's style, the type of its look is the object's. + for marker in ["1 () XW", "2 (Style) XW"] { + let r = read_ok(&layer(&format!("{look}{own}{marker}\n"))); + let mut looks = 0; + r.doc.walk(|n| looks += usize::from(super::is_look_slot(n.name.as_deref()))); + assert_eq!(looks, 0, "{marker}"); + } + // In the look of a group, the type is that of a copy the look draws: a slot without a story. + let group = "u\n%_/AI11Text :\n%_0 /FreeUndo ,\n%_0 /FrameIndex ,\n%_7 /StoryIndex ,\n%_;\n%_U\n"; + let r = read_ok(&layer(&format!("{look}{group}1 (Style) XW\n"))); + let mut slots = vec![]; + r.doc.walk(|n| { + if slot_of(n.name.as_deref()).is_some() { + slots.push(n.name.clone()); + } + }); + assert!(slots.len() == 1 && slots.iter().all(|n| super::is_look_slot(n.as_deref())), "{slots:?}"); +} + +/// A file in the legacy format (version 7) whose layer holds `art`, crop marks 0 0 200 100. +fn type_stream7(art: &str) -> String { + format!( + "%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 3.0\n%AI3_Cropmarks: 0 0 200 100\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n{}\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n", + layer(art) + ) +} + +/// The text objects of a legacy-format file whose layer holds `art`. +fn legacy_texts(art: &str) -> Vec { + let doc = match read(type_stream7(art).as_bytes()) { + Ok(r) => r.doc, + Err(e) => panic!("{e}"), + }; + art_texts(&doc) +} + +/// The characters of each text object of a legacy-format file whose setup is `setup` and whose +/// layer holds point type with the string `(chars)` in each font of `fonts`. +fn legacy_chars(setup: &str, fonts: &[&str], chars: &str) -> Vec { + let art: String = fonts.iter().map(|f| point_type("", chars).replace("/_Helvetica 12 Tf", &format!("/{f} 12 Tf"))).collect(); + let data = type_stream7(&art).replace("%%BeginSetup\n%%EndSetup", &format!("%%BeginSetup\n{setup}%%EndSetup")); + let doc = match read(data.as_bytes()) { + Ok(r) => r.doc, + Err(e) => panic!("{e}"), + }; + art_texts(&doc).iter().map(|t| t.runs.iter().map(|r| r.text.as_str()).collect()).collect() +} + +/// `TZ` (§3.3.1) gives a re-encoded font encoding pairs of its own: its strings decode by them +/// first, then by `TE`'s encoding when `useDefault` is 1, and other fonts' strings keep `TE`'s. `TZ` is read in an +/// `%AI3_BeginEncoding` section and in an `%%BeginEncoding` one, with a Multiple Master weight +/// vector after it, and without the direction operand. +#[test] +fn a_re_encoded_fonts_own_encoding_pairs_decode_only_its_strings() { + let setup = "[39/quoteright 96/grave 128/Adieresis\nTE\n\ + %AI3_BeginEncoding: _F F\n[ 39/quotesingle 200/eacute\n/_F/F 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n\ + %%BeginEncoding: _M M\n[ 39/quotesingle\n/_M/M 0 0 1 [0.5 0.25] TZ\n%%EndEncoding\n\ + %AI3_BeginEncoding: _N N\n[ 39/quotesingle\n/_N/N 0 1 TZ\n%AI3_EndEncoding AdobeType\n"; + let got = legacy_chars(setup, &["_F", "_M", "_N", "_G"], "\\047\\140\\200\\310"); + assert_eq!(got, ["'`Äé", "'`ÄÈ", "'`ÄÈ", "’`ÄÈ"]); + // The re-encoded fonts are the fonts they were made from. + let data = type_stream7(&point_type("", "a").replace("/_Helvetica", "/_M")) + .replace("%%BeginSetup\n%%EndSetup", "%%BeginSetup\n%%BeginEncoding: _M Courier\n[/_M/Courier 0 0 1 TZ\n%%EndEncoding\n%%EndSetup"); + let texts = art_texts(&read(data.as_bytes()).unwrap().doc); + assert_eq!(texts[0].runs[0].style.font_family, "Courier"); +} + +/// The reader does not use the pairs of a `TZ` whose font names aren't the last two operands, or +/// are followed by other values. The first `TZ` for a font is used, also when it has no pairs. +#[test] +fn a_tz_of_another_shape_changes_no_encoding() { + let setup = "[39/quoteright\nTE\n\ + %AI3_BeginEncoding: _F F\n[ 39/quotesingle\n/_F/F (x) 1 TZ\n%AI3_EndEncoding AdobeType\n\ + %AI3_BeginEncoding: _G G\n[ 39/quotesingle\n/_G 0 /G 1 TZ\n%AI3_EndEncoding AdobeType\n\ + %AI3_BeginEncoding: _H H\n[ 39/grave\n/_H/H 0 0 1 TZ\n[ 39/quotesingle\n/_H/H 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n\ + %AI3_BeginEncoding: _K K\n[/_K/K 0 0 1 TZ\n[ 39/quotesingle\n/_K/K 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n"; + assert_eq!(legacy_chars(setup, &["_F", "_G", "_H", "_K"], "\\047"), ["’", "’", "`", "’"]); +} + +/// A `TZ` whose `useDefault` is 0 leaves `TE`'s encoding out for its font (§3.3.1): the codes its +/// pairs leave out decode as Windows-1252. +#[test] +fn a_tz_with_use_default_0_leaves_te_out() { + let setup = "[39/quoteright 128/Adieresis\nTE\n\ + %AI3_BeginEncoding: _F F\n[ 96/grave\n/_F/F 0 0 0 TZ\n%AI3_EndEncoding TrueType\n\ + %AI3_BeginEncoding: _S S\n[/_S/S 0 0 0 TZ\n%AI3_EndEncoding AdobeType\n\ + %AI3_BeginEncoding: _M M\n[ 96/grave\n/_M/M 0 0 [0.5] TZ\n%AI3_EndEncoding AdobeType\n"; + assert_eq!(legacy_chars(setup, &["_F", "_S", "_M", "_G"], "\\047\\140\\200"), ["'`€", "'`€", "'`€", "’`Ä"]); +} + +/// Strings in a composite font `base-CMap` decode by that predefined CMap (codes to CIDs, then the +/// character collection's CIDs to Unicode), and the font is `base`; `TE`'s encoding does not apply +/// to them. Codes the CMap leaves out are dropped. A font whose name ends in no predefined CMap +/// decodes byte by byte. +#[test] +fn legacy_type_in_a_cjk_font_decodes_by_its_cmap() { + let typed = |font: &str, chars: &str| point_type("", chars).replace("/_Helvetica", &format!("/{font}")); + let cases: &[(&str, &str, &str)] = &[ + // 日 is 0x93FA and 本 0x967B in Shift-JIS; `\r` ends a paragraph. + ("83pv-RKSJ-H", "\\223\\372\\226{A\\r\\223\\372", "日本A\n日"), + // A tab stays a tab, also after a UTF-16 string's last whole code. + ("90ms-RKSJ-H", "\\223\\372\\tA", "日\tA"), + ("H", "F|\\tF|", "日\t日"), + ("UniJIS-UTF16-H", "e\\345\\t", "日\t"), + // One-byte codes in the Mac Shift-JIS CMap: 0x5C yen, 0x7E tilde, 0x80 backslash, 0xFD + // copyright, and the underscore and grave accent. + ("83pv-RKSJ-H", "\\\\~\\200\\375_`", "¥~\\©_`"), + ("90ms-RKSJ-H", "\\\\~_`", "¥~_`"), + ("90ms-RKSJ-V", "\\223\\372", "日"), + ("90pv-RKSJ-V", "\\223\\372", "日"), + // JIS row and cell: 日 is 0x4652. + ("H", "F|", "日"), + ("V", "F|", "日"), + ("EUC-H", "\\306\\374", "日"), + ("GBK-EUC-H", "\\326\\320", "中"), + ("GBpc-EUC-H", "\\326\\320", "中"), + ("B5pc-H", "\\244\\244", "中"), + ("KSCms-UHC-H", "\\307\\321", "한"), + ("KSCpc-EUC-H", "\\307\\321", "한"), + ("UniJIS-UCS2-H", "e\\345", "日"), + ("UniGB-UTF8-H", "\\344\\270\\255", "中"), + // An encoded U+FFFD is a character; the invalid byte 0xFF is dropped. + ("UniGB-UTF8-H", "\\357\\277\\275\\377\\344\\270\\255", "\u{fffd}中"), + ("UniJIS-UTF32-H", "\\000\\000e\\345", "日"), + ("UniAKR-UTF16-H", "\\254\\000", "가"), + // CMaps VectorCraft doesn't carry: read with the nearest carried one, row-and-cell codes in + // their EUC form (中 is 0x5650 in GB 2312, 한 0x4751 in KS X 1001), or byte by byte. + ("78-RKSJ-H", "\\223\\372", "日"), + ("RKSJ-V", "\\223\\372", "日"), + ("GB-H", "VP", "中"), + ("KSC-V", "GQ", "한"), + ("GBT-H", "AB", "AB"), + // Codes are as long as the code space range they fall in, and unmapped ones are dropped: + // 0x8540 as two bytes, and 0xFD and EUC's 0x8F (in no range) as one. + ("90ms-RKSJ-H", "\\205\\100\\223\\372A\\375B", "日AB"), + ("EUC-H", "\\217A\\306\\374", "A日"), + ]; + let art: String = cases.iter().map(|(cmap, chars, _)| typed(&format!("_Test-W3-{cmap}"), chars)).collect(); + let art = [art, typed("_Test-W3-Identity-H", "\\223"), typed("_Test-W3-UniFoo-UTF8-H", "\\223"), typed("_Helvetica", "\\223")].concat(); + let data = type_stream7(&art).replace("%%BeginSetup\n%%EndSetup", "%%BeginSetup\n[147/Adieresis\nTE\n%%EndSetup"); + let texts = art_texts(&read(data.as_bytes()).unwrap().doc); + let chars: Vec = texts.iter().map(|t| t.plain_text()).collect(); + let mut want: Vec<&str> = cases.iter().map(|(_, _, want)| *want).collect(); + want.extend(["Ä", "Ä", "Ä"]); + assert_eq!(chars, want); + let test = crate::import::family_style("Test-W3"); + for (t, (cmap, _, _)) in texts.iter().zip(cases) { + assert_eq!((&t.runs[0].style.font_family, &t.runs[0].style.font_style), (&test.0, &test.1), "{cmap}"); + } + assert_eq!(texts[0].paragraph_count(), 2); + assert_ne!(texts[cases.len()].runs[0].style.font_style, test.1, "an Identity CMap is not read"); + assert_ne!(texts[cases.len() + 1].runs[0].style.font_style, test.1, "`UniFoo` is not a character collection"); +} + +/// A font whose `TZ` gives encoding pairs is not a composite font, even when its name ends in a +/// CMap name: its strings decode byte by byte, and the font keeps its whole name. A `TZ` without +/// encoding pairs only names a composite font. +#[test] +fn a_re_encoded_font_ending_in_a_cmap_name_is_not_composite() { + let setup = "%AI3_BeginEncoding: _F-Bold-H F-Bold-H\n[ 39/quotesingle\n/_F-Bold-H/F-Bold-H 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n"; + assert_eq!(legacy_chars(setup, &["_F-Bold-H"], "F|'"), ["F|'"]); + let setup = "%AI3_BeginEncoding: _G-Bold-H G-Bold-H\n[ 65/A\n/_G-Bold-H/G-Bold-H 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n"; + assert_eq!(legacy_chars(setup, &["_G-Bold-H"], "F|"), ["F|"]); + let setup = "%AI3_BeginEncoding: _R-W3-83pv-RKSJ-H R-W3-83pv-RKSJ-H\n[/_R-W3-83pv-RKSJ-H/R-W3-83pv-RKSJ-H 0 1 1 TZ\n%AI3_EndEncoding AdobeType\n"; + assert_eq!(legacy_chars(setup, &["_R-W3-83pv-RKSJ-H"], "\\223\\372"), ["日"]); +} + +/// In a font with a Unicode CMap, a one-byte `(\r)` string, or a 0x0D byte after a string's last +/// whole UTF-16 code, still ends a paragraph, as in other fonts, and an overflow `(\r) TX` still +/// ends the story. +#[test] +fn legacy_type_in_a_utf16_font_keeps_its_paragraph_breaks() { + let art = point_type("", "e\\345") + .replace("/_Helvetica", "/_Test-W3-UniJIS-UTF16-H") + .replace("TO\n", "(\\r) Tx\n(e\\345\\r) Tx\n(e\\345) Tx\n(\\r) TX\nTO\n"); + let texts = legacy_texts(&art); + assert_eq!(texts[0].plain_text(), "日\n日\n日"); + assert_eq!(texts[0].paragraph_count(), 3); +} + +fn art_texts(doc: &Document) -> Vec { + art(doc).iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect() +} + +/// Point type at (10, 50): `attrs`, then the characters `text`. +fn point_type(attrs: &str, text: &str) -> String { + format!("0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n{attrs}\n({text}) Tx\nTO\n") +} + +/// `TC` and `TW` (§15.4.7) set the paragraph's letter and word spacing, `Tq` its hanging +/// punctuation and `Th` (§22) its hyphenation; each paragraph keeps the values in force at its +/// first character, and they last into the next text object. +#[test] +fn legacy_type_keeps_its_spacing_hanging_punctuation_and_hyphenation() { + let two_paragraphs = + point_type("10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th", "One\\r").replace("TO\n", "0 0 5 TC\n0 Tq\n0 0 4 5 6 Th\n(Two) Tx\nTO\n"); + let texts = legacy_texts(&format!("{two_paragraphs}{}", point_type("", "Three"))); + assert_eq!(texts.len(), 2); + let one = texts[0].para_at(0); + assert_eq!(one.justification.letter_spacing, [10.0, 15.0, 20.0]); + assert_eq!(one.justification.word_spacing, [70.0, 110.0, 140.0]); + assert!(one.roman_hanging && one.hyphenate); + let h = &one.hyphenation; + assert_eq!((h.after_first, h.before_last, h.hyphen_limit), (2, 3, 4)); + assert_eq!(h.words_longer_than, vectorcraft_doc::text::HyphenationOptions::default().words_longer_than, "no operand sets it"); + let two = texts[0].para_at(1); + assert_eq!(two.justification.letter_spacing, [0.0, 0.0, 5.0]); + assert_eq!(two.justification.word_spacing, [70.0, 110.0, 140.0], "word spacing stays"); + assert!(!two.roman_hanging && !two.hyphenate); + // Without the limit flag, any number of hyphens in a row. + assert_eq!((two.hyphenation.after_first, two.hyphenation.before_last, two.hyphenation.hyphen_limit), (4, 5, 0)); + // The next text object keeps them. + assert_eq!(texts[1].para_at(0), two); +} + +/// `Tg` (§15.3.4) turns binding punctuation on (1 and 3) or off (0 and 2); VectorCraft opens it on +/// as Burasagari's Force setting. Each paragraph of point type and area type keeps the value in +/// force at its first character, and it lasts into the next text object. +#[test] +fn legacy_type_keeps_its_binding_punctuation() { + use vectorcraft_doc::Burasagari; + let burasagari = |attrs: &str| legacy_texts(&point_type(attrs, "Hi"))[0].para_at(0).burasagari; + assert_eq!(burasagari(""), Burasagari::None); + for on in ["1", "3"] { + assert_eq!(burasagari(&format!("0 Tg\n{on} Tg")), Burasagari::Forced, "{on} Tg"); + } + for off in ["0", "2"] { + assert_eq!(burasagari(&format!("1 Tg\n{off} Tg")), Burasagari::None, "{off} Tg"); + } + let two_paragraphs = point_type("1 Tg", "One\\r").replace("TO\n", "0 Tg\n(Two) Tx\nTO\n"); + let texts = legacy_texts(&format!("{two_paragraphs}{}{}", point_type("3 Tg", "Three"), point_type("", "Four"))); + let each: Vec = vec![texts[0].para_at(0).burasagari, texts[0].para_at(1).burasagari, texts[1].para_at(0).burasagari]; + assert_eq!(each, [Burasagari::Forced, Burasagari::None, Burasagari::Forced]); + assert_eq!(texts[2].para_at(0).burasagari, Burasagari::Forced, "the next text object keeps it"); + let frame = "10 10 m\n110 10 L\n110 110 L\n10 110 L\nN"; + let area = format!("1 To\n1 0 0 1 10 110 0 Tp\n{frame}\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n1 Tg\n(Area) Tx\nTO\n"); + let texts = legacy_texts(&area); + assert!(matches!(texts[0].kind, vectorcraft_doc::TextKind::Area { .. })); + assert_eq!(texts[0].para_at(0).burasagari, Burasagari::Forced, "area type"); +} + +/// `TV` (§15.3.4) sets the writing direction of point type, area type, type on a path and linked +/// areas, and lasts into the next text object until it changes. +#[test] +fn legacy_type_keeps_its_writing_direction() { + let frame = "10 10 m\n110 10 L\n110 110 L\n10 110 L\nN"; + let area = format!("1 To\n1 0 0 1 10 110 0 Tp\n{frame}\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Area) Tx\nTO\n"); + let on_path = "2 To\n1 0 0 1 0 0 0 Tp\n10 10 m\n110 10 L\nN\nTP\n(Path) Tx\nTO\n"; + let linked = format!("1 To\n1 0 0 1 10 110 0 Tp\n{frame}\nTP\n1 0 0 1 200 110 0 Tp\n{frame}\nTP\n(Linked) Tx\nTO\n"); + let art = format!("{}{area}{on_path}{linked}{}", point_type("1 TV", "Point"), point_type("0 TV", "Flat")); + let texts = legacy_texts(&art); + let vertical: Vec = texts.iter().map(|t| t.vertical).collect(); + assert_eq!(vertical, [true, true, true, true, true, false]); + assert!(matches!(texts[1].kind, vectorcraft_doc::TextKind::Area { .. })); + assert!(matches!(texts[2].kind, vectorcraft_doc::TextKind::OnPath { .. })); + // Vertical point type runs down the canvas from `Tp`'s origin (10, 50), which opens at document + // (10, 50) on the 100 pt tall artboard, on the column's center line. + let long = &legacy_texts(&point_type("1 TV", "Point type"))[0]; + let bounds = long.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), long).bounds); + assert!(bounds.height() > bounds.width(), "{bounds:?}"); + assert!(bounds.x0 < 10.0 && bounds.x1 > 10.0, "{bounds:?}"); + assert!((bounds.y0 - 50.0).abs() < 1.0 && bounds.y1 > 60.0, "{bounds:?}"); + // A text object keeps the direction in force at its first character, with a warning when a later + // character has another; the mode lasts into the next text object. + let changed = point_type("1 TV", "First").replace("TO\n", "0 TV\n(Second) Tx\nTO\n"); + let r = legacy_read(&format!("{changed}{}", point_type("", "Next"))); + let changed = art_texts(&r.doc); + assert!(changed[0].vertical); + assert_eq!(changed[0].plain_text(), "FirstSecond"); + assert!(!changed[1].vertical); + assert_eq!(r.warnings, [DIRECTION_CHANGE_LEFT_OUT]); + // A direction that changes and changes back also warns. + let back = point_type("", "a").replace("TO\n", "1 TV\n(b) Tx\n0 TV\n(c) Tx\nTO\n"); + assert_eq!(legacy_read(&back).warnings, [DIRECTION_CHANGE_LEFT_OUT]); + // A `TV` that no character follows does not warn, and an object with no characters opens no + // type, while its `TV` lasts into the next object. + let trailing = point_type("", "a").replace("TO\n", "1 TV\nTO\n"); + assert!(legacy_read(&trailing).warnings.is_empty()); + let empty = legacy_texts(&format!("0 To\n1 0 0 1 10 50 0 Tp\nTP\n1 TV\nTO\n{}", point_type("", "Next"))); + assert_eq!((empty.len(), empty[0].vertical), (1, true)); + // `TV` before `To` counts, and `TV` after the last character only reaches the next object. + let before = legacy_texts(&format!("1 TV\n{}", point_type("", "Hi"))); + assert!(before[0].vertical); + let after = point_type("", "Hi").replace("TO\n", "1 TV\nTO\n"); + let after = legacy_texts(&format!("{after}{}", point_type("", "Next"))); + assert_eq!((after[0].vertical, after[1].vertical), (false, true)); + // An overflow break (`(\r) TX`) keeps the direction in force where it was read: at the start of + // the story it sets the object's direction, and later it warns when that differs. + let leading = legacy_read(&point_type("1 TV\n(\\r) TX\n0 TV", "Body")); + let leading = (art_texts(&leading.doc), leading.warnings); + assert_eq!((leading.0[0].vertical, leading.0[0].plain_text().as_str()), (true, "\nBody")); + assert_eq!(leading.1, [DIRECTION_CHANGE_LEFT_OUT]); + let inside = legacy_read(&point_type("", "a").replace("TO\n", "1 TV\n(\\r) TX\n0 TV\n(b) Tx\nTO\n")); + let inside = (art_texts(&inside.doc), inside.warnings); + assert_eq!((inside.0[0].vertical, inside.0[0].plain_text().as_str()), (false, "a\nb")); + assert_eq!(inside.1, [DIRECTION_CHANGE_LEFT_OUT]); +} + +/// An overflow break (`(\r) TX`) that type follows ends a paragraph as `(\r) Tx` does: an empty +/// paragraph it ends keeps the attributes in force where the break was read. +#[test] +fn an_overflow_break_keeps_the_paragraph_attributes_it_was_read_with() { + use vectorcraft_doc::Justify::{Center, Right}; + for op in ["Tx", "TX"] { + let leading = &legacy_texts(&point_type(&format!("1 Ta\n(\\r) {op}\n2 Ta"), "Body"))[0]; + assert_eq!((leading.para_at(0).justify, leading.para_at(1).justify), (Center, Right), "{op}"); + let empty = point_type("1 Ta", "a\\r").replace("TO\n", &format!("(\\r) {op}\n2 Ta\n(b) Tx\nTO\n")); + let empty = &legacy_texts(&empty)[0]; + assert_eq!(empty.plain_text(), "a\n\nb", "{op}"); + assert_eq!((empty.para_at(1).justify, empty.para_at(2).justify), (Center, Right), "{op}"); + } +} + +/// The glyph origins of a legacy-format text object. +fn legacy_origins(t: &vectorcraft_doc::TextObject) -> Vec<(f64, f64)> { + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.iter().map(|g| (g.origin.x, g.origin.y)).collect() +} + +/// `Ty` (§15.3.4) marks the characters of a Kumi block in vertical and in horizontal type, `TY` +/// marks them in horizontal type, and `Tv` keeps Roman characters upright in vertical type; `Tv` +/// may come inside the text path. All three last into the next text object. +#[test] +fn legacy_type_keeps_kumi_blocks_and_upright_roman_characters() { + let runs = |art: &str| -> Vec<(String, bool, bool)> { + let texts = legacy_texts(art); + texts[0].runs.iter().map(|r| (r.text.clone(), r.style.tate_chu_yoko, r.style.standard_vertical_roman)).collect() + }; + let kumi = |begin: &str, end: &str| point_type(&format!("(A) Tx\n{begin}\n(12) Tx\n{end}"), "B"); + let marked = vec![("A".to_string(), false, false), ("12".to_string(), true, false), ("B".to_string(), false, false)]; + assert_eq!(runs(&format!("1 TV\n{}", kumi("1 Ty", "0 Ty"))), marked); + assert_eq!(runs(&kumi("1 Ty", "0 Ty")), marked); + assert_eq!(runs(&kumi("1 TY", "0 TY")), marked); + assert!(!legacy_texts(&kumi("1 TY", "0 TY"))[0].vertical); + // `TY` records a block that the set text doesn't show: vertical type opens without it, and the + // block starts again in the next horizontal object. + let unmarked = vec![("A12B".to_string(), false, false)]; + assert_eq!(runs(&format!("1 TV\n{}", kumi("1 TY", "0 TY"))), unmarked); + let recorded = legacy_texts(&format!("1 TV\n1 TY\n{}0 TV\n{}", point_type("", "A"), point_type("", "B"))); + assert_eq!((recorded[0].runs[0].style.tate_chu_yoko, recorded[1].runs[0].style.tate_chu_yoko), (false, true)); + let upright = point_type("(a) Tx\n1 Tv", "b"); + assert_eq!(runs(&format!("1 TV\n{upright}")), [("a".to_string(), false, false), ("b".to_string(), false, true)]); + let in_path = point_type("", "c").replace("0 Tp\nTP", "0 Tp\n1 Tv\nTP"); + assert_eq!(runs(&in_path), [("c".to_string(), false, true)]); + assert_eq!(runs(&point_type("1 Tv\n(a) Tx\n0 Tv", "b")), [("a".to_string(), false, true), ("b".to_string(), false, false)]); + // Each one lasts into the next text object. + for (op, kept) in [("Ty", (true, false)), ("TY", (true, false)), ("Tv", (false, true))] { + let texts = legacy_texts(&format!("{}{}", point_type(&format!("1 {op}"), "a"), point_type("", "b"))); + let st = &texts[1].runs[0].style; + assert_eq!((st.tate_chu_yoko, st.standard_vertical_roman), kept, "{op}"); + } + // Horizontal type keeps the mark and doesn't move the characters. + let plain = &legacy_texts(&point_type("", "A12B"))[0]; + let in_horizontal = &legacy_texts(&kumi("1 Ty", "0 Ty"))[0]; + assert_eq!(legacy_origins(in_horizontal), legacy_origins(plain)); + // Two blocks with nothing between them open as one block. + let vertical = |attrs: &str, text: &str| legacy_texts(&format!("1 TV\n{}", point_type(attrs, text))).remove(0); + let two = vertical("1 Ty\n(AB) Tx\n0 Ty\n1 Ty", "CD"); + let one = vertical("1 Ty", "ABCD"); + assert_eq!(legacy_origins(&two), legacy_origins(&one)); + // Two or three digits that no block marks are set across the column by the layout's own rule. + let digits = vertical("", "12"); + assert!(!digits.runs[0].style.tate_chu_yoko); + assert_eq!(legacy_origins(&digits), legacy_origins(&vertical("1 Ty", "12"))); + assert_ne!(legacy_origins(&vertical("", "AB")), legacy_origins(&vertical("1 Ty", "AB"))); +} + +/// A legacy attribute whose operands are missing, are not numbers, or are flags other than 0 and +/// 1 leaves the attribute as it was, and operands are read by their place. +#[test] +fn legacy_type_attributes_with_bad_operands_stay_as_they_were() { + let set = "10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th\n2 Ta\n0 TA\n5 6 7 Ti"; + let bad = "/x 15 20 TC\n110 140 TW\n2 Tq\n1 2 2 3 4 Th\n1 1 (2) 3 4 Th\n/x Ta\n2 TA\n5 /x 7 Ti"; + let texts = legacy_texts(&point_type(&format!("{set}\n{bad}"), "Hi")); + let p = texts[0].para_at(0); + assert_eq!(p.justification.letter_spacing, [10.0, 15.0, 20.0]); + assert_eq!(p.justification.word_spacing, [70.0, 110.0, 140.0]); + assert!(p.roman_hanging && p.hyphenate); + assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 3, 4)); + assert_eq!(p.justify, vectorcraft_doc::Justify::Right); + assert_eq!((p.first_line_indent, p.left_indent, p.right_indent), (5.0, 6.0, 7.0)); + assert_eq!(texts[0].runs[0].style.kerning, Some(0.0), "kerning stays off"); + let texts = legacy_texts(&point_type("1 Tg\n4 Tg\n-1 Tg\n0.5 Tg\n/x Tg\n(0) Tg\nTg", "Hi")); + assert_eq!(texts[0].para_at(0).burasagari, vectorcraft_doc::Burasagari::Forced, "binding punctuation stays on"); + let texts = legacy_texts(&point_type("0 Tg\n4 Tg\n-1 Tg\n2.5 Tg", "Hi")); + assert_eq!(texts[0].para_at(0).burasagari, vectorcraft_doc::Burasagari::None, "binding punctuation stays off"); + let texts = legacy_texts(&point_type("1 TV\n1 Tv\n1 Ty\n2 TV\n/x TV\nTV\n-1 Tv\n(x) Tv\n0.5 Ty\n2 TY", "Hi")); + let st = &texts[0].runs[0].style; + assert!(texts[0].vertical && st.standard_vertical_roman && st.tate_chu_yoko); + let texts = legacy_texts(&point_type("2 TV\n-1 TV\n2 Tv\n-1 Tv\n0.5 Ty\n-1 Ty\n2 TY\n-1 TY\n1 TY\n2 TY\n0.5 TY", "Hi")); + let st = &texts[0].runs[0].style; + assert!(!texts[0].vertical && !st.standard_vertical_roman); + assert!(st.tate_chu_yoko, "`TY` stays on"); + let texts = legacy_texts(&point_type("2 TV\n-1 TV\n2 Tv\n-1 Tv\n0.5 Ty\n-1 Ty\n2 TY\n-1 TY", "Hi")); + assert!(!texts[0].runs[0].style.tate_chu_yoko); + // A scale or leading pair with a bad operand leaves both as they were; one operand is the + // horizontal scale (or the leading) of the format before version 7. + let texts = legacy_texts(&point_type("50 80 Tz\n14 3 Tl\n/x 120 Tz\n/x 20 Tl", "Hi")); + let st = &texts[0].runs[0].style; + assert_eq!((st.h_scale, st.v_scale, st.leading), (50.0, 80.0, Some(14.0))); + assert_eq!(texts[0].para_at(0).space_before, 3.0); + let st = &legacy_texts(&point_type("50 80 Tz\n120 Tz", "Hi"))[0].runs[0].style; + assert_eq!((st.h_scale, st.v_scale), (120.0, 100.0)); + // A start point that isn't a number leaves the matrix. + let good = &legacy_texts(&point_type("", "Hi"))[0]; + let bad = &legacy_texts(&point_type("", "Hi").replace("10 50 0 Tp", "10 50 /x Tp"))[0]; + assert_eq!(bad.xf, good.xf); +} + +/// `(text) justified TS` (special characters, §22.6) adds its characters to the story like `Tx` +/// and `Tj`, whichever its flag. Without a string, or outside a text object, it adds nothing. +#[test] +fn legacy_special_characters_join_the_story() { + let texts = legacy_texts(&point_type("", "One").replace("TO\n", "(\\t) 0 TS\n(Two\\r) 1 TS\n(Three) Tx\nTO\n")); + let [t] = texts.as_slice() else { panic!("{texts:?}") }; + assert_eq!(t.plain_text(), "One\tTwo\nThree"); + let texts = legacy_texts(&format!("(x) 0 TS\n{}", point_type("0 TS", "Hi"))); + let [t] = texts.as_slice() else { panic!("{texts:?}") }; + assert_eq!(t.plain_text(), "Hi"); +} + +/// A tab definition (`Xb`, `Xe`, `XB`, §22.6) sets the paragraph's tab stops, sorted by position +/// with one stop at each position; each paragraph keeps the stops in force at its first character, +/// and they last into the next text object. A definition with no stops leaves the default ones. +#[test] +fn legacy_tab_definitions_set_the_paragraph_tab_stops() { + use vectorcraft_doc::TabAlign; + let stops = |p: &vectorcraft_doc::ParaStyle| p.tabs.iter().map(|t| (t.position, t.align)).collect::>(); + let ruler = "36 5 Xb\n0 0 3 144 Xe\n0 0 1 72 Xe\n0 0 2 200.5 Xe\n0 0 4 250 Xe\n0 0 2 72 Xe\nXB"; + let two_paragraphs = point_type(ruler, "A\\tB\\r").replace("TO\n", "36 0 Xb\nXB\n(C\\tD) Tx\nTO\n"); + let texts = legacy_texts(&format!("{two_paragraphs}{}", point_type("", "E"))); + assert_eq!(texts.len(), 2); + let want = vec![(72.0, TabAlign::Left), (144.0, TabAlign::Right), (200.5, TabAlign::Center), (250.0, TabAlign::Decimal)]; + let one = texts[0].para_at(0); + assert_eq!(stops(one), want); + assert!(one.tabs.iter().all(|t| t.leader.is_empty() && t.align_on == '.')); + assert!(texts[0].para_at(1).tabs.is_empty(), "an empty definition leaves the default stops"); + assert!(texts[1].para_at(0).tabs.is_empty(), "the next text object keeps the empty definition"); + let texts = legacy_texts(&format!("{}{}", point_type(ruler, "A"), point_type("", "B"))); + assert_eq!(stops(texts[1].para_at(0)), want, "the next text object keeps the stops"); +} + +/// A tab description whose type is not 1 to 4 or whose position is missing, not a number, +/// negative or past 100,000 pt is skipped; so is one outside a tab definition, and an `XB` without +/// an `Xb` leaves the stops as they were. +#[test] +fn legacy_tab_descriptions_out_of_range_are_skipped() { + let bad = "0 0 5 90 Xe\n0 0 0 90 Xe\n0 0 1.5 90 Xe\n0 0 1 -1 Xe\n0 0 1 100001 Xe\n0 0 1 /x Xe\n1 Xe"; + let texts = legacy_texts(&point_type(&format!("0 0 1 10 Xe\n36 2 Xb\n{bad}\n0 0 3 100000 Xe\n0 0 1 0 Xe\nXB\nXB\n0 0 1 50 Xe"), "Hi")); + let tabs: Vec = texts[0].para_at(0).tabs.iter().map(|t| t.position).collect(); + assert_eq!(tabs, [0.0, 100_000.0]); +} + +/// A tab definition whose descriptions were all skipped leaves the default stops; a definition +/// keeps its first 1024 stops; and a definition left open (an `Xb` with no `XB`) ends at the next +/// text object's `To`, so that object's descriptions outside a definition are skipped. +#[test] +fn legacy_tab_definitions_skipped_capped_and_left_open() { + let positions = |t: &vectorcraft_doc::TextObject| t.para_at(0).tabs.iter().map(|t| t.position).collect::>(); + let all_skipped = format!("{}{}", point_type("36 1 Xb\n0 0 1 72 Xe\nXB", "A"), point_type("36 1 Xb\n0 0 9 90 Xe\nXB", "B")); + let texts = legacy_texts(&all_skipped); + assert_eq!(positions(&texts[0]), [72.0]); + assert!(texts[1].para_at(0).tabs.is_empty(), "a definition with every stop skipped leaves the default stops"); + let many: String = (0..1100).map(|i| format!("0 0 1 {i} Xe\n")).collect(); + let texts = legacy_texts(&point_type(&format!("36 1100 Xb\n{many}XB"), "C")); + assert_eq!(positions(&texts[0]).len(), 1024); + assert_eq!(positions(&texts[0]).last(), Some(&1023.0)); + let open = format!("{}{}", point_type("36 1 Xb\n0 0 1 72 Xe", "D"), point_type("0 0 1 90 Xe\nXB", "E")); + let texts = legacy_texts(&open); + assert!(texts[0].para_at(0).tabs.is_empty(), "an unended definition sets no stops"); + assert!(texts[1].para_at(0).tabs.is_empty(), "the next object's `To` ends the open definition"); +} + +/// Point type whose 1024 tab stops are followed by 2048 paragraph breaks, each after `attrs(i)`. +fn paragraphs_after_many_tabs(attrs: impl Fn(usize) -> String) -> String { + let many: String = (0..1024).map(|i| format!("0 0 1 {i} Xe\n")).collect(); + let breaks: String = (0..2048).map(|i| format!("{}(x\\r) Tx\n", attrs(i))).collect(); + point_type(&format!("36 1024 Xb\n{many}XB"), "A").replace("TO\n", &format!("{breaks}TO\n")) +} + +/// Paragraphs that start with the same attributes all keep the same tab stops, however many +/// there are, also when an attribute is set again to the value it has. +#[test] +fn legacy_tab_stops_last_through_many_paragraphs() { + for again in ["", "0 Ta\n"] { + let r = legacy_read(¶graphs_after_many_tabs(|_| again.to_string())); + let texts = art_texts(&r.doc); + let [t] = texts.as_slice() else { panic!("{texts:?}") }; + assert_eq!(t.paragraph_count(), 2049); + assert!((0..2049).all(|i| t.para_at(i).tabs.len() == 1024), "{again}"); + assert!(r.warnings.is_empty(), "{again}: {:?}", r.warnings); + } +} + +/// Each paragraph whose attributes differ from the paragraph before it holds its own copy of its +/// tab stops, and a text object's paragraphs hold no more than 1,048,576 stops: the paragraphs +/// past them take the default stops and keep their other attributes, with a warning. +#[test] +fn legacy_tab_stops_copied_into_paragraphs_are_capped() { + let r = legacy_read(¶graphs_after_many_tabs(|i| format!("{} Ta\n", i % 2))); + let texts = art_texts(&r.doc); + let [t] = texts.as_slice() else { panic!("{texts:?}") }; + let paras = t.paragraph_styles(); + assert_eq!(paras.len(), 2049); + assert_eq!(paras.iter().map(|p| p.tabs.len()).sum::(), 1 << 20); + assert!(paras[..1024].iter().all(|p| p.tabs.len() == 1024)); + assert!(paras[1024..].iter().all(|p| p.tabs.is_empty())); + assert_eq!((paras[2046].justify, paras[2047].justify), (vectorcraft_doc::Justify::Left, vectorcraft_doc::Justify::Center)); + assert_eq!(r.warnings, ["tab stops past VectorCraft's limits were left out"]); +} + +/// `Te` (end render, §22.6) reads in a text object with no operands and with four, inside a tab +/// definition too, and keeps nothing; so does `TM` (pop text matrix, §22.6). +#[test] +fn legacy_end_render_and_text_matrix_pop_read() { + for te in ["Te", "0 0 1 36 Te", "36 0 Xb\n0 0 1 36 Te\nXB", "1 0 0 1 10 50 Tm\nTM"] { + let texts = legacy_texts(&point_type(te, "Hi")); + let [t] = texts.as_slice() else { panic!("{te}: {texts:?}") }; + assert_eq!(t.plain_text(), "Hi", "{te}"); + } +} + +/// Spacing is kept to the ranges the Justification options take, a Minimum, Desired and Maximum +/// out of order go back to their defaults, and hyphenation's letter counts and limit to the ranges +/// `text.setFormat` takes. +#[test] +fn legacy_type_spacing_and_hyphenation_are_kept_in_range() { + let texts = legacy_texts(&point_type("-500 0 900 TC\n0 2000 5000 TW\n1 1 0 40 99 Th", "Hi")); + let p = texts[0].para_at(0); + assert_eq!(p.justification.letter_spacing, [-100.0, 0.0, 500.0]); + assert_eq!(p.justification.word_spacing, [0.0, 1000.0, 1000.0]); + assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (1, 15, 25)); + let texts = legacy_texts(&point_type("5 0 0 TC\n200 100 80 TW", "Hi")); + let j = &texts[0].para_at(0).justification; + let d = vectorcraft_doc::text::JustificationOptions::default(); + assert_eq!((j.letter_spacing, j.word_spacing), (d.letter_spacing, d.word_spacing)); +} + +/// A file's legacy type is read up to its allowance of characters, a single long run included. +#[test] +fn one_long_run_of_legacy_type_stops_at_the_allowance() { + // The reader's allowance, `MAX_CHARS`. + const ALLOWANCE: usize = 1 << 22; + let long = "a".repeat(ALLOWANCE + 10); + let texts = legacy_texts(&point_type("", &long)); + assert_eq!(texts[0].plain_text().chars().count(), ALLOWANCE); +} + +/// The fill and stroke colors of a text object's first run (None: no paint). +fn run_paint(n: &Node) -> (Option, Option) { + let NodeKind::Text(t) = &n.kind else { panic!("type: {:?}", n.kind) }; + (t.runs[0].style.fill.color(), t.runs[0].style.stroke.color()) +} + +/// Legacy type set in rendering modes 4 to 7 is a mask (§5.7): the text object is the clipping +/// path of its clipping group (`q` … `Q`) and clips the objects with it. Modes 4, 5 and 6 also +/// fill, stroke, or fill and stroke it; 7 paints nothing. +#[test] +fn legacy_type_in_a_mask_rendering_mode_clips_its_clipping_group() { + let (black, red) = (Some(Color::cmyk(0.0, 0.0, 0.0, 1.0)), Some(Color::rgb(1.0, 0.0, 0.0))); + let square = format!("1 0 0 Xa\n{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let cases = [("4", (black, None)), ("5", (None, red)), ("6", (black, red)), ("7", (None, None))]; + for (mode, paint) in cases { + let text = point_type(&format!("{mode} Tr\n1 0 0 XA\n1 w"), "Hi"); + let doc = legacy_read(&format!("q\n{text}{square}Q\n")).doc; + let a = art(&doc); + assert_eq!(a.len(), 1, "{mode} Tr"); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{mode} Tr: {:?}", a[0].kind) }; + assert_eq!(children.len(), 2, "{mode} Tr"); + assert_eq!(run_paint(&children[0]), paint, "{mode} Tr"); + assert!(matches!(children[1].kind, NodeKind::Path { clipping: false, .. }), "{mode} Tr"); + // The art takes its shape from the type: it is bounded by the characters, not the square. + let b = a[0].geometric_bounds().unwrap(); + assert!(b.width() < 50.0 && b.height() < 50.0, "{mode} Tr: {b:?}"); + } + // Directly in a layer, the layer clips. As with a `W` path in this reader, the art written before the + // type is clipped too. + let doc = legacy_read(&format!("{square}{}", point_type("7 Tr", "Hi"))).doc; + let NodeKind::Layer { children, clip: true, .. } = &doc.layers[0].kind else { panic!("{:?}", doc.layers[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Text(_)) && matches!(children[1].kind, NodeKind::Path { .. })); + // With a clipping path after it, the art shows where both are: the type clips a clipping group nested in it, and + // keeps its paint. + let doc = legacy_read(&format!("q\n{}{}h\nW\nn\n{square}Q\n", point_type("6 Tr\n1 0 0 XA\n1 w", "Hi"), rect_path(0.0, 0.0, 30.0, 30.0))).doc; + let a = art(&doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(run_paint(&children[0]), (black, red)); + let NodeKind::Group { children: inner, clip: true } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + assert!(matches!(inner[0].kind, NodeKind::Path { clipping: true, .. }) && matches!(inner[1].kind, NodeKind::Path { clipping: false, .. })); +} + +/// A filled clipping path (`W` then `f`) beside type used as a mask keeps its fill, which paints at its own path's level, +/// as beside another clipping path (the reader's rule for `W` paths). Written after the type, it is painted within the +/// type's mask, since a later mask narrows the clip set by the earlier ones (§5.6.2); written before it, the type doesn't +/// clip it. +#[test] +fn a_filled_clipping_path_beside_legacy_type_used_as_a_mask() { + let square = format!("1 0 0 Xa\n{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let filled = format!("0 0 1 Xa\n{}h\nW\nf\n", rect_path(0.0, 0.0, 30.0, 30.0)); + let text = point_type("7 Tr", "Hi"); + let is_clip = |n: &Node| matches!(n.kind, NodeKind::Path { clipping: true, .. }) && fill(n).color() == Some(Color::rgb(0.0, 0.0, 1.0)); + let is_art = |n: &Node| matches!(n.kind, NodeKind::Path { clipping: false, .. }) && fill(n).color() == Some(Color::rgb(1.0, 0.0, 0.0)); + // The type first: the filled path clips a clipping group inside the type's. + let doc = legacy_read(&format!("q\n{text}{filled}{square}Q\n")).doc; + let a = art(&doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Text(_)) && children.len() == 2, "{children:?}"); + let NodeKind::Group { children: inner, clip: true } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + assert!(is_clip(&inner[0]) && is_art(&inner[1]) && inner.len() == 2, "{inner:?}"); + // The path first: it clips the outer clipping group, so only the path clips its fill; the type clips the art. + let doc = legacy_read(&format!("q\n{filled}{text}{square}Q\n")).doc; + let a = art(&doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert!(is_clip(&children[0]) && children.len() == 2, "{children:?}"); + let NodeKind::Group { children: inner, clip: true } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + assert!(matches!(inner[0].kind, NodeKind::Text(_)) && is_art(&inner[1]) && inner.len() == 2, "{inner:?}"); +} + +/// `Tr` sets the rendering mode of all the type that follows (§15.3.2), in later text objects too: a second text +/// object with no `Tr` of its own is also a mask. +#[test] +fn a_legacy_mask_rendering_mode_lasts_into_the_next_text_object() { + let square = format!("1 0 0 Xa\n{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let second = point_type("", "Yo").replace("0 Tr\n", ""); + let doc = legacy_read(&format!("q\n{}{second}{square}Q\n", point_type("7 Tr", "Hi"))).doc; + let a = art(&doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Text(_)), "{children:?}"); + let NodeKind::Group { children: inner, clip: true } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + assert!(matches!(inner[0].kind, NodeKind::Text(_)) && matches!(inner[1].kind, NodeKind::Path { clipping: false, .. }), "{inner:?}"); +} + +/// Type in a mask rendering mode that can't be one clipping path doesn't clip, with a warning: area type with linked +/// areas (threaded frames), the type of wraparound text, and type in a compound path. +#[test] +fn legacy_type_used_as_a_mask_that_cannot_clip_is_left_unclipped() { + const WARNING: &str = "type used as a mask in linked areas, wraparound text or a compound path doesn't clip"; + let square = format!("1 0 0 Xa\n{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let linked = format!( + "1 To\n1 0 0 1 0 40 0 Tp\n{}n\nTP\n7 Tr\n/_Helvetica 12 Tf\n(Linked ) Tx\n1 0 0 1 60 40 0 Tp\n{}n\nTP\n(areas) Tx\nTO\n", + rect_path(0.0, 0.0, 50.0, 40.0), + rect_path(60.0, 0.0, 110.0, 40.0) + ); + let r = legacy_read(&format!("q\n{linked}{square}Q\n")); + let a = art(&r.doc); + let NodeKind::Group { children, clip: false } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(children.len(), 3); + assert_eq!(r.doc.text_threads.len(), 1); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // Also when the reader's limits leave one frame of a long story in linked areas. + let long = linked.replace("(areas) Tx", &format!("({}) Tx", "a".repeat(3_000_000))); + let r = legacy_read(&format!("q\n{long}{square}Q\n")); + let a = art(&r.doc); + let NodeKind::Group { children, clip: false } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(children.len(), 2); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // Wraparound text: the type is what flows around the other objects, which it doesn't clip. + let area = format!("1 To\n1 0 0 1 0 0 0 Tp\n{}n\nTP\n7 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Around) Tx\nTO\n", rect_path(0.0, 0.0, 100.0, 80.0)); + let r = legacy_read(&format!("q\n*w\n{area}{square}*W\nQ\n")); + let a = art(&r.doc); + let NodeKind::Group { children, clip: false } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + let NodeKind::Group { children: wrap, clip: false } = &children[0].kind else { panic!("{:?}", children[0].kind) }; + assert!(matches!(wrap[0].kind, NodeKind::Text(_)) && wrap.len() == 2, "{wrap:?}"); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // A compound path: its type is no clipping subpath, and the compound path doesn't clip the group. + let r = legacy_read(&format!("q\n*u\n{}f\n{}*U\n{square}Q\n", rect_path(0.0, 0.0, 30.0, 30.0), point_type("7 Tr", "Hi"))); + assert_eq!(unclipped_texts(&art(&r.doc)), 1); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // The same with the type in a group inside the compound path or the wraparound text. + let grouped = format!("u\n{}U\n", point_type("7 Tr", "Hi")); + let r = legacy_read(&format!("q\n*u\n{}f\n{grouped}*U\n{square}Q\n", rect_path(0.0, 0.0, 30.0, 30.0))); + assert_eq!(unclipped_texts(&art(&r.doc)), 1); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + let grouped = format!("u\n{area}U\n"); + let r = legacy_read(&format!("q\n*w\n{grouped}{square}*W\nQ\n")); + assert_eq!(unclipped_texts(&art(&r.doc)), 1); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // An opacity mask's art clips on its own, also on an object in wraparound text. + let mask_art: String = + format!("{}1 g\n{}f\n", point_type("7 Tr", "Hi"), rect_path(0.0, 0.0, 100.0, 100.0)).lines().map(|l| format!("%_{l}\n")).collect(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let r = legacy_read(&format!("q\n*w\n{area}{square}{mask}*W\nQ\n")); + assert!(r.warnings.iter().filter(|w| *w == WARNING).count() == 1, "{:?}", r.warnings); + let a = art(&r.doc); + let NodeKind::Group { children, .. } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + let NodeKind::Group { children: wrap, .. } = &children[0].kind else { panic!("{:?}", children[0].kind) }; + let Some(m) = wrap.iter().find_map(|n| n.extras().mask.clone()) else { panic!("{wrap:?}") }; + let NodeKind::Group { children: in_mask, clip: true } = &m.art.kind else { panic!("{:?}", m.art.kind) }; + assert!(matches!(in_mask[0].kind, NodeKind::Text(_)) && in_mask.len() == 2, "{in_mask:?}"); +} + +/// The text objects in `nodes` and the groups and compound paths under them, checking that nothing among them clips. +#[track_caller] +fn unclipped_texts(nodes: &[Arc]) -> usize { + let mut texts = 0; + for n in nodes { + assert!(!matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Path { clipping: true, .. }), "{:?}", n.kind); + texts += usize::from(matches!(n.kind, NodeKind::Text(_))); + texts += n.children().map_or(0, |c| unclipped_texts(c)); + } + texts +} + +/// Legacy type in rendering modes 0 to 3 is no mask (3: invisible, painting nothing). A mode that is not a whole +/// number from 0 to 9 leaves the mode as it was. +#[test] +fn legacy_type_in_other_rendering_modes_does_not_clip() { + let (black, red) = (Some(Color::cmyk(0.0, 0.0, 0.0, 1.0)), Some(Color::rgb(1.0, 0.0, 0.0))); + let square = format!("{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let cases = [("0 Tr", (black, None)), ("3 Tr", (None, None)), ("1 Tr\n4.5 Tr\n10 Tr\n-4 Tr\n/x Tr", (None, red))]; + for (modes, paint) in cases { + let text = point_type(&format!("{modes}\n1 0 0 XA\n1 w"), "Hi"); + let doc = legacy_read(&format!("q\n{text}{square}Q\n")).doc; + let a = art(&doc); + assert_eq!(a.len(), 1, "{modes}"); + let NodeKind::Group { children, clip: false } = &a[0].kind else { panic!("{modes}: {:?}", a[0].kind) }; + assert_eq!(run_paint(&children[0]), paint, "{modes}"); + } +} + +/// A legacy-format file whose layer holds `art`, read. +fn legacy_read(art: &str) -> Structure { + match read(type_stream7(art).as_bytes()) { + Ok(r) => r, + Err(e) => panic!("{e}"), + } +} + +/// The text objects of the first layer, with their ids, top to bottom: a threaded text object's +/// frames in file order. +fn art_frames(doc: &Document) -> Vec<(vectorcraft_doc::NodeId, vectorcraft_doc::TextObject)> { + art(doc).iter().rev().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((n.id, (**t).clone())) } else { None }).collect() +} + +/// An area's frame in the document. +fn frame_in_doc(t: &vectorcraft_doc::TextObject) -> Rect { + let vectorcraft_doc::TextKind::Area { frame } = &t.kind else { panic!("area type: {:?}", t.kind) }; + kurbo::Shape::bounding_box(&(t.xf * frame.to_bezpath())) +} + +/// Do two matrices match? +fn same_matrix(a: Affine, b: Affine) -> bool { + a.as_coeffs().iter().zip(b.as_coeffs()).all(|(p, q)| (p - q).abs() < 1e-9) +} + +/// Area type with linked areas (§15.5.3): each area's `Tp` … `TP` with its own matrix and frame, +/// the characters after each, and overflow text. It opens as one frame for each area, threaded in +/// file order, with the story in the first. +#[test] +fn legacy_area_type_with_linked_areas_is_threaded_frames() { + let text = format!( + "1 To\n1 0 0 1 0 40 0 Tp\n{}n\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Linked ) Tx\n\ + 0 1 -1 0 150 20 0 Tp\n{}n\nTP\n(areas\\r) Tx\n(and more) TX\n(\\r) TX\nTO\n", + rect_path(0.0, 0.0, 50.0, 40.0), + rect_path(110.0, 20.0, 150.0, 80.0) + ); + let r = legacy_read(&text); + let frames = art_frames(&r.doc); + let [(a, first), (b, second)] = frames.as_slice() else { panic!("two frames: {frames:?} {:?}", r.warnings) }; + assert_eq!(r.doc.text_threads, [vec![*a, *b]], "threaded in file order"); + let in_doc = |x0, y0, x1, y1| r.to_doc.transform_rect_bbox(Rect::new(x0, y0, x1, y1)); + assert!(near(frame_in_doc(first), in_doc(0.0, 0.0, 50.0, 40.0)), "{:?}", frame_in_doc(first)); + assert!(near(frame_in_doc(second), in_doc(110.0, 20.0, 150.0, 80.0)), "{:?}", frame_in_doc(second)); + // Each frame keeps its own area's matrix: the second's type runs up the page. + let placed = |m: [f64; 6]| r.to_doc * Affine::new(m) * Affine::FLIP_Y; + assert!(same_matrix(first.xf, placed([1.0, 0.0, 0.0, 1.0, 0.0, 40.0])), "{:?}", first.xf); + assert!(same_matrix(second.xf, placed([0.0, 1.0, -1.0, 0.0, 150.0, 20.0])), "{:?}", second.xf); + // The story: the characters after every area and the overflow text, in the first frame. + assert_eq!(first.plain_text(), "Linked areas\nand more"); + assert_eq!(first.paragraph_styles().len(), 2); + assert_eq!(second.plain_text(), ""); +} + +/// A linked area without a path is left out; a single area with a path is area type in no thread. +#[test] +fn legacy_area_type_leaves_out_a_linked_area_without_a_path() { + let area = |m: &str, path: Option, chars: &str| { + let path = path.map(|p| format!("{}n\n", rect_path(p.x0, p.y0, p.x1, p.y1))).unwrap_or_default(); + format!("{m} Tp\n{path}TP\n{chars}") + }; + let style = "0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n"; + let three = format!( + "1 To\n{}{}{}TO\n", + area("1 0 0 1 0 40 0", Some(Rect::new(0.0, 0.0, 50.0, 40.0)), &format!("{style}(One ) Tx\n")), + area("1 0 0 1 60 40 0", None, "(two ) Tx\n"), + area("1 0 0 1 110 40 0", Some(Rect::new(110.0, 0.0, 150.0, 40.0)), "(three) Tx\n"), + ); + let r = legacy_read(&three); + let frames = art_frames(&r.doc); + let [(a, first), (b, second)] = frames.as_slice() else { panic!("two frames: {frames:?} {:?}", r.warnings) }; + assert_eq!(r.doc.text_threads, [vec![*a, *b]]); + assert_eq!((first.plain_text().as_str(), second.plain_text().as_str()), ("One two three", "")); + let one = format!( + "1 To\n{}{}TO\n", + area("1 0 0 1 60 40 0", None, &format!("{style}(x) Tx\n")), + area("1 0 0 1 0 40 0", Some(Rect::new(0.0, 0.0, 50.0, 40.0)), "(y) Tx\n") + ); + let r = legacy_read(&one); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one frame: {frames:?}") }; + assert!(r.doc.text_threads.is_empty()); + assert_eq!(only.plain_text(), "xy"); + // The frame's own matrix, not the pathless area's. + assert!(same_matrix(only.xf, r.to_doc * Affine::translate((0.0, 40.0)) * Affine::FLIP_Y), "{:?}", only.xf); +} + +/// One text object reads at most 4,096 linked areas: the paths of the rest are left out, not read as +/// art, and their characters stay in the story. +#[test] +fn legacy_area_type_reads_up_to_its_limit_of_linked_areas() { + const LIMIT: usize = 4096; + let area = format!("1 0 0 1 0 0 0 Tp\n{}n\nTP\n", rect_path(0.0, 0.0, 50.0, 40.0)); + let text = format!("1 To\n{}0 Tr\n(a) Tx\n{area}(b) Tx\nTO\n", area.repeat(LIMIT)); + let r = legacy_read(&text); + let frames = art_frames(&r.doc); + assert_eq!(frames.len(), LIMIT); + assert_eq!(art(&r.doc).len(), LIMIT, "no art paths"); + assert_eq!(r.doc.text_threads.iter().map(Vec::len).collect::>(), [LIMIT]); + assert_eq!(frames[0].1.plain_text(), "ab"); + assert_eq!(r.warnings, [LINKED_AREAS_LEFT_OUT]); +} + +/// The frames of linked areas after the first copy the story's last paragraph attributes, and +/// those copies hold no more than 1,048,576 tab stops: the frames past them take the default +/// stops, with a warning. +#[test] +fn legacy_linked_area_frames_cap_their_copied_tab_stops() { + let many: String = (0..1024).map(|i| format!("0 0 1 {i} Xe\n")).collect(); + let area = format!("1 0 0 1 0 0 0 Tp\n{}n\nTP\n", rect_path(0.0, 0.0, 50.0, 40.0)); + let text = format!("1 To\n{}0 Tr\n36 1024 Xb\n{many}XB\n(a) Tx\nTO\n", area.repeat(4096)); + let r = legacy_read(&text); + let frames = art_frames(&r.doc); + assert_eq!(frames.len(), 4096); + let stops: Vec = frames.iter().map(|(_, f)| f.para_at(0).tabs.len()).collect(); + assert_eq!(stops.iter().filter(|&&n| n == 1024).count(), 1025); + assert_eq!(stops.iter().filter(|&&n| n == 0).count(), 3071); + assert_eq!(r.warnings, ["tab stops past VectorCraft's limits were left out"]); +} + +/// The warning when linked areas are left out. +const LINKED_AREAS_LEFT_OUT: &str = "linked type areas past VectorCraft's limits were left out"; +const DIRECTION_CHANGE_LEFT_OUT: &str = "type that changes writing direction inside a text object opens in the direction of its first character"; + +/// The frames of linked areas times the characters of their story are kept to the reader's +/// allowance of characters: a story of more than half of it gets one frame, and of a third, two. +#[test] +fn legacy_area_type_keeps_its_frames_times_characters_to_the_allowance() { + const ALLOWANCE: usize = 1 << 22; + let area = |x: f64| format!("1 0 0 1 {x} 0 0 Tp\n{}n\nTP\n", rect_path(x, 0.0, x + 50.0, 40.0)); + for (chars, kept) in [(ALLOWANCE / 2 + 1, 1), (ALLOWANCE / 3, 3), (ALLOWANCE / 3 + 1, 2)] { + let text = format!("1 To\n{}0 Tr\n({}) Tx\n{}{}TO\n", area(0.0), "a".repeat(chars), area(60.0), area(120.0)); + let r = legacy_read(&text); + let frames = art_frames(&r.doc); + assert_eq!(frames.len(), kept, "{chars}"); + assert_eq!(r.doc.text_threads.len(), usize::from(kept > 1), "{chars}"); + assert_eq!(frames[0].1.plain_text().len(), chars); + assert_eq!(r.warnings.iter().any(|w| w == LINKED_AREAS_LEFT_OUT), kept < 3, "{chars}"); + } +} + +/// Point type and type on a path have one text path (§15.2): one with more is read at its first. +#[test] +fn legacy_point_and_path_type_with_several_text_paths_use_the_first() { + let point = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n(a) Tx\n1 0 0 1 90 20 0 Tp\nTP\n(b) Tx\nTO\n"; + let r = legacy_read(point); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one object: {frames:?}") }; + assert!(matches!(only.kind, vectorcraft_doc::TextKind::Point) && r.doc.text_threads.is_empty()); + assert_eq!(only.plain_text(), "ab"); + assert!(same_matrix(only.xf, r.to_doc * Affine::translate((10.0, 50.0)) * Affine::FLIP_Y), "the first text path's matrix: {:?}", only.xf); + let on_path = "2 To\n1 0 0 1 0 0 0.5 Tp\n0 0 m\n100 0 L\nN\nTP\n0 Tr\n(a) Tx\n1 0 0 1 0 0 0 Tp\n0 50 m\n100 50 L\nN\nTP\n(b) Tx\nTO\n"; + let r = legacy_read(on_path); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one object: {frames:?}") }; + let vectorcraft_doc::TextKind::OnPath { path, start, .. } = &only.kind else { panic!("{:?}", only.kind) }; + assert!((start - 0.5).abs() < 1e-9, "the first text path's start: {start}"); + let along = kurbo::Shape::bounding_box(&(only.xf * path.to_bezpath())); + assert!((along.y0 - r.to_doc.transform_rect_bbox(Rect::new(0.0, 0.0, 100.0, 0.0)).y0).abs() < 1e-9, "{along:?}"); + assert!(same_matrix(only.xf, r.to_doc * Affine::FLIP_Y), "{:?}", only.xf); + // Type on a path whose first text path has no path: the first one with a path, its matrix and + // start included. + let later = "2 To\n1 0 0 1 30 30 0.25 Tp\nTP\n0 Tr\n(a) Tx\n1 0 0 1 5 0 0.5 Tp\n0 50 m\n100 50 L\nN\nTP\n(b) Tx\nTO\n"; + let r = legacy_read(later); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one object: {frames:?}") }; + let vectorcraft_doc::TextKind::OnPath { start, .. } = &only.kind else { panic!("{:?}", only.kind) }; + assert!((start - 0.5).abs() < 1e-9, "{start}"); + assert!(same_matrix(only.xf, r.to_doc * Affine::translate((5.0, 0.0)) * Affine::FLIP_Y), "{:?}", only.xf); + // Area type with no frame at all: point type at its first text path. + let frameless = "1 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n(a) Tx\n1 0 0 1 90 20 0 Tp\nTP\n(b) Tx\nTO\n"; + let r = legacy_read(frameless); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one object: {frames:?}") }; + assert!(matches!(only.kind, vectorcraft_doc::TextKind::Point), "{:?}", only.kind); + assert!(same_matrix(only.xf, r.to_doc * Affine::translate((10.0, 50.0)) * Affine::FLIP_Y), "{:?}", only.xf); +} + +/// The dictionary that follows a threaded text object (version 9 and later): its opacity mask and +/// text wrap go on every frame, and its name on the first frame, which holds the story. +#[test] +fn the_dictionary_after_linked_area_type_applies_to_its_frames() { + let dict = "%_/ArtDictionary :\n%_(Story) /String (AIArtName) ,\n%_12.5 /Real (AI11TextWrapOffset) ,\n\ + %_0 /Bool (AI11TextWrapInvert) ,\n%_/Mask :\n%_1 /Bool (Linked) ,\n%_0 /Bool (Disabled) ,\n%_X=\n\ + %_0 0 0 1 k\n%_0 0 m\n%_5 0 L\n%_5 5 L\n%_0 5 L\n%_0 0 L\n%_f\n%_X+\n%_ (Art) ,\n%_1 /Bool (Clipping) ,\n\ + %_0 /Bool (Inverted) ,\n%_; (AI9_Mask) ,\n%_;\n"; + let area = |x: f64| format!("1 0 0 1 {x} 40 0 Tp\n{}n\nTP\n", rect_path(x, 0.0, x + 50.0, 40.0)); + let text = format!("1 To\n{}0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(a) Tx\n{}{}(b) Tx\nTO\n{dict}", area(0.0), area(60.0), area(120.0)); + let r = read_ok(&layer(&text)); + let ids: Vec<_> = art_frames(&r.doc).into_iter().map(|(id, _)| id).collect(); + assert_eq!(r.doc.text_threads, std::slice::from_ref(&ids), "{:?}", r.warnings); + let nodes: Vec<&Node> = ids.iter().filter_map(|id| r.doc.node(*id)).collect(); + assert_eq!(nodes.len(), 3); + for n in &nodes { + assert!(n.extras().mask.is_some(), "every frame is masked: {:?}", n.id); + assert_eq!(wrap_of(n), Some(vectorcraft_doc::TextWrap { offset: 12.5, invert: false })); + } + let names: Vec<_> = nodes.iter().map(|n| n.name.as_deref()).collect(); + assert_eq!(names, [Some("Story"), None, None]); } #[test] fn what_it_doesnt_read_is_an_error_where_it_shows() { let e = read(stream(&layer("1 2 frobnicate\n")).as_bytes()).unwrap_err(); assert!(e.contains("`frobnicate`"), "{e}"); - let e = read(stream(&layer("(Jive) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n")).as_bytes()).unwrap_err(); - assert!(e.contains("pattern fills"), "{e}"); + let r = read(stream(&layer(&format!("(Jive) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(0.0, 0.0, 1.0, 1.0)))).as_bytes()).unwrap(); + assert_unread(&r, "pattern fills"); let e = read(stream(&layer("/SymbolInstance :\n(Dot) /SymbolRef ,\n;\n")).as_bytes()).unwrap_err(); assert!(e.contains("symbols"), "{e}"); // A mask with no owner must still be reported (#2004). @@ -944,6 +4577,220 @@ fn what_it_doesnt_read_is_an_error_where_it_shows() { read_ok(&format!("Adobe_level2_AI5 /initialize get exec\n{}", layer(""))); } +#[test] +fn a_group_still_open_at_the_end_is_an_error() { + let square = format!("{}f\n", rect_path(0.0, 0.0, 10.0, 10.0)); + for open in ["u", "q", "*u", "%_u"] { + let e = read(stream(&format!("{}{open}\n{square}", layer(""))).as_bytes()).unwrap_err(); + assert_eq!(e, "it ends inside a group or compound path", "{open}"); + } + // A group open inside a layer that doesn't end is the layer's error. + let unended = format!("%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\nu\n{square}"); + assert_eq!(read(stream(&unended).as_bytes()).unwrap_err(), "it ends inside a layer"); + // Patterns read with a group of their own still read. + assert!(read_ok(&format!("{DOTS}{}", layer(""))).doc.pattern("Dots").is_some()); +} + +#[test] +fn unresolved_pattern_reset_before_group_path_keeps_live_art() { + for (operator, draw, reset) in [("p", "f", "0 0 0 1 k"), ("P", "S", "0 0 0 1 K")] { + let body = format!("u\n(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n{reset}\n{}{draw}\nU\n", rect_path(0.0, 0.0, 4.0, 4.0),); + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{operator}: {:?}", result.unread); + let children = art(&result.doc); + assert_eq!(children.len(), 1, "{operator}: group count"); + let group_art = children[0].children().expect("group children"); + assert_eq!(group_art.len(), 1, "{operator}: live path count"); + assert!(matches!(group_art[0].kind, NodeKind::Path { .. })); + } +} + +#[test] +fn unresolved_pattern_in_dictionary_does_not_mark_following_path_unread() { + for (operator, draw) in [("p", "f"), ("P", "S")] { + let body = format!("/Unused :\n(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n;\n{}{draw}\n", rect_path(0.0, 0.0, 4.0, 4.0),); + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{operator}: {:?}", result.unread); + let children = art(&result.doc); + assert_eq!(children.len(), 1, "{operator}: live path count"); + assert!(matches!(children[0].kind, NodeKind::Path { .. })); + } +} + +#[test] +fn color_in_dictionary_does_not_clear_outer_unresolved_pattern() { + for (operator, draw, color) in [("p", "f", "0 0 0 1 k"), ("P", "S", "0 0 0 1 K")] { + let body = format!("(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n/Unused :\n{color}\n;\n{}{draw}\n", rect_path(0.0, 0.0, 4.0, 4.0),); + let result = read_ok(&layer(&body)); + assert_unread(&result, "pattern fills"); + assert_eq!(art(&result.doc).len(), 1, "{operator}: unread path placeholder"); + } +} + +#[test] +fn gradient_instance_after_unresolved_pattern_is_read() { + let defs = + "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n<00FF>\n0\n%_0 0 0 0 1 0 0 2 1 6 50 0 Bs\n%_0 0 0 0 0 0 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + for (operator, flag, draw) in [("p", "", "f"), ("P", "1 ", "S")] { + let body = format!( + "(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n{}{draw}\n{}{flag}Bb\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n10 0 0 10 100 50 Xm\n{draw}\n0 BB\n", + rect_path(0.0, 0.0, 4.0, 4.0), + rect_path(10.0, 0.0, 14.0, 4.0), + ); + let result = read(stream(&format!("{defs}{}", layer(&body))).as_bytes()).unwrap(); + assert_unread(&result, "pattern fills"); + let a = art(&result.doc); + assert_eq!(a.len(), 2, "{operator}"); + assert_eq!(result.unread[0].0, a[0].id, "{operator}: only the pattern's path is unread"); + } +} + +#[test] +fn unresolved_pattern_in_mask_art_stays_unread() { + let mask_path = rect_path(0.0, 0.0, 4.0, 4.0).lines().map(|line| format!("%_{line}\n")).collect::(); + let patterned = format!("%_(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{mask_path}%_f\n"); + // A placed file with no preview, and a symbol whose definition the file doesn't have. + let placed = "%_%AI5_BeginPlace\n%_%%FileType: 1\n%_[5 0 0 -5 0 200] 10 20 14 22 4 4 0\n%_(missing.png)`\n%_%%IncludeFile:missing.png\n%_~\n%_%AI5_EndPlace\n"; + let symbol = "%_/SymbolInstance :\n%_(Absent) /SymbolRef ,\n%_;\n"; + for (art_, kind) in [ + (patterned.as_str(), "pattern fills"), + ("%_/Mesh X!\n%_/End X!\n", "gradient meshes it can't read"), + (placed, "placed files"), + (symbol, "symbols"), + ("%_1 2 frobnicate\n", "`frobnicate`"), + ] { + let mask = format!( + "%_/ArtDictionary :\n%_/Mask :\n%_X=\n{art_}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_1 /Bool (Linked) ,\n%_; (AI9_Mask) ,\n%_;\n" + ); + let masked = format!("{RED}{}f\n{mask}", rect_path(0.0, 0.0, 4.0, 4.0)); + let e = read(stream(&layer(&masked)).as_bytes()).unwrap_err(); + assert!(e.contains(kind), "{e}"); + // In a group, the group is the unread object. + let result = read_ok(&layer(&format!("u\n{masked}U\n"))); + assert_unread(&result, kind); + assert!(result.hidden_unread.is_empty(), "{kind}: {:?}", result.hidden_unread); + // A disabled mask doesn't change how its object looks: what it holds is left out. + let disabled = masked.replace("%_1 /Bool (Linked) ,\n", "%_1 /Bool (Linked) ,\n%_1 /Bool (Disabled) ,\n"); + for body in [disabled.clone(), format!("u\n{disabled}U\n")] { + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{kind}: {:?}", result.unread); + assert!(result.hidden_unread.contains(kind), "{kind}: {:?}", result.hidden_unread); + } + } + // Operators a mask's art doesn't know are kept up to 16. + let ops = (0..40).map(|i| format!("%_op{i}\n")).collect::(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{ops}%_X+\n%_(Art) ,\n%_1 /Bool (Linked) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let result = read_ok(&layer(&format!("u\n{RED}{}f\n{mask}U\n", rect_path(0.0, 0.0, 4.0, 4.0)))); + assert_eq!(result.unread.len(), 1); + assert_eq!(result.unread[0].1.len(), 16); +} + +#[test] +fn hidden_unread_art_beside_drawn_look_needs_no_page_replacement() { + let hidden_path = rect_path(0.0, 0.0, 4.0, 4.0).lines().map(|line| format!("%_{line}\n")).collect::(); + for (operator, draw, reset) in [("p", "f", "0 0 0 1 k"), ("P", "S", "0 0 0 1 K")] { + let body = format!( + "u\n%_(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n{hidden_path}%_{draw}\n{reset}\n{}{draw}\nU\n", + rect_path(10.0, 0.0, 14.0, 4.0), + ); + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{operator}: {:?}", result.unread); + assert!(result.hidden_unread.contains("pattern fills")); + let children = art(&result.doc); + let group_art = children[0].children().expect("group children"); + assert_eq!(group_art.len(), 2); + assert!(matches!(group_art[1].kind, NodeKind::Path { .. })); + } +} + +#[test] +fn unknown_operator_on_hidden_line_does_not_mark_drawn_group_unread() { + let body = format!("u\n%_1 2 frobnicate\n{RED}{}f\nU\n", rect_path(10.0, 0.0, 14.0, 4.0)); + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{:?}", result.unread); + assert!(result.hidden_unread.contains("`frobnicate`")); + assert_eq!(art(&result.doc)[0].children().expect("group children").len(), 1); +} + +/// A commented closing delimiter does not hide a visible group's unread content. +#[test] +fn visible_group_closed_on_hidden_line_stays_unread() { + let body = format!("u\n1 2 frobnicate\n{RED}{}f\n%_U\n", rect_path(10.0, 0.0, 14.0, 4.0)); + let result = read_ok(&layer(&body)); + assert_eq!(result.unread.len(), 1); + assert!(result.unread[0].1.contains(&"`frobnicate`".to_string())); + assert!(!result.hidden_unread.contains("`frobnicate`")); +} + +/// `Xw` hides unread objects even when their operators are on ordinary lines. +#[test] +fn xw_hidden_unread_keeps_visible_group_sibling() { + for unread in + ["1 2 frobnicate\n", "(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n0 0 m\n4 0 L\n4 4 L\nf\n", "/SymbolInstance :\n(Absent) /SymbolRef ,\n;\n"] + { + let body = format!("u\n1 Xw\n{unread}0 Xw\n0 0 0 1 k\n{}f\nU\n", rect_path(10.0, 0.0, 14.0, 4.0)); + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{unread}: {:?}", result.unread); + assert!(!result.hidden_unread.is_empty(), "{unread}"); + let children = art(&result.doc); + let group_art = children[0].children().expect("group children"); + assert_eq!(group_art.iter().filter(|node| node.visible).count(), 1, "{unread}"); + } + let mut data = placed(true, "[5 0 0 -5 0 200]", "missing.png", None, "0 Xw\n"); + let at = data.windows(15).position(|w| w == b"%AI5_BeginPlace").unwrap(); + data.splice(at..at, *b"1 Xw\n"); + let result = read(&data).unwrap(); + assert!(result.unread.is_empty()); + assert!(result.hidden_unread.contains("placed files")); +} + +#[test] +fn hidden_unread_symbol_does_not_mark_drawn_group_unread() { + let body = format!("u\n%_/SymbolInstance :\n%_(Absent) /SymbolRef ,\n%_;\n{RED}{}f\nU\n", rect_path(10.0, 0.0, 14.0, 4.0)); + let result = read_ok(&layer(&body)); + assert!(result.unread.is_empty(), "{:?}", result.unread); + assert!(result.hidden_unread.contains("symbols")); + assert_eq!(art(&result.doc)[0].children().expect("group children").len(), 1); +} + +#[test] +fn unresolved_pattern_paint_persists_past_plain_group_until_replaced() { + for (operator, draw, reset) in [("p", "f", "0 0 0 1 k"), ("P", "S", "0 0 0 1 K")] { + let body = format!( + "u\n(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n{}{draw}\nU\n{}{draw}\n{reset}\n{}{draw}\n", + rect_path(0.0, 0.0, 4.0, 4.0), + rect_path(10.0, 0.0, 14.0, 4.0), + rect_path(20.0, 0.0, 24.0, 4.0), + ); + let result = read_ok(&layer(&body)); + assert_eq!(result.unread.len(), 2, "{operator}: {:?}", result.unread); + assert_eq!(art(&result.doc).len(), 3); + } +} + +#[test] +fn unresolved_pattern_paint_inside_clip_restores_at_q() { + for (operator, draw, reset) in [("p", "f", "0 0 0 1 k"), ("P", "S", "0 0 0 1 K")] { + let body = format!( + "q\n(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\n{}{draw}\nQ\n{}{draw}\n", + rect_path(0.0, 0.0, 4.0, 4.0), + rect_path(10.0, 0.0, 14.0, 4.0), + ); + let result = read_ok(&layer(&body)); + assert_eq!(result.unread.len(), 1, "{operator}: {:?}", result.unread); + assert_eq!(art(&result.doc).len(), 2); + + let body = format!( + "(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] {operator}\nq\n{reset}\n{}{draw}\nQ\n{}{draw}\n", + rect_path(0.0, 0.0, 4.0, 4.0), + rect_path(10.0, 0.0, 14.0, 4.0), + ); + let result = read_ok(&layer(&body)); + assert_eq!(result.unread.len(), 1, "{operator}: {:?}", result.unread); + assert_eq!(result.unread[0].0, art(&result.doc)[1].id); + } +} + #[test] fn sections_it_skips() { let body = "%AI5_Begin_NonPrinting\n%AI14_BeginSymbol\n0 Ae\nu\nfrobnicate\n%AI10_EndSymbol\n%AI3_BeginPattern: (P)\nU\nU\n%AI3_EndPattern\n%AI5_End_NonPrinting--\n\ @@ -951,6 +4798,422 @@ fn sections_it_skips() { %_/Document :\n%_/Binary : /ASCII85Decode ,\n%_(]<[%\n%;;;~>\n%_; (Profile) ,\n%_;\n"; let doc = read_ok(&format!("{body}{}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")))).doc; assert_eq!(art(&doc).len(), 1); + // A symbol whose art can't be read isn't kept. + assert!(doc.symbols.is_empty()); +} + +/// Symbol definitions as the editing data writes them, in a section that doesn't print. +fn symbols(defs: &str) -> String { + format!("%AI5_Begin_NonPrinting\n{defs}%AI5_End_NonPrinting--\n") +} + +/// A symbol named `name` whose art is `art` (in the symbol's space, y down), with the registration +/// point `registration` (1 to 9 from the top left, row by row). +fn symbol(name: &str, art: &str, registration: u32) -> String { + format!( + "%AI14_BeginSymbol\n({name})\n0 A\n0 Xw\n0 Ae\nu\n{art}U\n%_/ArtDictionary :\n%_{registration} /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n" + ) +} + +/// An instance of the symbol named `name`, `m` taking the symbol's art to art space. +fn instance(name: &str, m: [f64; 6]) -> String { + let [a, b, c, d, e, f] = m; + format!("/SymbolInstance :\n({name}) /SymbolRef ,\n{a} {b} {c} {d} {e} {f} /RTransformMatrix\n;\n") +} + +/// A red square of 4 points about the origin, as a symbol's art. +fn dot() -> String { + format!("{RED}{}f\n", rect_path(-2.0, -2.0, 2.0, 2.0)) +} + +/// The visual box of `n` in `doc`, its instances measured by their symbols' art. +fn instance_box(doc: &Document, n: &Node) -> Rect { + n.visual_bounds_with(&doc.symbol_boxes()).expect("a box") +} + +#[test] +fn a_symbol_comes_in_once_and_its_instances_stay_live() { + let body = symbols(&symbol("Dot", &dot(), 5)) + + &layer(&(instance("Dot", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]) + &instance("Dot", [2.0, 0.0, 0.0, -2.0, 100.0, 50.0]))); + let mut doc = read_ok(&body).doc; + assert_eq!(doc.symbols.len(), 1); + assert_eq!(doc.symbols[0].name, "Dot"); + assert!(doc.symbol_registration("Dot").is_center()); + let a = art(&doc); + assert_eq!(a.len(), 2); + let xfs: Vec<_> = a + .iter() + .map(|n| if let NodeKind::SymbolInstance { symbol, xf } = &n.kind { (symbol.clone(), *xf) } else { panic!("{:?}", n.kind) }) + .collect(); + assert_eq!(xfs[0].0, "Dot"); + assert_ne!(xfs[0].1, xfs[1].1); + assert_eq!(instance_box(&doc, &a[0]), Rect::new(18.0, 48.0, 22.0, 52.0)); + assert_eq!(instance_box(&doc, &a[1]), Rect::new(96.0, 46.0, 104.0, 54.0)); + // Editing the symbol's art changes both instances. + let wider = read_ok(&(symbols(&symbol("Dot", &format!("{RED}{}f\n", rect_path(-4.0, -2.0, 4.0, 2.0)), 5)) + &layer(""))).doc; + doc.symbols[0].art = wider.symbols[0].art.clone(); + assert_eq!(instance_box(&doc, &a[0]), Rect::new(16.0, 48.0, 24.0, 52.0)); + assert_eq!(instance_box(&doc, &a[1]), Rect::new(92.0, 46.0, 108.0, 54.0)); +} + +#[test] +fn an_instance_in_a_symbols_art_is_placed_from_the_canvas() { + // The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). + let nested = instance("Dot", [1.0, 0.0, 0.0, -1.0, -8081.0, 8237.0]); + let defs = symbols(&(symbol("Dot", &dot(), 5) + &symbol("Pair", &nested, 1))); + let body = format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{defs}{}", layer(&instance("Pair", [1.0, 0.0, 0.0, -1.0, 50.0, 50.0]))); + let doc = read_ok(&body).doc; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["Dot", "Pair"]); + assert_eq!(doc.symbol_registration("Pair"), vectorcraft_doc::SymbolRegistration(0)); + // Dot sits at (10, 5) in Pair's art, which the page instance puts at (50, 50). + let a = art(&doc); + assert_eq!(instance_box(&doc, &a[0]), Rect::new(58.0, 53.0, 62.0, 57.0)); +} + +#[test] +fn an_image_in_a_symbols_art_is_placed_from_the_canvas() { + // The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). The + // image's matrix is in the canvas's space turned y up about that point, as an instance's in a + // symbol's art is: its top left pixel goes to (-5, -2.5) in the symbol's art. + let m = "[ 5 0 0 5 -8096 8244.5 ]"; + let raster = format!( + "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceRGB XN\n{m} 2 1 0 Xh\n{m} 0 0 2 1 2 1 8 3 0 0 1 0 4 4 0 0\n\ + %%BeginData: 6\rXI\nABCDEF%%EndData\r\nXH\r\n%AI5_EndRaster\r\nN\n" + ); + let body = format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Pic", &raster, 5)), layer("")); + let doc = read_ok(&body).doc; + assert_eq!(doc.symbols.len(), 1); + let NodeKind::Image(im) = &doc.symbols[0].art.kind else { panic!("{:?}", doc.symbols[0].art.kind) }; + for ((u, v), want) in [((0.0, 0.0), (-5.0, -2.5)), ((2.0, 0.0), (5.0, -2.5)), ((0.0, 1.0), (-5.0, 2.5))] { + let got = im.xf * Point::new(u, v); + assert!((got - Point::new(want.0, want.1)).hypot() < 1e-9, "pixel ({u}, {v}): {got:?}, want {want:?}"); + } + // A linked image (`XG` and `XF`) is placed the same way. + let linked = raster7("(a.tif) 0 XG\n", m, (2, 1), "XF", ""); + let doc = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Link", &linked, 5)), layer(""))).doc; + let NodeKind::Image(link) = &doc.symbols[0].art.kind else { panic!("{:?}", doc.symbols[0].art.kind) }; + assert!(link.link.is_some()); + assert!((link.xf * Point::new(0.0, 0.0) - Point::new(-5.0, -2.5)).hypot() < 1e-9, "{:?}", link.xf); + // Without a template box the image can't be placed, so the symbol isn't read whole: its + // instance comes in as the page draws it. + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Pic", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&(symbols(&symbol("Pic", &raster, 5)) + &layer(&group))); + assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::>()); + assert_eq!(r.unread.len(), 1, "{:?}", r.warnings); +} + +#[test] +fn an_instance_keeps_its_hide_lock_transparency_and_clip() { + let m = [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]; + let art_ = format!( + "1 Xw\n{}0 Xw\n1 A\n{}0 A\n{}1 0.5 1 1 1 Xy\n0 0 Xd\n6 () XW\n0 Ae\nq\n{}{}h\nW\nn\nQ\n0 0.25 0 0 0 Xy\n{}", + instance("Dot", m), + instance("Dot", m), + instance("Dot", m), + instance("Dot", m), + rect_path(19.0, 49.0, 21.0, 51.0), + instance("Dot", m), + ); + let doc = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&art_))).doc; + let a = art(&doc); + assert_eq!(a.len(), 5); + assert!(!a[0].visible && !a[0].locked); + assert!(a[1].visible && a[1].locked); + // An instance's transparency is the `Xy` after it, as a group's is; one set before it isn't its. + assert_eq!((a[2].opacity, a[2].blend, a[2].isolate, a[2].knockout, a[2].knockout_shape), (0.5, BlendMode::Multiply, true, Knockout::On, true)); + assert_eq!((a[1].opacity, a[1].blend, a[1].isolate, a[1].knockout), (1.0, BlendMode::Normal, false, Knockout::Neutral)); + assert_eq!((a[3].opacity, a[4].opacity), (0.25, 1.0)); + let NodeKind::Group { children, clip: true } = &a[3].kind else { panic!("a clipping group: {:?}", a[3].kind) }; + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); + assert!(matches!(children[1].kind, NodeKind::SymbolInstance { .. })); +} + +/// The art of an opacity mask in a symbol's art takes ids of the document, as the rest of the art +/// does: no two objects of the document, in its layers or its symbols, share an id. +#[test] +fn a_symbols_opacity_mask_art_takes_ids_of_the_document() { + fn ids(n: &Node, out: &mut Vec) { + out.push(n.id); + if let Some(m) = n.extras().mask.as_ref() { + ids(&m.art, out); + } + for c in n.children().into_iter().flatten() { + ids(c, out); + } + } + let square = rect_path(-2.0, -2.0, 2.0, 2.0); + let mask_art: String = format!("1 g\n{square}f\n").lines().map(|l| format!("%_{l}\n")).collect(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let defs = symbols(&symbol("Masked", &format!("{RED}{square}f\n{mask}{}", dot()), 5)); + let shapes: String = (0..6).map(|i| format!("{RED}{}f\n", rect_path(f64::from(i) * 10.0, 0.0, f64::from(i) * 10.0 + 4.0, 4.0))).collect(); + let doc = read_ok(&(defs + &layer(&format!("{shapes}{}", instance("Masked", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))))).doc; + let mut all = Vec::new(); + for n in doc.layers.iter().chain(doc.symbols.iter().map(|s| &s.art)) { + ids(n, &mut all); + } + assert!(doc.symbols.iter().any(|s| s.art.children().into_iter().flatten().any(|c| c.extras().mask.is_some())), "the mask is read"); + let unique: std::collections::HashSet<_> = all.iter().copied().collect(); + assert_eq!(unique.len(), all.len(), "{all:?}"); +} + +/// A layer's `Xy` right after its last object, an instance, before the layer's `0 0 Xd` and +/// `7 () XW`, is the layer's; the instance's own state block (`6 () XW`) keeps it the instance's. +#[test] +fn a_layers_state_after_its_last_symbol_instance_is_the_layers() { + let last = instance("Dot", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]); + let doc = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&format!("{last}1 0.6 0 2 0 Xy\n0 0 Xd\n7 () XW\n")))).doc; + assert_eq!((doc.layers[0].opacity, doc.layers[0].blend), (0.6, BlendMode::Multiply)); + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].blend), (1.0, BlendMode::Normal)); + let doc = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&format!("{last}1 0.6 0 2 0 Xy\n0 0 Xd\n6 () XW\n")))).doc; + assert_eq!(doc.layers[0].opacity, 1.0); + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].blend), (0.6, BlendMode::Multiply)); +} + +#[test] +fn the_symbol_list_orders_the_symbols_and_names_stay_apart() { + let defs = symbol("A", &dot(), 5) + &symbol("B", &dot(), 5) + &symbol("A", &dot(), 5) + &symbol("C", &dot(), 9); + for list in [ + "%AI24_BeginSymbolList\n(C)\n(Ghost)\n(B)\n(C)\n%AI24_EndSymbolList\n", + "%AI10_BeginSymbolList\n(C)\n(Ghost)\n(B)\n(C)\n%AI10_EndSymbolList\n", + ] { + let doc = read_ok(&(symbols(&format!("{defs}{list}")) + &layer(&instance("A", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))).doc; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["C", "B", "A", "A 2"], "{list}"); + assert_eq!(doc.symbol_registration("C"), vectorcraft_doc::SymbolRegistration(8)); + // An instance names the first symbol the file gives that name. + assert!(matches!(&art(&doc)[0].kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "A")); + } +} + +/// A symbol whose art is filled with a pattern isn't kept: its instances come in as the page draws +/// them, within the box of its art. The pattern keeps the name it was numbered with. +#[test] +fn a_symbol_with_a_pattern_fill_isnt_kept() { + let pattern = DOTS.replace("(Dots)", "(Red\\n1)"); + let lawn = symbol("Lawn", &format!("(Red\\n1) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(-2.0, -2.0, 2.0, 2.0)), 5); + let r = read_ok(&format!("{pattern}{}{}", symbols(&lawn), layer(&instance("Lawn", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + assert_eq!(r.doc.patterns.iter().map(|p| p.name.as_str()).collect::>(), ["Red 2"]); + assert!(r.doc.symbols.is_empty()); + assert_unread(&r, "symbols"); + let (id, _) = &r.unread[0]; + assert_eq!(r.doc.node(*id).and_then(|n| n.geometric_bounds()), Some(Rect::new(18.0, 48.0, 22.0, 52.0))); + // A pattern chosen and then replaced by a color before the art is painted fills nothing. + let solid = symbol("Solid", &format!("(Red\\n1) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{RED}{}f\n", rect_path(-2.0, -2.0, 2.0, 2.0)), 5); + let r = read_ok(&format!("{pattern}{}{}", symbols(&solid), layer(&instance("Solid", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + assert_eq!(r.doc.symbols.len(), 1); + assert!(r.unread.is_empty()); +} + +#[test] +fn an_instance_of_a_symbol_it_doesnt_have_is_the_unread_object() { + let missing = instance("Absent", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]); + // Alone on the layer, the file isn't read: the page has no box for it. + let e = read(stream(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&missing))).as_bytes()).unwrap_err(); + assert!(e.contains("symbols"), "{e}"); + // In a group, the group is the unread object. + let group = format!("0 Ae\nu\n{missing}{RED}{}f\nU\n", rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&group))); + assert_unread(&r, "symbols"); + // Nor is a symbol whose art holds an instance of one the file doesn't have: the page has no box + // for its instances. + let holder = symbol("Holder", &(dot() + &instance("Absent", [1.0, 0.0, 0.0, -1.0, 0.0, 0.0])), 5); + let body = + format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&holder), layer(&instance("Holder", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))); + let e = read(stream(&body).as_bytes()).unwrap_err(); + assert!(e.contains("symbols"), "{e}"); + // An instance whose matrix doesn't have six finite numbers isn't read either. + let bad = "/SymbolInstance :\n(Dot) /SymbolRef ,\n1 0 0 -1 20 /RTransformMatrix\n;\n"; + let r = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&format!("0 Ae\nu\n{bad}U\n")))); + assert_unread(&r, "symbols"); +} + +#[test] +fn an_instance_whose_appearance_differs_from_its_symbols_comes_in_as_the_page_draws_it() { + let edited = "/SymbolInstance :\n(Dot) /SymbolRef ,\n1 0 0 -1 20 50 /RTransformMatrix\n,\n/Dictionary :\n; (AI19SymbolAppearanceMap) ,\n;\n"; + let r = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(edited))); + assert_unread(&r, "symbols"); + let (id, _) = &r.unread[0]; + assert_eq!(r.doc.node(*id).and_then(|n| n.geometric_bounds()), Some(Rect::new(18.0, 48.0, 22.0, 52.0)), "the box is the symbol's, placed"); + // The appearance changes are found in a dictionary that an array holds as a value without a key. + let in_array = "/SymbolInstance :\n(Dot) /SymbolRef ,\n1 0 0 -1 20 50 /RTransformMatrix\n,\n\ + /Array :\n/Dictionary :\n/Dictionary :\n; (AI19SymbolAppearanceMap) ,\n;\n;\n; (Edits) ,\n;\n"; + let r = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(in_array))); + assert_unread(&r, "symbols"); + // So does an instance of a symbol whose art isn't read whole, within that art's box. + let partial = symbol("Partial", &format!("{}f\n1 Xw\n1 2 frobnicate\n0 Xw\n", rect_path(-2.0, -2.0, 2.0, 2.0)), 5); + let r = read_ok(&(symbols(&partial) + &layer(&instance("Partial", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + assert!(r.doc.symbols.is_empty()); + assert_unread(&r, "symbols"); + let (id, _) = &r.unread[0]; + assert_eq!(r.doc.node(*id).and_then(|n| n.geometric_bounds()), Some(Rect::new(18.0, 48.0, 22.0, 52.0))); +} + +/// A symbol whose art holds an image that is left out (no matrix, a matrix with no area, data cut +/// short) isn't kept, so its instances don't draw it without the image. +#[test] +fn a_symbol_with_an_image_it_leaves_out_isnt_kept() { + for (what, image) in [ + ("no matrix", raster7("", "", (1, 1), "XI", "%FF0000\n")), + ("a matrix with no area", raster7("", "[ 0 0 0 0 0 0 ]", (1, 1), "XI", "%FF0000\n")), + ("data cut short", raster7("", "[ 1 0 0 1 0 0 ]", (2, 2), "XI", "%FF0000\n")), + ("no end", raster7("", "[ 1 0 0 1 0 0 ]", (1, 1), "XI", "%FF0000\n").replace("%AI5_EndRaster\n", "")), + ("art after a trailer", format!("%%PageTrailer\n{}", raster7("", "[ 1 0 0 1 0 0 ]", (1, 1), "XI", "%FF0000\n"))), + ] { + // With a template box, so that the image could be placed. + let defs = symbols(&symbol("Photo", &(dot() + &image), 5)); + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Photo", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{defs}{}", layer(&group))); + assert!(r.doc.symbols.is_empty(), "{what}"); + assert_eq!(r.unread.len(), 1, "{what}: {:?}", r.warnings); + } +} + +/// A symbol's art written as a group holding one object stays that group when the group is tagged +/// (`XT`), so the tag isn't lost. +#[test] +fn a_symbols_tagged_group_keeps_its_tag() { + let def = format!( + "%AI14_BeginSymbol\n(Tagged)\n0 A\n0 Xw\n0 Ae\nu\n{}U\n/AdobeURL (https://example.com/a) XT\n%_/ArtDictionary :\n%_5 /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n", + dot() + ); + let doc = read_ok(&(symbols(&def) + &layer(&instance("Tagged", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))).doc; + let art = &doc.symbols[0].art; + assert!(matches!(art.kind, NodeKind::Group { .. }), "{:?}", art.kind); + assert_eq!(tags(art).0, "https://example.com/a"); +} + +/// A definition whose art a trailer stops isn't kept, though the art before the trailer is whole. +#[test] +fn a_symbol_cut_off_by_a_trailer_isnt_kept() { + let cut = format!("%AI14_BeginSymbol\n(Cut)\n0 A\n0 Xw\n0 Ae\n{}%%PageTrailer\n{}%AI10_EndSymbol\n", dot(), dot()); + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Cut", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&(symbols(&cut) + &layer(&group))); + assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::>()); + assert_unread(&r, "symbols"); +} + +/// A symbol whose art holds type, a placed file, non-native art, an image it can't place or a +/// gradient the file doesn't define isn't kept. Its instances come in as the page draws them, within the box of the rest of its art, an +/// instance right on a layer as well as one in a group. +#[test] +fn a_symbols_art_it_leaves_out_gives_its_instances_the_box_of_the_rest() { + let typed = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n".to_string(); + let placed = "%AI5_BeginPlace\n%AI5_EndPlace\n".to_string(); + let foreign = + "/ForeignObject :\n1 /Version ,\n2 0 0 2 10 20 /RTransform ,\n10 20 /Origin ,\n1 2 5 8 /Bounds ,\n/Data ,\n%,u@!!/MSk8%41#ocdN=10d&\n%1H@\n;\n" + .to_string(); + let image = raster7("", "[ 1 0 0 1 0 0 ]", (1, 1), "XI", "%FF0000\n"); + let gradient = format!("Bb\n1 (Nowhere) 0 0 0 10 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", rect_path(-2.0, -2.0, 2.0, 2.0)); + let template = "%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n"; + for (what, left, head) in [ + ("type", typed, template), + ("a placed file", placed, template), + ("non-native art", foreign, template), + ("an image without a template box", image, ""), + ("a gradient the file doesn't define", gradient, template), + ] { + let defs = symbols(&symbol("Mixed", &(dot() + &left), 5)); + let body = format!("{head}{defs}{}", layer(&instance("Mixed", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))); + let r = read(stream(&body).as_bytes()).unwrap_or_else(|e| panic!("{what}: {e}")); + assert!(r.doc.symbols.is_empty(), "{what}"); + assert_unread(&r, "symbols"); + let (id, _) = &r.unread[0]; + assert_eq!(r.doc.node(*id).and_then(|n| n.geometric_bounds()), Some(Rect::new(18.0, 48.0, 22.0, 52.0)), "{what}"); + } + // A gradient the file doesn't define on a path that isn't painted paints nothing. + // Nor does one on a path that a group's start drops, for the paths after it. + let square = rect_path(-2.0, -2.0, 2.0, 2.0); + for (what, unpainted) in [ + ("not painted", format!("Bb\n1 (Nowhere) 0 0 0 10 1 0 0 1 0 0 Bg\n{square}n\n0 BB\n")), + ("dropped", format!("Bb\n1 (Nowhere) 0 0 0 10 1 0 0 1 0 0 Bg\n{square}0 BB\nu\n{square}f\nU\n")), + ] { + let defs = symbols(&symbol("Kept", &(dot() + &unpainted), 5)); + let r = read_ok(&format!("{template}{defs}{}", layer(&instance("Kept", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + assert_eq!(r.doc.symbols.len(), 1, "{what}: {:?}", r.warnings); + assert!(r.unread.is_empty(), "{what}"); + } +} + +#[test] +fn symbols_that_hold_each_other_lose_the_instances_that_close_the_loop() { + let m = [1.0, 0.0, 0.0, -1.0, 0.0, 0.0]; + let defs = symbols(&(symbol("S1", &instance("S2", m), 5) + &symbol("S2", &instance("S1", m), 5))); + let r = + read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{defs}{}", layer(&(dot() + &instance("S1", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))))); + assert!(r.warnings.contains(&vectorcraft_doc::depth::symbols_note()), "{:?}", r.warnings); + assert!(!r.doc.clone().limit_depth(), "nothing is left that draws itself"); +} + +/// A definition after the first layer isn't read: the symbols were checked before that layer, and +/// one read later could hold an instance of a symbol the file doesn't have. +#[test] +fn a_symbol_defined_after_the_first_layer_is_not_read() { + let late = symbols(&symbol("Late", &(dot() + &instance("Absent", [1.0, 0.0, 0.0, -1.0, 0.0, 0.0])), 5)); + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Late", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{late}{}", layer(&dot()), layer(&group))); + assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::>()); + assert_unread(&r, "symbols"); +} + +/// A filled square at x = `10 × i` (5 pt wide), to tell the alternatives of versioned content apart. +fn alt_square(i: u32) -> String { + let x = f64::from(i) * 10.0; + rect_path(x, 0.0, x + 5.0, 5.0) + "f\n" +} + +/// The left edges of the layer's art, in order: which [`alt_square`]s came in. +fn squares(doc: &Document) -> Vec { + art(doc).iter().filter_map(|n| n.geometric_bounds()).map(|b| b.x0.round()).collect() +} + +/// Versioned content holds alternatives of the same art for newer and older versions (newer +/// files write a Dimension tool group, then the same group again for a version in between, then +/// plain art): only the first alternative is read, so the art comes in once, however many +/// alternatives follow and whatever versioned content is nested in them. +#[test] +fn versioned_content_reads_one_alternative() { + let (begin, between, alternate, end) = ( + "%AI17_Begin_Content_if_version_gt:24 11\n", + "%AI17_Alternate_Content_if_version_gt:24 10\n", + "%AI17_Alternate_Content\n", + "%AI17_End_Versioned_Content\n", + ); + let (a, b, c) = (alt_square(1), alt_square(2), alt_square(3)); + let cases = [ + ("one alternative", format!("{begin}{a}{end}"), vec![10.0]), + ("two alternatives", format!("{begin}{a}{alternate}{b}{end}"), vec![10.0]), + ("three alternatives", format!("{begin}{a}{between}{b}{alternate}{c}{end}"), vec![10.0]), + // Blocks nested in the first alternative read their own first; those in a later one aren't read. + ( + "nested", + format!( + "{begin}{a}{begin}{b}{alternate}{c}{end}{between}{}{begin}{}{alternate}{}{end}{alternate}{}{end}", + alt_square(4), + alt_square(5), + alt_square(6), + alt_square(7) + ), + vec![10.0, 20.0], + ), + // Art after the block is read as usual. + ("art after it", format!("{begin}{a}{between}{b}{alternate}{c}{end}{}", alt_square(8)), vec![10.0, 80.0]), + ]; + for (case, body, want) in cases { + let s = read_ok(&layer(&body)); + assert_eq!(squares(&s.doc), want, "{case}"); + assert!(!s.warnings.iter().any(|w| w == read::VERSIONED_UNENDED), "{case}: {:?}", s.warnings); + } +} + +/// Versioned content whose end is missing is read whole, with a note, rather than losing the rest +/// of the file. +#[test] +fn versioned_content_that_does_not_end_is_read_with_a_note() { + let body = format!("%AI17_Begin_Content_if_version_gt:24 11\n{}%AI17_Alternate_Content_if_version_gt:24 10\n{}", alt_square(1), alt_square(2)); + let s = read_ok(&layer(&body)); + assert_eq!(squares(&s.doc), [10.0, 20.0]); + assert!(s.warnings.iter().any(|w| w == read::VERSIONED_UNENDED), "{:?}", s.warnings); } /// Non-native art (a placed PDF's content) keeps its PDF as ASCII85 in comment lines after @@ -965,6 +5228,166 @@ fn non_native_art_that_is_not_a_pdf_is_left_out_with_a_note() { assert!(s.warnings.iter().any(|w| w.starts_with(read::NON_NATIVE_ART_UNREAD)), "{:?}", s.warnings); } +/// The same data in a symbol's definition: its `%_` line with a `(` opens no string, so the +/// definition ends at its own end marker and the symbol after it comes in. +#[test] +fn non_native_art_in_a_symbol_ends_at_the_definitions_end() { + let foreign = "/ForeignObject :\n1 /Version ,\n2 0 0 2 10 20 /RTransform ,\n10 20 /Origin ,\n1 2 5 8 /Bounds ,\n/Data ,\n%,u@!!/MSk8%41#ocdN=10d&\n%_O%*mGn(RduU.]4`[u[.f\n%_;(]<[%\n%1H@\n;\n"; + let defs = symbols(&(symbol("Pdf", &format!("{foreign}{}", dot()), 5) + &symbol("Dot", &dot(), 5))); + let s = read_ok(&(defs + &layer(&instance("Dot", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + let names: Vec<&str> = s.doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert!(names.contains(&"Dot"), "{names:?}"); + let a = art(&s.doc); + assert_eq!(a.len(), 1); + assert!(matches!(&a[0].kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Dot"), "{:?}", a[0].kind); +} + +/// Comment lines between a dictionary's name and its `:`, or an entry's key and its `,`, don't hide +/// the data from the scan of a symbol's definition. +#[test] +fn non_native_art_with_comments_in_a_symbol_ends_at_the_definitions_end() { + let foreign = "/ForeignObject\n%note\n:\n1 /Version ,\n2 0 0 2 10 20 /RTransform ,\n10 20 /Origin ,\n1 2 5 8 /Bounds ,\n/Data\n%note\n,\n%,u@!!/MSk8%41#ocdN=10d&\n%_O%*mGn(RduU.]4`[u[.f\n%_;(]<[%\n%1H@\n;\n"; + let defs = symbols(&(symbol("Pdf", &format!("{foreign}{}", dot()), 5) + &symbol("Dot", &dot(), 5))); + let s = read_ok(&(defs + &layer(&instance("Dot", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + let names: Vec<&str> = s.doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert!(names.contains(&"Dot"), "{names:?}"); +} + +/// A string keys an entry as a name does: `(Data) ,` doesn't hide the data from the scan of a +/// symbol's definition either. +#[test] +fn non_native_art_keyed_by_a_string_in_a_symbol_ends_at_the_definitions_end() { + for key in ["(Data)", "<44617461>"] { + let foreign = format!( + "/ForeignObject :\n1 /Version ,\n2 0 0 2 10 20 /RTransform ,\n10 20 /Origin ,\n1 2 5 8 /Bounds ,\n{key} ,\n%,u@!!/MSk8%41#ocdN=10d&\n%_O%*mGn(RduU.]4`[u[.f\n%_;(]<[%\n%1H@\n;\n" + ); + let defs = symbols(&(symbol("Pdf", &format!("{foreign}{}", dot()), 5) + &symbol("Dot", &dot(), 5))); + let s = read_ok(&(defs + &layer(&instance("Dot", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + let names: Vec<&str> = s.doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert!(names.contains(&"Dot"), "{key}: {names:?}"); + } +} + +/// A `/Binary` dictionary's data in a skipped alternate: its `%_` line with a `(` opens no string, +/// so the block ends at its own end marker. +#[test] +fn binary_data_in_a_skipped_alternate_ends_at_the_blocks_end() { + let binary = "%_/Document :\n%_/Binary : /ASCII85Decode ,\n%_(]<[%\n%;;;~>\n%_; (Profile) ,\n%_;\n"; + let body = format!( + "%AI17_Begin_Content_if_version_gt:24 4\n%AI17_Alternate_Content\n{binary}frobnicate\n%AI17_End_Versioned_Content\n{}", + layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")) + ); + let s = read_ok(&body); + assert_eq!(art(&s.doc).len(), 1); + assert!(!s.warnings.iter().any(|w| w == read::VERSIONED_UNENDED), "{:?}", s.warnings); +} + +/// A text document's data, the free type's undo copy included: its `%_` line with a `(` opens no +/// string, even after a line that reads as another section's end marker, so the section ends at +/// its own end marker and the art after it comes in. +#[test] +fn text_document_data_ends_at_the_sections_end() { + for ty in ["AI11TextDocument", "AI11UndoFreeTextDocument"] { + let document = + format!("%AI11_BeginTextDocument\n/{ty} : /ASCII85Decode ,\n%,u@!!/MSk8\n%AI3_EndPattern\n%_(]<[%\n%;;;~>\n%_;\n%AI11_EndTextDocument\n"); + let s = read_ok(&format!("{document}{}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")))); + assert_eq!(art(&s.doc).len(), 1, "{ty}"); + } +} + +/// Data without its `~>` isn't skipped: the section still ends at its own end marker, with no `~>` +/// after it, with one in a later section, and with later data that holds a `(` on a `%_` line. +#[test] +fn data_without_its_end_does_not_hide_the_sections_end() { + let unended = "%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n%,u@!!/MSk8\n%AI11_EndTextDocument\n"; + let ended = "%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n%,u@!!/MSk8\n%_(]<[%\n%;;;~>\n%_;\n%AI11_EndTextDocument\n"; + let art_layer = layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")); + for body in [format!("{unended}{art_layer}"), format!("{unended}{art_layer}{ended}"), format!("{unended}{ended}{art_layer}")] { + let s = read_ok(&body); + assert_eq!(art(&s.doc).len(), 1, "{body}"); + } +} + +/// Data without its `~>` is skipped up to the section's end marker: its `%_` line with a `(` opens +/// no string, so the section ends there and the art after it comes in. A `%` right after the key +/// starts no marker, so it doesn't end the data. +#[test] +fn data_without_its_end_holding_a_string_ends_at_the_sections_end() { + let art_layer = layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")); + for document in [ + "%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n%,u@!!/MSk8\n%_(]<[%\n%AI11_EndTextDocument\n", + "%AI11_BeginTextDocument\r\n/AI11TextDocument : /ASCII85Decode ,\r\n%_(]<[%\r\n%AI11_EndTextDocument\r\n", + "%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,%AI11_EndTextDocument\n%_(]<[%\n%AI11_EndTextDocument\n", + ] { + let s = read_ok(&format!("{document}{art_layer}")); + assert_eq!(art(&s.doc).len(), 1, "{document}"); + } +} + +/// Data without its `~>` stops at the start of a section of the same kind nested after it too, so +/// the outer section still ends at its own end marker and not at the nested one's. +#[test] +fn data_without_its_end_stops_at_a_nested_sections_start() { + let square = rect_path(0.0, 0.0, 1.0, 1.0) + "f\n"; + let body = format!( + "%AI17_Begin_Content_if_version_gt:24 4\n%AI17_Alternate_Content\n/Binary : /ASCII85Decode ,\n%_(]<[%\n\ + %AI17_Begin_Content_if_version_gt:23 1\nfrobnicate\n%AI17_End_Versioned_Content\n{square}%AI17_End_Versioned_Content\n{}", + layer(&square) + ); + let s = read_ok(&body); + assert_eq!(art(&s.doc).len(), 1); + assert!(!s.warnings.iter().any(|w| w == read::VERSIONED_UNENDED), "{:?}", s.warnings); +} + +/// Versioned content that doesn't end is scanned again for the swatches' names: data with its `~>` +/// is still skipped, though data with none comes after it, and the dictionary open where the +/// content starts still counts. +#[test] +fn swatch_names_are_found_past_data_in_versioned_content_that_does_not_end() { + let entries = "1 /Version ,\n2 0 0 2 10 20 /RTransform ,\n10 20 /Origin ,\n1 2 5 8 /Bounds ,\n/Data ,\n%,u@!!/MSk8%41#ocdN=10d&\n%_O%*mGn(RduU.]4`[u[.f\n%_;(]<[%\n%1H@\n;\n0 0 Xd\n6 () XW\n0 Ae\n"; + let alternate = "%AI17_Begin_Content_if_version_gt:24 4\n%AI17_Alternate_Content\n"; + let sea = format!("0 1 1 0 (Sea) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0)); + let unended = "%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n%,u@!!/MSk8\n%AI11_EndTextDocument\n"; + for art_text in [format!("{alternate}/ForeignObject :\n{entries}{sea}{unended}"), format!("/ForeignObject :\n{alternate}{entries}{sea}{unended}")] + { + let body = format!("{}{}", DOTS.replace("(Dots)", "(Sea\\n1)"), layer(&art_text)); + let d = read(stream(&body).as_bytes()).unwrap().doc; + let names: Vec<&str> = d.patterns.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["Sea 2"], "{art_text}"); + } +} + +/// A search for where data stops that found nothing outside a section doesn't stop a later +/// section's data at that section's end, so the named color after it still takes its name first. +/// The `/Binary` holds a group, where the reader doesn't take what follows its key as data. +#[test] +fn swatch_names_are_found_past_data_in_a_section_after_a_search_outside_sections_found_nothing() { + let sea = format!("0 1 1 0 (Sea) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0)); + let before = "/Binary :\nu\n/ASCII85Decode ,\nU\n;\n"; + for section in [ + "%AI17_Begin_Content_if_version_gt:24 4\n%AI17_Alternate_Content\n/Binary : /ASCII85Decode ,\n%_(]<[%\n%AI17_End_Versioned_Content\n", + "%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n%_(]<[%\n%AI11_EndTextDocument\n", + ] { + let art_text = format!("{before}{section}{sea}"); + let body = format!("{}{}", DOTS.replace("(Dots)", "(Sea\\n1)"), layer(&art_text)); + let d = read(stream(&body).as_bytes()).unwrap().doc; + let names: Vec<&str> = d.patterns.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["Sea 2"], "{art_text}"); + } +} + +/// The names the swatches take are found past the same data: a named color after it still takes +/// its name first, and the pattern named after it is numbered. +#[test] +fn swatch_names_are_found_past_non_native_art_data() { + let foreign = "/ForeignObject :\n1 /Version ,\n2 0 0 2 10 20 /RTransform ,\n10 20 /Origin ,\n1 2 5 8 /Bounds ,\n/Data ,\n%,u@!!/MSk8%41#ocdN=10d&\n%_O%*mGn(RduU.]4`[u[.f\n%_;(]<[%\n%1H@\n;\n0 0 Xd\n6 () XW\n0 Ae\n"; + let sea = format!("0 1 1 0 (Sea) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0)); + let body = format!("{}{}", DOTS.replace("(Dots)", "(Sea\\n1)"), layer(&format!("{foreign}{sea}"))); + let d = read(stream(&body).as_bytes()).unwrap().doc; + let names: Vec<&str> = d.patterns.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["Sea 2"]); +} + /// A PDF with one page of `size` points holding `content`. fn tiny_pdf(size: f64, content: &str) -> Vec { let objects = [ @@ -1206,17 +5629,79 @@ fn editing_data_past_256_mib_is_read() { assert!(raw.len() < 1 << 20, "zeros compress"); let data = decode_private(&raw).unwrap(); assert_eq!(data.len(), body.len()); - assert!(too_large().contains("512 MB")); + assert_eq!(too_large(), format!("it decompresses to more than {} MB", max_data() >> 20)); +} + +/// The limit is an eighth of installed memory, never under the 512 MiB every 64-bit build read +/// before and never over 2 GiB (#3510). +#[cfg(target_pointer_width = "64")] +#[test] +fn the_editing_data_limit_follows_installed_memory() { + const GIB: u64 = 1 << 30; + assert_eq!(data_limit(None), 512 << 20, "unknown memory keeps the old limit"); + assert_eq!(data_limit(Some(2 * GIB)), 512 << 20); + assert_eq!(data_limit(Some(4 * GIB)), 512 << 20); + assert_eq!(data_limit(Some(8 * GIB)), GIB); + assert_eq!(data_limit(Some(12 * GIB)), 3 * GIB / 2); + assert_eq!(data_limit(Some(16 * GIB)), 2 * GIB); + assert_eq!(data_limit(Some(256 * GIB)), 2 * GIB, "capped, so a tiny file can't take all of a big machine"); + assert!((MIN_DATA..=MAX_DATA).contains(&max_data())); +} + +/// On a machine with 8 GiB or more, editing data past the old 512 MiB limit opens with its layers +/// (#3510, #4628): a layered file whose rasters unpack to 600 MiB. +#[cfg(target_pointer_width = "64")] +#[test] +fn editing_data_past_512_mib_is_read_where_memory_allows() { + if max_data() < 601 << 20 { + return; + } + let mut body = stream(&format!("{}{}", layer(&rect_path(0.0, 0.0, 10.0, 10.0)), layer(&rect_path(20.0, 20.0, 30.0, 30.0)))).into_bytes(); + let filler = vec![b'%'; (600 << 20) - body.len()]; + let at = body.windows(14).position(|w| w == b"%%PageTrailer\n").unwrap(); + body.splice(at..at, filler); + let raw = [&b"%AI12_CompressedData"[..], &crate::ps::deflate(&body)].concat(); + let data = decode_private(&raw).unwrap(); + assert_eq!(data.len(), body.len()); + drop(body); + let r = read(&data).unwrap(); + assert_eq!(r.doc.layers.len(), 2, "both layers are read"); +} + +/// Past the limit the data is still refused, so the file opens as its PDF part with a note. +#[test] +fn editing_data_past_the_limit_is_refused() { + let raw = [&b"%AI12_CompressedData"[..], &crate::ps::deflate(b"%%")].concat(); + assert!(Codec::Zlib.decode(raw.get(20..).unwrap(), 1).is_err()); + assert!(Codec::Zlib.decode(raw.get(20..).unwrap(), 2).is_ok()); } #[test] fn many_zstandard_frames_are_read_in_one_pass_and_capped() { let frame = zstd(b" "); let frames = |n: usize| -> Vec { [&b"%AI24_ZStandard_Data"[..], &frame.repeat(n), &[0; 64]].concat() }; - let started = std::time::Instant::now(); - assert_eq!(decode_private(&frames(4000)).unwrap().len(), 4000); - assert!(decode_private(&frames(50_000)).unwrap_err().contains("Zstandard")); - assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed()); + let (few, many) = (frames(4000), frames(50_000)); + let before = padding_looks(); + assert_eq!(decode_private(&few).unwrap().len(), 4000); + assert!(decode_private(&many).unwrap_err().contains("Zstandard")); + // The first byte of each of the 4,000 frames and of the 4,097 read before the cap, and the + // 64 zeros of padding once: looking past the frames to the padding before each frame would + // look at 64 or more bytes per frame. + let looked = padding_looks() - before; + assert!(looked <= 2 * (4000 + 4097 + 64), "looked at {looked} bytes for padding"); +} + +/// A Zstandard frame that ends in a zero byte keeps it: only the zeros after the last frame are +/// padding. +#[test] +fn a_zstandard_frame_ending_in_a_zero_byte_is_read_whole() { + // Magic number, a single-segment header with a 1-byte content size of 3, and one raw block + // (last, 3 bytes) holding `ab` and a zero byte. + let frame = [0x28, 0xB5, 0x2F, 0xFD, 0x20, 3, 0x19, 0, 0, b'a', b'b', 0]; + for padding in [0, 64] { + let raw = [&b"%AI24_ZStandard_Data"[..], &frame, &frame, &vec![0; padding]].concat(); + assert_eq!(decode_private(&raw).unwrap(), b"ab\0ab\0"); + } } #[test] @@ -1239,14 +5724,15 @@ fn artboards_after_what_stops_the_reading() { let array = format!("%_/Array :\n{}{}%_; (ArtboardArray) ,\n", board("one", 0), board("two", 200)); // Art in the document's own data that the reader can't follow comes before the artboards. let data = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n%_/Dictionary :\nLB\n{array}%_; /NotRecorded ,\n%_;\n"); - let boards: Vec<_> = super::artboards(data.as_bytes()).into_iter().map(|(n, r)| (n, r.x0)).collect(); + let boards: Vec<_> = super::artboards(data.as_bytes()).0.into_iter().map(|(n, r)| (n, r.x0)).collect(); assert_eq!(boards, [("one".to_string(), 0.0), ("two".to_string(), 200.0)]); } #[test] fn a_compound_clipping_path_with_a_fill_paints_once_under_its_clip() { - // GUARDS: the painted copies of a compound's clipping subpaths went into the compound itself, - // doubling each subpath, so under even-odd the clip cancelled to nothing. + // GUARDS: copies that painted a compound's clipping subpaths went into the compound itself, + // doubling each subpath, so under even-odd the clip cancelled to nothing. The compound + // clipping path keeps the fill itself. let art_ = format!( "0 Ae\nq\n{RED}{}f\n1 XR\n*u\n0 0 0 0 0 0 1 Xa\n{}W\nf\n{}W\nf\n*U\nQ\n", rect_path(0.0, 0.0, 100.0, 100.0), @@ -1255,14 +5741,13 @@ fn a_compound_clipping_path_with_a_fill_paints_once_under_its_clip() { ); let doc = read_ok(&layer(&art_)).doc; let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("a clipping group") }; - assert_eq!(children.len(), 3, "{children:#?}"); + assert_eq!(children.len(), 2, "{children:#?}"); let NodeKind::Compound { children: clip, rule } = &children[0].kind else { panic!("{:?}", children[0].kind) }; assert_eq!(*rule, vectorcraft_geom::FillRule::EvenOdd); assert_eq!(clip.len(), 2); assert!(clip.iter().all(|c| matches!(c.kind, NodeKind::Path { clipping: true, .. }))); - let NodeKind::Compound { children: painted, .. } = &children[1].kind else { panic!("{:?}", children[1].kind) }; - assert_eq!((painted.len(), fill(&children[1]).color()), (2, Some(Color::rgb(0.0, 0.0, 1.0)))); - assert_eq!(fill(&children[2]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); + assert_eq!(fill(&children[0]).color(), Some(Color::rgb(0.0, 0.0, 1.0))); + assert_eq!(fill(&children[1]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); } #[test] @@ -1287,12 +5772,14 @@ const ART_STYLES: &str = "%AI9_BeginArtStyles\n\ /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n\ - /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n3 /Real (horz) ,\n4 /Real (vert) ,\n; /Dict ;\n /Part ,\n;\n\ + /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n1 /Int (blnd) ,\n0.75 /Real (opac) ,\n5 /Real (blur) ,\n\ + 0 /Int (csrc) ,\n/FillStyle : 0 O\n0 0 0 1 0 0 0 Xa\n0 1 Xd\n/Def ;\n (sclr) ,\n3 /Real (horz) ,\n4 /Real (vert) ,\n; /Dict ;\n /Part ,\n;\n\ /KnownStyle :\n(Lit) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n1 (G) 0 0 0 1 1 0 0 1 0 0 Bg\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n\ - /BasicFilter :\n(Adobe Outer Glow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n0.5 /Real (opac) ,\n2 /Real (blur) ,\n; /Dict ;\n /Part ,\n;\n\ + /BasicFilter :\n(Adobe Outer Glow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n2 /Int (blnd) ,\n0.5 /Real (opac) ,\n2 /Real (blur) ,\n\ + /FillStyle : 0 O\n0 0 0 0 1 1 0 Xa\n0 1 Xd\n/Def ;\n (sclr) ,\n; /Dict ;\n /Part ,\n;\n\ %AI9_EndArtStyles\n"; #[test] @@ -1314,6 +5801,528 @@ fn an_object_with_a_style_this_reads_comes_in_as_itself() { assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); } +/// An art style named `name`: a blue fill under a red 2 pt stroke written as a Stroke Offset filter +/// whose `StrokeOffsetInside` entry is `inside` (`None`: left out). +fn offset_stroke_style(name: &str, inside: Option) -> String { + let switch = inside.map(|v| format!("{v} /Bool (StrokeOffsetInside) ,\n")).unwrap_or_default(); + offset_stroke_style_with(name, &switch, OFFSET_STROKE) +} + +/// The Stroke Offset stroke of [`offset_stroke_style`]: red, 2 pt, butt caps, miter joins, solid. +const OFFSET_STROKE: &str = "0 R\n0 1 1 0 1 0 0 XA\n0 J 0 j 2 w 10 M []0 d\n0 XR\n1 0 Xd"; + +/// An art style named `name`: a blue fill under a Stroke Offset filter whose dictionary holds +/// `entries` and the stroke style `stroke` (what follows `/StrokeStyle :`). +fn offset_stroke_style_with(name: &str, entries: &str, stroke: &str) -> String { + format!( + "/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Adobe Stroke Offset) 1 0 /Filter ,\n1 /Visible ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n{entries}(Side) /String (DisplayString) ,\n\ + /StrokeStyle : {stroke}\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n" + ) +} + +#[test] +fn a_stroke_offset_filter_is_a_stroke_aligned_inside_or_outside() { + // GUARDS: a style's stroke aligned inside or outside (Stroke panel › Align Stroke) left the object as its drawn look. + use vectorcraft_doc::StrokeAlign; + for (inside, align) in [(Some(1), Some(StrokeAlign::Inside)), (Some(0), Some(StrokeAlign::Outside)), (None, None), (Some(2), None)] { + let r = read_ok(&format!("%AI9_BeginArtStyles\n{}%AI9_EndArtStyles\n{}", offset_stroke_style("Edge", inside), layer(&styled_square("Edge")))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let stroke = a[0].appearance.stroke().map(|s| (s.align, s.width, s.paint.color())); + match align { + Some(align) => { + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look"); + assert_eq!(stroke, Some((align, 2.0, Some(Color::rgb(1.0, 0.0, 0.0))))); + assert_eq!(fill(&a[0]).color(), Some(Color::rgb(0.0, 0.0, 1.0))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + } + // Without a 0/1 switch, which side it paints isn't known: the drawn look stays. + None => assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{inside:?}: {:?}", r.warnings), + } + } +} + +/// A Stroke Offset stroke keeps the caps, joins, miter limit, dashes and width profile of its +/// style, as a Stroke Style Filter's does. +#[test] +fn a_stroke_offset_filter_keeps_its_strokes_style() { + use vectorcraft_doc::StrokeAlign; + let profile = "/Dictionary : /NotRecorded ,\n/Array :\n0 /Real ,\n1 /Real ,\n; (BSVariableWidthTValuesArray) ,\n\ + /Array :\n1 /Real ,\n0.1 /Real ,\n; (BSCenteredWidthsArray) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n"; + let entries = format!("0 /Bool (StrokeOffsetInside) ,\n{profile}"); + let stroke = "0 R\n0 1 1 0 1 0 0 XA\n1 J 2 j 3 w 4 M [5 10 ]0 d\n0 XR\n1 0 Xd"; + let style = offset_stroke_style_with("Edge", &entries, stroke); + let r = read_ok(&format!("%AI9_BeginArtStyles\n{style}%AI9_EndArtStyles\n{}", layer(&styled_square("Edge")))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look"); + let s = a[0].appearance.stroke().expect("a stroke"); + assert_eq!((s.align, s.width, s.cap, s.join, s.miter_limit), (StrokeAlign::Outside, 3.0, LineCap::Round, LineJoin::Bevel, 4.0)); + assert_eq!(s.dash.as_ref().map(|d| d.pattern.clone()), Some(vec![5.0, 10.0])); + assert_eq!(s.profile.as_ref().map(|p| p.points.clone()), Some(vec![(0.0, 1.0, 1.0), (1.0, 0.1, 0.1)])); +} + +/// A Stroke Offset stroke this doesn't read as a stroke keeps the object's drawn look: a switch +/// written as another kind, dashes aligned to corners and path ends, a gradient. +#[test] +fn a_stroke_offset_filter_with_a_stroke_this_does_not_read_keeps_the_drawn_look() { + let outside = "0 /Bool (StrokeOffsetInside) ,\n"; + let gradient = "0 R\nBb\n0 0 0 0 Bh\n2 (Red ramp) 0 0 90 1 1 0 0 1 0 0 1 Bg\n0 BB\n0 J 0 j 2 w 10 M []0 d\n0 XR\n1 0 Xd"; + let cases = [ + ("a switch written as a number", offset_stroke_style_with("Edge", "1 /Int (StrokeOffsetInside) ,\n", OFFSET_STROKE)), + ( + "dashes aligned to corners", + offset_stroke_style_with( + "Edge", + &format!("{outside}/Dictionary : /NotRecorded ,\n1 /Bool (BSDashAdj) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n"), + &OFFSET_STROKE.replace("[]0 d", "[5 10 ]0 d"), + ), + ), + ("a gradient", offset_stroke_style_with("Edge", outside, gradient)), + ]; + for (why, style) in cases { + let r = read_ok(&format!("%AI9_BeginArtStyles\n{style}%AI9_EndArtStyles\n{}", layer(&styled_square("Edge")))); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{why}: {:?}", r.warnings); + } +} + +/// A listed `[Default]` style whose stroke is aligned outside comes in as the default graphic +/// style with that stroke. +#[test] +fn a_default_style_with_a_stroke_aligned_outside_comes_in() { + use vectorcraft_doc::StrokeAlign; + let r = + read_ok(&format!("{}{}", styles_and_list(&[offset_stroke_style("[Default]", Some(0))], &["[Default]"]), layer(&styled_square("[Default]")))); + assert_eq!(style_names(&r.doc), [("[Default]".to_string(), 1)]); + let stroke = r.doc.graphic_styles[0].appearance.stroke().map(|s| (s.align, s.width)); + assert_eq!(stroke, Some((StrokeAlign::Outside, 2.0))); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look"); + assert_eq!(a[0].extras().graphic_style, Some(1)); +} + +#[test] +fn a_symbol_defined_before_the_art_styles_reads_its_styled_objects() { + // GUARDS: objects in a symbol defined ahead of `%AI9_BeginArtStyles` (as Illustrator 24 writes + // its editing data) found no style and came in as their drawn look. + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + let styled = format!("u\n{RED}{}f\nU\n%_{hidden_rect}f\n1 (Blue) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let r = read_ok(&format!("{}{ART_STYLES}{}", symbols(&symbol("Tag", &styled, 1)), layer(""))); + let art = &r.doc.symbols.first().expect("the symbol").art; + let object = match &art.kind { + NodeKind::Group { children, .. } if children.len() == 1 => &children[0], + _ => art, + }; + assert!(matches!(object.kind, NodeKind::Path { .. }), "the object, not its look: {art:#?}"); + assert_eq!(object.appearance.fill().and_then(|f| f.paint.color()), Some(Color::rgb(0.0, 0.0, 1.0))); + let effects: Vec<_> = object.appearance.effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(effects, ["stylize.dropShadow"]); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + +/// `node` is the red square of [`styled_square`] read as itself with [`ART_STYLES`]' `Blue`: a blue +/// fill and a drop shadow, not the look it draws. +fn assert_blue_square(node: &Node) { + assert!(matches!(node.kind, NodeKind::Path { .. }), "the object, not its look: {node:#?}"); + assert_eq!(fill(node).color(), Some(Color::rgb(0.0, 0.0, 1.0))); + let effects: Vec<_> = node.appearance.effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(effects, ["stylize.dropShadow"]); +} + +/// An object in a pattern's art with an art style the file defines comes in as itself, as in a +/// symbol's art, whichever section comes first. +#[test] +fn an_object_in_a_patterns_art_with_a_style_this_reads_comes_in_as_itself() { + let pattern = format!("%AI3_BeginPattern: (P)\n(P) 0 0 10 10\n0 A\n0 Xw\n{}E\n%AI3_EndPattern\n", styled_square("Blue")); + for body in [format!("{ART_STYLES}{pattern}{}", layer("")), format!("{pattern}{ART_STYLES}{}", layer(""))] { + let r = read_ok(&body); + let def = r.doc.pattern("P").unwrap_or_else(|| panic!("{:?} {:?}", r.unread, r.warnings)); + let [square] = def.art.as_slice() else { panic!("{:#?}", def.art) }; + assert_blue_square(square); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + } +} + +/// The same in a pattern defined in the version 7 form: a layer's tile string holding the object. +#[test] +fn an_object_in_a_version_7_patterns_tile_with_a_style_this_reads_comes_in_as_itself() { + let tile = styled_square("Blue").replace('\n', "\r"); + let layers = format!("(0 O 0 R 0 0 0 1 k 0 0 0 1 K) @\n(\r{tile}) &\n"); + let s = pattern_read7(&format!("{ART_STYLES}{}", pattern7("Grid", &layers)), &pattern_layer7("Art", "")); + let def = s.doc.pattern("Grid").unwrap_or_else(|| panic!("{:?} {:?}", s.unread, s.warnings)); + let [square] = def.art.as_slice() else { panic!("{:#?}", def.art) }; + assert_blue_square(square); +} + +/// An object in a brush's art with an art style the file defines comes in as itself, and the brush +/// that uses the art is kept. +#[test] +fn an_object_in_a_brushs_art_with_a_style_this_reads_comes_in_as_itself() { + let section = format!("%AI8_BeginBrushPattern\n(Dot art)\n0 A\n{}%AI8_EndBrushPattern\n", styled_square("Blue")); + let r = read_ok(&format!("{section}{ART_STYLES}{}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(""))); + let lib = vectorcraft_brush::library(&r.doc); + let spray = lib.iter().find(|b| b.name == "Spray").unwrap_or_else(|| panic!("{:?}", r.warnings)); + assert!(matches!(spray.kind, vectorcraft_brush::BrushKind::Scatter(_)), "{:?}", spray.kind); + let art = spray.art(); + let [square] = art.as_slice() else { panic!("{art:#?}") }; + assert_blue_square(square); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + +/// The art of an opacity mask in a brush's art takes ids of the document, as the rest of the art +/// does: no object of the brush's art shares an id with an object of the layers. +#[test] +fn a_brushs_opacity_mask_art_takes_ids_of_the_document() { + fn ids(n: &Node, out: &mut Vec) { + out.push(n.id); + if let Some(m) = n.extras().mask.as_ref() { + ids(&m.art, out); + } + for c in n.children().into_iter().flatten() { + ids(c, out); + } + } + let square = rect_path(0.0, 0.0, 10.0, 10.0); + let mask_art: String = format!("1 g\n{square}f\n").lines().map(|l| format!("%_{l}\n")).collect(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let section = format!("%AI8_BeginBrushPattern\n(Dot art)\n0 A\n{RED}{square}f\n{mask}%AI8_EndBrushPattern\n"); + let shapes: String = (0..12).map(|i| format!("{RED}{}f\n", rect_path(f64::from(i) * 20.0, 0.0, f64::from(i) * 20.0 + 10.0, 10.0))).collect(); + let r = read_ok(&format!("{section}{}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(&shapes))); + let lib = vectorcraft_brush::library(&r.doc); + let spray = lib.iter().find(|b| b.name == "Spray").unwrap_or_else(|| panic!("{:?}", r.warnings)); + let art = spray.art(); + assert!(art.iter().any(|n| n.extras().mask.is_some()), "the mask is read: {art:#?}"); + let mut all = Vec::new(); + for n in r.doc.layers.iter().map(|l| &**l).chain(art) { + ids(n, &mut all); + } + let unique: std::collections::HashSet<_> = all.iter().copied().collect(); + assert_eq!(unique.len(), all.len(), "{all:?}"); +} + +/// An art styles section inside a symbol's, a pattern's or a brush's art is skipped: the file's own +/// art styles still style the layers' objects read after the definition. +#[test] +fn art_styles_inside_a_definition_leave_the_files_art_styles_alone() { + let nested = format!("%AI9_BeginArtStyles\n{}%AI9_EndArtStyles\n", fill_style("Other", "0 0 0 0 1 0 0 Xa\n")); + let square = styled_square("Blue"); + let definitions = [ + symbols(&symbol("Tag", &format!("{nested}{square}"), 1)), + format!("%AI3_BeginPattern: (P)\n(P) 0 0 10 10\n0 A\n0 Xw\n{nested}{square}E\n%AI3_EndPattern\n"), + format!("%AI8_BeginBrushPattern\n(Dot art)\n0 A\n{nested}{square}%AI8_EndBrushPattern\n"), + ]; + for definition in definitions { + let r = read_ok(&format!("{ART_STYLES}{definition}{}", layer(&square))); + let a = art(&r.doc); + let [object] = a.as_slice() else { panic!("{definition}: {a:#?}") }; + assert_blue_square(object); + } +} + +/// An art style named `name` (its bytes as written) that fills with colour `xa` (`c m y k r g b Xa`). +fn fill_style(name: &str, xa: &str) -> String { + fill_style_with(name, xa, "") +} + +/// [`fill_style`] with the filters `extra` after its fills. +fn fill_style_with(name: &str, xa: &str, extra: &str) -> String { + format!( + "/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n{extra};\n" + ) +} + +/// An art style named `name` with a drop shadow (every setting, Darkness) and no fills or strokes. +fn shadow_style(name: &str) -> String { + format!( + "/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n2 /Int (blnd) ,\n0.75 /Real (opac) ,\n3 /Real (horz) ,\n4 /Real (vert) ,\n5 /Real (blur) ,\n1 /Int (csrc) ,\n50 /Real (dark) ,\n; /Dict ;\n /Part ,\n;\n" + ) +} + +/// The art styles `defs` and the style list of `listed` (each written between parentheses as given). +fn styles_and_list(defs: &[String], listed: &[&str]) -> String { + let list: String = listed.iter().map(|n| format!("({n})\n")).collect(); + format!("%AI9_BeginArtStyles\n{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n{list}%AI9_EndArtStyleList\n", defs.concat()) +} + +/// A red square with its drawn look, read as itself with the art style `name` (`1 (name) XW`). +fn styled_square(name: &str) -> String { + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + format!("0 Ae\nu\n{RED}{}f\nU\n%_{hidden_rect}f\n1 ({name}) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)) +} + +fn style_names(doc: &Document) -> Vec<(String, u32)> { + doc.graphic_styles.iter().map(|g| (g.name.clone(), g.id)).collect() +} + +#[test] +fn listed_styles_replace_the_default_graphic_styles_and_link_their_objects() { + let defs = [fill_style("Red", "0 0 0 0 1 0 0 Xa\n"), fill_style("Blue", "0 0 0 0 0 0 1 Xa\n"), shadow_style("Shadow")]; + let r = read_ok(&format!("{}{}", styles_and_list(&defs, &["Red", "Blue", "Shadow"]), layer(&styled_square("Blue")))); + assert_eq!(style_names(&r.doc), [("Red".to_string(), 1), ("Blue".to_string(), 2), ("Shadow".to_string(), 3)]); + let blue = &r.doc.graphic_styles[1]; + assert_eq!(blue.appearance.fill().and_then(|f| f.paint.color()), Some(Color::rgb(0.0, 0.0, 1.0))); + let shadow = &r.doc.graphic_styles[2]; + assert_eq!(shadow.appearance.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.dropShadow"]); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look"); + assert_eq!(a[0].extras().graphic_style, Some(2)); +} + +#[test] +fn only_listed_styles_that_are_defined_and_read_come_in_once() { + // `Lit` paints with a gradient placed on each object; `Missing` has no definition. + let defs = [fill_style("Blue", "0 0 0 0 0 0 1 Xa\n"), ART_STYLES.lines().filter(|l| !l.starts_with('%')).map(|l| format!("{l}\n")).collect()]; + let r = read_ok(&format!("{}{}", styles_and_list(&defs, &["Blue", "Missing", "", "Lit", "Blue"]), layer(""))); + assert_eq!(style_names(&r.doc), [("Blue".to_string(), 1)]); +} + +#[test] +fn a_style_the_list_does_not_have_is_no_link() { + let defs = [fill_style("Blue", "0 0 0 0 0 0 1 Xa\n"), fill_style("Anon", "0 0 0 0 0 1 0 Xa\n")]; + let r = read_ok(&format!("{}{}", styles_and_list(&defs, &["Blue"]), layer(&styled_square("Anon")))); + assert_eq!(style_names(&r.doc), [("Blue".to_string(), 1)]); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert_eq!(fill(&a[0]).color(), Some(Color::rgb(0.0, 1.0, 0.0)), "the object still takes its appearance"); + assert_eq!(a[0].extras().graphic_style, None); +} + +#[test] +fn a_group_with_a_listed_style_is_linked() { + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + let group = format!("0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{hidden_rect}f\n%_U\n1 (Shadow) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let r = read_ok(&format!("{}{}", styles_and_list(&[shadow_style("Shadow")], &["Shadow"]), layer(&group))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(a[0].extras().graphic_style, Some(1)); +} + +#[test] +fn an_object_whose_transparency_differs_from_its_listed_style_is_not_linked() { + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + let square = + format!("0 Ae\nu\n{RED}{}f\nU\n1 0.6 0 2 0 Xy\n6 () XW\n%_0 1 0 0 0 Xy\n%_{hidden_rect}f\n1 (Blue) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let r = read_ok(&format!("{}{}", styles_and_list(&[fill_style("Blue", "0 0 0 0 0 0 1 Xa\n")], &["Blue"]), layer(&square))); + assert_eq!(style_names(&r.doc), [("Blue".to_string(), 1)]); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert_eq!(fill(&a[0]).color(), Some(Color::rgb(0.0, 0.0, 1.0))); + assert_eq!(a[0].opacity, 0.6); + assert_eq!(a[0].extras().graphic_style, None, "the style has full opacity"); +} + +#[test] +fn ai_import_registration_style_does_not_carry_over_previous_color_6205() { + // Regression test for #6205: + // A background shape sets a spot colour ("Shemen"). + // A following object has an art style with [Registration] at 0% tint. + // The object must resolve the Registration style ([Registration] 0% / #ffffff) + // rather than falling back to the prior spot color. + let defs = [fill_style("RegWhite", "1 1 1 1 ([Registration]) 1 Xs\n")]; + let background = format!("0 0.67 0.73 0.26 (Shemen) 0 0 Xx\n{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let styled_obj = styled_square("RegWhite"); + let content = format!("{background}{styled_obj}"); + let r = read_ok(&format!("{}{}", styles_and_list(&defs, &["RegWhite"]), layer(&content))); + let a = art(&r.doc); + assert_eq!(a.len(), 2, "{a:#?}"); + // First object is background in Shemen spot + let Paint::Solid { swatch: s0, .. } = fill(&a[0]) else { panic!("{:#?}", a[0]) }; + assert_eq!(s0.as_deref(), Some("Shemen")); + // Second object is styled in RegWhite: [Registration] at 0% tint (#ffffff) + let Paint::Solid { swatch, tint, color } = fill(&a[1]) else { panic!("{:#?}", a[1]) }; + assert_eq!(swatch.as_deref(), Some(vectorcraft_color::swatch::REGISTRATION)); + assert_eq!(tint, 0.0); + assert_eq!(color, Color::cmyk(1.0, 1.0, 1.0, 1.0).tinted(0.0)); +} + +#[test] +fn a_listed_style_keeps_its_transparency_and_links_objects_that_have_it() { + let blend = "/BasicFilter :\n(Blend Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /BlendStyle : 1 0.6 1 1 0 Xy\n0 J 0 j 1 w 10 M []0 d0 XR\n/Def ;\n (BlendStyle) ,\n; /Dict ;\n /Part ,\n"; + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + let square = + format!("0 Ae\nu\n{RED}{}f\nU\n1 0.6 1 1 0 Xy\n6 () XW\n%_0 1 0 0 0 Xy\n%_{hidden_rect}f\n1 (Blue) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let r = read_ok(&format!("{}{}", styles_and_list(&[fill_style_with("Blue", "0 0 0 0 0 0 1 Xa\n", blend)], &["Blue"]), layer(&square))); + let g = &r.doc.graphic_styles[0]; + assert_eq!((g.name.as_str(), g.opacity, g.blend, g.isolate, g.knockout), ("Blue", 0.6, BlendMode::Multiply, true, Knockout::On)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert_eq!(a[0].extras().graphic_style, Some(1), "{a:#?}"); +} + +#[test] +fn a_path_with_a_listed_style_that_fills_below_the_contents_is_linked() { + let below = "/KnownStyle :\n(Under) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n"; + let r = read_ok(&format!("{}{}", styles_and_list(&[below.to_string()], &["Under"]), layer(&styled_square("Under")))); + assert_eq!(r.doc.graphic_styles[0].appearance.contents_index, Some(1)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert_eq!(fill(&a[0]).color(), Some(Color::rgb(0.0, 0.0, 1.0))); + assert_eq!(a[0].extras().graphic_style, Some(1), "{a:#?}"); +} + +#[test] +fn a_style_name_outside_ascii_links_its_objects() { + // The list writes the name with escapes; the object's marker writes its UTF-8 bytes. + let defs = [fill_style("Caf\u{e9} \u{3a9}", "0 0 0 0 0 0 1 Xa\n")]; + let r = read_ok(&format!("{}{}", styles_and_list(&defs, &["Caf\\303\\251 \\316\\251"]), layer(&styled_square("Caf\u{e9} \u{3a9}")))); + assert_eq!(style_names(&r.doc), [("Caf\u{e9} \u{3a9}".to_string(), 1)]); + assert_eq!(art(&r.doc)[0].extras().graphic_style, Some(1)); +} + +#[test] +fn an_object_in_a_symbols_art_with_a_listed_style_is_linked() { + let defs = styles_and_list(&[fill_style("Blue", "0 0 0 0 0 0 1 Xa\n")], &["Blue"]); + let body = + format!("{defs}{}{}", symbols(&symbol("Tile", &styled_square("Blue"), 5)), layer(&instance("Tile", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))); + let r = read_ok(&body); + assert_eq!(style_names(&r.doc), [("Blue".to_string(), 1)]); + let tile = &r.doc.symbols[0].art; + assert!(matches!(tile.kind, NodeKind::Path { .. }), "{tile:#?}"); + assert_eq!(fill(tile).color(), Some(Color::rgb(0.0, 0.0, 1.0))); + assert_eq!(tile.extras().graphic_style, Some(1), "{tile:#?}"); + // A symbol's art written as a group holding one object stays that group when the group is + // linked to the style. + let empty = "/KnownStyle :\n(Empty) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n"; + let defs = styles_and_list(&[empty.to_string()], &["Empty"]); + let square = rect_path(0.0, 0.0, 10.0, 10.0); + let hidden = square.replace('\n', "\n%_"); + // The styled group is the definition's own group, without one around it. + let group = format!( + "%AI14_BeginSymbol\n(Group)\n0 A\n0 Xw\n0 Ae\nu\n{RED}{square}f\nU\n%_u\n%_{hidden}f\n%_U\n1 (Empty) XW\n\ + %_/ArtDictionary :\n%_5 /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n%AI10_EndSymbol\n" + ); + let body = format!("{defs}{}{}", symbols(&group), layer(&instance("Group", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))); + let art = &read_ok(&body).doc.symbols[0].art; + assert!(matches!(art.kind, NodeKind::Group { .. }), "{art:#?}"); + assert_eq!(art.extras().graphic_style, Some(1), "{art:#?}"); +} + +/// Editing data with symbols and no layers (a symbol library) gives its symbols: in the symbol +/// list's order with the unlisted one after them, with their registration points and the images +/// their art shows, without the one holding an instance of a symbol the data doesn't define, and +/// with the object linked to a listed graphic style linked to it by its id. +#[test] +fn a_symbol_library_without_layers_gives_its_symbols() { + let styles = styles_and_list(&[fill_style("Blue", "0 0 0 0 0 0 1 Xa\n")], &["Blue"]); + // The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). + let nested = instance("Dot", [1.0, 0.0, 0.0, -1.0, -8081.0, 8237.0]); + let lost = instance("Ghost", [1.0, 0.0, 0.0, -1.0, -8081.0, 8237.0]); + let m = "[ 5 0 0 5 -8096 8244.5 ]"; + let raster = format!( + "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceRGB XN\n{m} 2 1 0 Xh\n{m} 0 0 2 1 2 1 8 3 0 0 1 0 4 4 0 0\n\ + %%BeginData: 6\rXI\nABCDEF%%EndData\r\nXH\r\n%AI5_EndRaster\r\nN\n" + ); + let defs = symbols( + &(symbol("Dot", &dot(), 1) + + &symbol("Pic", &raster, 5) + + &symbol("Pair", &nested, 5) + + &symbol("Tile", &styled_square("Blue"), 5) + + &symbol("Lost", &lost, 5)), + ); + let list = "%AI24_BeginSymbolList\n(Tile)\n(Pair)\n(Lost)\n(Dot)\n%AI24_EndSymbolList\n"; + let body = format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{styles}{defs}{list}"); + let read = super::symbols(stream(&body).as_bytes()).expect("the library's symbols"); + let names: Vec<&str> = read.symbols.iter().map(|(s, _)| s.name.as_str()).collect(); + assert_eq!(names, ["Tile", "Pair", "Dot", "Pic"]); + let registrations: Vec = read.symbols.iter().map(|(_, r)| r.0).collect(); + let center = vectorcraft_doc::SymbolRegistration::CENTER.0; + assert_eq!(registrations, [center, center, 0, center]); + let Some(((tile, _), (pair, _))) = read.symbols.first().zip(read.symbols.get(1)) else { panic!("two symbols") }; + assert_eq!(tile.art.extras().graphic_style, Some(1), "{:#?}", tile.art); + // Dot sits at (10, 5) in Pair's art. + let mut doc = Document::new(1.0, 1.0); + doc.symbols = read.symbols.iter().map(|(s, _)| s.clone()).collect(); + assert_eq!(pair.art.visual_bounds_with(&doc.symbol_boxes()), Some(Rect::new(8.0, 3.0, 12.0, 7.0))); + let keys: Vec = + doc.symbols.iter().filter_map(|s| if let NodeKind::Image(im) = &s.art.kind { Some(im.key.clone()) } else { None }).collect(); + assert_eq!(keys.len(), 1); + assert_eq!(read.images.keys().cloned().collect::>(), keys); + // Without symbols there are none to give. + assert!(super::symbols(stream(&styles).as_bytes()).is_none()); +} + +#[test] +fn an_object_in_a_patterns_art_with_a_listed_style_is_linked() { + let defs = styles_and_list(&[fill_style("Blue", "0 0 0 0 0 0 1 Xa\n")], &["Blue"]); + let pattern = format!("%AI3_BeginPattern: (P)\n(P) 0 0 10 10\n0 A\n0 Xw\n{}E\n%AI3_EndPattern\n", styled_square("Blue")); + let r = read_ok(&format!("{defs}{pattern}{}", layer(""))); + assert_eq!(style_names(&r.doc), [("Blue".to_string(), 1)]); + let def = r.doc.pattern("P").unwrap_or_else(|| panic!("{:?}", r.warnings)); + let [square] = def.art.as_slice() else { panic!("{:#?}", def.art) }; + assert_eq!(fill(square).color(), Some(Color::rgb(0.0, 0.0, 1.0))); + assert_eq!(square.extras().graphic_style, Some(1), "{square:#?}"); +} + +/// The art of an opacity mask in a pattern's art takes ids of the document, as the rest of the art +/// does: no object of the pattern's art shares an id with an object of the layers. +#[test] +fn a_patterns_opacity_mask_art_takes_ids_of_the_document() { + fn ids(n: &Node, out: &mut Vec) { + out.push(n.id); + if let Some(m) = n.extras().mask.as_ref() { + ids(&m.art, out); + } + for c in n.children().into_iter().flatten() { + ids(c, out); + } + } + let square = rect_path(0.0, 0.0, 10.0, 10.0); + let mask_art: String = format!("1 g\n{square}f\n").lines().map(|l| format!("%_{l}\n")).collect(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let pattern = format!("%AI3_BeginPattern: (P)\n(P) 0 0 10 10\n0 A\n0 Xw\n{RED}{square}f\n{mask}E\n%AI3_EndPattern\n"); + let shapes: String = (0..12).map(|i| format!("{RED}{}f\n", rect_path(f64::from(i) * 20.0, 0.0, f64::from(i) * 20.0 + 10.0, 10.0))).collect(); + let r = read_ok(&format!("{pattern}{}", layer(&shapes))); + let def = r.doc.pattern("P").unwrap_or_else(|| panic!("{:?}", r.warnings)); + assert!(def.art.iter().any(|n| n.extras().mask.is_some()), "the mask is read: {:#?}", def.art); + let mut all = Vec::new(); + for n in r.doc.layers.iter().chain(&def.art) { + ids(n, &mut all); + } + let unique: std::collections::HashSet<_> = all.iter().copied().collect(); + assert_eq!(unique.len(), all.len(), "{all:?}"); +} + +#[test] +fn an_object_in_a_version_7_patterns_tile_with_a_listed_style_is_linked() { + let defs = styles_and_list(&[fill_style("Blue", "0 0 0 0 0 0 1 Xa\n")], &["Blue"]); + let tile = styled_square("Blue").replace('\n', "\r"); + let layers = format!("(0 O 0 R 0 0 0 1 k 0 0 0 1 K) @\n(\r{tile}) &\n"); + let s = pattern_read7(&format!("{defs}{}", pattern7("Grid", &layers)), &pattern_layer7("Art", "")); + assert_eq!(style_names(&s.doc), [("Blue".to_string(), 1)]); + let def = s.doc.pattern("Grid").unwrap_or_else(|| panic!("{:?}", s.warnings)); + let [square] = def.art.as_slice() else { panic!("{:#?}", def.art) }; + assert_eq!(fill(square).color(), Some(Color::rgb(0.0, 0.0, 1.0))); + assert_eq!(square.extras().graphic_style, Some(1), "{square:#?}"); +} + +#[test] +fn without_a_style_list_the_default_graphic_styles_stay() { + let defaults = style_names(&Document::new(1.0, 1.0)); + let r = read_ok(&format!("{ART_STYLES}{}", layer(&styled_square("Blue")))); + assert_eq!(style_names(&r.doc), defaults); + assert_eq!(art(&r.doc)[0].extras().graphic_style, None); + let r = read_ok(&format!("{}{}", styles_and_list(&[shadow_style("Shadow")], &["Missing"]), layer(""))); + assert_eq!(style_names(&r.doc), defaults, "a list naming no style it can read"); +} + #[test] fn an_object_with_a_feather_style_comes_in_with_a_live_effect() { let feather_style = "%AI9_BeginArtStyles\n\ @@ -1321,7 +6330,7 @@ fn an_object_with_a_feather_style_comes_in_with_a_live_effect() { /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n\ - /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n8 /Real (rad) ,\n; /Dict ;\n /Part ,\n;\n\ + /BasicFilter :\n(Adobe Fuzzy Mask) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n8 /Real (Radius) ,\n; /Dict ;\n /Part ,\n;\n\ %AI9_EndArtStyles\n"; let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Soft) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); @@ -1333,6 +6342,466 @@ fn an_object_with_a_feather_style_comes_in_with_a_live_effect() { assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); } +/// An art style section with style `PF`: an Effect › Pathfinder filter with `Command` `command` +/// and `Mix` `mix` in the object's chain, over a fill and stroke that paint nothing. +fn pathfinder_styles(command: u32, mix: f64) -> String { + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(PF) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Adobe Pathfinder) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + 0 /Bool (RemovePoints) ,\n{mix} /Real (Mix) ,\n1 /Bool (ConvertCustom) ,\n{command} /Int (Command) ,\n1 /Real (TrapMaxTint) ,\n\ + 1 /Real (TrapAspect) ,\n0.4 /Real (TrapTint) ,\n0.25 /Real (TrapThickness) ,\n0 /Bool (TrapReverse) ,\n10 /Real (Precision) ,\n\ + (Op) /UnicodeString (DisplayString) ,\n0 /Bool (TrapConvertCustom) ,\n0.05 /Real (TrapTintTolerance) ,\n1 /Bool (ExtractUnpainted) ,\n\ + ; /Dict ;\n /Part ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ) +} + +/// A group of a red and a blue square with style `PF`: its drawn look (one path of their area), +/// then the group on `%_` lines. +fn pathfinder_group() -> String { + let hidden = |color: &str, x: f64| format!("{color}{}f\n", rect_path(x, 0.0, x + 10.0, 10.0)).replace('\n', "\n%_"); + format!( + "0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}{}U\n1 (PF) XW\n", + rect_path(0.0, 0.0, 15.0, 10.0), + hidden(RED, 0.0), + hidden("0 0 1 0 0 0 1 Xa\n", 5.0) + ) +} + +#[test] +fn a_group_with_a_pathfinder_effect_keeps_its_members_and_the_effect() { + // GUARDS: the style was not read, and the group came in as its drawn look: one path, with no effect. + let r = read_ok(&format!("{}{}", pathfinder_styles(0, 0.5), layer(&pathfinder_group()))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let members = a[0].children().cloned().unwrap_or_default(); + assert_eq!(members.len(), 2, "the squares, not the look: {a:#?}"); + assert!(members.iter().all(|m| matches!(m.kind, NodeKind::Path { .. })), "{members:#?}"); + assert_eq!((fill(&members[0]).color(), fill(&members[1]).color()), (Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0)))); + let effects: Vec<_> = a[0].appearance.effects.iter().map(|e| (e.id.as_str(), e.visible)).collect(); + assert_eq!(effects, [("pathfinder.add", true)]); + assert!(a[0].appearance.items.is_empty(), "{:?}", a[0].appearance); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + +#[test] +fn each_pathfinder_operation_on_a_group_draws_as_vectorcraft_draws_it() { + // GUARDS: only Add (`Command` 0) was read; the other operations came in as the drawn look's one path. + let ops = [ + (1, "pathfinder.intersect"), + (2, "pathfinder.exclude"), + (3, "pathfinder.subtract"), + (4, "pathfinder.minusBack"), + (5, "pathfinder.divide"), + (6, "pathfinder.outline"), + (7, "pathfinder.trim"), + (8, "pathfinder.merge"), + (9, "pathfinder.crop"), + (10, "pathfinder.hardMix"), + (11, "pathfinder.softMix"), + ]; + for (command, id) in ops { + let mix = if command == 11 { 0.3 } else { 0.5 }; + let r = read_ok(&format!("{}{}", pathfinder_styles(command, mix), layer(&pathfinder_group()))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{command}: {a:#?}"); + let members = a[0].children().cloned().unwrap_or_default(); + assert_eq!(members.len(), 2, "{command}: the squares, not the look: {a:#?}"); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{command}: {:?}", a[0].appearance) }; + assert_eq!((e.id.as_str(), e.visible), (id, true), "{command}"); + let params = if command == 11 { serde_json::json!({"mixingRate": 30.0}) } else { serde_json::json!({}) }; + assert_eq!(e.params, params, "{command}"); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{command}: {:?}", r.warnings); + // The same squares in a group made in VectorCraft, with the effect of that operation. + let square = |m: &Arc| { + let bounds = m.geometric_bounds().unwrap(); + Arc::new(Node::path(m.id, vectorcraft_geom::shapes::rectangle(bounds), vectorcraft_doc::Appearance::basic(fill(m), Paint::None, 0.0))) + }; + let mut own = Node::group(a[0].id, members.iter().map(square).collect()); + own.appearance.effects.push(vectorcraft_doc::Effect { id: id.into(), params: params.clone(), visible: true }); + // Each result's box and paints; Outline's lines start where each square's path starts, so + // the results are compared in a sorted order. + let faces = |g: &Node| -> Vec { + let mut faces: Vec = vectorcraft_effects::pathfinder_children(g, None) + .unwrap() + .iter() + .map(|n| { + let b = n.geometric_bounds().unwrap_or_default(); + let round = |v: f64| (v * 1000.0).round() / 1000.0; + let paints = (n.appearance.fill_paint().color(), n.appearance.stroke_paint().color()); + format!("{:?} {paints:?}", Rect::new(round(b.x0), round(b.y0), round(b.x1), round(b.y1))) + }) + .collect(); + faces.sort(); + faces + }; + let (opened, made) = (faces(&a[0]), faces(&own)); + assert!(!made.is_empty(), "{command}"); + assert_eq!(opened, made, "{command}"); + } +} + +#[test] +fn a_pathfinder_style_this_does_not_read_keeps_the_drawn_look() { + // Trap, and a Precision other than the one read. + let other = pathfinder_styles(0, 0.5).replace("10 /Real (Precision)", "5 /Real (Precision)"); + let intersect = pathfinder_styles(1, 0.5).replace("10 /Real (Precision)", "5 /Real (Precision)"); + for styles in [pathfinder_styles(12, 0.5), other, intersect] { + let r = read_ok(&format!("{styles}{}", layer(&pathfinder_group()))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let look = a[0].children().cloned().unwrap_or_default(); + assert_eq!(look.len(), 1, "the look's one path: {a:#?}"); + assert!(a[0].appearance.effects.is_empty(), "{:?}", a[0].appearance); + } +} + +#[test] +fn a_path_with_a_pathfinder_effect_keeps_its_drawn_look() { + // Effect › Pathfinder doesn't apply to a lone path: its style stays the drawn look's. + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_{hidden_rect}f\n1 (PF) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let r = read_ok(&format!("{}{}", pathfinder_styles(0, 0.5), layer(&art_))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "the look, not the path: {a:#?}"); + let mut effects = 0; + r.doc.walk(|n| effects += n.appearance.effects.len()); + assert_eq!(effects, 0); +} + +#[test] +fn an_object_with_bas_relief_comes_in_with_its_settings() { + // GUARDS: Bas Relief's settings block wasn't read, so the object came in as its drawn look. + let settings: Vec = [ + &[0, 0, 0, 1][..], + b"Dtl ", + &[0; 4], + b"long", + &5i32.to_be_bytes(), + b"Smth", + &[0; 4], + b"long", + &9i32.to_be_bytes(), + b"LghD", + &0x2000u32.to_be_bytes(), + b"LghD", + b"LDTR", + ] + .concat(); + let lines: String = crate::ps::ascii85(&settings).lines().map(|l| format!("%{l}\n")).collect(); + let style = format!( + "%AI9_BeginArtStyles\n\ + /KnownStyle :\n(Carved) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n\ + /BasicFilter :\n(PSAdapter_plugin_BsRl) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/Binary : /ASCII85Decode ,\n{lines}; (data) ,\n\ + {} /Int (dataSize) ,\n; /Dict ;\n /Part ,\n;\n\ + %AI9_EndArtStyles\n", + settings.len() + ); + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_0 0 0 1 k\n%_{hidden_rect}f\n1 (Carved) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let r = read_ok(&format!("{style}{}", layer(&art_))); + let a = art(&r.doc); + assert_eq!(a.len(), 1); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look"); + let [relief] = a[0].appearance.effects.as_slice() else { panic!("{:#?}", a[0].appearance) }; + assert_eq!( + (relief.id.as_str(), &relief.params), + ("sketch.basRelief", &serde_json::json!({"detail": 5.0, "smoothness": 9.0, "lightDirection": "topRight"})) + ); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + +#[test] +fn an_object_with_convert_to_shape_comes_in_as_itself_with_the_effect_live() { + // GUARDS: `Adobe Shape Effects` wasn't read, so the object came in as its drawn look. + let styles = |keys: &str| { + format!( + "%AI9_BeginArtStyles\n\ + /KnownStyle :\n(Boxed) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Adobe Shape Effects) 1 0 /Filter ,\n1 /Visible ,\n(ShapeEffect.aip) /PluginFileName ,\n(Shape) /Title ,\n\ + /Dictionary : /NotRecorded ,\n(Rectangle) /UnicodeString (DisplayString) ,\n{keys}; /Dict ;\n /Part ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n\ + %AI9_EndArtStyles\n" + ) + }; + let hidden_rect = rect_path(20.0, 20.0, 90.0, 60.0).replace('\n', "\n%_"); + // The drawn look is the shape: 20 pt wider on each side and 6 pt taller. + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Boxed) XW\n", rect_path(0.0, 14.0, 110.0, 66.0)); + let keys = "0 /Int (Shape) ,\n150 /Real (AbsWidth) ,\n0 /Real (Absolute) ,\n40 /Real (AbsHeight) ,\n20 /Real (RelWidth) ,\n15 /Real (CornerRadius) ,\n6 /Real (RelHeight) ,\n"; + let r = read_ok(&format!("{}{}", styles(keys), layer(&art_))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look: {a:#?}"); + let b = a[0].geometric_bounds().unwrap(); + assert_eq!((b.width(), b.height()), (70.0, 40.0), "the object keeps its own path"); + assert_eq!(fill(&a[0]).color(), Some(Color::rgb(0.0, 0.0, 1.0))); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{:?}", a[0].appearance.effects) }; + assert_eq!( + (e.id.as_str(), e.params["relative"].as_bool(), e.params["extraW"].as_f64(), e.params["extraH"].as_f64()), + ("convertToShape.rectangle", Some(true), Some(40.0), Some(12.0)) + ); + // A shape that isn't read: the drawn look. + let r = read_ok(&format!("{}{}", styles(&keys.replace("0 /Int (Shape)", "7 /Int (Shape)")), layer(&art_))); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + +#[test] +fn an_object_with_path_effects_comes_in_as_itself_with_them_live() { + // GUARDS: an object with Offset Path, Outline Object or Outline Stroke came in as its drawn look. + let styles = |offset: &str| { + format!( + "%AI9_BeginArtStyles\n\ + /KnownStyle :\n(Rim) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Adobe Offset Path) 1 0 /Filter ,\n1 /Visible ,\n(OffsetPath.aip) /PluginFileName ,\n(Offset Path) /Title ,\n\ + /Dictionary : /NotRecorded ,\n{offset}; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Adobe Outline Type) 1 0 /Filter ,\n0 /Visible ,\n(ArtConverters.aip) /PluginFileName ,\n(Outline Object) /Title ,\n\ + /Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Adobe Outline Stroke) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n\ + %AI9_EndArtStyles\n" + ) + }; + let hidden_rect = rect_path(20.0, 20.0, 60.0, 50.0).replace('\n', "\n%_"); + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Rim) XW\n", rect_path(16.0, 16.0, 64.0, 54.0)); + let offset = "4 /Real (ofst) ,\n6 /Real (mlim) ,\n1 /Int (jntp) ,\n"; + let r = read_ok(&format!("{}{}", styles(offset), layer(&art_))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look: {a:#?}"); + let b = a[0].geometric_bounds().unwrap(); + assert_eq!((b.width(), b.height()), (40.0, 30.0), "the object keeps its own path"); + let effects: Vec<_> = a[0].appearance.effects.iter().map(|e| (e.id.as_str(), e.params.clone(), e.visible)).collect(); + assert_eq!( + effects, + [ + ("path.offsetPath", serde_json::json!({"offset": 4.0, "joins": "bevel", "miterLimit": 6.0}), true), + ("path.outlineObject", serde_json::json!({}), false), + ("path.outlineStroke", serde_json::json!({}), true), + ] + ); + // An Offset Path without its Miter Limit: the drawn look. + let r = read_ok(&format!("{}{}", styles("4 /Real (ofst) ,\n1 /Int (jntp) ,\n"), layer(&art_))); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + +/// The paint of a blue fill in a style. +const BLUE_FILL: Option<&str> = Some("0 0 0 0 0 0 1 Xa\n"); + +/// An art style section with style `Bent`: effect `name` with dictionary `keys` on the whole +/// object, over a fill painting with `paint`, or over a fill and stroke that paint nothing. +fn distort_styles(name: &str, keys: &str, paint: Option<&str>) -> String { + let (paints, color) = match paint { + Some(p) => ("0 1", p), + None => ("0 0", ""), + }; + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Bent) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n({name}) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{keys}; /Dict ;\n /Part ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{color}{paints} Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ) +} + +/// Free Distort's 16 entries for a 40 × 30 pt object whose source frame is its own box, with its +/// destination corners `dst` (top left, top right, bottom left, bottom right, art space). +fn free_distort_keys(dst: [[f64; 2]; 4]) -> String { + let src = [[20.0, 50.0], [60.0, 50.0], [20.0, 20.0], [60.0, 20.0]]; + let mut out = String::new(); + for (which, c) in [("src", src), ("dst", dst)] { + for (i, [h, v]) in c.into_iter().enumerate() { + out += &format!("{h} /Real ({which}{i}h) ,\n{v} /Real ({which}{i}v) ,\n"); + } + } + out +} + +#[test] +fn an_object_with_a_distort_effect_that_draws_alike_comes_in_as_itself_with_it_live() { + // GUARDS: only type took Distort & Transform effects; a path with Transform, Twist, a still Tweak, + // Pucker & Bloat at 0 or an affine Free Distort came in as its drawn look. + let hidden_rect = rect_path(20.0, 20.0, 60.0, 50.0).replace('\n', "\n%_"); + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0)); + // A slanted box: its corners make a parallelogram. + let slanted = free_distort_keys([[25.0, 50.0], [65.0, 50.0], [20.0, 20.0], [60.0, 20.0]]); + for (name, keys, id) in [ + ("Adobe Transform", "5 /Real (moveH_Pts) ,\n0.5 /Real (rotate_Radians) ,\n0 /Bool (transformPatterns) ,\n", "distort.transform"), + ("Adobe Twirl", "45 /Real (angle) ,\n", "distort.twist"), + ("Adobe Scribble and Tweak", "30 /Real (horz) ,\n0 /Bool (anch) ,\n0 /Bool (in) ,\n0 /Bool (out) ,\n", "distort.tweak"), + ("Adobe Punk and Bloat", "0 /Real (d_factor) ,\n", "distort.puckerBloat"), + ("Adobe Free Distort", slanted.as_str(), "distort.freeDistort"), + ("Adobe Free Distort", "", "distort.freeDistort"), + ] { + let r = read_ok(&format!("{}{}", distort_styles(name, keys, BLUE_FILL), layer(&art_))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{name}: {:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{name}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "{name}: the object, not its look: {a:#?}"); + let b = a[0].geometric_bounds().unwrap(); + assert_eq!((b.width(), b.height()), (40.0, 30.0), "{name}: the object keeps its own path"); + assert_eq!(fill(&a[0]).color(), Some(Color::rgb(0.0, 0.0, 1.0)), "{name}"); + let ids: Vec<_> = a[0].appearance.effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, [id], "{name}"); + } +} + +#[test] +fn an_object_with_a_distort_effect_drawn_another_way_keeps_its_drawn_look() { + // Pucker & Bloat and Zig Zag draw other outlines than the file's, a Free Distort whose corners + // aren't a parallelogram bends the curves differently, and Transform's copies paint as one path. + let hidden_rect = rect_path(20.0, 20.0, 60.0, 50.0).replace('\n', "\n%_"); + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0)); + let bent = free_distort_keys([[25.0, 50.0], [65.0, 52.0], [20.0, 20.0], [60.0, 20.0]]); + for (name, keys) in [ + ("Adobe Punk and Bloat", "-50 /Real (d_factor) ,\n"), + ("Adobe Zigzag", "3 /Real (amount) ,\n1 /Real (absoluteness) ,\n"), + ("Adobe Free Distort", bent.as_str()), + ("Adobe Scribble and Tweak", "30 /Real (horz) ,\n"), + ("Adobe Transform", "1 /Bool (randomize) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"), + ("Adobe Transform", "5 /Real (moveH_Pts) ,\n2 /Int (numCopies) ,\n0 /Bool (transformPatterns) ,\n"), + ] { + let r = read_ok(&format!("{}{}", distort_styles(name, keys, BLUE_FILL), layer(&art_))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{name}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{name}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{name}: {:?}", r.warnings); + } +} + +/// The gradient `G`, white to black, defined for a document. +const GRADIENT_G: &str = "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n"; + +#[test] +fn an_object_whose_outline_moves_away_from_its_gradient_keeps_its_drawn_look() { + // GUARDS: a gradient stays where it is placed while Transform, Twist or Free Distort moves the + // outline, so the live object lost the gradient its drawn look shows. + let gradient = Some("Bb\n0 0 0 0 Bh\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n"); + let hidden_rect = rect_path(20.0, 20.0, 60.0, 50.0).replace('\n', "\n%_"); + let object = format!( + "0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_1 (G) 20 35 0 40 1 0 0 1 0 0 Bg\n%_{hidden_rect}f\n%_0 BB\n1 (Bent) XW\n", + rect_path(16.0, 16.0, 64.0, 54.0) + ); + let hidden = |color: &str, x: f64| format!("{color}{}f\n", rect_path(x, 0.0, x + 10.0, 10.0)).replace('\n', "\n%_"); + let shaded = format!("Bb\n1 (G) 5 5 0 10 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", rect_path(5.0, 0.0, 15.0, 10.0)).replace('\n', "\n%_"); + let group = format!("0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}{shaded}U\n1 (Bent) XW\n", rect_path(0.0, 0.0, 15.0, 10.0), hidden(RED, 0.0)); + let slanted = free_distort_keys([[25.0, 50.0], [65.0, 50.0], [20.0, 20.0], [60.0, 20.0]]); + let moves = [ + ("Adobe Transform", "5 /Real (moveH_Pts) ,\n0 /Bool (transformPatterns) ,\n"), + ("Adobe Twirl", "45 /Real (angle) ,\n"), + ("Adobe Free Distort", slanted.as_str()), + ]; + for (name, keys) in moves { + // A gradient in the style, and one on a member of a group. + for (paint, art_) in [(gradient, &object), (None, &group)] { + let r = read_ok(&format!("{GRADIENT_G}{}{}", distort_styles(name, keys, paint), layer(art_))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{name}: {a:#?}"); + assert!(a[0].appearance.effects.is_empty(), "{name}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{name}: {:?}", r.warnings); + } + } + // An effect that leaves the outline where it is keeps the gradient under it. + let r = read_ok(&format!("{GRADIENT_G}{}{}", distort_styles("Adobe Punk and Bloat", "", gradient), layer(&object))); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "{a:#?}"); + assert!(matches!(fill(&a[0]), Paint::Gradient(_)), "{:?}", fill(&a[0])); +} + +/// A group with style `Bent`, its drawn look one path, holding a red and a blue square. +fn distort_group() -> String { + let hidden = |color: &str, x: f64| format!("{color}{}f\n", rect_path(x, 0.0, x + 10.0, 10.0)).replace('\n', "\n%_"); + format!( + "0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}{}U\n1 (Bent) XW\n", + rect_path(0.0, 0.0, 15.0, 10.0), + hidden(RED, 0.0), + hidden("0 0 1 0 0 0 1 Xa\n", 5.0) + ) +} + +#[test] +fn a_group_with_a_transform_keeps_its_members_and_the_effect() { + // GUARDS: the group came in as its drawn look, one path with no effect. + let keys = "5 /Real (moveH_Pts) ,\n0 /Bool (transformPatterns) ,\n"; + let r = read_ok(&format!("{}{}", distort_styles("Adobe Transform", keys, None), layer(&distort_group()))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let members = a[0].children().cloned().unwrap_or_default(); + assert_eq!(members.len(), 2, "the squares, not the look: {a:#?}"); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{:?}", a[0].appearance) }; + assert_eq!((e.id.as_str(), e.params["moveH"].as_f64()), ("distort.transform", Some(5.0))); + assert!(a[0].appearance.items.is_empty(), "{:?}", a[0].appearance); +} + +/// `styles` (from [`distort_styles`]) with a red stroke 2 pt wide in place of the stroke that +/// paints nothing. +fn with_red_stroke(styles: &str) -> String { + styles.replace("/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd", "/StrokeStyle : 0 R\n0 1 1 0 1 0 0 XA\n0 1 0 0 0 Xy\n0 J 0 j 2 w 10 M []0 d\n0 XR\n1 0 Xd") +} + +#[test] +fn twist_and_a_scaling_transform_are_read_only_where_their_outline_is_known() { + // GUARDS: Twist was read on curves, strokes and groups, and Transform scaling a stroked object, + // where the outline VectorCraft draws hasn't been checked. + let object = |hidden: &str| { + format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{}f\n%_0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0), hidden.replace('\n', "\n%_")) + }; + let square = object(&rect_path(20.0, 20.0, 60.0, 50.0)); + let curved = object("20 35 m\n20 45 60 45 60 35 c\n60 25 20 25 20 35 c\n"); + let twist = distort_styles("Adobe Twirl", "45 /Real (angle) ,\n", BLUE_FILL); + let scale = "0.5 /Real (scaleH_Factor) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"; + let corner = distort_styles("Adobe Transform", &format!("0 /Int (pinPoint) ,\n{scale}"), BLUE_FILL); + let center = distort_styles("Adobe Transform", scale, BLUE_FILL); + let moved = distort_styles("Adobe Transform", "0 /Int (pinPoint) ,\n5 /Real (moveH_Pts) ,\n0 /Bool (transformPatterns) ,\n", BLUE_FILL); + let read = |styles: &str, art_: &str| read_ok(&format!("{styles}{}", layer(art_))); + for (what, r) in [ + ("a twisted curve", read(&twist, &curved)), + ("a twisted stroke", read(&with_red_stroke(&twist), &square)), + ("a twisted group", read(&distort_styles("Adobe Twirl", "45 /Real (angle) ,\n", None), &distort_group())), + ("a stroke scaled from a corner", read(&with_red_stroke(&corner), &square)), + ("a stroke scaled from the center", read(&with_red_stroke(¢er), &square)), + ] { + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert!(a[0].appearance.effects.is_empty(), "{what}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings); + } + for (what, r) in [ + ("a twisted square", read(&twist, &square)), + ("a stroke moved from a corner", read(&with_red_stroke(&moved), &square)), + ("a fill scaled from a corner", read(&corner, &square)), + ("a fill scaled from the center", read(¢er, &square)), + ] { + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }) && a[0].appearance.effects.len() == 1, "{what}: {a:#?}"); + } + let r = read(&twist, &square); + let a = art(&r.doc); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{:?}", a[0].appearance) }; + assert_eq!((e.id.as_str(), e.params["angle"].as_f64()), ("distort.twist", Some(45.0))); +} + #[test] fn a_bare_comment_line_in_a_prolog_leaves_its_end_alone() { // GUARDS: a bare `%` line's empty marker matched the empty begin marker of a section that has none. @@ -1363,7 +6832,7 @@ fn a_styled_object_inside_a_drawn_look_survives_it() { /// that shadow, not as its drawn look. #[test] fn an_object_with_a_darkness_shadow_comes_in_as_itself() { - let styles = ART_STYLES.replace("3 /Real (horz) ,\n", "1 /Int (csrc) ,\n50 /Real (dark) ,\n3 /Real (horz) ,\n"); + let styles = ART_STYLES.replace("0 /Int (csrc) ,\n", "1 /Int (csrc) ,\n50 /Real (dark) ,\n"); let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_{hidden_rect}f\n1 (Blue) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); let r = read_ok(&format!("{styles}{}", layer(&art_))); @@ -1392,6 +6861,30 @@ fn a_styled_object_keeps_the_transparency_written_on_its_look() { assert_eq!(a.len(), 1, "{a:#?}"); assert_eq!(fill(&a[0]).color(), Some(Color::rgb(0.0, 0.0, 1.0))); assert_eq!((a[0].opacity, a[0].blend), (0.6, BlendMode::Multiply)); + assert!(!a[0].knockout_shape); + let r = read_ok(&format!("{ART_STYLES}{}", layer(&art_.replace("1 0.6 0 2 0 Xy", "1 0.6 0 2 1 Xy")))); + assert!(art(&r.doc)[0].knockout_shape, "written on the look"); +} + +/// The knockout shape flag written on a text object's look goes to the object, or, where the look +/// draws more than the type, opaque or not, to the group that holds the look and the object. +#[test] +fn a_text_objects_look_gives_it_the_knockout_shape() { + let look = "0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\nU\n1 0.2 0 1 1 Xy\n0 0 Xd\n6 () XW\n"; + let own = "%_/AI11Text :\n%_0 /FreeUndo ,\n%_0 /FrameIndex ,\n%_0 /StoryIndex ,\n%_;\n"; + let doc = read_ok(&layer(&format!("{look}{own}1 (Style) XW\n"))).doc; + let a = art(&doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert_eq!((a[0].opacity, a[0].knockout_shape), (0.2, true)); + let drawing = look.replace("U\n", &format!("{RED}{}f\nU\n", rect_path(0.0, 0.0, 10.0, 10.0))); + for (state, opacity) in [("1 0.2 0 1 1 Xy", 0.2), ("0 1 0 1 1 Xy", 1.0)] { + let drawn = drawing.replace("1 0.2 0 1 1 Xy", state); + let doc = read_ok(&layer(&format!("{drawn}{own}1 (Style) XW\n"))).doc; + let a = art(&doc); + assert_eq!(a.len(), 1, "{state}: {a:#?}"); + assert_eq!((a[0].opacity, a[0].knockout_shape), (opacity, true), "{state}"); + assert!(a[0].children().unwrap().iter().all(|n| !n.knockout_shape), "{state}: {a:#?}"); + } } /// An envelope is written on `%_` lines as a group holding the mesh that shapes it, with its @@ -1434,6 +6927,776 @@ fn an_envelope_mesh_is_not_read_as_art() { assert!(art(&doc).iter().any(|n| has_mesh(n)), "{:#?}", art(&doc)); } +/// An envelope whose contents are being edited is written the other way round: its contents, a +/// group on `%_` lines, then its dictionary, which holds the mesh that shapes them. The contents +/// aren't drawn as they are, only the distorted art on the plain lines after them. +#[test] +fn an_envelope_s_contents_being_edited_are_not_read_as_art() { + let corner = |x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| { + format!("%_[0.82 0.83 0.83 1 {x} {y} {} {} 1 {} {} 1] /N X#\n", next.0, next.1, prev.0, prev.1) + }; + let mesh = format!( + "%_/Mesh X!\n%_(DeviceRGB) /CS X#\n%_[0 0] /P X#\n{}{}{}{}%_0 /E X#\n%_/End X!\n%_0 0 Xd\n%_6 () XW\n", + corner(0, 0, (0, 10), (10, 0)), + corner(0, 40, (10, 40), (0, 30)), + corner(40, 40, (40, 30), (30, 40)), + corner(40, 0, (30, 0), (40, 10)), + ); + let contents: String = rect_path(0.0, 0.0, 80.0, 20.0).lines().map(|l| format!("%_{l}\n")).collect(); + let body = format!( + "%_u\n%_u\n%_0 0 1 0 0 0 1 Xa\n{contents}%_f\n%_U\n%_9 () XW\n%_U\n%_/ArtDictionary :\n%_1 /Bool (AIDeformEditModeKey) ,\n\ + %_3 /Int (AIDeformStyle) ,\n%_X=\n{mesh}%_X+\n%_ (AIDeformArtKey) ,\n%_;\n%_\n%_9 () XW\n{RED}{}f\n", + rect_path(0.0, 0.0, 40.0, 40.0) + ); + let doc = read_ok(&layer(&body)).doc; + let a = art(&doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert_eq!(fill(&a[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); +} + +/// `art` on `%_` lines. +fn commented(art: &str) -> String { + art.lines().map(|l| format!("%_{l}\n")).collect() +} + +/// Envelope Options as new envelopes have them (Distort Appearance, Anti-Alias, Clipping Mask), +/// Fidelity 50, the contents not being edited. +const ENVELOPE_KEYS: &str = "131073 /Int (AIDeformOptionsKey) ,\n50 /Int (AIDeformFidelityKey) ,\n0 /Bool (AIDeformEditModeKey) ,\n"; + +/// An envelope as the editing data writes it: on `%_` lines a group holding `before`, then the +/// dictionary with `keys`, the art `block` in its `AIDeformArtKey` block and the kind `kind`; then +/// `drawn` in a group on plain lines, and the plugin's `XP`. +fn envelope_parts(before: &str, keys: &str, block: &str, kind: u32, drawn: &str) -> String { + format!( + "{}%_/ArtDictionary :\n{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_{kind} /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", + commented(&format!("u\n{before}U\n")), + commented(keys), + commented(block), + ) +} + +/// An envelope of `content` (in the plain group the editing data puts round it) shaped by the mesh +/// `shape`. +pub(super) fn envelope_of(shape: &str, keys: &str, content: &str, kind: u32, drawn: &str) -> String { + envelope_parts(shape, keys, &format!("u\n{content}U\n9 () XW\n"), kind, drawn) +} + +/// A grid point's place in art space and its handle towards a neighbour. +type MeshAt<'a> = &'a dyn Fn((usize, usize)) -> (f64, f64); +type MeshHandle<'a> = &'a dyn Fn((usize, usize), (usize, usize)) -> (f64, f64); + +/// A grey `/Mesh` of `cols`×`rows` patches (`/P [i j]`, `i` along x, column by column), each +/// corner of patch `(i, j)` at `at`, from the one nearest the origin up, across and down, with its +/// handles towards the next corner and the previous one at `handle`; `anchor`, written after the +/// second corner of the first patch, puts an anchor on its second edge. +fn mesh_text(cols: usize, rows: usize, at: MeshAt<'_>, handle: MeshHandle<'_>, anchor: Option<[f64; 6]>) -> String { + let mut s = format!("/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[{cols} {rows}] /Size X#\n/Data X#\n/DeviceGray /CS X#\n"); + for i in 0..cols { + for j in 0..rows { + s += &format!("[{i} {j}] /P X#\n"); + let (a, b, c, d) = ((i, j), (i, j + 1), (i + 1, j + 1), (i + 1, j)); + for (k, (p, next, prev)) in [(a, b, d), (b, c, a), (c, d, b), (d, a, c)].into_iter().enumerate() { + let ((x, y), (nx, ny), (px, py)) = (at(p), handle(p, next), handle(p, prev)); + s += &format!("[0.8 1 {x} {y} {nx} {ny} 1 {px} {py} 1] /N X#\n"); + if let (1, Some([x, y, ax, ay, bx, by])) = (k, anchor.filter(|_| (i, j) == (0, 0))) { + s += &format!("[{x} {y} {ax} {ay} {bx} {by} 1] /A X#\n"); + } + } + s += "/E X#\n"; + } + } + s + "/End X!\n" +} + +/// A grid in art space, its points `step` apart from (40, 20), handles a third of the way. +pub(super) fn straight_mesh(cols: usize, rows: usize, step: (f64, f64)) -> String { + let at = move |(i, j): (usize, usize)| (40.0 + i as f64 * step.0, 20.0 + j as f64 * step.1); + let third = move |p: (usize, usize), q: (usize, usize)| { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + }; + mesh_text(cols, rows, &at, &third, None) +} + +/// The red rectangle 40 20 160 80 in art space, which is the same box in the document's. +pub(super) fn envelope_content() -> String { + format!("{RED}{}f\n", rect_path(40.0, 20.0, 160.0, 80.0)) +} + +/// What envelope `kind` draws of [`envelope_content`]: the rectangle's edges, many points to a +/// side, mapped as VectorCraft maps them, as a red path in art space. +pub(super) fn drawn_content(kind: &vectorcraft_doc::live::EnvelopeKind) -> String { + let rect = Rect::new(40.0, 20.0, 160.0, 80.0); + drawn_box(kind, rect, rect) +} + +/// What envelope `kind`, mapping from box `src`, draws of a red rectangle `rect`, as in +/// [`drawn_content`]. +fn drawn_box(kind: &vectorcraft_doc::live::EnvelopeKind, src: Rect, rect: Rect) -> String { + let map = vectorcraft_doc::live::envelope_mapper(kind, src); + let corners = [Point::new(rect.x0, rect.y0), Point::new(rect.x1, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)]; + let mut s = RED.to_string(); + for (k, a) in corners.iter().enumerate() { + let b = corners[(k + 1) % 4]; + for t in 0..64 { + let q = map(a.lerp(b, f64::from(t) / 64.0)); + s += &format!("{} {} {}\n", q.x, 100.0 - q.y, if k == 0 && t == 0 { "m" } else { "L" }); + } + } + s + "f\n" +} + +/// The live envelope `n` is: its content, kind, fidelity, editing and options. +fn live_envelope(n: &Node) -> (&[Arc], &vectorcraft_doc::live::EnvelopeKind, f64, bool, vectorcraft_doc::live::EnvelopeOptions) { + match &n.kind { + NodeKind::Envelope { content, kind, fidelity, editing, options, frame } => { + assert_eq!(**frame, kurbo::Affine::IDENTITY); + (content, kind, *fidelity, *editing, *options) + } + other => panic!("not a live envelope: {other:#?}"), + } +} + +/// A warp's dictionary keys: style number `style`, bend, horizontal and vertical distortion as +/// fractions, and the orientation (vertical with `rotate` 1). +pub(super) fn warp_keys(style: u32, bend: f64, h: f64, v: f64, rotate: u32) -> String { + format!( + "{ENVELOPE_KEYS}{style} /Int (DeformStyle) ,\n{h} /Real (DeformHoriz) ,\n{bend} /Real (DeformValue) ,\n{v} /Real (DeformVert) ,\n{rotate} /Bool (Rotate) ,\n(Warp) /UnicodeString (DisplayString) ,\n" + ) +} + +/// An envelope made with a warp opens as that live envelope of its contents, its style, bend, +/// distortions (fractions in the file) and orientation read; the warp's drawn art goes. +#[test] +fn a_warp_envelope_opens_live() { + use vectorcraft_doc::live::EnvelopeKind; + for (style, bend, h, v, rotate, id) in + [(1, 0.5, 0.0, 0.0, 0, "arc"), (1, 0.5, -0.2, 0.3, 1, "arc"), (8, 0.5, 0.0, 0.0, 0, "flag"), (15, 0.5, 0.0, 0.0, 0, "twist")] + { + let want = EnvelopeKind::Warp { style: id.into(), bend: bend * 100.0, h: h * 100.0, v: v * 100.0, horizontal: rotate == 0 }; + let body = + envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(style, bend, h, v, rotate), &envelope_content(), 1, &drawn_content(&want)); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, kind, fidelity, editing, options) = live_envelope(&a[0]); + let EnvelopeKind::Warp { style: s, bend: b, h: dh, v: dv, horizontal } = kind else { panic!("{kind:?}") }; + assert_eq!((s.as_str(), *horizontal), (id, rotate == 0)); + assert!([(*b, bend), (*dh, h), (*dv, v)].iter().all(|(got, f)| (got - f * 100.0).abs() < 1e-9), "{kind:?}"); + assert_eq!((fidelity, editing, options), (50.0, false, vectorcraft_doc::live::EnvelopeOptions::NEW)); + assert_eq!(content.len(), 1, "{content:#?}"); + assert!(matches!(content[0].kind, NodeKind::Path { .. }), "{content:#?}"); + assert_eq!(fill(&content[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + } +} + +/// Every warp style number reads as its style, in Effect › Warp's order. +#[test] +fn warp_envelopes_read_every_style() { + use vectorcraft_doc::live::EnvelopeKind; + let ids = [ + "arc", + "arcLower", + "arcUpper", + "arch", + "bulge", + "shellLower", + "shellUpper", + "flag", + "wave", + "fish", + "rise", + "fisheye", + "inflate", + "squeeze", + "twist", + ]; + for (n, id) in ids.iter().enumerate() { + let want = EnvelopeKind::Warp { style: (*id).into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true }; + let keys = warp_keys(n as u32 + 1, 0.3, 0.0, 0.0, 0); + let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &keys, &envelope_content(), 1, &drawn_content(&want)))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{id}: {a:#?}"); + assert_eq!(live_envelope(&a[0]).1, &want, "{id}"); + } +} + +/// An envelope made with a mesh opens as a live mesh envelope: its rows and columns, its points +/// row by row from the top left, and each point's four handles, a moved point and an uneven handle +/// included. +#[test] +fn a_mesh_envelope_opens_live_with_its_points_and_handles() { + use vectorcraft_doc::live::{EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP}; + // 3 columns 40 apart and 2 rows 30 apart from (40, 20); the inner point (1, 1) moved, and its + // handle towards (2, 1) longer and off the line. + let at = |(i, j): (usize, usize)| if (i, j) == (1, 1) { (90.0, 55.0) } else { (40.0 + i as f64 * 40.0, 20.0 + j as f64 * 30.0) }; + let handle = |p: (usize, usize), q: (usize, usize)| { + if (p, q) == ((1, 1), (2, 1)) { + return (108.0, 62.0); + } + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + }; + let shape = mesh_text(3, 2, &at, &handle, None); + // Row r of the envelope is row 2 - r of the file (art space has y up). + let doc_pt = |(x, y): (f64, f64)| Point::new(x, 100.0 - y); + let mut points = vec![]; + let mut handles = vec![]; + for r in 0..=2usize { + for c in 0..=3usize { + let g = (c, 2 - r); + let p = doc_pt(at(g)); + points.push(p); + let mut h = [kurbo::Vec2::ZERO; 4]; + let towards = |q: Option<(usize, usize)>| q.filter(|q| q.0 <= 3 && q.1 <= 2).map_or(kurbo::Vec2::ZERO, |q| doc_pt(handle(g, q)) - p); + h[H_RIGHT] = towards(Some((g.0 + 1, g.1))); + h[H_LEFT] = towards(g.0.checked_sub(1).map(|i| (i, g.1))); + h[H_UP] = towards(Some((g.0, g.1 + 1))); + h[H_DOWN] = towards(g.1.checked_sub(1).map(|j| (g.0, j))); + handles.push(h); + } + } + let want = EnvelopeKind::Mesh { rows: 2, cols: 3, points: points.clone(), handles: handles.clone() }; + let r = read_ok(&layer(&envelope_of(&shape, ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&want)))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let EnvelopeKind::Mesh { rows, cols, points: got, handles: got_h } = live_envelope(&a[0]).1 else { panic!("{a:#?}") }; + assert_eq!((*rows, *cols, got.len(), got_h.len()), (2, 3, 12, 12)); + for (k, (p, q)) in got.iter().zip(&points).enumerate() { + assert!((*p - *q).hypot() < 1e-6, "point {k}: {p:?}, not {q:?}"); + } + // The moved inner point (row 1, column 1): each of its handles, the uneven one towards the right. + let inner = 4 + 1; + assert!((got[inner] - Point::new(90.0, 45.0)).hypot() < 1e-6, "{:?}", got[inner]); + for slot in [H_RIGHT, H_LEFT, H_DOWN, H_UP] { + assert!((got_h[inner][slot] - handles[inner][slot]).hypot() < 1e-6, "slot {slot}: {:?} vs {:?}", got_h[inner], handles[inner]); + } + assert!((got_h[inner][H_RIGHT] - kurbo::Vec2::new(18.0, -7.0)).hypot() < 1e-6, "{:?}", got_h[inner]); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +/// An envelope made with a top object opens as a live envelope whose top path is the edge of its +/// one-patch mesh, an anchor on the edge included; its contents stay the rectangle. +#[test] +fn a_top_object_envelope_opens_live_with_its_outline() { + use vectorcraft_doc::live::EnvelopeKind; + // Corners (40, 20) (40, 80) (160, 80) (160, 20); the top edge bows up through an anchor at (100, 95). + let at = |(i, j): (usize, usize)| (40.0 + i as f64 * 120.0, 20.0 + j as f64 * 60.0); + let handle = |p: (usize, usize), q: (usize, usize)| match (p, q) { + ((0, 1), (1, 1)) => (60.0, 88.0), + ((1, 1), (0, 1)) => (140.0, 88.0), + _ => { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + } + }; + let shape = mesh_text(1, 1, &at, &handle, Some([100.0, 95.0, 70.0, 95.0, 130.0, 95.0])); + let mut bp = kurbo::BezPath::new(); + bp.move_to((40.0, 20.0)); + bp.curve_to((60.0, 12.0), (70.0, 5.0), (100.0, 5.0)); + bp.curve_to((130.0, 5.0), (140.0, 12.0), (160.0, 20.0)); + bp.curve_to((160.0, 40.0), (160.0, 60.0), (160.0, 80.0)); + bp.curve_to((120.0, 80.0), (80.0, 80.0), (40.0, 80.0)); + bp.curve_to((40.0, 60.0), (40.0, 40.0), (40.0, 20.0)); + bp.close_path(); + let want = EnvelopeKind::TopObject { path: vectorcraft_geom::PathData::from_bezpath(&bp), corners: None }; + let r = read_ok(&layer(&envelope_of(&shape, ENVELOPE_KEYS, &envelope_content(), 3, &drawn_content(&want)))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, kind, ..) = live_envelope(&a[0]); + let EnvelopeKind::TopObject { path, corners } = kind else { panic!("{kind:?}") }; + let anchors: Vec = path.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p)).collect(); + for p in [(40.0, 20.0), (100.0, 5.0), (160.0, 20.0), (160.0, 80.0), (40.0, 80.0)] { + assert!(anchors.iter().any(|q| (*q - Point::from(p)).hypot() < 1e-6), "{p:?} not in {anchors:?}"); + } + // The mesh's four corners are kept as the outline's corners. + let corners = corners.expect("the saved corners"); + let at: Vec = corners.iter().map(|i| anchors[*i as usize]).collect(); + let want_corners = [(40.0, 20.0), (160.0, 20.0), (160.0, 80.0), (40.0, 80.0)].map(Point::from); + assert!(at.iter().zip(want_corners).all(|(p, q)| (*p - q).hypot() < 1e-6), "{at:?}"); + // The curve through the anchor: its handles there run level. + let mid = path.subpaths.iter().flat_map(|s| s.anchors.iter()).find(|a| (a.p - Point::new(100.0, 5.0)).hypot() < 1e-6).unwrap(); + assert!((mid.h_in.y - 5.0).abs() < 1e-6 && (mid.h_out.y - 5.0).abs() < 1e-6, "{mid:?}"); + assert_eq!(content.len(), 1, "{content:#?}"); + assert_eq!(fill(&content[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +/// Envelope Options come from the options word, Fidelity from its own key. +#[test] +fn an_envelope_reads_its_options_and_fidelity() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, PreserveShape}; + let shape = straight_mesh(1, 1, (120.0, 60.0)); + // A flat 1 × 1 mesh over the box draws the box as it is. + let drawn = drawn_content(&EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)], + handles: vec![], + }); + for (word, fidelity, options) in [ + ( + 65536, + 80, + EnvelopeOptions { + anti_alias: false, + preserve_shape: PreserveShape::Transparency, + distort_appearance: false, + distort_linear_gradients: false, + distort_pattern_fills: false, + bounds_margin: [0.0; 4], + }, + ), + ( + 0x20007, + 100, + EnvelopeOptions { + anti_alias: true, + preserve_shape: PreserveShape::ClippingMask, + distort_appearance: true, + distort_linear_gradients: true, + distort_pattern_fills: true, + bounds_margin: [0.0; 4], + }, + ), + ( + 0x20002, + 0, + EnvelopeOptions { + anti_alias: true, + preserve_shape: PreserveShape::ClippingMask, + distort_appearance: false, + distort_linear_gradients: false, + distort_pattern_fills: true, + bounds_margin: [0.0; 4], + }, + ), + ] { + let keys = format!("{word} /Int (AIDeformOptionsKey) ,\n{fidelity} /Int (AIDeformFidelityKey) ,\n0 /Bool (AIDeformEditModeKey) ,\n"); + let r = read_ok(&layer(&envelope_of(&shape, &keys, &envelope_content(), 2, &drawn))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{word}: {a:#?}"); + let (_, _, got_fidelity, _, got) = live_envelope(&a[0]); + assert_eq!((got_fidelity, got), (f64::from(fidelity), options), "{word}"); + } +} + +/// The red rectangle 40 20 160 80 with a red stroke 10 pt wide, its art 130 × 70 with the stroke. +fn stroked_content() -> String { + format!("{RED}0 1 1 0 1 0 0 XA\n10 w\n{}b\n", rect_path(40.0, 20.0, 160.0, 80.0)) +} + +/// A one-patch mesh over the stroked art of [`stroked_content`], and that patch as a flat grid. +fn stroked_shape() -> (String, Vec) { + let at = |(i, j): (usize, usize)| (35.0 + i as f64 * 130.0, 15.0 + j as f64 * 70.0); + let third = |p: (usize, usize), q: (usize, usize)| { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + }; + (mesh_text(1, 1, &at, &third, None), vec![Point::new(35.0, 15.0), Point::new(165.0, 15.0), Point::new(35.0, 85.0), Point::new(165.0, 85.0)]) +} + +/// An envelope whose file saves the size of its art with the stroke maps from that box, in a +/// synthetic mesh and top object. Their drawn art is the box mapped onto the shape, and the +/// geometric box would leave the stroke 5 pt past it. +#[test] +fn an_envelope_saved_with_its_stroke_maps_from_the_stroked_box() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeMap}; + let (mesh, points) = stroked_shape(); + let keys = format!("{ENVELOPE_KEYS}70 /Real (AIDeformArtHeightKey) ,\n130 /Real (AIDeformArtWidthKey) ,\n"); + let outer = Rect::new(35.0, 15.0, 165.0, 85.0); + let flat = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }; + let drawn = drawn_box(&flat, outer, outer); + for kind in [2, 3] { + let r = read_ok(&layer(&envelope_of(&mesh, &keys, &stroked_content(), kind, &drawn))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(r.warnings.is_empty(), "kind {kind}: {:?}", r.warnings); + let (.., options) = live_envelope(&a[0]); + assert_eq!(options.bounds_margin, [5.0_f32 / 60.0, 5.0 / 60.0, 5.0 / 120.0, 5.0 / 120.0]); + let src = EnvelopeMap::of(&a[0]).unwrap().src(); + assert!( + (src.x0 - 35.0).abs() < 1e-3 && (src.y0 - 15.0).abs() < 1e-3 && (src.x1 - 165.0).abs() < 1e-3 && (src.y1 - 85.0).abs() < 1e-3, + "{src:?}" + ); + } +} + +/// With Distort Appearance off the stroke is drawn after the distortion: the envelope maps from the +/// geometric box whatever size its file saves. +#[test] +fn an_envelope_without_distort_appearance_maps_from_the_geometric_box() { + use vectorcraft_doc::live::EnvelopeMap; + let keys = "65536 /Int (AIDeformOptionsKey) ,\n50 /Int (AIDeformFidelityKey) ,\n0 /Bool (AIDeformEditModeKey) ,\n70 /Real (AIDeformArtHeightKey) ,\n130 /Real (AIDeformArtWidthKey) ,\n"; + let outer = Rect::new(35.0, 15.0, 165.0, 85.0); + let flat = vectorcraft_doc::live::EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(35.0, 15.0), Point::new(165.0, 15.0), Point::new(35.0, 85.0), Point::new(165.0, 85.0)], + handles: vec![], + }; + let drawn = drawn_box(&flat, outer, outer); + let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), keys, &stroked_content(), 2, &drawn))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(!live_envelope(&a[0]).4.distort_appearance); + assert_eq!(live_envelope(&a[0]).4.bounds_margin, [0.0; 4]); + let src = EnvelopeMap::of(&a[0]).unwrap().src(); + assert!((src.width() - 120.0).abs() < 1e-6 && (src.height() - 60.0).abs() < 1e-6, "{src:?}"); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +/// An envelope maps from the geometric box when its file saves that box's size, saves no size, +/// saves a size that isn't a number or saves a size far from both boxes; contents without a stroke +/// have one box, and contents with no height have no margins. +#[test] +fn an_envelope_not_saved_with_its_stroke_maps_from_the_geometric_box() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeMap}; + let (mesh, points) = stroked_shape(); + let inner = Rect::new(40.0, 20.0, 160.0, 80.0); + let flat = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }; + // The stroked art mapped from the geometric box: it reaches past the mesh by the stroke's share. + let drawn = drawn_box(&flat, inner, Rect::new(35.0, 15.0, 165.0, 85.0)); + let sizes = [ + "60 /Real (AIDeformArtHeightKey) ,\n120 /Real (AIDeformArtWidthKey) ,\n", + "", + "(tall) /UnicodeString (AIDeformArtHeightKey) ,\n(wide) /UnicodeString (AIDeformArtWidthKey) ,\n", + "70 /Real (AIDeformArtHeightKey) ,\n", + "1000 /Real (AIDeformArtHeightKey) ,\n1000 /Real (AIDeformArtWidthKey) ,\n", + "71 /Real (AIDeformArtHeightKey) ,\n131 /Real (AIDeformArtWidthKey) ,\n", + ]; + for size in sizes { + let keys = format!("{ENVELOPE_KEYS}{size}"); + let r = read_ok(&layer(&envelope_of(&mesh, &keys, &stroked_content(), 2, &drawn))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{size}: {a:#?}"); + let (.., options) = live_envelope(&a[0]); + assert_eq!(options.bounds_margin, [0.0; 4], "{size}"); + let src = EnvelopeMap::of(&a[0]).unwrap().src(); + assert!((src.width() - 120.0).abs() < 1e-6 && (src.height() - 60.0).abs() < 1e-6, "{size}: {src:?}"); + } + let keys = format!("{ENVELOPE_KEYS}60 /Real (AIDeformArtHeightKey) ,\n120 /Real (AIDeformArtWidthKey) ,\n"); + let plain = drawn_content(&EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)], + handles: vec![], + }); + let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &keys, &envelope_content(), 2, &plain))); + let a = art(&r.doc); + assert_eq!(live_envelope(&a[0]).4.bounds_margin, [0.0; 4]); + // A stroke so thin that the saved geometric size also lies close to the stroked box. + let thin = format!("{RED}0 1 1 0 1 0 0 XA\n0.2 w\n{}b\n", rect_path(40.0, 20.0, 160.0, 80.0)); + let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &keys, &thin, 2, &plain))); + assert_eq!(live_envelope(&art(&r.doc)[0]).4.bounds_margin, [0.0; 4]); + // A stroked straight line: 120 × 0 without its stroke, and 120 × 10 as saved. + let keys = format!("{ENVELOPE_KEYS}10 /Real (AIDeformArtHeightKey) ,\n120 /Real (AIDeformArtWidthKey) ,\n"); + let line = format!("{RED}0 1 1 0 1 0 0 XA\n10 w\n40 20 m\n160 20 L\nS\n"); + let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &keys, &line, 2, &plain))); + for n in art(&r.doc) { + if let NodeKind::Envelope { options, .. } = &n.kind { + assert_eq!(options.bounds_margin, [0.0; 4]); + } + } +} + +/// An envelope's contents keep their groups: a group of two rectangles stays that group. +#[test] +fn an_envelope_s_contents_keep_their_groups() { + use vectorcraft_doc::live::EnvelopeKind; + let group = format!( + "u\n{RED}{}f\n{}f\nU\n/ArtDictionary :\n(Pair) /String (AIArtName) ,\n;\n", + rect_path(40.0, 20.0, 90.0, 80.0), + rect_path(110.0, 20.0, 160.0, 80.0) + ); + let mut drawn = RED.to_string(); + drawn += &format!("{}f\n{}f\n", rect_path(40.0, 20.0, 90.0, 80.0), rect_path(110.0, 20.0, 160.0, 80.0)); + let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &group, 2, &drawn))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, kind, ..) = live_envelope(&a[0]); + assert!(matches!(kind, EnvelopeKind::Mesh { rows: 1, cols: 1, .. }), "{kind:?}"); + assert_eq!(content.len(), 1, "{content:#?}"); + assert_eq!(content[0].name.as_deref(), Some("Pair")); + let kids = content[0].children().unwrap(); + assert_eq!(kids.len(), 2, "{kids:#?}"); + assert!(kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. })), "{kids:#?}"); +} + +/// While an envelope's contents are edited, the contents come first and the mesh is in the +/// dictionary: the envelope opens live all the same, in Edit Contents. +#[test] +fn an_envelope_whose_contents_are_edited_opens_live_in_edit_contents() { + use vectorcraft_doc::live::EnvelopeKind; + let at = |(i, j): (usize, usize)| (40.0 + i as f64 * 120.0, 20.0 + j as f64 * 60.0); + let handle = |p: (usize, usize), q: (usize, usize)| match (p, q) { + ((0, 1), (1, 1)) => (70.0, 95.0), + ((1, 1), (0, 1)) => (130.0, 95.0), + _ => { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + } + }; + let mesh = mesh_text(1, 1, &at, &handle, None); + let mut bp = kurbo::BezPath::new(); + bp.move_to((40.0, 20.0)); + bp.curve_to((70.0, 5.0), (130.0, 5.0), (160.0, 20.0)); + bp.curve_to((160.0, 40.0), (160.0, 60.0), (160.0, 80.0)); + bp.curve_to((120.0, 80.0), (80.0, 80.0), (40.0, 80.0)); + bp.curve_to((40.0, 60.0), (40.0, 40.0), (40.0, 20.0)); + bp.close_path(); + let want = EnvelopeKind::TopObject { path: vectorcraft_geom::PathData::from_bezpath(&bp), corners: None }; + let keys = ENVELOPE_KEYS.replace("0 /Bool (AIDeformEditModeKey)", "1 /Bool (AIDeformEditModeKey)"); + let body = envelope_parts(&envelope_content(), &keys, &format!("0 g\n{mesh}"), 3, &drawn_content(&want)); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, kind, _, editing, _) = live_envelope(&a[0]); + assert!(editing); + assert!(matches!(kind, EnvelopeKind::TopObject { .. }), "{kind:?}"); + assert_eq!(content.len(), 1, "{content:#?}"); + assert!(matches!(content[0].kind, NodeKind::Path { .. }), "{content:#?}"); + assert_eq!(fill(&content[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); +} + +/// An envelope that doesn't read (a warp style number past the list, a mesh envelope whose shape +/// isn't a mesh, one whose plugin never closes it) keeps its drawn art, with one note; the art +/// round it is read as ever. +#[test] +fn an_envelope_that_doesnt_read_keeps_its_drawn_art() { + let blue = "0 0 1 1 0 0 1 Xa\n"; + let drawn = format!("{blue}{}f\n", rect_path(40.0, 20.0, 160.0, 80.0)); + let mesh = straight_mesh(1, 1, (120.0, 60.0)); + let cases = [ + envelope_of(&mesh, &warp_keys(99, 0.5, 0.0, 0.0, 0), &envelope_content(), 1, &drawn), + envelope_of(&format!("{}f\n", rect_path(40.0, 20.0, 160.0, 80.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn), + envelope_of(&mesh, ENVELOPE_KEYS, &envelope_content(), 7, &drawn), + envelope_of(&mesh, &ENVELOPE_KEYS.replace("131073", "131081"), &envelope_content(), 2, &drawn), + envelope_of(&mesh, ENVELOPE_KEYS, &envelope_content(), 2, &drawn).replace("(Adobe Deform Plugin) 1 0 0 XP\n", ""), + ]; + for case in cases { + let body = format!("{RED}{}f\n{case}{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0), rect_path(190.0, 0.0, 200.0, 10.0)); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 3, "{case}\n{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }) && matches!(a[2].kind, NodeKind::Path { .. }), "{a:#?}"); + let NodeKind::Group { children, .. } = &a[1].kind else { panic!("{a:#?}") }; + assert_eq!(fill(&children[0]).color(), Some(Color::rgb(0.0, 0.0, 1.0)), "{case}"); + assert_eq!(r.warnings, [super::envelope::DRAWN], "{case}"); + } +} + +/// An envelope whose contents don't come out as its drawn art (its warp bends them another way) +/// keeps the drawn art. +#[test] +fn an_envelope_that_doesnt_come_out_as_drawn_keeps_its_drawn_art() { + use vectorcraft_doc::live::EnvelopeKind; + let other = EnvelopeKind::Warp { style: "arc".into(), bend: -50.0, h: 0.0, v: 0.0, horizontal: true }; + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(1, 0.5, 0.0, 0.0, 0), &envelope_content(), 1, &drawn_content(&other)); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN]); +} + +/// A document of `n` warped text objects, with the art the live warp makes of each, in its look. +fn warped_type_doc(n: usize) -> (Document, Vec) { + use vectorcraft_doc::{Appearance, Effect, TextObject}; + let mut doc = Document::new(400.0, 200.0); + let mut looks = vec![]; + let mut layer = Node::layer(doc.alloc_id(), "Art", vectorcraft_doc::LayerColor::Preset(0)); + for i in 0..n { + let t = TextObject::point(kurbo::Point::new(20.0, 40.0 + 40.0 * i as f64), "TILT", Default::default()); + let mut text = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + let mut appearance = Appearance::default(); + appearance.effects.push(Effect { id: "warp.arc".into(), params: serde_json::json!({"bend": 40.0}), visible: true }); + text.appearance = appearance.into(); + text.name = Some(format!("Type {i}")); + text.locked = i == 0; + text.visible = i != 0; + let mut look = vectorcraft_effects::expand_outlined(None, &text, None).unwrap(); + look.id = doc.alloc_id(); + looks.push(super::envelope::WarpedLook { slot: text.id, look, left_out: None }); + layer.children_mut().unwrap().push(Arc::new(text)); + } + doc.layers = vec![Arc::new(layer)]; + (doc, looks) +} + +/// Warped text objects share the import's budget of checks. One past it keeps its drawn art with its +/// text object's name and state, as one that fails the check does, and its box and wrap setting. +#[test] +fn warped_type_past_the_budget_comes_in_as_its_look() { + let (mut doc, mut looks) = warped_type_doc(2); + let (first, second) = (looks[0].slot, looks[1].slot); + let left_out = Rect::new(1.0, 2.0, 3.0, 4.0); + looks[1].left_out = Some(left_out); + let wrap = vectorcraft_doc::TextWrap::default(); + doc.node_mut(second).unwrap().extras_mut().wrap = Some(wrap); + let warped = super::envelope::WarpedType { looks, checks: 1, ..Default::default() }; + let mut restyled = vec![Rect::new(5.0, 6.0, 7.0, 8.0), left_out]; + assert_eq!(warped.settle(&mut doc, Some, &Default::default(), &mut restyled), 1); + assert_eq!(restyled, [Rect::new(5.0, 6.0, 7.0, 8.0)]); + assert!(matches!(doc.node(first).unwrap().kind, NodeKind::Text(_))); + let kept = doc.node(second).unwrap(); + assert!(matches!(kept.kind, NodeKind::Group { .. } | NodeKind::Path { .. }), "{kept:#?}"); + assert_eq!((kept.name.as_deref(), kept.visible, kept.locked), (Some("Type 1"), true, false)); + assert_eq!(kept.extras().wrap, Some(wrap)); +} + +/// The budget for warped type is what the envelopes left: their checks and the page's share they +/// spent, with the page they are held to. +#[test] +fn warped_type_gets_what_the_envelopes_left_of_the_budget() { + let flat = vectorcraft_doc::live::EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)], + handles: vec![], + }; + let exact = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&flat)))); + let beside = format!("{RED}{}f\n", rect_path(40.5, 20.0, 160.5, 80.0)); + let shifted = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &beside))); + for r in [&exact, &shifted] { + assert_eq!(r.warped_type.checks, super::envelope::MAX_CHECKED - 1); + assert!(r.warped_type.page.is_some()); + } + live_envelope(&art(&shifted.doc)[0]); + assert!(shifted.warped_type.spent.any > exact.warped_type.spent.any); +} + +/// In a file with an artboard list, warped type is held to the first artboard, not to the crop marks. +#[test] +fn warped_type_is_held_to_the_first_artboard() { + let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 200 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_300 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_/Dictionary :\n%_400 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_600 -150 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let r = read_ok(&format!("{boards}{}", layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 40.0, 40.0))))); + assert_eq!(r.doc.artboards[0].rect, Rect::new(0.0, 0.0, 300.0, 200.0)); + assert_eq!(r.warped_type.page, Some(Rect::new(0.0, 0.0, 300.0, 200.0))); +} + +/// Type whose Warp is hidden draws no warp, so it stays type even with no check left. +#[test] +fn type_with_a_hidden_warp_stays_type() { + let (mut doc, looks) = warped_type_doc(1); + let slot = looks[0].slot; + let mut appearance = (*doc.node(slot).unwrap().appearance).clone(); + appearance.effects[0].visible = false; + doc.node_mut(slot).unwrap().appearance = appearance.into(); + let warped = super::envelope::WarpedType { looks, checks: 0, ..Default::default() }; + assert_eq!(warped.settle(&mut doc, Some, &Default::default(), &mut vec![]), 0); + assert!(matches!(doc.node(slot).unwrap().kind, NodeKind::Text(_))); +} + +/// A warped frame of threaded type stays type, whatever its look draws: the thread's frames share +/// one story. So does a slot that became no text object. +#[test] +fn warped_type_in_a_thread_stays_type() { + let (mut doc, looks) = warped_type_doc(2); + let (first, second) = (looks[0].slot, looks[1].slot); + let warped = super::envelope::WarpedType { looks, ..Default::default() }; + assert_eq!(warped.settle(&mut doc, |id| (id != second).then_some(id), &[first].into(), &mut vec![]), 0); + assert!(matches!(doc.node(first).unwrap().kind, NodeKind::Text(_))); + assert!(matches!(doc.node(second).unwrap().kind, NodeKind::Text(_))); +} + +/// What is left of the page's share of the budget decides, and the page's share counts only for +/// what the document shows. +#[test] +fn warped_type_on_the_page_spends_what_is_left_of_the_budget() { + use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE}; + let (doc, mut looks) = warped_type_doc(2); + // The second object shows; the first is hidden. Each look draws a little more than its object. + let mark = read_ok(&layer(&format!("{RED}{}f\n", rect_path(2.0, 2.0, 2.6, 2.6)))); + let mark = art(&mark.doc)[0].clone(); + for (i, w) in looks.iter_mut().enumerate() { + w.look.visible = true; + w.look = Node::group(vectorcraft_doc::NodeId(u64::MAX - 10 - i as u64), vec![Arc::new(w.look.clone()), mark.clone()]); + } + let copy = |w: &super::envelope::WarpedLook| super::envelope::WarpedLook { slot: w.slot, look: w.look.clone(), left_out: None }; + let page = Some(Rect::new(0.0, 60.0, 60.0, 100.0)); + let settle = |w: &super::envelope::WarpedLook, spent| { + let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, page }; + warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![]) + }; + let spent = || super::envelope::Spent { any: MAX_DIFFERENCE / 2.0, solid: MAX_SOLID_DIFFERENCE / 2.0 }; + assert_eq!(settle(&looks[1], Default::default()), 0); + assert_eq!(settle(&looks[1], spent()), 1); + assert_eq!(settle(&looks[0], spent()), 0); +} + +/// An envelope that comes out close to its drawn art, but with more of the page differing than the +/// page check can take from the live envelopes (its drawn art 2 pt to the side on a 200 × 100 +/// page), keeps the drawn art, so the file still opens from its layers. +#[test] +fn an_envelope_that_differs_from_its_drawn_art_over_the_page_keeps_it() { + let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0)); + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &shifted); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN]); +} + +/// An envelope whose drawn art holds an object the reader can't read keeps that drawn art, which +/// the page's art replaces. +#[test] +fn an_envelope_whose_drawn_art_holds_an_unread_object_keeps_it() { + let flat = vectorcraft_doc::live::EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)], + handles: vec![], + }; + let drawn = format!("{}frobnicate\n", drawn_content(&flat)); + let r = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.unread.iter().map(|(id, _)| *id).collect::>(), [a[0].id]); + assert_eq!(r.warnings, [super::envelope::DRAWN]); +} + +/// A live envelope takes its drawn art's own properties: its name here. +#[test] +fn a_live_envelope_keeps_its_drawn_art_s_name() { + let flat = vectorcraft_doc::live::EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)], + handles: vec![], + }; + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&flat)) + .replace("U\n9 () XW\n(Adobe Deform Plugin)", "U\n/ArtDictionary :\n(Bent) /String (AIArtName) ,\n;\n9 () XW\n(Adobe Deform Plugin)"); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + live_envelope(&a[0]); + assert_eq!(a[0].name.as_deref(), Some("Bent")); +} + +/// The same envelope beside the page opens live: what differs off the page isn't counted. +#[test] +fn an_envelope_off_the_page_opens_live_when_it_draws_close_to_its_drawn_art() { + let at = |(i, j): (usize, usize)| (300.0 + i as f64 * 120.0, 20.0 + j as f64 * 60.0); + let third = |p: (usize, usize), q: (usize, usize)| { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + }; + let content = format!("{RED}{}f\n", rect_path(300.0, 20.0, 420.0, 80.0)); + let shifted = format!("{RED}{}f\n", rect_path(302.0, 20.0, 422.0, 80.0)); + let r = read_ok(&layer(&envelope_of(&mesh_text(1, 1, &at, &third, None), ENVELOPE_KEYS, &content, 2, &shifted))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + live_envelope(&a[0]); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + #[test] fn a_gradient_mesh_reads_as_a_patch() { let corner = |rgb: &str, x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| { @@ -1502,7 +7765,7 @@ fn vector_opacity_mask_keeps_its_art_and_does_not_paint_as_a_sibling() { assert_eq!(fill(&a[1]).color(), Some(Color::rgb(1.0, 0.0, 0.0)), "mask colour must not leak"); let m = a[0].extras().mask.as_ref().unwrap(); assert_eq!((m.clip, m.invert, m.disabled, m.linked), (true, invert, disabled, linked)); - let mask_path = &m.art.children().unwrap()[0].children().unwrap()[0]; + let mask_path = &m.art.children().unwrap()[0]; assert!(matches!(mask_path.kind, NodeKind::Path { .. })); assert_eq!(mask_path.geometric_bounds(), Some(Rect::new(10.0, 40.0, 30.0, 80.0))); assert_ne!(mask_path.id, a[0].id); @@ -1512,6 +7775,84 @@ fn vector_opacity_mask_keeps_its_art_and_does_not_paint_as_a_sibling() { } } +/// Mask art that sets no paint of its own paints with the paint before its dictionary: the writer +/// leaves out paint that doesn't change. In a user's file, white letters were masked by a rectangle +/// with no colour, which came in black and hid them. +/// The unread pattern flags it also takes aren't covered here: an owner painted with a pattern the +/// file doesn't have is unread itself, which hides whether its mask art is. +#[test] +fn opacity_mask_art_without_its_own_paint_takes_the_paint_before_its_dictionary() { + let paint = "0 0 0 0 k\n1 O\n0 1 0 0 K\n1 R\n2 w\n1 J\n1 j\n4 M\n[3 1] 0 d\n1 XR\n"; + let owner = format!("{paint}{}B\n", rect_path(10.0, 20.0, 50.0, 60.0)); + let hidden_rect = rect_path(10.0, 20.0, 30.0, 60.0).lines().map(|l| format!("%_{l}\n")).collect::(); + let mask = |own_paint: &str| { + format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{own_paint}{hidden_rect}%_B\n%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n") + }; + let fill_layer = |n: &Node| n.appearance.fill().cloned(); + let stroke_layer = |n: &Node| n.appearance.stroke().cloned(); + let rule = |n: &Node| match &n.kind { + NodeKind::Path { rule, .. } => Some(*rule), + _ => None, + }; + + let r = read_ok(&layer(&format!("{owner}{}", mask("")))); + let a = art(&r.doc); + let m = a[0].extras().mask.as_ref().unwrap(); + // The owner has the paint set, none of it the default, so equal layers mean it was taken. + let (f, s) = (fill_layer(&a[0]).unwrap(), stroke_layer(&a[0]).unwrap()); + assert!(f.overprint && s.overprint); + assert_eq!((s.width, s.cap, s.join, s.miter_limit), (2.0, LineCap::Round, LineJoin::Round, 4.0)); + assert_eq!(s.dash.as_ref().map(|d| (d.pattern.clone(), d.offset)), Some((vec![3.0, 1.0], 0.0))); + assert_eq!(rule(&a[0]), Some(vectorcraft_geom::FillRule::EvenOdd)); + assert_eq!(fill_layer(&m.art), Some(f)); + assert_eq!(stroke_layer(&m.art), Some(s)); + assert_eq!(rule(&m.art), rule(&a[0])); + + // Paint the mask's art sets for itself stays in the mask: an object after the dictionary that + // sets none paints with the owner's. + let own = "%_1 g\n%_0 O\n%_0 G\n%_0 R\n%_5 w\n%_0 J\n%_0 j\n%_10 M\n%_[] 0 d\n%_0 XR\n"; + let following = format!("{}B\n", rect_path(70.0, 20.0, 80.0, 30.0)); + let r = read_ok(&layer(&format!("{owner}{}{following}", mask(own)))); + let a = art(&r.doc); + assert_eq!(a.len(), 2); + let m = a[0].extras().mask.as_ref().unwrap(); + assert_ne!(stroke_layer(&m.art), stroke_layer(&a[0]), "the mask's art has its own paint"); + assert_eq!(fill_layer(&a[1]), fill_layer(&a[0])); + assert_eq!(stroke_layer(&a[1]), stroke_layer(&a[0])); + assert_eq!(rule(&a[1]), rule(&a[0])); +} + +/// An opacity mask's art of one shown object is that object; other art is read into a group. +#[test] +fn opacity_mask_art_of_one_object_is_that_object() { + let owner = format!("{RED}{}f\n", rect_path(10.0, 20.0, 50.0, 60.0)); + let square = "%_1 g\n%_10 20 m\n%_10 60 L\n%_30 60 L\n%_30 20 L\n%_f\n"; + let read_art = |ops: &str| { + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{ops}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let r = read_ok(&layer(&format!("{owner}{mask}"))); + art(&r.doc)[0].extras().mask.as_ref().unwrap().art.clone() + }; + assert!(matches!(read_art(square).kind, NodeKind::Path { .. })); + // A group is one object: it stays a group, holding its path. + let grouped = read_art(&format!("%_u\n{square}%_U\n")); + let NodeKind::Group { children, clip: false } = &grouped.kind else { panic!("{:?}", grouped.kind) }; + assert!(matches!(children.as_slice(), [p] if matches!(p.kind, NodeKind::Path { .. }))); + // Two objects are held in a group. + let two = read_art(&format!("{square}{square}")); + assert!(matches!(&two.kind, NodeKind::Group { children, clip: false } if children.len() == 2), "{:?}", two.kind); + // A clipping path alone keeps its group, which clips. + let clipped = read_art("%_10 20 m\n%_10 60 L\n%_30 60 L\n%_30 20 L\n%_h\n%_W\n%_n\n"); + assert!(matches!(&clipped.kind, NodeKind::Group { children, clip: true } if children.len() == 1), "{:?}", clipped.kind); + // A hidden object stays in a group, which doesn't draw it. + let hidden = read_art(&format!("%_1 Xw\n{square}%_0 Xw\n")); + let NodeKind::Group { children, clip: false } = &hidden.kind else { panic!("{:?}", hidden.kind) }; + assert!(matches!(children.as_slice(), [p] if !p.visible && matches!(p.kind, NodeKind::Path { .. }))); + // So does a guide, which a group leaves out when guides aren't drawn. + let guide = read_art("%_10 20 m\n%_30 60 L\n%_(N) *\n"); + let NodeKind::Group { children, clip: false } = &guide.kind else { panic!("{:?}", guide.kind) }; + assert!(matches!(children.as_slice(), [p] if matches!(p.kind, NodeKind::Path { guide: true, .. }))); +} + /// `9 () XW` also follows legacy compound member groups. The final gradient paints /// every member; the initial black paint is a placeholder, not a separate black object. #[test] @@ -1570,11 +7911,133 @@ fn stroked_path_guides_from_the_star_operator() { assert!(matches!(n.appearance.items[0], AppearanceItem::Stroke(_))); } +/// [`stream`] with a template box centred on (306.5, 395.5): the canvas runs 8,191.5 points each +/// way from there. +fn canvas_stream(body: &str) -> String { + stream(body).replacen("%%EndComments", "%AI3_TemplateBox: 306.5 395.5 306.5 395.5\n%%EndComments", 1) +} + +/// The straight guide path from (`x0`, `y0`) to (`x1`, `y1`), `(op) *`. +fn guide_line(x0: f64, y0: f64, x1: f64, y1: f64, op: &str) -> String { + format!("{x0} {y0} m\n{x1} {y1} L\n({op}) *\n") +} + +/// #779: a straight `(N) *` guide path across the whole canvas, directly on a layer or sublayer, is +/// a ruler guide on that layer, at its place in the document; it leaves no path behind. +#[test] +fn canvas_wide_guide_paths_are_ruler_guides_of_their_layer() { + let body = format!( + "{}{}{RED}{}f\n%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(Sub) Ln\n{}LB\n%AI5_EndLayer--\n", + guide_line(-7885.0, 40.0, 8498.0, 40.0, "N"), + guide_line(25.0, 8587.0, 25.0, -7796.0, "N"), + rect_path(0.0, 0.0, 10.0, 10.0), + guide_line(-7885.0, 90.0, 8498.0, 90.0, "N"), + ); + let doc = read(canvas_stream(&layer(&body)).as_bytes()).unwrap().doc; + let top = &doc.layers[0]; + let kids = top.children().unwrap(); + assert_eq!(kids.len(), 2, "the square and the sublayer"); + assert!(matches!(kids[0].kind, NodeKind::Path { guide: false, .. })); + let sub = &kids[1]; + assert!(sub.children().unwrap().is_empty()); + let want = [ + Guide { vertical: false, pos: 60.0, artboard: None, layer: Some(top.id) }, + Guide { vertical: true, pos: 25.0, artboard: None, layer: Some(top.id) }, + Guide { vertical: false, pos: 10.0, artboard: None, layer: Some(sub.id) }, + ]; + assert_eq!(doc.guides, want); +} + +/// #779: a straight `(N) *` guide path from edge to edge of one artboard is a ruler guide of that +/// artboard. +#[test] +fn artboard_wide_guide_paths_are_ruler_guides_of_their_artboard() { + // The crop marks' artboard, 0 0 200 100. + let doc = read(canvas_stream(&layer(&guide_line(0.0, 30.0, 200.0, 30.0, "N"))).as_bytes()).unwrap().doc; + assert_eq!(doc.guides, [Guide { vertical: false, pos: 70.0, artboard: Some(1), layer: Some(doc.layers[0].id) }]); + assert!(art(&doc).is_empty()); + // The second of two artboards: art space x 400 to 600, y -150 to 0. + let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 200 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_300 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_/Dictionary :\n%_400 0 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_600 -150 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let doc = read_ok(&format!("{boards}{}", layer(&guide_line(500.0, 0.0, 500.0, -150.0, "N")))).doc; + assert_eq!(doc.artboards[1].id, 2); + assert_eq!(doc.guides, [Guide { vertical: true, pos: 500.0, artboard: Some(2), layer: Some(doc.layers[0].id) }]); +} + +/// Guide paths that aren't ruler guides stay guide paths: `(S) *` ones (guides made from objects), +/// even across the whole canvas or an artboard, short ones, slanted ones, and ones in a group. +#[test] +fn other_guide_paths_stay_guide_paths() { + let cases = [ + guide_line(-7885.0, 40.0, 8498.0, 40.0, "S"), + guide_line(20.0, 40.0, 80.0, 40.0, "S"), + guide_line(20.0, 40.0, 80.0, 40.0, "N"), + guide_line(0.0, 30.0, 200.0, 30.0, "S"), + guide_line(-7885.0, -7796.0, 8498.0, 8587.0, "N"), + format!("u\n{}U\n", guide_line(-7885.0, 40.0, 8498.0, 40.0, "N")), + format!("1 Xw\n{}0 Xw\n", guide_line(-7885.0, 40.0, 8498.0, 40.0, "N")), + "-7885 40 m\n306 40 L\n8498 40 L\n(N) *\n".to_string(), + ]; + for body in cases { + let doc = read(canvas_stream(&layer(&body)).as_bytes()).unwrap().doc; + assert!(doc.guides.is_empty(), "{body}"); + assert_eq!(art(&doc).len(), 1, "{body}"); + } +} + +/// The layer whose `Lb` has `ops` as its options (the first one in the file). +fn layer_with(ops: &str) -> Node { + let doc = read_ok(&format!("%AI5_BeginLayer\n{ops} Lb\n(L) Ln\nLB\n%AI5_EndLayer--\n")).doc; + Node::clone(&doc.layers[0]) +} + +/// #779: the template flag four places after the colour index makes a template layer; locking, +/// printing and dimming keep their own flags. In thirteen and fourteen operands the flag before +/// the colour index and the last one change nothing. +#[test] +fn the_template_flag_of_a_layer() { + let l = layer_with("1 1 0 0 1 0 0 4 255 79 255 1 50 0"); + let NodeKind::Layer { template, printable, dim_images, color, .. } = l.kind else { panic!() }; + assert!(template && !printable && l.locked); + assert_eq!((dim_images, color), (Some(50), LayerColor::Preset(4))); + for ops in ["1 1 1 1 1 0 1 5 1 2 3 1 30 0", "1 1 1 1 1 0 0 5 1 2 3 1 30 1", "1 1 1 1 1 0 1 5 1 2 3 1 30"] { + let l = layer_with(ops); + let NodeKind::Layer { template, printable, dim_images, color, .. } = l.kind else { panic!() }; + assert!(template && printable && !l.locked, "{ops}"); + assert_eq!((dim_images, color), (Some(30), LayerColor::Preset(5)), "{ops}"); + } + let l = layer_with("1 1 1 1 0 0 1 0 79 128 255 0 50 0"); + assert!(matches!(l.kind, NodeKind::Layer { template: false, .. })); +} + +/// The colour index is one place earlier in eleven and twelve operands, as in ten, and the twelfth +/// is the dimming percentage; with nine it is one place earlier still. +#[test] +fn layer_options_of_nine_to_twelve_operands() { + let options = |l: Node| match l.kind { + NodeKind::Layer { template, dim_images, color, .. } => (template, dim_images, color), + _ => panic!(), + }; + assert_eq!(options(layer_with("1 1 1 1 1 0 3 1 2 3 1")), (true, Some(50), LayerColor::Preset(3))); + assert_eq!(options(layer_with("1 1 1 1 1 0 3 1 2 3 0 25")), (false, Some(25), LayerColor::Preset(3))); + assert_eq!(options(layer_with("1 1 1 1 1 0 -1 10 20 30 1 25")), (true, Some(25), LayerColor::Custom([10, 20, 30]))); + assert_eq!(options(layer_with("1 1 1 1 0 0 3 1 2 3")), (false, None, LayerColor::Preset(3))); + assert_eq!(options(layer_with("1 1 1 1 0 2 1 2 3")), (false, None, LayerColor::Preset(2))); +} + /// A blend's record as the editing data writes it after `(Adobe Path Blends) 1 0 n XP`: `DCBA`, -/// version 1, then (as far as the reader reads it) the number of keys at word 10 and a record of -/// six words per key starting with its id. Hand-written; the other words are zero. -fn blend_record(ids: &[char]) -> String { - let mut words: Vec = vec![u32::from_le_bytes(*b"DCBA"), 1, 0, 0, 0, 0, 0, 0, 0, 0, ids.len() as u32]; +/// Specified Steps, then (as far as the reader reads it) the number of keys at word 10 and a record +/// of six words per key starting with its id. Hand-written; the other words are zero. +pub(super) fn blend_record(ids: &[char]) -> String { + blend_record_spaced(ids, 1, 0.0, 0) +} + +/// [`blend_record`] with the spacing `spacing` at word 1 (0 Smooth Color, 1 Specified Steps, 2 +/// Specified Distance), the distance `distance` at word 2 and `steps` at word 4. +fn blend_record_spaced(ids: &[char], spacing: u32, distance: f32, steps: u32) -> String { + let mut words: Vec = vec![u32::from_le_bytes(*b"DCBA"), spacing, distance.to_bits(), 0, steps, 0, 0, 0, 0, 0, ids.len() as u32]; for id in ids { words.extend([*id as u32, 0, 0, 0, 0, 0]); } @@ -1599,20 +8062,32 @@ fn blend_part(kind: &str, id: Option<&str>) -> String { /// A blend of two 20 pt squares, red on the left (key `A`) and blue on the right (`B`), along /// `spine` (path operators, `%_` lines), with its drawn steps (three between the keys) and the /// record `record`. -fn blend_file(spine: &str, ids: [Option<&str>; 2], record: &str) -> String { - let (red, blue) = ([1.0, 0.0, 0.0], [0.0, 0.0, 1.0]); +pub(super) fn blend_file(spine: &str, ids: [Option<&str>; 2], record: &str) -> String { + blend_file_colored(spine, ids, record, [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]) +} + +/// [`blend_file`] with the left key in RGB `from`, the right one in `to`, and the steps drawn +/// between their colors. +fn blend_file_colored(spine: &str, ids: [Option<&str>; 2], record: &str, from: [f64; 3], to: [f64; 3]) -> String { + blend_file_apart(spine, ids, record, from, to, 100.0, 3) +} + +/// [`blend_file_colored`] with the right key `apart` points right of the left one and `between` +/// steps drawn between them. +fn blend_file_apart(spine: &str, ids: [Option<&str>; 2], record: &str, from: [f64; 3], to: [f64; 3], apart: f64, between: usize) -> String { let mut art = String::from("%_0 Ae\n%_u\n"); - art += &square(0.0, 40.0, 20.0, red, true); + art += &square(0.0, 40.0, 20.0, from, true); art += &blend_part("K", ids[0]); - art += &square(100.0, 40.0, 20.0, blue, true); + art += &square(apart, 40.0, 20.0, to, true); art += &blend_part("K", ids[1]); art += spine; art += "%_N\n"; art += &blend_part("S", None); art += "%_U\n%_9 () XW\nu\n"; - for i in 0..5 { - let t = i as f64 / 4.0; - art += &square(t * 100.0, 40.0, 20.0, [1.0 - t, 0.0, t], false); + for i in 0..between + 2 { + let t = i as f64 / (between + 1) as f64; + let rgb = [0, 1, 2].map(|c| from[c] + (to[c] - from[c]) * t); + art += &square(t * apart, 40.0, 20.0, rgb, false); } art += "U\n9 () XW\n0 Ae\n"; art += record; @@ -1647,6 +8122,35 @@ fn a_blend_comes_in_as_a_live_blend() { assert!(!s.warnings.iter().any(|w| w == super::blend::DRAWN), "{:?}", s.warnings); } +/// A blend whose spine was never edited has no spine written, only its keys: its spine is the +/// straight line between the keys' centres, in the record's order (here the left key, named `B`, +/// first), and the blend comes in live. +#[test] +fn a_blend_with_no_spine_written_runs_straight_between_its_keys() { + let spine_part = format!("%_N\n{}", blend_part("S", None)); + let body = blend_file("", [Some("B"), Some("A")], &blend_record(&['B', 'A'])); + assert!(body.contains(&spine_part)); + let (blend, warnings) = read_blend(&body.replace(&spine_part, "")); + let NodeKind::Blend { children, spec } = &blend.kind else { panic!("a live blend: {:?} {warnings:?}", blend.kind) }; + assert!(!warnings.iter().any(|w| w == super::blend::DRAWN), "{warnings:?}"); + assert_eq!(spec.spacing, vectorcraft_doc::live::BlendSpacing::Steps(3)); + let spine = spec.spine.as_ref().and_then(|p| p.subpaths.first()).expect("a spine"); + let points: Vec<(f64, f64)> = spine.anchors.iter().map(|a| (a.p.x, a.p.y)).collect(); + assert_eq!(points.len(), 2, "{points:?}"); + assert!((points[0].0 - 10.0).abs() < 0.01 && (points[1].0 - 110.0).abs() < 0.01, "from the left key to the right one: {points:?}"); + assert_eq!(spec.key_anchors, vec![0, 1]); + assert_eq!(vectorcraft_doc::blend::blend_expand(children, spec).len(), 5); +} + +/// The tags after a blend's drawn steps are the live blend's. +#[test] +fn a_live_blend_keeps_the_tags_of_its_drawn_steps() { + let body = blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &blend_record(&['A', 'B'])); + let (blend, warnings) = read_blend(&body.replace("\nU\n9 () XW\n0 Ae\n", "\nU\n/sku (B-1) XT\n9 () XW\n0 Ae\n")); + assert!(matches!(blend.kind, NodeKind::Blend { .. }), "a live blend: {:?} {warnings:?}", blend.kind); + assert_eq!(tags(&blend).1, [tag("sku", "B-1")]); +} + /// A spine written from the right key to the left one keeps the keys in their order on it (the /// red key first), sitting on its last and first anchors. #[test] @@ -1657,6 +8161,123 @@ fn a_blends_spine_written_backwards_keeps_its_keys_order() { assert_eq!(spec.key_anchors, vec![1, 0], "the red key on the spine's end, the blue one on its start"); } +/// A blend's spacing comes from its record: Specified Distance with its distance (25 pt from one +/// step's edge to the corresponding edge of the next lays three out between keys 100 pt apart), +/// Smooth Color (keys 3/255 apart in blue take three steps), and Specified Steps with the steps +/// counted from the drawn ones, whatever its record's word 4 holds. The distance counts along the +/// spine between the keys, also where the spine runs on past the last key. +#[test] +fn a_blend_keeps_its_spacing() { + use vectorcraft_doc::live::BlendSpacing; + let straight = "%_10 50 m\n%_110 50 L\n"; + let longer = "%_10 50 m\n%_110 50 L\n%_1010 50 L\n"; + let (red, nearly_red, blue) = ([1.0, 0.0, 0.0], [1.0, 0.0, 3.0 / 255.0], [0.0, 0.0, 1.0]); + for (spine, record, (from, to), spacing) in [ + (straight, blend_record_spaced(&['A', 'B'], 2, 25.0, 3), (red, blue), BlendSpacing::Distance(25.0)), + (longer, blend_record_spaced(&['A', 'B'], 2, 25.0, 3), (red, blue), BlendSpacing::Distance(25.0)), + (straight, blend_record_spaced(&['A', 'B'], 0, 4.0, 3), (red, nearly_red), BlendSpacing::SmoothColor), + (straight, blend_record_spaced(&['A', 'B'], 1, 25.0, 3), (red, blue), BlendSpacing::Steps(3)), + (straight, blend_record_spaced(&['A', 'B'], 1, 12.5, 7), (red, blue), BlendSpacing::Steps(3)), + ] { + let (blend, warnings) = read_blend(&blend_file_colored(spine, [Some("A"), Some("B")], &record, from, to)); + let NodeKind::Blend { children, spec } = &blend.kind else { panic!("a live blend for {spacing:?}: {:?} {warnings:?}", blend.kind) }; + assert_eq!(spec.spacing, spacing); + assert_eq!(vectorcraft_doc::blend::blend_expand(children, spec).len(), 5, "{spacing:?}"); + assert!(!warnings.iter().any(|w| w == super::blend::DRAWN), "{spacing:?}: {warnings:?}"); + } +} + +/// Smooth Color blends of two 20 pt squares 200 pt apart come in live with the steps drawn +/// between them: 254 from red to blue, and 9 between two red squares. +#[test] +fn a_smooth_color_blend_comes_in_with_its_drawn_steps() { + use vectorcraft_doc::live::BlendSpacing; + let (red, blue) = ([1.0, 0.0, 0.0], [0.0, 0.0, 1.0]); + for (to, between) in [(blue, 254), (red, 9)] { + let record = blend_record_spaced(&['A', 'B'], 0, 4.0, between as u32); + let body = blend_file_apart("%_10 50 m\n%_210 50 L\n", [Some("A"), Some("B")], &record, red, to, 200.0, between); + let (blend, warnings) = read_blend(&body); + let NodeKind::Blend { children, spec } = &blend.kind else { panic!("a live blend for {between} steps: {:?} {warnings:?}", blend.kind) }; + assert_eq!(spec.spacing, BlendSpacing::SmoothColor); + assert_eq!(vectorcraft_doc::blend::blend_expand(children, spec).len(), between + 2); + assert!(!warnings.iter().any(|w| w == super::blend::DRAWN), "{between}: {warnings:?}"); + } +} + +/// A blend whose spacing doesn't lay out its drawn steps keeps them: a distance that lays out +/// nine, and Smooth Color between red and blue (more steps than the three drawn); and so does a +/// spacing the reader doesn't know or a distance that isn't a positive number. +#[test] +fn a_blend_whose_spacing_doesnt_lay_out_its_steps_keeps_them() { + let straight = "%_10 50 m\n%_110 50 L\n"; + for record in [ + blend_record_spaced(&['A', 'B'], 2, 10.0, 9), + blend_record_spaced(&['A', 'B'], 0, 4.0, 254), + blend_record_spaced(&['A', 'B'], 3, 25.0, 3), + blend_record_spaced(&['A', 'B'], 2, 0.0, 3), + blend_record_spaced(&['A', 'B'], 2, f32::NAN, 3), + blend_record_spaced(&['A', 'B'], 2, 1e-30, 3), + ] { + let (blend, warnings) = read_blend(&blend_file(straight, [Some("A"), Some("B")], &record)); + assert!(!matches!(blend.kind, NodeKind::Blend { .. }), "{record}: {:?}", blend.kind); + assert_eq!(blend.children().map(|c| c.len()), Some(5), "the five drawn squares"); + assert!(warnings.iter().any(|w| w == super::blend::DRAWN), "{warnings:?}"); + } +} + +/// Three keys with Specified Distance, unevenly spaced on a straight spine (red at x 0, blue at +/// 100, green at 150, 20 pt squares): 25 pt lays three steps out between the first two keys and +/// one between the last two, and a blend drawn that way comes in live. The same seven objects +/// drawn two and two between the keys keep their drawn steps. +#[test] +fn a_blend_of_three_keys_keeps_its_distance_between_each_pair() { + use vectorcraft_doc::live::BlendSpacing; + let (red, blue, green) = ([1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]); + let mix = |a: [f64; 3], b: [f64; 3], t: f64| [0, 1, 2].map(|c| a[c] + (b[c] - a[c]) * t); + let file = |drawn: &[(f64, [f64; 3])]| { + let mut art = String::from("%_0 Ae\n%_u\n"); + for (x, rgb, id) in [(0.0, red, "A"), (100.0, blue, "B"), (150.0, green, "C")] { + art += &square(x, 40.0, 20.0, rgb, true); + art += &blend_part("K", Some(id)); + } + art += "%_10 50 m\n%_110 50 L\n%_160 50 L\n%_N\n"; + art += &blend_part("S", None); + art += "%_U\n%_9 () XW\nu\n"; + for &(x, rgb) in drawn { + art += &square(x, 40.0, 20.0, rgb, false); + } + art += "U\n9 () XW\n0 Ae\n"; + art += &blend_record_spaced(&['A', 'B', 'C'], 2, 25.0, 0); + art + }; + let three_and_one = [ + (0.0, red), + (25.0, mix(red, blue, 0.25)), + (50.0, mix(red, blue, 0.5)), + (75.0, mix(red, blue, 0.75)), + (100.0, blue), + (125.0, mix(blue, green, 0.5)), + (150.0, green), + ]; + let (blend, warnings) = read_blend(&file(&three_and_one)); + let NodeKind::Blend { children, spec } = &blend.kind else { panic!("a live blend: {:?} {warnings:?}", blend.kind) }; + assert_eq!(spec.spacing, BlendSpacing::Distance(25.0)); + assert_eq!(vectorcraft_doc::blend::blend_steps(children, spec), vec![3, 1]); + let two_and_two = [ + (0.0, red), + (100.0 / 3.0, mix(red, blue, 1.0 / 3.0)), + (200.0 / 3.0, mix(red, blue, 2.0 / 3.0)), + (100.0, blue), + (350.0 / 3.0, mix(blue, green, 1.0 / 3.0)), + (400.0 / 3.0, mix(blue, green, 2.0 / 3.0)), + (150.0, green), + ]; + let (blend, warnings) = read_blend(&file(&two_and_two)); + assert!(!matches!(blend.kind, NodeKind::Blend { .. }), "{:?}", blend.kind); + assert_eq!(blend.children().map(|c| c.len()), Some(7), "the seven drawn squares"); + assert!(warnings.iter().any(|w| w == super::blend::DRAWN), "{warnings:?}"); +} + /// A curved spine (a line, a curve and a line) is read with its points exactly; a blend whose drawn /// steps don't follow it (they are drawn on a straight line here) keeps its drawn steps. #[test] @@ -1731,6 +8352,60 @@ fn a_blend_it_cant_read_keeps_its_drawn_steps() { } } +/// A blend's opacity defines the knockout shape when the state block after its record says so, +/// live or as its drawn steps. An `Xy` that is the layer's leaves the blend's as it was. +#[test] +fn a_blend_keeps_its_knockout_shape() { + let straight = "%_10 50 m\n%_110 50 L\n"; + let keys = [Some("A"), Some("B")]; + let record = blend_record(&['A', 'B']); + let garbled = "(Adobe Path Blends) 1 0 16 XP\n%00112233445566778899AABBCCDDEEFF\n".to_string(); + for (record, live) in [(&record, true), (&garbled, false)] { + let body = format!("{}0 0.6 0 1 1 Xy\n0 0 Xd\n6 () XW\n", blend_file(straight, keys, record)); + let doc = read_ok(&layer(&body)).doc; + assert_eq!(matches!(art(&doc)[0].kind, NodeKind::Blend { .. }), live, "{:?}", art(&doc)[0].kind); + assert!(art(&doc)[0].knockout_shape, "live: {live}"); + } + let blend = blend_file(straight, keys, &record); + // Written after its drawn steps, before the record. + let doc = read_ok(&layer(&blend.replace("\nU\n9 () XW\n0 Ae\n", "\nU\n0 0.6 0 1 1 Xy\n9 () XW\n0 Ae\n"))).doc; + assert!(matches!(art(&doc)[0].kind, NodeKind::Blend { .. }), "{:?}", art(&doc)[0].kind); + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].knockout_shape), (0.6, true)); + let doc = read_ok(&layer(&format!("{blend}0 0.6 0 1 1 Xy\n1 0.35 0 0 0 Xy\n0 0 Xd\n7 () XW\n"))).doc; + assert!(art(&doc)[0].knockout_shape, "the blend's own"); + assert!(!doc.layers[0].knockout_shape, "the layer's own"); + let doc = read_ok(&layer(&format!("{blend}1 0.35 0 0 1 Xy\n0 0 Xd\n7 () XW\n"))).doc; + assert!(!art(&doc)[0].knockout_shape, "the blend's own"); + assert!(doc.layers[0].knockout_shape, "the layer's own"); +} + +/// A blend's transparency (here knockout on, as blends are written) is the state block after its +/// record, as a group's follows its end: the live blend's, or its drawn steps' where they stay. It +/// is the blend's own, not the next object's. +#[test] +fn a_blends_transparency_follows_its_record() { + let state = "0 0.6 0 1 0 Xy\n0 0 Xd\n6 () XW\n"; + let next = format!("0 1 0 0 0 Xy\n{RED}{}f\n", rect_path(150.0, 40.0, 170.0, 60.0)); + let straight = "%_10 50 m\n%_110 50 L\n"; + let garbled = "(Adobe Path Blends) 1 0 16 XP\n%00112233445566778899AABBCCDDEEFF\n".to_string(); + for (record, live) in [(blend_record(&['A', 'B']), true), (garbled, false)] { + let body = format!("{}{state}{next}", blend_file(straight, [Some("A"), Some("B")], &record)); + let a = art(&read_ok(&layer(&body)).doc); + assert_eq!(a.len(), 2, "{a:?}"); + assert_eq!(matches!(a[0].kind, NodeKind::Blend { .. }), live, "{:?}", a[0].kind); + assert_eq!((a[0].opacity, a[0].knockout), (0.6, Knockout::On), "live: {live}"); + assert_eq!(a[1].opacity, 1.0, "the next object's own state"); + } + // A layer whose last object is a blend: a state block that ends `7 () XW` before `LB` is the + // layer's, and the blend keeps the state it had. + let body = format!("{}1 0.35 0 0 0 Xy\n0 0 Xd\n7 () XW\n", blend_file(straight, [Some("A"), Some("B")], &blend_record(&['A', 'B']))); + let doc = read_ok(&layer(&body)).doc; + assert_eq!((doc.layers[0].opacity, doc.layers[0].blend), (0.35, BlendMode::Multiply), "the layer's state"); + let a = art(&doc); + assert!(matches!(a[0].kind, NodeKind::Blend { .. }), "{:?}", a[0].kind); + assert_eq!((a[0].opacity, a[0].blend), (1.0, BlendMode::Normal), "the blend's own state"); +} + /// The blend is live: moving a key moves the steps between it and the other key with it. #[test] fn moving_a_blends_key_moves_its_steps() { @@ -1760,3 +8435,1639 @@ fn a_blend_record_is_read_to_its_length() { let (blend, warnings) = read_blend(&blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &longer)); assert!(matches!(blend.kind, NodeKind::Blend { .. }), "{warnings:?}"); } + +/// An object's dictionary with the text wrap `entries` (each a `values (key) ,` line). +fn wrap_dictionary(entries: &[&str]) -> String { + let lines: String = entries.iter().map(|e| format!("%_{e}\n")).collect(); + format!("%_/ArtDictionary :\n{lines}%_;\n%_\n") +} + +/// The wrap outline a file may keep beside the options: art, then its key. +const WRAP_PATH: &str = "X=\n%_4 As\n%_0 0 m\n%_0 20 L\n%_20 20 L\n%_20 0 L\n%_f\n%_X+\n%_ (AI11TextWrapPath) ,"; + +fn wrap_of(n: &Node) -> Option { + n.extras().wrap +} + +#[test] +fn wrap_dictionary_path() { + let dict = wrap_dictionary(&[WRAP_PATH, "0 /Bool (AI11TextWrapInvert) ,", "12.5 /Real (AI11TextWrapOffset) ,"]); + let r = read_ok(&layer(&format!("{RED}{}f\n{dict}", rect_path(10.0, 10.0, 50.0, 50.0)))); + let kids = art(&r.doc); + assert_eq!(kids.len(), 1, "the kept outline isn't art: {:?}", r.warnings); + assert_eq!(wrap_of(&kids[0]), Some(vectorcraft_doc::TextWrap { offset: 12.5, invert: false })); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +#[test] +fn wrap_dictionary_invert_and_default() { + let inverted = wrap_dictionary(&["12.5 /Real (AI11TextWrapOffset) ,", "1 /Bool (AI11TextWrapInvert) ,"]); + let default = wrap_dictionary(&["0 /Bool (AI11TextWrapInvert) ,"]); + let plain = wrap_dictionary(&["(Plain) /String (AIArtName) ,"]); + let r = read_ok(&layer(&format!( + "{RED}{}f\n{inverted}{}f\n{default}{}f\n{plain}", + rect_path(0.0, 0.0, 10.0, 10.0), + rect_path(20.0, 0.0, 30.0, 10.0), + rect_path(40.0, 0.0, 50.0, 10.0) + ))); + let kids = art(&r.doc); + assert_eq!(kids.len(), 3); + assert_eq!(wrap_of(&kids[0]), Some(vectorcraft_doc::TextWrap { offset: 12.5, invert: true })); + assert_eq!(wrap_of(&kids[1]), Some(vectorcraft_doc::TextWrap::default()), "6 pt when the offset isn't given"); + assert_eq!(wrap_of(&kids[2]), None, "an object without wrap options isn't a wrap object"); + assert_eq!(kids[2].name.as_deref(), Some("Plain")); +} + +#[test] +fn wrap_dictionary_bad_offset() { + let offsets = ["nan /Real", "1e308 /Real", "(far) /String", "2000 /Real", "-2000 /Real"]; + let mut body = RED.to_string(); + for (i, offset) in offsets.iter().enumerate() { + let x = 20.0 * i as f64; + body += &format!("{}f\n", rect_path(x, 0.0, x + 10.0, 10.0)); + body += &wrap_dictionary(&[&format!("{offset} (AI11TextWrapOffset) ,"), "1 /Bool (AI11TextWrapInvert) ,"]); + } + // An offset that isn't a number, with nothing else of the options, isn't a wrap object. + body += &format!("{}f\n", rect_path(200.0, 0.0, 210.0, 10.0)); + body += &wrap_dictionary(&["(far) /String (AI11TextWrapOffset) ,", "7 /Bool (AI11TextWrapInvert) ,"]); + let r = read_ok(&layer(&body)); + let offsets: Vec> = art(&r.doc).iter().map(|n| wrap_of(n).map(|w| w.offset)).collect(); + assert_eq!(offsets, [Some(6.0), Some(1000.0), Some(6.0), Some(1000.0), Some(-1000.0), None]); + assert!(art(&r.doc).iter().take(5).all(|n| wrap_of(n).is_some_and(|w| w.invert))); +} + +#[test] +fn wrap_dictionary_group() { + let dict = wrap_dictionary(&["6 /Real (AI11TextWrapOffset) ,", "0 /Bool (AI11TextWrapInvert) ,"]); + let r = read_ok(&layer(&format!("u\n{RED}{}f\n{}f\nU\n{dict}", rect_path(0.0, 0.0, 10.0, 10.0), rect_path(20.0, 0.0, 30.0, 10.0)))); + let kids = art(&r.doc); + assert_eq!(kids.len(), 1); + assert_eq!(wrap_of(&kids[0]), Some(vectorcraft_doc::TextWrap::default())); + let NodeKind::Group { children, .. } = &kids[0].kind else { panic!("a group: {:?}", kids[0].kind) }; + assert_eq!(children.len(), 2); + assert!(children.iter().all(|c| wrap_of(c).is_none() && matches!(c.kind, NodeKind::Path { .. }))); +} + +/// Wraparound text in the version 7 format (§15.4.2): `*w`, objects, the area text, the objects it +/// wraps around, `*W`. +#[test] +fn legacy_wrap_group() { + let text = format!("1 To\n1 0 0 1 0 0 0 Tp\n{}n\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Around) Tx\nTO\n", rect_path(0.0, 0.0, 100.0, 80.0)); + // The last object's own dictionary gives its options. + let own = wrap_dictionary(&["3 /Real (AI11TextWrapOffset) ,", "1 /Bool (AI11TextWrapInvert) ,"]); + let body = format!( + "*w\n{RED}{}f\n{text}{}f\n{}f\n{own}*W\n", + rect_path(0.0, 0.0, 5.0, 5.0), + rect_path(30.0, 30.0, 50.0, 50.0), + rect_path(60.0, 30.0, 70.0, 50.0) + ); + let r = read_ok(&layer(&body)); + let kids = art(&r.doc); + assert_eq!(kids.len(), 1, "{:?}", r.warnings); + let NodeKind::Group { children, clip: false } = &kids[0].kind else { panic!("a group: {:?}", kids[0].kind) }; + let wraps: Vec<(bool, bool)> = children.iter().map(|c| (matches!(c.kind, NodeKind::Text(_)), wrap_of(c).is_some())).collect(); + assert_eq!(wraps, [(false, true), (true, false), (false, true), (false, true)], "objects before the text are wrap objects too: {:?}", r.warnings); + let none = Some(vectorcraft_doc::TextWrap { offset: 0.0, invert: false }); + assert_eq!(wrap_of(&children[0]), none, "no offset"); + assert_eq!(wrap_of(&children[2]), none, "no offset"); + assert_eq!(wrap_of(&children[3]), Some(vectorcraft_doc::TextWrap { offset: 3.0, invert: true })); + assert!(!r.warnings.iter().any(|w| w.contains("*w") || w.contains("*W")), "{:?}", r.warnings); +} + +/// A wraparound group with no type in it: each of its objects is a wrap object, with no offset. +#[test] +fn legacy_wrap_group_without_text() { + let body = format!("*w\n{RED}{}f\n{}f\n*W\n", rect_path(0.0, 0.0, 5.0, 5.0), rect_path(30.0, 30.0, 50.0, 50.0)); + let r = read_ok(&layer(&body)); + let kids = art(&r.doc); + assert_eq!(kids.len(), 1, "{:?}", r.warnings); + let NodeKind::Group { children, clip: false } = &kids[0].kind else { panic!("a group: {:?}", kids[0].kind) }; + let wraps: Vec<_> = children.iter().map(|c| wrap_of(c)).collect(); + assert_eq!(wraps, [Some(vectorcraft_doc::TextWrap { offset: 0.0, invert: false }); 2]); +} + +/// `*w` and `*W` take no operands, and a wraparound group can't be an element of a compound path. +#[test] +fn legacy_wrap_group_errors() { + let square = format!("{RED}{}f\n", rect_path(0.0, 0.0, 5.0, 5.0)); + for (body, error) in [ + (format!("1 *w\n{square}*W\n"), "`*w` takes no operands"), + (format!("*w\n{square}0 *W\n"), "`*W` takes no operands"), + (format!("*u\n*w\n{square}*W\n*U\n"), "a wraparound group is inside a compound path"), + (format!("*u\nu\n*w\n{square}*W\nU\n*U\n"), "a wraparound group is inside a compound path"), + ] { + let e = read(stream(&layer(&body)).as_bytes()).unwrap_err(); + assert!(e.contains(error), "{body:?}: {e}"); + } +} + +/// The printer's crop marks Illustrator draws after the last layer (`%AI3_BeginCrops`, inside +/// `userdict /AI3_noCropMarks known not { … } if`) aren't art outside the layers: the file reads +/// from its layers, without them (the crop area is `%AI3_Cropmarks`). +#[test] +fn crop_marks_after_the_layers_are_not_art() { + let crops = "%AI3_BeginCrops\nuserdict /AI3_noCropMarks known not {\n0 A\nu\n0 R\n1 1 1 1 ([Registration]) 0 XS\n\ + 0 J 0 j 0.5 w 4 M []0 d\n0 XR\n-9 -400 m\n-36 -400 L\nS\nU\n} if\n%AI3_EndCrops\n"; + let r = read_ok(&format!("{}{crops}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")))); + assert_eq!(art(&r.doc).len(), 1); + assert_eq!(r.doc.layers.len(), 1); +} + +/// The name of an Objects on Path record. +const ALIGN_ON_PATH: &str = "Adobe Align On Path"; // brand-ok: the record's name in the files +/// The ids of an Objects on Path group's path and its four objects. +const ON_PATH_IDS: [&str; 5] = [ + "0a6d1e52-0000-4000-8000-000000000001", + "0a6d1e52-0000-4000-8000-000000000002", + "0a6d1e52-0000-4000-8000-000000000003", + "0a6d1e52-0000-4000-8000-000000000004", + "0a6d1e52-0000-4000-8000-000000000005", +]; +const OPEN_PATH: &str = "20 20 m\n100 80 L\n180 20 L\nS\n"; +const CLOSED_PATH: &str = + "40 50 m\n40 66.57 66.86 80 100 80 c\n133.14 80 160 66.57 160 50 c\n160 33.43 133.14 20 100 20 c\n66.86 20 40 33.43 40 50 c\ns\n"; + +/// An Objects on Path group: the stroked `path` with the id `ids[0]`, then a 10 × 6 red square for +/// each other id, 50 pt apart from x 20, whose frame is turned `angle` radians. +fn on_path_group(path: &str, ids: &[&str], angle: f64) -> String { + use vectorcraft_testkit::ai::on_path_member; + let (first, rest) = ids.split_first().unwrap(); + let mut group = format!("0 Ae\nu\n/ConstraintGroup :\n128 /GroupType ,\n;\n0 0 1 0 0 0 1 XA\n2 w\n{path}{}", on_path_member(first, None, 0.0)); + for (i, id) in rest.iter().enumerate() { + let x = 20.0 + 50.0 * i as f64; + group += &format!("{RED}{}f\n{}", rect_path(x, 40.0, x + 10.0, 46.0), on_path_member(id, Some(i), angle)); + } + group + "U\n" +} + +/// The group the layer of `body` holds first, and its Objects on Path record. +fn on_path(body: &str) -> (Arc, Option) { + let doc = read_ok(body).doc; + let g = art(&doc).first().cloned().unwrap(); + let rec = g.extras().objects_on_path.as_deref().cloned(); + (g, rec) +} + +/// An Objects on Path group opens as one, with its path, its objects in their order along the path, +/// Pivot and Rotate, and its art where the file draws it; the same art without the record opens as a +/// plain group. +#[test] +fn an_objects_on_path_group_opens_with_its_path_objects_and_options() { + use vectorcraft_testkit::ai::{on_path_options, on_path_record}; + let group = on_path_group(OPEN_PATH, &ON_PATH_IDS, 0.5); + let record = on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &on_path_options(4, 0, std::f64::consts::FRAC_PI_6, "")); + let (g, rec) = on_path(&format!("{record}{}", layer(&group))); + let rec = rec.expect("an Objects on Path group"); + let kids = g.children().unwrap(); + assert_eq!(kids.len(), 5); + let NodeKind::Path { path, .. } = &kids.iter().find(|c| c.id == rec.path).unwrap().kind else { panic!("the path") }; + assert!(path.subpaths.first().is_some_and(|s| !s.closed), "the open path"); + let child = |id| kids.iter().find(|c| c.id == id).unwrap(); + let xs: Vec = rec.members.iter().map(|m| child(m.id).geometric_bounds().unwrap().x0).collect(); + assert_eq!(xs, [20.0, 70.0, 120.0, 170.0], "the objects in the file's order"); + for m in &rec.members { + let center = child(m.id).geometric_bounds().unwrap().center(); + assert_eq!((m.angle, m.frame), (-0.5, kurbo::Affine::rotate_about(-0.5, center)), "the frame turned counterclockwise"); + } + assert!((rec.rotate - 30.0).abs() < 1e-9, "{}", rec.rotate); + assert_eq!(rec.pivot, 0); + let (plain, none) = on_path(&layer(&group)); + assert!(none.is_none()); + let kinds = |g: &Node| g.children().unwrap().iter().map(|c| c.kind.clone()).collect::>(); + assert_eq!(kinds(&g), kinds(&plain), "the art stays where it is drawn"); +} + +/// A group on a closed path opens as an Objects on Path group too. +#[test] +fn an_objects_on_path_group_on_a_closed_path_opens_live() { + use vectorcraft_testkit::ai::{on_path_options, on_path_record}; + let record = on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &on_path_options(4, 4, 0.0, "")); + let (g, rec) = on_path(&format!("{record}{}", layer(&on_path_group(CLOSED_PATH, &ON_PATH_IDS, 0.0)))); + let rec = rec.expect("an Objects on Path group"); + let NodeKind::Path { path, .. } = &g.children().unwrap().iter().find(|c| c.id == rec.path).unwrap().kind else { panic!("the path") }; + assert!(path.subpaths.first().is_some_and(|s| s.closed), "the closed path"); + assert_eq!((rec.members.len(), rec.pivot, rec.rotate), (4, 4, 0.0)); +} + +/// A record the group can't be read from, or with options an Objects on Path group doesn't hold, +/// leaves the group a plain group with its art. +#[test] +fn an_objects_on_path_record_that_doesnt_fit_leaves_a_plain_group() { + use vectorcraft_testkit::ai::{on_path_options, on_path_record}; + let [p, a, b, c, d] = ON_PATH_IDS; + let options = |more: &str| on_path_options(4, 4, 0.0, more); + let good = options(""); + let group = on_path_group(OPEN_PATH, &ON_PATH_IDS, 0.0); + assert!(on_path(&format!("{}{}", on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good), layer(&group))).1.is_some()); + let cases: Vec<(&str, String, String)> = vec![ + ("the path's id is missing", on_path_record(ALIGN_ON_PATH, &["0a6d1e52-ffff", a, b, c, d], &good), group.clone()), + ("an object's id is missing", on_path_record(ALIGN_ON_PATH, &[p, a, b, c], &good), group.clone()), + ("an id twice", on_path_record(ALIGN_ON_PATH, &[p, a, b, b, d], &good), group.clone()), + ("objects out of order", on_path_record(ALIGN_ON_PATH, &[p, b, a, c, d], &good), group.clone()), + ("a spacing", on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &options("%_56.5 /Real (Spacing) ,\n")), group.clone()), + ("an option this reader doesn't know", on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &options("%_1 /Bool (Flip) ,\n")), group.clone()), + ( + "uneven spacing", + on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good.replace("1 /Bool (IsEquiSpaced)", "0 /Bool (IsEquiSpaced)")), + group.clone(), + ), + ( + "a later start", + on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good.replace("0 /Real (StartRangeFraction)", "0.25 /Real (StartRangeFraction)")), + group.clone(), + ), + ("a pivot past 8", on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &on_path_options(4, 9, 0.0, "")), group.clone()), + ("another constraint", on_path_record("Some Other Constraint", &ON_PATH_IDS, &good), group.clone()), + ( + "another version", + on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good).replace("%_1 /Int (Constraint Verison)", "%_2 /Int (Constraint Verison)"), + group.clone(), + ), + ("an object without its angle", on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good), group.replace("%_(0) /String (BBAccumRotation) ,\n", "")), + ( + "another child in the group", + on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good), + group.replace("U\n", &format!("{}f\nU\n", rect_path(0.0, 0.0, 5.0, 5.0))), + ), + ("a path without its key", on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &good), group.replace("%_1 /Bool (KeyPath) ,\n", "")), + ]; + for (why, record, group) in cases { + let (g, rec) = on_path(&format!("{record}{}", layer(&group))); + assert!(rec.is_none(), "{why}"); + assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "{why}"); + assert!(g.children().unwrap().len() >= 5, "{why}: the art is kept"); + } +} + +/// The path and objects of a group are measured once however many records name it: a thousand +/// copies of a record open about as fast as one copy followed by 999 records whose path id is +/// missing, when the group opens live, when its long path has no length, and when its first object +/// is a group of many paths and its last object has no bounds. +#[test] +fn repeated_objects_on_path_records_dont_measure_the_objects_again() { + use vectorcraft_testkit::ai::{on_path_member, on_path_options, on_path_record}; + let paths: String = (0..20_000).map(|i| format!("{}f\n", rect_path(f64::from(i % 200), 40.0, f64::from(i % 200) + 1.0, 46.0))).collect(); + let big = format!("u\n{RED}{paths}U\n{}", on_path_member(ON_PATH_IDS[1], Some(0), 0.0)); + let empty = format!("u\nU\n{}", on_path_member(ON_PATH_IDS[2], Some(1), 0.0)); + let still = format!("20 20 m\n{}S\n", "20 20 L\n".repeat(20_000)); + let cases = [ + ("a live group", OPEN_PATH.to_string(), big.clone(), 2, true), + ("a path without length", still, big.clone(), 2, false), + ("an object without bounds", OPEN_PATH.to_string(), format!("{big}{empty}"), 3, false), + ]; + for (why, path, objects, n, live) in cases { + let ids = &ON_PATH_IDS[..n]; + let group = format!( + "0 Ae\nu\n/ConstraintGroup :\n128 /GroupType ,\n;\n0 0 1 0 0 0 1 XA\n2 w\n{path}{}{objects}U\n", + on_path_member(ids[0], None, 0.0) + ); + let record = on_path_record(ALIGN_ON_PATH, ids, &on_path_options(n - 1, 4, 0.0, "")); + let (start, end) = (record.find("%_/Dictionary :\n%_1 /Int").unwrap(), record.find("%_; (Constraint Data)").unwrap()); + let copy = &record[start..end]; + let unresolved = copy.replace(ids[0], "0a6d1e52-ffff-4000-8000-000000000000"); + let one = format!("{}{copy}{}{}", &record[..start], unresolved.repeat(999), &record[end..]); + let many = format!("{}{}{}", &record[..start], copy.repeat(1000), &record[end..]); + let time = |data: &str| { + let started = std::time::Instant::now(); + let doc = read_ok(&format!("{data}{}", layer(&group))).doc; + let elapsed = started.elapsed(); + let g = art(&doc)[0].clone(); + assert_eq!(g.children().unwrap().len(), n, "{why}"); + assert_eq!(g.extras().objects_on_path.is_some(), live, "{why}"); + elapsed + }; + // The fastest of three runs each, taken in turn, so that other tests running at the same + // time weigh on both. + let (mut fastest_one, mut fastest_many) = (std::time::Duration::MAX, std::time::Duration::MAX); + for _ in 0..3 { + fastest_one = fastest_one.min(time(&one)); + fastest_many = fastest_many.min(time(&many)); + } + assert!(fastest_many < fastest_one * 5, "{why}: one copy: {fastest_one:?}, 1000 copies: {fastest_many:?}"); + } +} + +/// The copy of the drawn group that follows it as versioned content is skipped: the group opens once, +/// live. +#[test] +fn an_objects_on_path_group_in_versioned_content_opens_once() { + use vectorcraft_testkit::ai::{on_path_options, on_path_record}; + let record = on_path_record(ALIGN_ON_PATH, &ON_PATH_IDS, &on_path_options(4, 4, 0.0, "")); + let group = on_path_group(OPEN_PATH, &ON_PATH_IDS, 0.0); + let copy = group.replace("/ConstraintGroup :\n128 /GroupType ,\n;\n", ""); + let versioned = format!("%AI17_Begin_Content_if_version_gt:24 14\n{group}%AI17_Alternate_Content\n{copy}%AI17_End_Versioned_Content\n"); + let doc = read_ok(&format!("{record}{}", layer(&versioned))).doc; + let kids = art(&doc); + assert_eq!(kids.len(), 1); + assert_eq!(kids[0].children().unwrap().len(), 5); + assert!(kids[0].extras().objects_on_path.is_some()); +} + +// ---- brushes ------------------------------------------------------------------------------ + +const CALLIGRAPHIC: &str = "Adobe Calligraphic Brush Tool"; +const SCATTER: &str = "Adobe Scatter Brush Tool"; +const ART_BRUSH: &str = "Adobe ArtOnPath Brush Tool"; +const PATTERN_BRUSH: &str = "Adobe PatternOnPath Brush Tool"; +const BRISTLE: &str = "Adobe dBrush Brush Tool"; + +/// A plug-in object of plug-in `kind` named `name`, its parameters `params` split into strings of +/// 16 characters at most (`-` after each but the last, `.` after that). +fn plugin_object(kind: &str, name: &str, params: &str) -> String { + let chars: Vec = params.chars().collect(); + let chunks: Vec = chars.chunks(16).map(|c| c.iter().collect()).collect(); + let n = chunks.len(); + let lines: String = chunks.iter().enumerate().map(|(i, c)| format!("({c}) {}\n", if i + 1 == n { "." } else { "-" })).collect(); + format!("%AI5_Begin_NonPrinting\nNp\n%AI8_BeginPluginObject\n({kind})\n({name})\n{lines}%AI8_EndPluginObject\n%AI5_End_NonPrinting--\n") +} + +/// The brush manager's order of the brushes `brushes` (plug-in, name). +fn brush_order(brushes: &[(&str, &str)]) -> String { + let params: String = brushes.iter().map(|(k, n)| format!(" {k}/ {n}/")).collect(); + plugin_object(brush::MANAGER, brush::MANAGER, ¶ms) +} + +/// A brush's art named `name`: a filled square of side `side`. +fn brush_art(name: &str, side: f64) -> String { + format!("%AI8_BeginBrushPattern\n({name})\n0 A\n0 g\n{}f\n%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, side, side)) +} + +/// A Calligraphic brush with diameter 2 to 6, roundness 40 to 60 and angle -30 to 10, the diameter +/// varying at random, the roundness fixed and the angle with the pen's pressure. +const NIB: &str = "1 2 6 40 60 -30 10 1 0 2 0"; +/// A Scatter brush of the art `Dot art`: size 50% to 150% at random, spacing 120% to 200% fixed, +/// scatter -25% to 25% with the pressure, rotation -45° to 30° at random and following the path. +const SPRAY: &str = "2 /Dot art/ 5 1 0 0 / 0 0.5 1.5 1 1.2 2 0 -0.25 0.25 2 -45 30 1 1 0"; +/// An Art brush of the art `Ribbon art`. +const RIBBON: &str = "2 / Ribbon art/ / / / / 0 0/ 5 0 0 0 / 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1"; +/// A Pattern brush of four tiles (the fourth slot empty) at 80%. +const FENCE: &str = "2 / Tile one/ Tile two/ Tile three/ / Tile five/ 0 0/ 0 1 / 1 1 0.8 0 4 0 0 0 0.8 0.8 0 0 0 0 0"; +/// A Bristle brush: stiffness 60%, thickness 40%, density 30%, opacity 80%, length 150%, size 2 mm. +const MOP: &str = "0 4 0.6 0.4 0.3 0.8 1.5 2 library shape"; + +/// The brushes of the five kinds, their art and the manager's order (the Bristle brush first). +fn five_brushes() -> String { + let order = brush_order(&[(BRISTLE, "Mop"), (CALLIGRAPHIC, "Nib"), (SCATTER, "Spray"), (ART_BRUSH, "Ribbon"), (PATTERN_BRUSH, "Fence")]); + let art: String = ["Dot art", "Ribbon art", "Tile one", "Tile two", "Tile three", "Tile five"].iter().map(|n| brush_art(n, 4.0)).collect(); + let objects = [ + (CALLIGRAPHIC, "Nib", NIB), + (SCATTER, "Spray", SPRAY), + (ART_BRUSH, "Ribbon", RIBBON), + (PATTERN_BRUSH, "Fence", FENCE), + (BRISTLE, "Mop", MOP), + ]; + let objects: String = objects.iter().map(|(k, n, p)| plugin_object(k, n, p)).collect(); + format!("{art}{order}{objects}") +} + +fn brush_named<'a>(lib: &'a [vectorcraft_brush::Brush], name: &str) -> &'a vectorcraft_brush::BrushKind { + match lib.iter().find(|b| b.name == name) { + Some(b) => &b.kind, + None => panic!("no brush {name} in {:?}", lib.iter().map(|b| &b.name).collect::>()), + } +} + +/// The brush manager's order gives the kind and name of each brush, in the panel's order. +#[test] +fn the_brush_managers_order_gives_each_brushs_kind_in_order() { + let params = format!(" {BRISTLE}/ Mop/ {CALLIGRAPHIC}/ Nib/ {SCATTER}/ Spray/ {ART_BRUSH}/ Ribbon/ {PATTERN_BRUSH}/ Fence /"); + let order = brush::parse_brush_manager(¶ms).unwrap(); + use brush::Tool; + let want = [(Tool::Bristle, "Mop"), (Tool::Calligraphic, "Nib"), (Tool::Scatter, "Spray"), (Tool::Art, "Ribbon"), (Tool::Pattern, "Fence ")]; + assert_eq!(order, want.map(|(t, n)| (t, n.to_string())), "a name keeps its trailing spaces"); + assert_eq!(brush::parse_brush_manager(" Some Other Plugin/ Thing/"), None); +} + +/// A file's brushes replace the default ones, in the manager's order, with their values. A pattern +/// brush is left out (which slot holds which tile isn't known), with a note. +#[test] +fn a_files_brushes_come_in_with_their_values_in_the_panels_order() { + let r = read_ok(&format!("{}{}", five_brushes(), layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n")))); + let lib = vectorcraft_brush::library(&r.doc); + let names: Vec<&str> = lib.iter().map(|b| b.name.as_str()).collect(); + assert_eq!(names, ["Mop", "Nib", "Spray", "Ribbon"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w == "brushes VectorCraft can't read yet were left out of the Brushes panel (1)"), "{:?}", r.warnings); + use vectorcraft_brush::{BrushKind, Variation}; + let BrushKind::Calligraphic(c) = brush_named(&lib, "Nib") else { panic!("calligraphic") }; + assert_eq!((c.angle, c.roundness, c.size), (-10.0, 50.0, 4.0)); + assert_eq!(c.variation, [20.0, 10.0, 2.0]); + assert_eq!(c.modes, Some([Variation::Pressure, Variation::Fixed, Variation::Random])); + let BrushKind::Scatter(s) = brush_named(&lib, "Spray") else { panic!("scatter") }; + assert_eq!((s.size, s.spacing, s.scatter, s.rotation), ((50.0, 150.0), (120.0, 200.0), (-25.0, 25.0), (-45.0, 30.0))); + assert_eq!(s.modes, Some([Variation::Random, Variation::Fixed, Variation::Pressure, Variation::Random])); + assert!(s.rotation_relative_to_path); + assert_eq!(s.art.geometric_bounds().map(|b| (b.width(), b.height())), Some((4.0, 4.0)), "the art of its section"); + let BrushKind::Art(a) = brush_named(&lib, "Ribbon") else { panic!("art") }; + assert!(a.art.geometric_bounds().is_some(), "the art of its section"); + assert_eq!(a.colorization, vectorcraft_brush::Colorization::Tints, "its code"); + let BrushKind::Bristle(b) = brush_named(&lib, "Mop") else { panic!("bristle") }; + let got = [b.stiffness, b.thickness, b.density, b.opacity, b.length, b.size]; + let want = [60.0, 40.0, 30.0, 80.0, 150.0, 2.0 * 72.0 / 25.4]; + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-9), "{got:?}"); +} + +/// A Pattern brush's five slots name its art sections, in its order, an empty slot naming none; +/// its scale comes in as a percentage. +#[test] +fn a_pattern_brushs_five_slots_are_kept() { + let d = brush::parse_tool_object(brush::Tool::Pattern, "Fence", FENCE).unwrap(); + let brush::DraftKind::Pattern { tiles, scale } = d.kind else { panic!("{d:?}") }; + let s = |n: &str| Some(n.to_string()); + assert_eq!(tiles, [s("Tile one"), s("Tile two"), s("Tile three"), None, s("Tile five")]); + assert!((scale - 80.0).abs() < 1e-9); + let d = brush::parse_tool_object(brush::Tool::Scatter, "Spray", SPRAY).unwrap(); + assert!(matches!(d.kind, brush::DraftKind::Scatter { ref art, .. } if art == "Dot art"), "{d:?}"); + let d = brush::parse_tool_object(brush::Tool::Art, "Ribbon", RIBBON).unwrap(); + assert!(matches!(d.kind, brush::DraftKind::Art { ref art, .. } if art == "Ribbon art"), "{d:?}"); +} + +/// A brush's art filled with a pattern the file defines before it is read, with that pattern. +#[test] +fn a_brushs_art_takes_the_patterns_defined_before_it() { + let dots = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_0 0 0 1 k\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"; + let art_ = format!( + "%AI8_BeginBrushPattern\n(Dot art)\n0 A\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n%AI8_EndBrushPattern\n", + rect_path(0.0, 0.0, 4.0, 4.0) + ); + let r = read_ok(&format!("{dots}{art_}{}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(""))); + let lib = vectorcraft_brush::library(&r.doc); + let vectorcraft_brush::BrushKind::Scatter(s) = brush_named(&lib, "Spray") else { panic!("scatter") }; + assert!(matches!(fill(&s.art), Paint::Pattern { ref pattern, .. } if pattern == "Dots"), "{:?}", r.warnings); +} + +/// A spot color that only a brush's art uses comes in as a swatch, and the art's process colors +/// count toward the document's color mode, as a pattern's do. +#[test] +fn a_brushs_art_brings_its_spot_colors_and_color_mode() { + let section = format!("%AI8_BeginBrushPattern\n(Dot art)\n0 A\n0 1 1 0 (Ink) 0 x\n{}f\n%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, 4.0, 4.0)); + let r = read_ok(&format!("{section}{}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(""))); + let lib = vectorcraft_brush::library(&r.doc); + assert!(matches!(brush_named(&lib, "Spray"), vectorcraft_brush::BrushKind::Scatter(_)), "{:?}", r.warnings); + let ink = r.doc.swatch("Ink").map(|s| (s.paint.color(), s.global, s.spot)); + assert_eq!(ink, Some((Some(Color::cmyk(0.0, 1.0, 1.0, 0.0)), true, true)), "{:?}", r.warnings); + assert_eq!(r.doc.color_mode, ColorMode::Cmyk); + // Art that isn't kept brings nothing. + let odd = "%AI8_BeginBrushPattern\n(Odd art)\n0 1 1 0 (Lost ink) 0 x\n0 0 m\n1 1 L\nnotanoperator\nf\n%AI8_EndBrushPattern\n"; + let r = read_ok(&format!("{odd}{}{}", plugin_object(SCATTER, "Odd", &SPRAY.replace("Dot art", "Odd art")), layer(""))); + assert!(r.doc.swatch("Lost ink").is_none()); + assert_eq!(r.doc.color_mode, ColorMode::Rgb); + // Nor does art that only a brush left out uses (a pattern brush). + let tile = "%AI8_BeginBrushPattern\n(Tile one)\n0 A\n0 1 1 0 (Fence ink) 0 x\n0 0 m\n4 0 L\n4 4 L\nf\n%AI8_EndBrushPattern\n"; + let r = read_ok(&format!("{tile}{}{}", plugin_object(PATTERN_BRUSH, "Fence", FENCE), layer(""))); + assert!(vectorcraft_brush::library(&r.doc).is_empty(), "{:?}", r.warnings); + assert!(r.doc.swatch("Fence ink").is_none()); + assert_eq!(r.doc.color_mode, ColorMode::Rgb); +} + +/// A spot color that the page's art and a brush's art both define keeps the page's value, and a +/// brush art section that a later one of the same name replaces brings none of its colors. +#[test] +fn a_brushs_art_colors_come_after_the_pages_and_a_replaced_sections_bring_nothing() { + let section = |ink: &str, color: &str| { + format!("%AI8_BeginBrushPattern\n(Dot art)\n0 A\n{color} ({ink}) 0 x\n{}f\n%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, 4.0, 4.0)) + }; + let page = layer(&format!("0 0 1 0 (Ink) 0 x\n{}f", rect_path(0.0, 0.0, 10.0, 10.0))); + let body = format!("{}{}{}{page}", section("Gone ink", "1 0 0 0"), section("Ink", "0 1 1 0"), plugin_object(SCATTER, "Spray", SPRAY)); + let r = read_ok(&body); + assert!(matches!(brush_named(&vectorcraft_brush::library(&r.doc), "Spray"), vectorcraft_brush::BrushKind::Scatter(_))); + assert_eq!(r.doc.swatch("Ink").and_then(|s| s.paint.color()), Some(Color::cmyk(0.0, 0.0, 1.0, 0.0)), "{:?}", r.warnings); + assert!(r.doc.swatch("Gone ink").is_none()); +} + +/// The art of a file's brushes brings each color name's first definition once, and at most +/// [`super::brush::MAX_BRUSH_ART_COLORS`] names; the colors it leaves out still count toward the +/// color mode, and art that no brush uses, or that a later section replaces, takes no places. +#[test] +fn brush_art_keeps_each_color_name_once_and_a_bounded_number_of_names() { + let open = |sections: &[(&str, &str)]| { + let defs: String = sections + .iter() + .map(|(name, colors)| { + format!("%AI8_BeginBrushPattern\n({name})\n0 A\n{colors}{}f\n%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, 4.0, 4.0)) + }) + .collect(); + let mist = plugin_object(SCATTER, "Mist", &SPRAY.replace("Dot art", "Dash art")); + read_ok(&format!("{defs}{}{mist}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(""))).doc + }; + let max = super::brush::MAX_BRUSH_ART_COLORS; + let ink = "0 1 1 0 (Ink) 0 x\n"; + let many: String = (0..max).map(|i| format!("1 0 0 0 (Name {i}) 0 x\n")).collect(); + // One name repeated takes one place. + let doc = open(&[("Dot art", &format!("{}{ink}", "1 0 0 0 (Same) 0 x\n".repeat(max)))]); + assert!(doc.swatch("Same").is_some() && doc.swatch("Ink").is_some()); + // Different names fill the places: the name past them is left out, and its color still counts. + let doc = open(&[("Dot art", &format!("{many}{ink}"))]); + assert!(doc.swatch("Name 0").is_some() && doc.swatch("Ink").is_none()); + assert_eq!(doc.color_mode, ColorMode::Cmyk); + // The places are shared by the art of every brush, and a name in the art of two takes one. + let doc = open(&[("Dot art", &many), ("Dash art", ink)]); + assert_eq!(vectorcraft_brush::library(&doc).len(), 2); + assert!(doc.swatch("Name 0").is_some() && doc.swatch("Ink").is_none()); + let half: String = many.lines().take(max / 2).map(|l| format!("{l}\n")).collect(); + let doc = open(&[("Dot art", &half), ("Dash art", &format!("{half}{ink}"))]); + assert!(doc.swatch("Name 0").is_some() && doc.swatch("Ink").is_some()); + // The color operators of every brush's art take places before the gradient stops of any. + let stops: String = (0..max / 250) + .map(|g| { + let named: String = (0..250).map(|s| format!("%_0 0 1 0 (Stop {g} {s}) 0 0 5 1 6 50 {} Bs\n", s * 100 / 250)).collect(); + format!("%AI5_BeginGradient: (G{g})\n(G{g}) 0 250 Bd\n[\n<00FF>\n0\n{named}BD\n%AI5_EndGradient\n") + }) + .collect(); + let doc = open(&[("Dot art", &stops), ("Dash art", ink)]); + assert!(doc.swatch("Stop 0 0").is_some() && doc.swatch("Ink").is_some(), "{:?}", doc.swatch("Stop 0 0")); + // Art that no brush uses, and art that a later section of its name replaces, take no places. + let doc = open(&[("Other art", &many), ("Dot art", &many), ("Dot art", ink)]); + assert!(doc.swatch("Ink").is_some() && doc.swatch("Name 0").is_none()); +} + +/// A global process color that only a brush's art defines with its color operator stays a process +/// color when a gradient of the file names it as a stop, as the page's own definition does (#1771). +#[test] +fn a_brushs_art_defines_a_process_color_that_a_gradient_stop_names() { + let defs = "%AI5_BeginGradient: (Brand)\n(Brand) 0 2 Bd\n[\n<00FF>\n0\n\ + %_0.93 0.1 0 0 (Test Cyan) 0 0 5 1 6 50 0 Bs\n%_0 0 0 0 1 0 0 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let section = format!( + "%AI8_BeginBrushPattern\n(Dot art)\n0 A\n0.93 0.1 0 0 (Test Cyan) 0 0 Xk\n{}f\n%AI8_EndBrushPattern\n", + rect_path(0.0, 0.0, 4.0, 4.0) + ); + let doc = read_ok(&format!("{defs}{section}{}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(""))).doc; + assert!(matches!(brush_named(&vectorcraft_brush::library(&doc), "Spray"), vectorcraft_brush::BrushKind::Scatter(_))); + let sw = doc.swatch("Test Cyan").unwrap(); + assert!(sw.global && !sw.spot, "a global process color, not an ink: {sw:?}"); +} + +/// A brush art section inside a symbol's definition isn't kept, so its spot colors make no swatch. +#[test] +fn brush_art_inside_a_symbol_brings_no_colors() { + let section = + format!("%AI8_BeginBrushPattern\n(Dot art)\n0 A\n0 1 1 0 (Hidden ink) 0 x\n{}f\n%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, 4.0, 4.0)); + let body = format!("{}{}{}", symbol("S", &format!("{section}{}", dot()), 5), plugin_object(SCATTER, "Spray", SPRAY), layer("")); + let r = read_ok(&body); + assert!(r.doc.symbols.iter().any(|s| s.name == "S"), "{:?}", r.warnings); + assert!(r.doc.swatch("Hidden ink").is_none()); +} + +/// A brush's art filled with a pattern defined in the version 7 form places the tiles with the +/// fill's offset, scale, rotation, reflection and shear operands, and a brush whose art has such a +/// fill without all nine of them isn't read. +#[test] +fn a_brushs_art_places_a_version_7_patterns_tiles_with_its_operands() { + let def = pattern7("Grid", "(0 g) @ _ &\n"); + let read_with = |ops: &str| { + let section = format!("%AI8_BeginBrushPattern\n(Dot art)\n0 A\n(Grid) {ops} p\n{}f\n%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, 4.0, 4.0)); + read_ok(&format!("{def}{section}{}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(""))) + }; + let placed = |ops: &str| { + let r = read_with(ops); + let lib = vectorcraft_brush::library(&r.doc); + let vectorcraft_brush::BrushKind::Scatter(s) = brush_named(&lib, "Spray") else { panic!("scatter") }; + match fill(&s.art) { + Paint::Pattern { xf, .. } => xf, + p => panic!("{ops}: {p:?} {:?}", r.warnings), + } + }; + let plain = placed("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"); + // The operands and the move they make from the plain placement (a b c d e f): those of + // `a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear` with y down, as the + // art's space has it. + let cases = [ + ("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, -15.0]), + ("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, 0.353553, -1.035276, 0.353553, -5.0, -7.0]), + ]; + for (ops, want) in cases { + let got = (placed(ops) * plain.inverse()).as_coeffs(); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6), "{ops}: {got:?}"); + } + let r = read_with("0 0 1 1 0 0 0 0 [1 0 0 1 0 0]"); + assert!(!vectorcraft_brush::library(&r.doc).iter().any(|b| b.name == "Spray"), "{:?}", r.warnings); +} + +/// A Scatter brush whose 15 numbers start with 1 colors its art with Tints of the stroke, and one +/// whose 15 numbers start with 0 keeps the art's colors. The field before the art's name doesn't +/// count: a brush whose first field is 1 is read by its 15 numbers, and one with 8 numbers, as older +/// files write their brushes, isn't read as a Scatter brush. +#[test] +fn a_scatter_brush_in_tints_comes_in_tinted() { + use vectorcraft_brush::{BrushKind, Colorization}; + let read = |params: &str| { + let r = read_ok(&format!("{}{}{}", brush_art("Dot art", 4.0), plugin_object(SCATTER, "Spray", params), layer(""))); + vectorcraft_brush::library(&r.doc).into_iter().find(|b| b.name == "Spray") + }; + for (field, first, colorization) in + [("2", "1", Colorization::Tints), ("2", "0", Colorization::None), ("1", "1", Colorization::Tints), ("1", "0", Colorization::None)] + { + let params = format!("{field} /Dot art/ 5 0 0 0 / {first} 1 1 0 1 1 0 0 0 0 0 0 0 0 0"); + let Some(b) = read(¶ms) else { panic!("{params}: not read") }; + let BrushKind::Scatter(s) = b.kind else { panic!("scatter") }; + assert_eq!(s.colorization, colorization, "{params}"); + } + let older = "1 /Dot art/ 0 1 / 1 0 1 0 1 0 0 0"; + assert_eq!(brush::parse_tool_object(brush::Tool::Scatter, "Spray", older), Err(brush::BrushError::Values)); + assert!(read(older).is_none(), "8 numbers aren't a Scatter brush's"); +} + +/// A brush's art section `name`: in a group, a frame (a rectangle from `frame.0` to `frame.1` on +/// both axes, painted by `op` and followed by `after`) and a filled square from 0 to 4. +fn framed_art(name: &str, frame: (f64, f64), op: &str, after: &str) -> String { + format!( + "%AI8_BeginBrushPattern\n({name})\n0 A\n0 Xw\nu\n0 XR\n{}{op}\n{after}0 g\n{}f\nU\n%AI8_EndBrushPattern\n", + rect_path(frame.0, frame.0, frame.1, frame.1), + rect_path(0.0, 0.0, 4.0, 4.0) + ) +} + +/// The frame of a brush's art, an unnamed, unpainted rectangle at the art's bounds, isn't part of +/// the art, closed or open with its first corner again at the end. A frame wider than the art is +/// part of it, and so are a painted rectangle and a named one, which aren't frames. +#[test] +fn a_brushs_frame_is_left_out_only_at_the_arts_bounds() { + use vectorcraft_brush::BrushKind; + let named = "%_/ArtDictionary :\n%_/XMLUID : (Edge) ; (AI10_ArtUID) ,\n%_;\n%_\n"; + for (why, frame, op, after, kept) in [ + ("exact", (0.0, 4.0), "n", "", false), + ("open", (0.0, 4.0), "N", "", false), + ("wider", (-1.0, 5.0), "n", "", true), + ("filled", (0.0, 4.0), "f", "", true), + ("named", (0.0, 4.0), "n", named, true), + ] { + let params = "2 /Dot art/ 5 0 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0"; + let r = read_ok(&format!("{}{}{}", framed_art("Dot art", frame, op, after), plugin_object(SCATTER, "Spray", params), layer(""))); + let lib = vectorcraft_brush::library(&r.doc); + let BrushKind::Scatter(s) = brush_named(&lib, "Spray") else { panic!("scatter") }; + if kept { + assert!(matches!(s.art.kind, NodeKind::Group { .. }), "{why}: {:#?}", s.art); + assert_eq!(s.art.children().map(|c| c.len()), Some(2), "{why}"); + } else { + assert_eq!(s.art.geometric_bounds().map(|b| b.width()), Some(4.0), "{why}: {:#?}", s.art); + assert!(matches!(s.art.kind, NodeKind::Path { .. }), "{why}: the square alone: {:#?}", s.art); + } + } +} + +/// A brush's art group that is hidden, locked, isolated or has a note keeps that state when its +/// frame is left out: the group stays, without the frame, rather than becoming its one other object. +#[test] +fn a_brushs_frame_leaves_the_groups_own_state() { + use vectorcraft_doc::{Appearance, FillLayer, NodeId}; + let square = Rect::new(0.0, 0.0, 4.0, 4.0); + let paint = FillLayer::new(Paint::solid(Color::BLACK)); + let ap = Appearance { items: vec![AppearanceItem::Fill(paint)], effects: vec![], contents_index: None }; + let dot = Node::path(NodeId(2), vectorcraft_geom::shapes::rectangle(square), ap); + let frame = Node::path(NodeId(1), vectorcraft_geom::shapes::rectangle(square), Default::default()); + let group = Node::group(NodeId(3), vec![Arc::new(frame), Arc::new(dot)]); + assert!(matches!(super::brush::without_frame(group.clone()).kind, NodeKind::Path { .. }), "a plain group is its one object"); + // A closed path through the four corners across the square, not along its sides, isn't a frame. + let corners = [Point::new(0.0, 0.0), Point::new(4.0, 4.0), Point::new(4.0, 0.0), Point::new(0.0, 4.0)]; + let crossing = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&corners, true)); + let bowtie = Node::path(NodeId(4), crossing, Default::default()); + let dot = group.children().and_then(|c| c.last().cloned()).unwrap(); + let crossed = Node::group(NodeId(5), vec![Arc::new(bowtie), dot]); + assert_eq!(super::brush::without_frame(crossed).children().map(|c| c.len()), Some(2), "a path across the corners stays"); + // An open path along three sides isn't a frame; one that comes back to its first corner is. + let sides = [Point::new(0.0, 0.0), Point::new(4.0, 0.0), Point::new(4.0, 4.0), Point::new(0.0, 4.0)]; + let around = [sides.as_slice(), &sides[..1]].concat(); + for (why, anchors, frame) in [("three sides", sides.as_slice(), false), ("back to the first corner", around.as_slice(), true)] { + let open = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(anchors, false)); + let dot = group.children().and_then(|c| c.last().cloned()).unwrap(); + let g = Node::group(NodeId(6), vec![Arc::new(Node::path(NodeId(7), open, Default::default())), dot]); + let left = if frame { None } else { Some(2) }; + assert_eq!(super::brush::without_frame(g).children().map(|c| c.len()), left, "{why}"); + } + // A rectangle with settings of its own (a note, Show Center, hidden) isn't a frame. + for why in ["note", "show center", "hidden"] { + let mut g = group.clone(); + if let Some(Some(first)) = g.children_mut().map(|c| c.first_mut()) { + let first = Arc::make_mut(first); + match why { + "note" => first.extras_mut().attrs = Some(Box::new(vectorcraft_doc::ObjectAttributes { note: "edge".into(), ..Default::default() })), + "show center" => { + first.extras_mut().attrs = Some(Box::new(vectorcraft_doc::ObjectAttributes { show_center: Some(true), ..Default::default() })) + } + _ => first.visible = false, + } + } + assert_eq!(super::brush::without_frame(g).children().map(|c| c.len()), Some(2), "{why}: the rectangle stays"); + } + for why in ["hidden", "locked", "isolated", "note"] { + let mut g = group.clone(); + (g.visible, g.locked, g.isolate) = (why != "hidden", why == "locked", why == "isolated"); + if why == "note" { + g.extras_mut().attrs = Some(Box::new(vectorcraft_doc::ObjectAttributes { note: "edge".into(), ..Default::default() })); + } + let out = super::brush::without_frame(g); + assert!(matches!(out.kind, NodeKind::Group { .. }), "{why}: {out:#?}"); + assert_eq!(out.children().map(|c| c.len()), Some(1), "{why}: the frame left out"); + assert_eq!((out.visible, out.locked, out.isolate), (why != "hidden", why == "locked", why == "isolated"), "{why}"); + assert_eq!(out.extras().attrs.as_ref().map(|a| a.note.as_str()), (why == "note").then_some("edge"), "{why}"); + } +} + +/// Leaving out a frame that is exactly the art's bounds doesn't move what a Scatter or Art brush +/// draws: the pieces along a path are where they are with the frame kept. +#[test] +fn a_brushs_frame_at_the_arts_bounds_draws_the_same_without_it() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Scatter}; + let scatter = ("Spray", "Dot art", SCATTER, "2 /Dot art/ 5 0 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0"); + for (name, art_name, tool, params) in [scatter, ("Ribbon", "Ribbon art", ART_BRUSH, RIBBON)] { + let r = read_ok(&format!("{}{}{}", framed_art(art_name, (0.0, 4.0), "n", ""), plugin_object(tool, name, params), layer(""))); + let lib = vectorcraft_brush::library(&r.doc); + let read = lib.iter().find(|b| b.name == name).cloned().unwrap(); + let art = match &read.kind { + BrushKind::Scatter(s) => s.art.clone(), + BrushKind::Art(a) => a.art.clone(), + k => panic!("{name}: {k:?}"), + }; + let bounds = art.geometric_bounds().unwrap(); + assert_eq!((bounds.width(), bounds.height()), (4.0, 4.0), "{name}"); + assert!(matches!(art.kind, NodeKind::Path { .. }), "{name}: the frame left out: {art:#?}"); + let frame = Node::path(vectorcraft_doc::NodeId(90), vectorcraft_geom::shapes::rectangle(bounds), Default::default()); + let framed_art = Node::group(vectorcraft_doc::NodeId(91), vec![Arc::new(frame), Arc::new(art)]); + let kind = match &read.kind { + BrushKind::Scatter(s) => BrushKind::Scatter(Scatter { art: framed_art, ..s.clone() }), + BrushKind::Art(a) => BrushKind::Art(ArtBrush { art: framed_art, ..a.clone() }), + k => panic!("{name}: {k:?}"), + }; + let framed = Brush { kind, ..read.clone() }; + let mut line = kurbo::BezPath::new(); + line.move_to((0.0, 0.0)); + line.line_to((100.0, 30.0)); + let stroke = vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 1.0); + let at = |b: &Brush| -> Vec<[i64; 4]> { + vectorcraft_brush::stroke_pieces(&r.doc, b, &line, &stroke) + .iter() + .filter_map(|n| n.geometric_bounds()) + .map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| (v * 1000.0).round() as i64)) + .collect() + }; + let (without, with) = (at(&read), at(&framed)); + assert!(!without.is_empty(), "{name}"); + if name == "Spray" { + assert!(without.len() > 10, "{without:?}"); + } + assert_eq!(without, with, "{name}"); + } +} + +/// A file without brush objects keeps the default brushes. +#[test] +fn a_file_without_brushes_keeps_the_default_ones() { + let r = read_ok(&layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n"))); + assert!(!r.doc.unknown.contains_key(vectorcraft_brush::DOC_KEY)); +} + +/// A brush whose object can't be read, or whose art is missing or can't be read, is left out with a +/// note; the layers and the other brushes still come in. +#[test] +fn a_brush_that_cant_be_read_leaves_the_layers_and_other_brushes() { + let bad_art = "%AI8_BeginBrushPattern\n(Odd art)\n0 g\n0 0 m\n1 1 L\nnotanoperator\nf\n%AI8_EndBrushPattern\n"; + let objects = [ + plugin_object(CALLIGRAPHIC, "Nib", NIB), + plugin_object(CALLIGRAPHIC, "Short", "1 2 3"), + plugin_object(CALLIGRAPHIC, "Huge", "1 2 inf 40 60 -30 10 1 0 2 0"), + plugin_object(SCATTER, "Odd", &SPRAY.replace("Dot art", "Odd art")), + plugin_object(SCATTER, "Lost", &SPRAY.replace("Dot art", "Nowhere")), + plugin_object(ART_BRUSH, "Bare", "2 / / / / / / 0 0/ 5 0 0 0 / 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1"), + plugin_object(BRISTLE, "Nib", MOP), + ] + .concat(); + let r = read_ok(&format!("{bad_art}{objects}{}", layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n")))); + assert_eq!(art(&r.doc).len(), 1, "the layer's art"); + let lib = vectorcraft_brush::library(&r.doc); + assert_eq!(lib.iter().map(|b| b.name.as_str()).collect::>(), ["Nib"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.ends_with("Brushes panel (6)")), "{:?}", r.warnings); +} + +/// Files with brush objects and no brushes VectorCraft reads get an empty list, not the defaults. +#[test] +fn a_file_whose_brushes_are_all_left_out_has_none() { + let r = read_ok(&format!("{}{}", plugin_object(PATTERN_BRUSH, "Fence", FENCE), layer(""))); + assert!(vectorcraft_brush::library(&r.doc).is_empty()); +} + +/// A brush object that ends after its plug-in name is counted as a brush left out, and the file +/// gets no default brushes. +#[test] +fn a_brush_object_without_a_name_is_counted_as_left_out() { + let nameless = format!("%AI5_Begin_NonPrinting\nNp\n%AI8_BeginPluginObject\n({CALLIGRAPHIC})\n%AI8_EndPluginObject\n%AI5_End_NonPrinting--\n"); + let r = read_ok(&format!("{nameless}{}", layer(""))); + assert!(vectorcraft_brush::library(&r.doc).is_empty(), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.ends_with("Brushes panel (1)")), "{:?}", r.warnings); + let r = read_ok(&format!("{}{nameless}{}", plugin_object(CALLIGRAPHIC, "Nib", NIB), layer(""))); + let lib = vectorcraft_brush::library(&r.doc); + assert_eq!(lib.iter().map(|b| b.name.as_str()).collect::>(), ["Nib"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.ends_with("Brushes panel (1)")), "{:?}", r.warnings); +} + +/// A gradient's `Br` (a stop's ramp) isn't a brush: the gradient keeps its stops. +#[test] +fn a_gradients_br_is_not_a_brush() { + let gradient = + "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n0 0 0 0 1 1 1 2 1 6 50 0 Bs\n0 0 0 1 0 0 0 2 0.5 6 50 100 Bs\n0 Br\nBD\n%AI5_EndGradient\n"; + let art_ = format!("{}Bb\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n10 0 0 10 100 50 Xm\nf\n0 BB\n", rect_path(0.0, 0.0, 20.0, 20.0)); + let r = read_ok(&format!("{gradient}{}", layer(&art_))); + assert!(!r.doc.unknown.contains_key(vectorcraft_brush::DOC_KEY)); + let Paint::Gradient(g) = fill(&art(&r.doc)[0]) else { panic!("a gradient: {:?}", r.warnings) }; + assert_eq!(g.gradient.stops.len(), 2); +} + +/// The Brush Options codes for how a Calligraphic brush's values vary: Tilt, Bearing and Rotation +/// are the pen's other channels (#372: a 6D Art Pen brush varies its diameter with the pressure, +/// its roundness with the bearing and its angle with the barrel's rotation). The stylus wheel isn't +/// read: it varies at random, as an unknown code does. +#[test] +fn a_calligraphic_brushs_pen_channels_come_in_by_their_codes() { + use vectorcraft_brush::Variation::{Bearing, Fixed, Pressure, Random, Rotation, Tilt}; + let modes = |params: &str| { + let d = brush::parse_tool_object(brush::Tool::Calligraphic, "Pen", params).unwrap(); + let brush::DraftKind::Calligraphic(c) = d.kind else { panic!("{d:?}") }; + c.modes.unwrap() + }; + assert_eq!(modes("1 51 69 13 57 -346 14 2 5 6 0"), [Rotation, Bearing, Pressure]); + assert_eq!(modes("1 2 6 40 60 -30 10 4 4 4 0"), [Tilt, Tilt, Tilt]); + assert_eq!(modes("1 2 6 40 60 -30 10 3 3 3 0"), [Random, Random, Random], "the stylus wheel"); + assert_eq!(modes("1 4 4 50 50 10 10 3 9 9 0"), [Fixed, Fixed, Fixed], "nothing to vary"); +} + +/// A 6D Art Pen brush: diameter 4 to 8 with the pressure, roundness 30 to 50 with the bearing and +/// angle -150 to 210 with the barrel's rotation. +const SIX_D: &str = "1 4 8 30 50 -150 210 2 5 6 0"; + +/// The style `Inked`: a stroke in red of weight `weight` with the Calligraphic brush `brush` at +/// diameter, roundness and angle `settings` (each its value and variation either side), varying by +/// the codes `codes`, its angle relative to `relative` (0 the page). +fn brushed_style(brush: &str, weight: f64, settings: [(f64, f64); 3], codes: [u8; 3], relative: u8) -> String { + let [(d, dv), (r, rv), (a, av)] = settings; + let [dm, rm, am] = codes; + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Inked) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n({CALLIGRAPHIC}) 1 0 /Filter ,\n1 /Visible ,\n(Calligraphic Brush) /Title ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ + /StrokeStyle : 0 R\n0 1 1 0 1 0 0 XA\n0 1 0 0 0 Xy\n0 J 0 j {weight} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n\ + {d} /Real (Diameter) ,\n{dv} /Real (DiameterVariation) ,\n{dm} /Int (DiameterDependsOn) ,\n\ + {r} /Real (Roundness) ,\n{rv} /Real (RoundnessVariation) ,\n{rm} /Int (RoundnessDependsOn) ,\n\ + {a} /Real (Angle) ,\n{av} /Real (AngleVariation) ,\n{am} /Int (AngleDependsOn) ,\n{relative} /Int (AngleRelativeTo) ,\n\ + ({brush}) /UnicodeString (DisplayString) ,\n/GObjRef : ({brush}) ({CALLIGRAPHIC}) /PluginObject ; (Brush) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /FillStyle : 0 O\n0 0 0 0 k\n0 0 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ) +} + +/// The settings [`SIX_D`] has, as an art style writes them. +const SIX_D_SETTINGS: [(f64, f64); 3] = [(6.0, 2.0), (40.0, 10.0), (30.0, 180.0)]; + +/// A brushed path as the file writes it: its drawn look (a filled outline) in a group, then the +/// path itself on `%_` lines, unpainted, with the style `Inked`. +fn brushed_path() -> String { + let line = "20 20 m\n100 60 L\n"; + format!("0 Ae\nu\n{RED}{}f\nU\n0 0 Xd\n6 () XW\n%_{}n\n1 (Inked) XW\n", rect_path(20.0, 18.0, 100.0, 62.0), line.replace('\n', "\n%_")) +} + +/// A path drawn with a Calligraphic brush comes in as the path, its stroke in that brush at its +/// weight (the weight scales the brush), not as its drawn look: here a 6D Art Pen brush, whose +/// channels the brush keeps (#372). +#[test] +fn a_path_with_a_calligraphic_brush_comes_in_brushed() { + let def = plugin_object(CALLIGRAPHIC, "Six D", SIX_D); + let style = brushed_style("Six D", 0.5, SIX_D_SETTINGS, [2, 5, 6], 0); + let r = read_ok(&format!("{def}{style}{}", layer(&brushed_path()))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the path, not its look: {a:#?}"); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let st = a[0].appearance.stroke().unwrap(); + assert_eq!((st.brush.as_deref(), st.width, st.paint.color()), (Some("Six D"), 0.5, Some(Color::rgb(1.0, 0.0, 0.0)))); + assert!(a[0].appearance.fill().is_none_or(|f| f.paint.is_none()), "{:?}", a[0].appearance); + use vectorcraft_brush::{BrushKind, Variation}; + let lib = vectorcraft_brush::library(&r.doc); + let BrushKind::Calligraphic(c) = brush_named(&lib, "Six D") else { panic!("calligraphic") }; + assert_eq!(c.modes, Some([Variation::Rotation, Variation::Bearing, Variation::Pressure])); + // With no pen recorded on the path, the nib is the brush's own at the stroke's weight. + let pieces = vectorcraft_brush::stroke_pieces(&r.doc, &lib[0], &a[0].path_data().unwrap().to_bezpath(), st); + let height = pieces.iter().filter_map(|n| n.geometric_bounds()).map(|b| b.height()).fold(0.0, f64::max); + assert!(height > 40.0 && height < 46.0, "the line's rise and about half the nib's 3 pt: {height}"); +} + +/// A brushed path keeps its drawn look when its stroke can't be read as the brush: the object's +/// own settings differ from the brush's (Options of Selected Object), its angle follows the path, +/// or the file defines no brush of its name. +#[test] +fn a_brushed_path_the_brush_cant_draw_keeps_its_drawn_look() { + let def = plugin_object(CALLIGRAPHIC, "Six D", SIX_D); + let mut own = SIX_D_SETTINGS; + own[0] = (9.0, 2.0); + let cases = [ + ("its own settings", def.clone(), brushed_style("Six D", 1.0, own, [2, 5, 6], 0)), + ("its own modes", def.clone(), brushed_style("Six D", 1.0, SIX_D_SETTINGS, [2, 5, 4], 0)), + ("an angle on the path", def.clone(), brushed_style("Six D", 1.0, SIX_D_SETTINGS, [2, 5, 6], 1)), + ("no such brush", def, brushed_style("Other", 1.0, SIX_D_SETTINGS, [2, 5, 6], 0)), + ]; + for (why, def, style) in cases { + let r = read_ok(&format!("{def}{style}{}", layer(&brushed_path()))); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{why}: the drawn look, {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{why}: {:?}", r.warnings); + } +} + +/// The entries of an Art brush's filter for a path that stretches its art, at the brush's own width. +const STRETCHED: [(&str, &str, &str); 12] = [ + ("Proportional", "0", "Bool"), + ("Segmented", "0", "Bool"), + ("Scaling", "1", "Real"), + ("MinScaling", "1", "Real"), + ("MaxScaling", "1", "Real"), + ("ScaleYDependsOn", "0", "Int"), + ("Spacing", "0", "Real"), + ("UpsideDown", "0", "Int"), + ("Counterclockwise", "0", "Int"), + ("Adjustment", "1", "Int"), + ("FoldAdjustment", "1", "Bool"), + ("Colorization", "1", "Int"), +]; + +/// The style `Inked`: a stroke in red of weight `weight` with the Art brush `brush`, with the entries +/// `entries` and `more` after them. +fn art_style(brush: &str, weight: f64, entries: &[(&str, &str, &str)], more: &str) -> String { + let entries: String = entries.iter().map(|(key, value, kind)| format!("{value} /{kind} ({key}) ,\n")).collect(); + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Inked) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n({ART_BRUSH}) 1 0 /Filter ,\n1 /Visible ,\n(Art Brush) /Title ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ + {entries}{more}/StrokeStyle : 0 R\n0 1 1 0 1 0 0 XA\n0 1 0 0 0 Xy\n0 J 0 j {weight} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n\ + ({brush}) /UnicodeString (DisplayString) ,\n/GObjRef : ({brush}) ({ART_BRUSH}) /PluginObject ; (Brush) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /FillStyle : 0 O\n0 0 0 0 k\n0 0 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ) +} + +/// A brush's art named `name`: a wide block with a narrow one on top of it (art space: y up). +fn lopsided_art(name: &str) -> String { + format!( + "%AI8_BeginBrushPattern\n({name})\n0 A\n0 g\n{}f\n{}f\n%AI8_EndBrushPattern\n", + rect_path(0.0, 0.0, 40.0, 4.0), + rect_path(0.0, 4.0, 10.0, 8.0) + ) +} + +/// A path drawn with an Art brush comes in as the path, its stroke in that brush at its weight (the +/// weight scales the art across the path), not as its drawn look. The art runs along the path as +/// the file draws it: the side of its section with y up goes to the right of the path's direction. +#[test] +fn a_path_with_an_art_brush_comes_in_brushed() { + let def = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON)); + let more = "15 /Int (Adobe Effect Expand Before Version) ,\n"; + let r = read_ok(&format!("{def}{}{}", art_style("Ribbon", 2.0, &STRETCHED, more), layer(&brushed_path()))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the path, not its look: {a:#?}"); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let st = a[0].appearance.stroke().unwrap(); + assert_eq!((st.brush.as_deref(), st.width, st.paint.color()), (Some("Ribbon"), 2.0, Some(Color::rgb(1.0, 0.0, 0.0)))); + let lib = vectorcraft_brush::library(&r.doc); + let vectorcraft_brush::BrushKind::Art(brush) = brush_named(&lib, "Ribbon") else { panic!("art") }; + assert_eq!((brush.width, brush.colorization), (100.0, vectorcraft_brush::Colorization::Tints)); + // Along a straight line, y down: the art is 8 tall at weight 1, its narrow block below the wide one. + let line = kurbo::BezPath::from_vec(vec![kurbo::PathEl::MoveTo(Point::new(0.0, 0.0)), kurbo::PathEl::LineTo(Point::new(100.0, 0.0))]); + let pieces = vectorcraft_brush::stroke_pieces(&r.doc, &lib[0], &line, st); + let b = pieces.iter().filter_map(|n| n.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert!((b.height() - 16.0).abs() < 1e-3 && (b.width() - 100.0).abs() < 1e-3, "weight 2 doubles the art across, and it stretches along: {b:?}"); + assert!((b.y0 + 8.0).abs() < 1e-3, "{b:?}"); + let filled = |x: f64, y: f64| { + pieces.iter().any(|n| { + let mut hit = false; + n.walk(&mut |c| hit |= c.path_data().is_some_and(|p| kurbo::Shape::winding(&p.to_bezpath(), Point::new(x, y)) != 0)); + hit + }) + }; + assert!(filled(50.0, -4.0), "the wide block is above the line"); + assert!(filled(10.0, 4.0) && !filled(50.0, 4.0), "the narrow block is below it"); +} + +/// A fill under the brush stays on the path. +#[test] +fn a_filled_path_with_an_art_brush_comes_in_brushed() { + let def = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON)); + let style = art_style("Ribbon", 1.0, &STRETCHED, "").replace("0 0 0 0 k\n0 0 Xd", "0 0 1 0 k\n0 1 Xd"); + let r = read_ok(&format!("{def}{style}{}", layer(&brushed_path()))); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "{a:#?}"); + assert_eq!(a[0].appearance.items.len(), 2, "{:?}", a[0].appearance); + assert_eq!(a[0].appearance.stroke().and_then(|s| s.brush.as_deref()), Some("Ribbon")); +} + +/// A compound path with an Art brush comes in as the compound path, its stroke in that brush. +#[test] +fn a_compound_path_with_an_art_brush_comes_in_brushed() { + let def = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON)); + let object = format!( + "0 Ae\nu\n{RED}{}f\nU\n0 0 Xd\n6 () XW\n%_*u\n%_20 20 m\n%_100 20 L\n%_n\n%_20 60 m\n%_100 60 L\n%_n\n%_*U\n1 (Inked) XW\n", + rect_path(20.0, 18.0, 100.0, 62.0) + ); + let r = read_ok(&format!("{def}{}{}", art_style("Ribbon", 1.0, &STRETCHED, ""), layer(&object))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Compound { .. }), "{a:#?}"); + assert_eq!(a[0].appearance.stroke().and_then(|s| s.brush.as_deref()), Some("Ribbon")); +} + +/// An Art brush draws only art of paths, compound paths and groups in solid fills: not an image, a +/// mask, an effect, a gradient or pattern, a stroke, or art with no length along the path. +#[test] +fn an_art_brush_bends_only_paths_in_solid_fills() { + use vectorcraft_color::gradient::{Gradient, GradientPaint, GradientStop}; + use vectorcraft_doc::{Effect, ImageObject, NodeId, OpacityMask}; + let def = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON)); + let r = read_ok(&format!("{def}{}", layer(&brushed_path()))); + let lib = vectorcraft_brush::library(&r.doc); + let vectorcraft_brush::BrushKind::Art(brush) = brush_named(&lib, "Ribbon") else { panic!("art") }; + let plain = &brush.art; + assert!(brush::art_bends(plain), "{plain:#?}"); + let with = |change: &dyn Fn(&mut Node)| { + let mut n = plain.clone(); + change(&mut n); + n + }; + let image = ImageObject { key: "k".into(), width: 4, height: 4, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); + let cases = [ + ("an image", Node::new(NodeId(90), NodeKind::Image(Box::new(image)))), + ("a mask", with(&|n| n.extras_mut().mask = Some(Box::new(OpacityMask::new(plain.clone(), true))))), + ("an effect", with(&|n| n.appearance.effects.push(Effect { id: "stylize.dropShadow".into(), params: Default::default(), visible: true }))), + ( + "an effect on a fill", + with(&|n| { + n.appearance.set_fill(Paint::solid(Color::BLACK)); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.effects.push(Effect { id: "stylize.dropShadow".into(), params: Default::default(), visible: true }); + } + }), + ), + ("a gradient", with(&|n| n.appearance.set_fill(Paint::Gradient(Box::new(gradient.clone()))))), + ("a stroke", with(&|n| n.appearance.set_stroke(Paint::solid(Color::BLACK)))), + ]; + let wrong: Vec<&str> = cases.iter().filter(|(_, art)| brush::art_bends(art)).map(|(why, _)| *why).collect(); + assert!(wrong.is_empty(), "{wrong:?}"); +} + +/// An Art brushed path keeps its drawn look when the brush wouldn't draw it the way the file does: +/// its settings aren't those of art that stretches along the path at the brush's own width and +/// color, the brush's own aren't, its art isn't read, or the brush isn't one the panel keeps. +#[test] +fn an_art_brushed_path_the_brush_cant_draw_keeps_its_drawn_look() { + let good = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON)); + let with = |key: &str, value: &str| -> Vec<(String, String, String)> { + STRETCHED.iter().map(|(k, v, t)| ((*k).to_string(), if *k == key { value.to_string() } else { (*v).to_string() }, (*t).to_string())).collect() + }; + let style_with = |key: &str, value: &str| { + let owned = with(key, value); + let entries: Vec<(&str, &str, &str)> = owned.iter().map(|(k, v, t)| (k.as_str(), v.as_str(), t.as_str())).collect(); + art_style("Ribbon", 1.0, &entries, "") + }; + let plain_style = art_style("Ribbon", 1.0, &STRETCHED, ""); + let flipped = "2 / Ribbon art/ / / / / 0 0/ 5 0 0 0 / 1 1 1 0 1 1 0 0 1 1 0 0 0 0 1"; + let wide = "2 / Ribbon art/ / / / / 0 0/ 5 0 0 0 / 1 1 2 0 1 0 0 0 2 2 0 0 0 0 1"; + let own_colors = "2 / Ribbon art/ / / / / 0 0/ 5 0 0 0 / 1 0 1 0 1 0 0 0 1 1 0 0 0 0 1"; + let dots = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_0 0 0 1 k\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"; + let patterned = format!( + "%AI8_BeginBrushPattern\n(Ribbon art)\n0 A\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n%AI8_EndBrushPattern\n", + rect_path(0.0, 0.0, 4.0, 4.0) + ); + let malformed: Vec<(&str, &str, &str)> = STRETCHED.iter().map(|&(k, v, t)| if k == "Segmented" { (k, "1", "Real") } else { (k, v, t) }).collect(); + let cases = [ + ("a switch written as another kind", good.clone(), art_style("Ribbon", 1.0, &malformed, "")), + ("art in a pattern", format!("{dots}{patterned}{}", plugin_object(ART_BRUSH, "Ribbon", RIBBON)), plain_style.clone()), + ("tints of a swatch's ink", good.clone(), plain_style.replace("0 1 1 0 1 0 0 XA", "0 0 0 0 1 0.5 0 (Brand orange) 0 1 XK")), + ( + "art with no length", + format!( + "%AI8_BeginBrushPattern\n(Ribbon art)\n0 A\n0 g\n0 0 m\n0 40 L\nf\n%AI8_EndBrushPattern\n{}", + plugin_object(ART_BRUSH, "Ribbon", RIBBON) + ), + plain_style.clone(), + ), + ( + "art with a stroke", + format!( + "%AI8_BeginBrushPattern\n(Ribbon art)\n0 A\n0 G\n2 w\n{}S\n%AI8_EndBrushPattern\n{}", + rect_path(0.0, 0.0, 40.0, 8.0), + plugin_object(ART_BRUSH, "Ribbon", RIBBON) + ), + plain_style.clone(), + ), + ( + "a width other than the brush's 100%", + format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", wide)), + art_style( + "Ribbon", + 1.0, + &STRETCHED.map(|e| if matches!(e.0, "Scaling" | "MinScaling" | "MaxScaling") { (e.0, "2", e.2) } else { e }), + "", + ), + ), + ( + "a brush that keeps its art's colors", + format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", own_colors)), + art_style("Ribbon", 1.0, &STRETCHED.map(|e| if e.0 == "Colorization" { (e.0, "0", e.2) } else { e }), ""), + ), + ("an entry that isn't read", good.clone(), art_style("Ribbon", 1.0, &STRETCHED, "1 /Int (SomeOtherSetting) ,\n")), + ( + "an effect on the path", + good.clone(), + plain_style.replace( + ";\n /Part ,\n;\n%AI9_EndArtStyles", + ";\n /Part ,\n/BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n2 /Int (blnd) ,\n0.75 /Real (opac) ,\n3 /Real (horz) ,\n4 /Real (vert) ,\n5 /Real (blur) ,\n1 /Int (csrc) ,\n50 /Real (dark) ,\n; /Dict ;\n /Part ,\n;\n%AI9_EndArtStyles", + ), + ), + ("proportional", good.clone(), style_with("Proportional", "1")), + ("between guides", good.clone(), style_with("Segmented", "1")), + ("its own width", good.clone(), style_with("Scaling", "2")), + ("a width that varies", good.clone(), style_with("MaxScaling", "2")), + ("a width on the pen", good.clone(), style_with("ScaleYDependsOn", "2")), + ("spacing", good.clone(), style_with("Spacing", "1")), + ("flipped", good.clone(), style_with("UpsideDown", "1")), + ("flipped the other way", good.clone(), style_with("Counterclockwise", "1")), + ("another adjustment", good.clone(), style_with("Adjustment", "2")), + ("no fold adjustment", good.clone(), style_with("FoldAdjustment", "0")), + ("its own colorization", good.clone(), style_with("Colorization", "0")), + ("tints and shades", good.clone(), style_with("Colorization", "2")), + ("hue shift", good.clone(), style_with("Colorization", "3")), + ("start of a guide", good.clone(), art_style("Ribbon", 1.0, &STRETCHED, "5 /Real (StartSegmentLength) ,\n")), + ("variable width", good.clone(), art_style("Ribbon", 1.0, &STRETCHED, "2 /Int (BSWidthSource) ,\n")), + ( + "width arrays", + good.clone(), + art_style( + "Ribbon", + 1.0, + &STRETCHED, + "/Array :\n0 /Real ,\n1 /Real ,\n; (BSVariableWidthTValuesArray) ,\n/Array :\n1 /Real ,\n2 /Real ,\n; (BSCenteredWidthsArray) ,\n", + ), + ), + ("a brush that flips", format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", flipped)), plain_style.clone()), + ("another brush width", format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", wide)), plain_style.clone()), + ("art not read", plugin_object(ART_BRUSH, "Ribbon", RIBBON), plain_style.clone()), + ("no such brush", good.clone(), art_style("Other", 1.0, &STRETCHED, "")), + ]; + let mut wrong = vec![]; + for (why, def, style) in cases { + let r = read_ok(&format!("{def}{style}{}", layer(&brushed_path()))); + let lib = vectorcraft_brush::library(&r.doc); + let art_read = why == "art not read" || why == "no such brush" || lib.iter().any(|b| b.name == "Ribbon"); + if !matches!(art(&r.doc)[0].kind, NodeKind::Group { .. }) || !r.warnings.iter().any(|w| w.contains("drawn look")) || !art_read { + wrong.push(why); + } + } + assert!(wrong.is_empty(), "these came in live, or their art wasn't read: {wrong:?}"); +} + +/// The name a stroke's brush has is the panel's, for a Calligraphic brush too: a left-out brush of +/// that name doesn't hide the one kept. +#[test] +fn a_calligraphic_brushed_stroke_takes_the_brush_the_panel_keeps_under_its_name() { + let style = brushed_style("Six D", 1.0, SIX_D_SETTINGS, [2, 5, 6], 0); + let path = layer(&brushed_path()); + let r = read_ok(&format!("{}{}{style}{path}", plugin_object(PATTERN_BRUSH, "Six D", FENCE), plugin_object(CALLIGRAPHIC, "Six D", SIX_D))); + assert!(matches!(art(&r.doc)[0].kind, NodeKind::Path { .. }), "the pattern brush is left out"); +} + +/// The name a stroke's brush has is the panel's: a left-out brush of that name doesn't hide the one +/// kept, and a kept one of another kind isn't drawn as the name's Art brush. +#[test] +fn an_art_brushed_stroke_takes_the_brush_the_panel_keeps_under_its_name() { + let style = art_style("Ribbon", 1.0, &STRETCHED, ""); + let path = layer(&brushed_path()); + let art_def = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON)); + let r = read_ok(&format!("{}{art_def}{style}{path}", plugin_object(PATTERN_BRUSH, "Ribbon", FENCE))); + assert!(matches!(art(&r.doc)[0].kind, NodeKind::Path { .. }), "the pattern brush is left out"); + let r = read_ok(&format!("{}{art_def}{style}{path}", plugin_object(CALLIGRAPHIC, "Ribbon", NIB))); + assert!(matches!(art(&r.doc)[0].kind, NodeKind::Group { .. }), "the panel's Ribbon is the Calligraphic brush"); +} + +/// Type drawn with an Art brush keeps its drawn look under the type, which takes no style. +#[test] +fn type_with_an_art_brush_keeps_its_drawn_look() { + let own: String = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n7 /StoryIndex ,\n;\n".lines().map(|l| format!("%_{l}\n")).collect(); + let object = format!( + "0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{RED}{}f\nU\n0 0 Xd\n6 () XW\n{own}1 (Inked) XW\n", + rect_path(20.0, 18.0, 100.0, 62.0) + ); + let def = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON)); + let r = read_ok(&format!("{def}{}{}", art_style("Ribbon", 1.0, &STRETCHED, ""), layer(&object))); + let a = art(&r.doc); + assert_eq!((a.len(), a[0].children().map(Vec::len), slot_of(a[1].name.as_deref())), (2, Some(1), Some(Some(7))), "the look and the type, {a:#?}"); + let mut brushed = 0; + r.doc.walk(|n| brushed += usize::from(n.appearance.stroke().is_some_and(|s| s.brush.is_some()))); + assert_eq!(brushed, 0, "{:?}", r.warnings); +} + +use read::{GRAPH_PLAIN, GRAPH_UNENDED}; + +/// Editing data in the legacy format (version 7 specification, chapter 2): `%AI5_FileFormat 2.0`, +/// the art size and the template box in the header, then `body`. +fn stream7(body: &str) -> String { + format!( + "%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 2.0\n%AI5_ArtSize: 612 792\n%AI3_TemplateBox: 306 396 306 396\n%%EndComments\n\ + %%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n{body}\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n" + ) +} + +/// One layer named `name` in the legacy format (ten operands before `Lb`) holding `art`. +fn layer7(name: &str, art: &str) -> String { + format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n({name}) Ln\n0 A\n{art}\nLB\n%AI5_EndLayer--\n") +} + +/// A graph's data on `%_` lines, in the order the version 7 specification's chapter 17 gives: +/// bounds, style and dialog settings, a subscription, three axes, a column width and the table +/// (two rows of two cells, one of them empty). +const GRAPH_DATA: &str = "%_Gs\n%_10 10 110 90 Gb\n%_3 0 0 12 1 1 0 0 2 30 0 Gy\n%_6 1 1 0 80 70 0\n%_ 50 60 80 70 Gd\n%_0 1 Gj\n\ + %_1 () Ga 0 12 0 0 0 0 0 () 0 0 GA\n%_2 () Ga 0 12 0 1 0.5 0 1 () 0 0 GA\n%_3 () Ga 0 12 0 4 1 0 0 () 0 0 GA\n%_40 Gw\n\ + %_2 2 1 1 Gz\n%_() Gc (East) Gc\n%_(Q1) Gc 7 Gc GC\n"; + +/// A graph's settings (`Gt` … `GT`): a design's name and paint operators on `%_` lines. +const GRAPH_SETTINGS: &str = "%_Gt\n%_(Bars) GD\n%_0.5 G\n%_0 g\n%_1 0 Gv\n%_GT\n"; + +/// A graph whose drawn art is `art` (in its group, then `%_GS`). +fn graph(settings: &str, art: &str) -> String { + format!("{GRAPH_DATA}{settings}u\n{art}U\n%_GS\n") +} + +/// A filled bar of a graph, with its `Go` tag. +fn bar(x: f64) -> String { + format!("0 0 0 1 k\n{}f\n%_2 0 0 0 Go\n", rect_path(x, 10.0, x + 20.0, 50.0)) +} + +/// The gray (`k`) of `n`'s stroke. +fn stroke_k(n: &Node) -> Option { + match n.appearance.stroke().and_then(|s| s.paint.color()) { + Some(Color::Gray { k }) => Some(k), + _ => None, + } +} + +/// A graph opens as its drawn art: the bar comes in, in its group, with one note. +#[test] +fn a_graph_opens_as_its_drawn_art() { + let r = read(stream7(&layer7("Graph", &graph(GRAPH_SETTINGS, &bar(10.0)))).as_bytes()).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 1); + let NodeKind::Group { children, clip: false } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(children.len(), 1); + assert!(matches!(children[0].kind, NodeKind::Path { .. })); + assert_eq!(fill(&children[0]).color(), Some(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + assert_eq!(r.warnings, [GRAPH_PLAIN]); + assert!(r.hidden_unread.is_empty(), "the records aren't unread art: {:?}", r.hidden_unread); + // Two graphs, the second without settings: one note still. + let two = format!("{}{}", graph(GRAPH_SETTINGS, &bar(10.0)), graph("", &bar(40.0))); + let r = read(stream7(&layer7("Graph", &two)).as_bytes()).unwrap(); + assert_eq!(art(&r.doc).len(), 2); + assert_eq!(r.warnings, [GRAPH_PLAIN]); + // A graph with only the records a minimal one needs (bounds and table), and the newer header. + let minimal = "%_Gs\n%_0 0 50 50 Gb\n%_1 1 1 1 Gz\n%_3 Gc GC\n"; + let r = read_ok(&layer(&format!("{minimal}u\n{}U\n%_GS\n", bar(0.0)))); + assert_eq!(art(&r.doc).len(), 1); + assert_eq!(r.warnings, [GRAPH_PLAIN]); +} + +/// Paint operators on `%_` lines in a graph's settings set nothing; the same operators in its drawn +/// art, and after it, paint as usual. +#[test] +fn a_graphs_settings_paint_nothing_and_its_drawn_art_paints_as_usual() { + let stroked = |x: f64| format!("{}S\n", rect_path(x, 60.0, x + 5.0, 70.0)); + let drawn = format!("{}0.25 G\n{}", stroked(0.0), stroked(10.0)); + let body = format!("0.75 G\n{}0.5 G\n{}", graph(GRAPH_SETTINGS, &drawn), stroked(20.0)); + let r = read(stream7(&layer7("Graph", &body)).as_bytes()).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 2); + let kids = a[0].children().unwrap(); + assert_eq!(stroke_k(&kids[0]), Some(0.25), "the gray set before the graph, not its settings' `%_0.5 G`"); + assert_eq!(stroke_k(&kids[1]), Some(0.75), "a gray set in the drawn art"); + assert_eq!(stroke_k(&a[1]), Some(0.5), "a gray set after the graph"); +} + +/// Graph operators outside a graph stay operators the reader doesn't know: an error on a layer that +/// shows, noted as unread on `%_` lines (as any operator there), and no graph note. +#[test] +fn graph_operators_outside_a_graph_are_unknown() { + for stray in ["Gs\n", "Go\n", "1 2 Gc\n"] { + let err = read(stream7(&layer7("L", &format!("{}{stray}", rect_path(0.0, 0.0, 5.0, 5.0)))).as_bytes()).unwrap_err(); + assert!(err.contains("operators VectorCraft doesn't know"), "{stray}: {err}"); + } + for (stray, op) in [("%_2 0 0 0 Go\n", "`Go`"), ("%_GS\n", "`GS`"), ("%_1 2 Gc\n", "`Gc`")] { + let r = read(stream7(&layer7("L", &format!("{}f\n{stray}", rect_path(0.0, 0.0, 5.0, 5.0)))).as_bytes()).unwrap(); + assert!(r.hidden_unread.contains(op), "{stray}: {:?}", r.hidden_unread); + assert!(r.warnings.is_empty(), "{stray}: {:?}", r.warnings); + } +} + +/// A graph that starts inside another is noted and the first goes on; one that doesn't end stops at +/// its layer's end, with the art read so far, and the next layer reads as usual. +#[test] +fn malformed_graphs_keep_their_art() { + let nested = format!("{GRAPH_DATA}u\n{}%_Gs\n{}U\n%_GS\n", bar(0.0), bar(30.0)); + let r = read(stream7(&layer7("Graph", &nested)).as_bytes()).unwrap(); + assert_eq!(art(&r.doc)[0].children().unwrap().len(), 2); + assert_eq!(r.warnings, [GRAPH_PLAIN, GRAPH_UNENDED]); + + let unended = format!("{GRAPH_DATA}%_Gt\nu\n{}U\n", bar(0.0)); + let next = format!("%_0.5 G\n{}S\n", rect_path(0.0, 60.0, 5.0, 70.0)); + let r = read(stream7(&format!("{}{}", layer7("Graph", &unended), layer7("Next", &next))).as_bytes()).unwrap(); + assert_eq!(art(&r.doc).len(), 1, "the drawn art read before the layer ended"); + let after = r.doc.layers[1].children().unwrap(); + assert_eq!(stroke_k(&after[0]), Some(0.5), "the next layer isn't in the graph's settings"); + assert_eq!(r.warnings, [GRAPH_PLAIN, GRAPH_UNENDED]); + + // One that doesn't end before the file does. + let cut = stream7(&layer7("Graph", &format!("{GRAPH_DATA}u\n{}U\n", bar(0.0)))).replace("LB\n%AI5_EndLayer--\n", ""); + assert!(read(cut.as_bytes()).is_err(), "a layer that doesn't end is still an error"); +} + +/// A graph's records in the shapes the specification's appendix A gives: several cells on one line, +/// strings, arrays and names as operands, and empty groups among its drawn art. +#[test] +fn a_graphs_records_take_their_operands() { + let settings = "%_Gt\n%_(Bars) GD [1 2 3] 0 Ge\n%_/Name 1 Gi (a) (b) Gl\n%_1 2 3 4 Gm 0 Gp 1 Gr 0 G+ 2 G1 0 Gf 0 Gg 0 Gx 1 GX\n%_GT\n"; + let drawn = format!("u\nU\nu\nu\nU\nU\n{}", bar(10.0)); + let r = read(stream7(&layer7("Graph", &graph(settings, &drawn))).as_bytes()).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 1); + let kids = a[0].children().unwrap(); + fn paths(n: &Node) -> usize { + match n.children() { + Some(c) => c.iter().map(|c| paths(c)).sum(), + None => usize::from(matches!(n.kind, NodeKind::Path { .. })), + } + } + assert!(matches!(kids.last().map(|k| &k.kind), Some(NodeKind::Path { .. })), "the bar is kept after the empty groups: {kids:?}"); + assert_eq!(paths(&a[0]), 1, "the empty groups hold no art"); + assert_eq!(r.warnings, [GRAPH_PLAIN]); +} + +/// Editing data in the legacy format (`%AI5_FileFormat 2.0`, ten `Lb` operands), then `body`. +fn mask_stream7(body: &str) -> String { + format!( + "%!PS-Adobe-3.0\n%%Creator: test\n%%BoundingBox: 0 0 200 200\n%AI5_FileFormat 2.0\n%AI5_ArtSize: 200 200\n\ + %AI3_TemplateBox: 100 100 100 100\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n{body}\n\ + %%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n" + ) +} + +/// The start of a legacy layer named `name`, `masks` its multi-layer mask flag (`Lb`'s sixth operand). +fn begin7(name: &str, masks: u8) -> String { + format!("%AI5_BeginLayer\n1 1 1 1 0 {masks} 1 79 128 255 Lb\n({name}) Ln\n") +} + +const END7: &str = "LB\n%AI5_EndLayer--\n"; + +/// `Mb`, an 80 by 80 point mask path painted `W n`, `Md` (the version 7 specification's §10.4 order). +fn mask_start() -> String { + format!("Mb\n{}h\nW\nn\nMd\n", rect_path(40.0, 40.0, 120.0, 120.0)) +} + +/// A filled square at `x`. +fn masked(x: f64) -> String { + format!("0.5 0 0 0 k\n{}f\n", rect_path(x, x, x + 140.0, x + 140.0)) +} + +/// A layer's objects as a tree: `p` a path, `c` a clipping path, `o` a compound path, `g[…]` a +/// group, `k[…]` a clipping group, `l[…]` a sublayer. +fn mask_tree(nodes: &[Arc]) -> String { + let one = |n: &Arc| match &n.kind { + NodeKind::Layer { children, .. } => format!("l[{}]", mask_tree(children)), + NodeKind::Group { children, clip: false } => format!("g[{}]", mask_tree(children)), + NodeKind::Group { children, clip: true } => format!("k[{}]", mask_tree(children)), + NodeKind::Path { clipping: true, .. } => "c".into(), + NodeKind::Path { .. } => "p".into(), + NodeKind::Compound { .. } => "o".into(), + k => format!("{k:?}"), + }; + nodes.iter().map(one).collect::>().join(" ") +} + +fn read7(body: &str) -> Structure { + match read(mask_stream7(body).as_bytes()) { + Ok(r) => r, + Err(e) => panic!("{e}"), + } +} + +/// Each layer's tree, and whether the layer itself clips. +fn layer_trees(doc: &Document) -> Vec<(String, String, bool)> { + doc.layers + .iter() + .map(|l| { + let NodeKind::Layer { children, clip, .. } = &l.kind else { panic!("a layer") }; + (l.name.clone().unwrap_or_default(), mask_tree(children), *clip) + }) + .collect() +} + +/// A multi-layer mask (version 7 specification §10.4: `Mb`, the mask path, `Md`, objects in two +/// layers, `MB`) comes in as a clipping group in each layer it covers, each clipped by a copy of +/// the mask's path; what follows `MB` isn't clipped. +#[test] +fn a_multi_layer_mask_clips_each_layer_it_covers() { + let body = format!("{}{}{}{END7}{}{}MB\n{}{END7}", begin7("A", 1), mask_start(), masked(15.0), begin7("B", 1), masked(30.0), masked(150.0)); + let r = read7(&body); + assert_eq!(layer_trees(&r.doc), [("A".to_string(), "k[c p]".to_string(), false), ("B".to_string(), "k[c p] p".to_string(), false)]); + let mask = |l: usize| r.doc.layers[l].children().unwrap()[0].children().unwrap()[0].clone(); + let (a, b) = (mask(0), mask(1)); + assert_ne!(a.id, b.id, "each layer has a copy of its own"); + assert_eq!(a.geometric_bounds(), b.geometric_bounds()); + let bounds = a.geometric_bounds().unwrap(); + assert_eq!((bounds.width(), bounds.height()), (80.0, 80.0)); + assert!(r.warnings.iter().any(|w| w.contains("clipping group in each layer")), "{:?}", r.warnings); + // The layers' flag saying they have multi-layer masks changes nothing. + let unflagged = read7(&body.replace(&begin7("A", 1), &begin7("A", 0)).replace(&begin7("B", 1), &begin7("B", 0))); + assert_eq!(format!("{:?}", unflagged.doc.layers), format!("{:?}", r.doc.layers)); +} + +#[test] +fn a_multi_layer_mask_in_one_layer_or_over_three() { + let one = format!("{}{}{}MB\n{}{END7}", begin7("A", 1), mask_start(), masked(15.0), masked(150.0)); + assert_eq!(layer_trees(&read7(&one).doc), [("A".to_string(), "k[c p] p".to_string(), false)]); + let three = format!( + "{}{}{}{END7}{}{}{END7}{}{}MB\n{END7}", + begin7("A", 1), + mask_start(), + masked(15.0), + begin7("B", 1), + masked(30.0), + begin7("C", 1), + masked(45.0) + ); + let trees: Vec<_> = layer_trees(&read7(&three).doc).into_iter().map(|(_, t, clip)| (t, clip)).collect(); + assert_eq!(trees, vec![("k[c p]".to_string(), false); 3]); + // Objects before the mask's path are masked too; a layer between with nothing in it stays empty. + let before = format!( + "{}Mb\n{}{}h\nW\nn\nMd\n{END7}{}{END7}{}{}MB\n{END7}", + begin7("A", 1), + masked(15.0), + rect_path(40.0, 40.0, 120.0, 120.0), + begin7("B", 1), + begin7("C", 1), + masked(45.0) + ); + let trees: Vec<_> = layer_trees(&read7(&before).doc).into_iter().map(|(_, t, _)| t).collect(); + assert_eq!(trees, ["k[c p]", "", "k[c p]"]); +} + +#[test] +fn a_multi_layer_mask_in_a_group_or_sublayer() { + // Begun and ended in a group of one layer. + let grouped = format!("{}u\n{}{}MB\n{}U\n{END7}", begin7("A", 1), mask_start(), masked(15.0), masked(150.0)); + assert_eq!(layer_trees(&read7(&grouped).doc)[0].1, "g[k[c p] p]"); + // A sublayer in the mask: what the mask covers in the layer around it and in the sublayer. + let nested = format!("{}{}{}{}{}{END7}{}MB\n{END7}", begin7("A", 1), mask_start(), masked(15.0), begin7("S", 1), masked(30.0), masked(45.0)); + assert_eq!(layer_trees(&read7(&nested).doc)[0].1, "k[c p] l[k[c p]] k[c p]"); +} + +#[test] +fn a_multi_layer_masks_path_can_be_painted_or_compound() { + // `W f`: the path also paints, once, under what the mask covers after it: its fill is a path of its own in the first + // layer, and the copies of the mask in each layer have no fill. + let black = Some(Color::cmyk(0.0, 0.0, 0.0, 1.0)); + let painted = format!("{}Mb\n0 0 0 1 k\n{}h\nW\nf\nMd\n{}MB\n{END7}", begin7("A", 1), rect_path(40.0, 40.0, 120.0, 120.0), masked(15.0)); + let doc = read7(&painted).doc; + assert_eq!(layer_trees(&doc)[0].1, "k[c p p]"); + let group = doc.layers[0].children().unwrap()[0].clone(); + let kids = group.children().unwrap(); + assert_eq!(fill(&kids[0]), Paint::None, "the clipping path has no fill"); + assert_eq!(fill(&kids[1]).color(), black, "the painted path first"); + let two = format!( + "{}Mb\n0 0 0 1 k\n{}h\nW\nf\nMd\n{}{END7}{}{}MB\n{END7}", + begin7("A", 1), + rect_path(40.0, 40.0, 120.0, 120.0), + masked(15.0), + begin7("B", 1), + masked(30.0) + ); + let doc = read7(&two).doc; + assert_eq!(layer_trees(&doc), [("A".to_string(), "k[c p p]".to_string(), false), ("B".to_string(), "k[c p]".to_string(), false)]); + let kids = |l: usize| doc.layers[l].children().unwrap()[0].children().unwrap().to_vec(); + let (a, b) = (kids(0), kids(1)); + assert_eq!((fill(&a[0]), fill(&b[0])), (Paint::None, Paint::None), "no copy of the mask paints"); + assert_eq!(fill(&a[1]).color(), black); + assert_eq!(fill(&b[1]).color(), Some(Color::cmyk(0.5, 0.0, 0.0, 0.0)), "layer B's square, unpainted over"); + // A compound path of clipping paths. + let compound = format!( + "{}Mb\n*u\n{}h\nW\nn\n{}h\nW\nn\n*U\nMd\n{}MB\n{END7}", + begin7("A", 1), + rect_path(40.0, 40.0, 80.0, 80.0), + rect_path(90.0, 90.0, 120.0, 120.0), + masked(15.0) + ); + assert_eq!(layer_trees(&read7(&compound).doc)[0].1, "k[o p]"); + // A filled one over two layers: its fill is a compound path of its own in the first, whose paths don't clip. + let filled = format!( + "{}Mb\n0 0 0 1 k\n*u\n{}h\nW\nf\n{}h\nW\nf\n*U\nMd\n{}{END7}{}{}MB\n{END7}", + begin7("A", 1), + rect_path(40.0, 40.0, 80.0, 80.0), + rect_path(90.0, 90.0, 120.0, 120.0), + masked(15.0), + begin7("B", 1), + masked(30.0) + ); + let doc = read7(&filled).doc; + assert_eq!(layer_trees(&doc), [("A".to_string(), "k[o o p]".to_string(), false), ("B".to_string(), "k[o p]".to_string(), false)]); + let kids = |l: usize| doc.layers[l].children().unwrap()[0].children().unwrap().to_vec(); + let (a, b) = (kids(0), kids(1)); + assert_eq!((fill(&a[0]), fill(&b[0])), (Paint::None, Paint::None), "no copy of the mask paints"); + assert_eq!(fill(&a[1]).color(), black); + let NodeKind::Compound { children: subpaths, .. } = &a[1].kind else { panic!("{:?}", a[1].kind) }; + assert!(subpaths.iter().all(|p| matches!(p.kind, NodeKind::Path { clipping: false, .. })), "{subpaths:#?}"); + let mut ids = std::collections::HashSet::new(); + for l in &doc.layers { + l.walk(&mut |n| assert!(ids.insert(n.id), "{:?} appears twice", n.id)); + } +} + +/// `Mv` starts a mask as `Mb` does, `ME` defines one as `Md` does, and `Mi` changes nothing. +#[test] +fn other_multi_layer_mask_operators() { + let body = format!("{}{}{}{END7}{}{}MB\n{}{END7}", begin7("A", 1), mask_start(), masked(15.0), begin7("B", 1), masked(30.0), masked(150.0)); + let plain = format!("{:?}", read7(&body).doc.layers); + let aliases = body.replace("Mb\n", "Mv\n").replace("Md\n", "ME\n"); + assert_eq!(format!("{:?}", read7(&aliases).doc.layers), plain); + let with_mi = body.replace("Md\n", "Md\nMi\n").replace("MB\n", "Mi\nMB\n"); + assert_eq!(format!("{:?}", read7(&with_mi).doc.layers), plain); +} + +#[test] +fn a_malformed_multi_layer_mask_is_an_error() { + let path = format!("{}h\nW\nn\n", rect_path(40.0, 40.0, 120.0, 120.0)); + let sq = masked(15.0); + let cases = [ + ("an end without a start", format!("{sq}MB\n")), + ("a definition without a start", format!("{path}Md\n{sq}")), + ("no mask path", format!("Mb\n{sq}Md\n{sq}MB\n")), + ("a start inside another", format!("Mb\nMb\n{path}Md\n{sq}MB\n")), + ("an end before the definition", format!("Mb\n{path}MB\n")), + ("a definition in another group", format!("Mb\nu\n{path}Md\n{sq}MB\nU\n")), + ("a group crossing the end", format!("{}u\n{sq}MB\nU\n", mask_start())), + ("a group crossing the start", format!("u\n{}{sq}U\nMB\n", mask_start())), + ]; + for (why, art) in cases { + let body = format!("{}{art}{END7}", begin7("A", 1)); + let e = read(mask_stream7(&body).as_bytes()).unwrap_err(); + assert!(e.contains("mask"), "{why}: {e}"); + } + let layered = [ + ("a layer ends before the definition", format!("{}Mb\n{sq}{END7}{}{path}Md\nMB\n{END7}", begin7("A", 1), begin7("B", 1))), + ("a group open at the layer's end", format!("{}{}u\n{sq}{END7}{}U\nMB\n{END7}", begin7("A", 1), mask_start(), begin7("B", 1))), + ("the end of the file inside the mask", format!("{}{}{sq}{END7}", begin7("A", 1), mask_start())), + ]; + for (why, body) in layered { + let e = read(mask_stream7(&body).as_bytes()).unwrap_err(); + assert!(e.contains("mask"), "{why}: {e}"); + } + // Outside the layers, `Md` has nowhere to take its path from. + let outside = format!("Mb\nMd\n{}{path}{sq}MB\n{END7}", begin7("A", 1)); + let e = read(mask_stream7(&outside).as_bytes()).unwrap_err(); + assert!(e.contains("mask"), "{e}"); +} + +/// A clipping path painted among the masked objects clips its whole layer, as outside a mask. +#[test] +fn a_layers_clipping_path_in_a_multi_layer_mask_clips_the_layer() { + let path = format!("{}h\nW\nn\n", rect_path(10.0, 10.0, 190.0, 190.0)); + let body = format!("{}{}{}{path}{}MB\n{END7}", begin7("A", 1), mask_start(), masked(15.0), masked(30.0)); + assert_eq!(layer_trees(&read7(&body).doc), [("A".to_string(), "c k[c p p]".to_string(), true)]); +} + +/// `Mb` before the first layer it covers and `MB` after the last one's `LB`. +#[test] +fn a_multi_layer_mask_begun_or_ended_between_layers() { + let body = format!( + "Mb\n{}{}h\nW\nn\nMd\n{}{END7}{}{}{END7}MB\n{}{}{END7}", + begin7("A", 1), + rect_path(40.0, 40.0, 120.0, 120.0), + masked(15.0), + begin7("B", 1), + masked(30.0), + begin7("C", 1), + masked(150.0) + ); + let trees: Vec<_> = layer_trees(&read7(&body).doc).into_iter().map(|(_, t, _)| t).collect(); + assert_eq!(trees, ["k[c p]", "k[c p]", "p"]); +} + +/// Each copy of the mask counts toward the most objects read, with its points. +#[test] +fn copies_of_a_multi_layer_mask_count_toward_the_limit() { + let points: String = (0..2_000_001).map(|i| format!("{} 40 L\n", 40 + i % 80)).collect(); + let mask = format!("Mb\n40 40 m\n{points}h\nW\nn\nMd\n"); + let one = format!("{}{mask}{}MB\n{END7}", begin7("A", 1), masked(15.0)); + assert_eq!(layer_trees(&read7(&one).doc)[0].1, "k[c p]"); + let two = format!("{}{mask}{}{END7}{}{}MB\n{END7}", begin7("A", 1), masked(15.0), begin7("B", 1), masked(30.0)); + let e = read(mask_stream7(&two).as_bytes()).unwrap_err(); + assert!(e.contains("objects"), "{e}"); + // A filled mask's fill, a path of its own, counts too. + let filled = format!("{}{}{}MB\n{END7}", begin7("A", 1), mask.replace("W\nn\n", "W\nf\n"), masked(15.0)); + let e = read(mask_stream7(&filled).as_bytes()).unwrap_err(); + assert!(e.contains("objects"), "{e}"); +} diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 24a3a27365..eae8bc1381 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -5,36 +5,37 @@ //! and `%AI11_EndTextDocument`, ASCII85 of nested dictionaries with numbers for keys. A text object //! in a layer is only a stub naming its story in it (`/StoryIndex`). //! -//! The format isn't documented. What is read here was worked out from the files of the project's -//! users, used locally and never committed, by comparing it with the type their pages draw: the -//! meaning of each key below was checked against the page's own type in more than a thousand text -//! objects, and it is only used for the keys that matched. A story the reader doesn't recognise (area -//! type, type on a path, anything with a frame that has more than a point and a matrix) is left -//! alone: it has no text, and the importer says so. +//! The format isn't documented. Most of what is read here was worked out from the files of the +//! project's users, used locally and never committed, by comparing it with the type their pages +//! draw: the meaning of those keys was checked against the page's own type in more than a thousand +//! text objects, and it is only used for the keys that matched. The Type on a Path Options of key +//! 11 of a frame come from test files saved with one option changed at a time, used locally and +//! never committed. Point type, area type and type on a path are read; a story in a frame of any +//! other kind is left alone: it has no text, and the importer says so. //! //! Where type sits: a story lays its lines out round a point `F` (the anchor: the start of a line of //! left-aligned type, the middle of a centred one, the end of a right-aligned one), each line with an //! offset from it. A right-to-left paragraph (key `33` of its attributes) swaps the two: its //! "left"-aligned lines end at the anchor and its "right"-aligned ones start there. The frame of the //! story gives a matrix that carries that layout onto the canvas of the app, which is 16383 points a -//! side; the canvas's centre, 8191.5, is the centre of the file's `%AI3_TemplateBox`. See -//! [`Story::place`]. +//! side; the canvas's centre, 8191.5, is the centre of the file's `%AI3_TemplateBox`. A story without +//! a layout has its point type's anchor at its frame's point. See [`Story::place`]. use std::collections::BTreeMap; use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{CharStyle, Justify, Node, NodeId, NodeKind, ParaStyle, TextKind, TextObject, TextRun}; +use vectorcraft_doc::{CharStyle, Justify, Node, NodeId, NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, TextKind, TextObject, TextRun}; use vectorcraft_geom::{Affine, PathData, Point, Rect}; /// Longest story read (bytes). -const MAX_STORY: usize = 1 << 20; +pub(crate) const MAX_STORY: usize = 1 << 20; /// Biggest text document read (bytes, decoded). -const MAX_BYTES: usize = 64 << 20; +pub(crate) const MAX_BYTES: usize = 64 << 20; /// Deepest nesting read. const MAX_DEPTH: usize = 64; /// Most values read. -const MAX_VALUES: usize = 4_000_000; +pub(crate) const MAX_VALUES: usize = 4_000_000; /// The centre of the app's canvas, in the units of its text document. pub(super) const CANVAS_CENTRE: f64 = 8191.5; @@ -235,20 +236,138 @@ fn read(bytes: &[u8]) -> Option { } } +/// Most character styles read of a text document, and most styles a run's style is followed +/// through to the ones they are based on. +const MAX_SHEETS: usize = 4096; +const MAX_SHEETS_BASED_ON: usize = 16; + /// Most frames read of one story, and most path segments of a frame. -const MAX_FRAMES: usize = 4096; -const MAX_SEGMENTS: usize = 1 << 16; +pub(crate) const MAX_FRAMES: usize = 4096; +pub(crate) const MAX_SEGMENTS: usize = 1 << 16; /// Where a frame puts its story's text. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq)] enum FrameKind { /// Point type: the matrix carries the layout (its anchor at the origin of its lines) onto the /// canvas. Point([f64; 6]), - /// Area type flowed inside a path: its cubic segments on the canvas, four points each. - Area(Vec<[f64; 8]>), + /// Area type flowed inside a path: its cubic segments on the canvas, four points each, and the + /// Area Type Options the frame keeps. + Area(Vec<[f64; 8]>, AreaFrame), /// Type on a path, from `start` to `end` (segment index and the place in that segment). - OnPath { segments: Vec<[f64; 8]>, start: f64, end: f64 }, + OnPath { segments: Vec<[f64; 8]>, start: f64, end: f64, options: PathFrame }, +} + +/// The Type on a Path Options a frame of type on a path keeps at key 11. Each stays at its default +/// where the frame leaves the key out or keeps a value that can't be read. A frame with key 6 true +/// keeps its defaults: what that state stores for these options isn't known. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +struct PathFrame { + /// Key 1: 1 Skew, 2 3D Ribbon, 3 Stair Step, 4 Gravity. Rainbow is the key left out. + effect: PathEffect, + /// Key 2: 0 Ascender, 1 Descender, 2 Center. Baseline is the key left out. + align: PathAlign, + /// Key 0: the type is flipped across its path. The frame's path runs as it did before the flip, + /// from the start of its range. + flip: bool, +} + +impl PathFrame { + /// The options frame data `carries` keeps. + fn read(carries: &Val) -> PathFrame { + let Some(options) = carries.get("11") else { return PathFrame::default() }; + if matches!(options.get("6"), Some(Val::Bool(true))) { + return PathFrame::default(); + } + let code = |k: &str| options.get(k).and_then(Val::num); + let effect = match code("1") { + Some(1.0) => PathEffect::Skew, + Some(2.0) => PathEffect::Ribbon3d, + Some(3.0) => PathEffect::StairStep, + Some(4.0) => PathEffect::Gravity, + _ => PathEffect::Rainbow, + }; + let align = match code("2") { + Some(0.0) => PathAlign::Ascender, + Some(1.0) => PathAlign::Descender, + Some(2.0) => PathAlign::Center, + _ => PathAlign::Baseline, + }; + PathFrame { effect, align, flip: matches!(options.get("0"), Some(Val::Bool(true))) } + } +} + +/// The Area Type Options an area frame keeps, in the units of the text document: each `None` +/// where the frame leaves the key out or keeps a value that can't be read, so the option stays as +/// it was. +#[derive(Debug, Clone, Default, PartialEq)] +struct AreaFrame { + /// Key 3, the rows. + rows: Option, + /// Key 4, the columns. + columns: Option, + /// Key 7, the gutter between rows. + row_gutter: Option, + /// Key 8, the gutter between columns. + column_gutter: Option, + /// Key 10, the first baseline (`0` its kind, `1` its minimum). Without it the first baseline + /// is Ascent. + first_baseline: Option<(vectorcraft_doc::FirstBaseline, f64)>, +} + +/// Longest gutter or first-baseline minimum, as `text.areaOptions` caps them: read in the units of +/// the text document, and again in document points once scaled. +const MAX_AREA_LENGTH: f64 = 10_000.0; + +impl AreaFrame { + /// The options frame data `carries` keeps. + fn read(carries: &Val) -> AreaFrame { + // A whole number, at most `max`. + let whole = |v: &Val, max: f64| v.num().filter(|n| n.fract() == 0.0 && *n >= 0.0).map(|n| n.min(max) as usize); + let max = vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS; + let count = |k: &str| carries.get(k).and_then(|v| whole(v, max as f64)).filter(|n| *n >= 1); + let length = |v: Option<&Val>| v.and_then(Val::num).filter(|n| *n >= 0.0).map(|n| n.min(MAX_AREA_LENGTH)); + let first_baseline = carries.get("10").and_then(|b| { + use vectorcraft_doc::FirstBaseline as F; + let kind = match whole(b.get("0")?, 99.0)? { + 0 => F::Fixed, + 2 => F::CapHeight, + 3 => F::Leading, + 4 => F::XHeight, + // Em Box Height (5) and Legacy (6) have no first baseline of their own here: the + // first baseline stays as it was. + _ => return None, + }; + Some((kind, length(b.get("1")).unwrap_or(0.0))) + }); + AreaFrame { + rows: count("3"), + columns: count("4"), + row_gutter: length(carries.get("7")), + column_gutter: length(carries.get("8")), + first_baseline, + } + } + + /// Sets the options it keeps on `area`, its lengths at `scale` (document points to a unit). + fn apply(&self, area: &mut vectorcraft_doc::AreaOptions, scale: f64) { + if let Some(n) = self.rows { + area.rows = n; + } + if let Some(n) = self.columns { + area.columns = n; + } + // A gutter the frame leaves out stays as it was. + let (row, column) = (area.row_gutter.unwrap_or(area.gutter), area.gutter); + let scaled = |g: f64| (g * scale).min(MAX_AREA_LENGTH); + let row = self.row_gutter.map_or(row, scaled); + area.gutter = self.column_gutter.map_or(column, scaled); + area.row_gutter = (row != area.gutter).then_some(row); + if let Some((kind, min)) = self.first_baseline { + area.first_baseline = kind; + area.first_baseline_min = scaled(min); + } + } } /// A paragraph's attributes, as the text document keeps them. @@ -281,6 +400,11 @@ pub(super) struct Story { paras: Vec<(usize, Para)>, /// `(characters, style)` in order. runs: Vec<(usize, Style)>, + /// Type on a path: the spacing its first frame's layout implies ([`path_spacing`]). + path_spacing: f64, + /// Vertical type (Type › Type Orientation › Vertical): its lines are columns, from right to + /// left. Its layout's lines run down from the anchor, each column further left. + vertical: bool, } #[derive(Clone, Debug)] @@ -296,6 +420,13 @@ struct Style { fill: Option, stroke: Option, stroke_width: f64, + /// Key 12, the case: 1 Small Caps, 2 All Caps. + caps: u8, + /// Key 35 at 3: Tate-chu-yoko, the characters set across the column as one block. + tate_chu_yoko: bool, + /// Key 35 at 1 (Standard): Standard Vertical Roman Alignment, half-width characters upright in + /// a column. Any other value, or no key in the run, its character style or the defaults, is off. + standard_vertical_roman: bool, } /// The text document of an editing copy. @@ -305,6 +436,12 @@ pub(super) struct Texts { /// The character and paragraph styles a story starts from. defaults: Val, para_defaults: Val, + /// The document's character styles (`[Normal Character Style]` first), each a name, the + /// character style it is based on (key 5, an index into these) and its attributes (key 6). + char_sheets: Vec, + /// The document's paragraph styles (`[Normal Paragraph Style]` first), each a name, its + /// attributes (key 5) and the paragraph style it is based on (key 6, an index into these). + para_sheets: Vec, frames: Vec, } @@ -343,11 +480,17 @@ impl Texts { .map(|f| f.get("0").and_then(|f| f.get("0")).and_then(|f| f.get("0")).and_then(Val::str).unwrap_or_default().to_string()) .collect(); let main = doc.get("1")?; + let sheets = |key: &str| -> Vec { + let list = doc.get("0").and_then(|d| d.get(key)).and_then(|s| s.get("0")).map(Val::list).unwrap_or_default(); + list.iter().take(MAX_SHEETS).map(|s| s.get("0").cloned().unwrap_or(Val::Dict(BTreeMap::new()))).collect() + }; Some(Texts { stories: main.get("1")?.list().to_vec(), fonts, defaults: main.get("2")?.clone(), para_defaults: main.get("3").cloned().unwrap_or(Val::Dict(BTreeMap::new())), + char_sheets: sheets("5"), + para_sheets: sheets("6"), frames: doc.get("0")?.get("8")?.get("0")?.list().to_vec(), }) } @@ -368,7 +511,7 @@ impl Texts { None => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some(m) => m.nums()?.try_into().ok()?, })), - 1 => Some(FrameKind::Area(segments()?)), + 1 => Some(FrameKind::Area(segments()?, AreaFrame::read(carries))), 2 => { let range = carries.get("6").and_then(Val::nums).unwrap_or_default(); let segments = segments()?; @@ -384,30 +527,54 @@ impl Texts { let start = finite(range.first()).unwrap_or(0.0).clamp(0.0, n); (start, finite(range.get(1)).unwrap_or(n).clamp(start, n)) }; - Some(FrameKind::OnPath { segments, start, end }) + Some(FrameKind::OnPath { segments, start, end, options: PathFrame::read(carries) }) } _ => None, } } + /// Is frame `i` vertical type? Key 1 of what it carries: 2 vertical, 0 or none horizontal. Any + /// other value is ignored: horizontal. + fn frame_vertical(&self, i: usize) -> bool { + let orientation = self.frames.get(i).and_then(|f| f.get("0")).and_then(|f| f.get("2")).and_then(|c| c.get("1")); + orientation.and_then(Val::num) == Some(2.0) + } + /// Story `i`, if its frames are of kinds this reads. pub(super) fn story(&self, i: usize) -> Option { let s = self.stories.get(i)?; let text = s.get("0")?.get("0")?.str().filter(|t| t.len() <= MAX_STORY)?.to_string(); let view = s.get("1")?; - let frames: Vec = view - .get("0")? - .list() - .iter() - .take(MAX_FRAMES) - .map(|f| f.get("0").and_then(Val::num).and_then(|n| self.frame(n as usize))) - .collect::>()?; + let indices: Vec = + view.get("0")?.list().iter().take(MAX_FRAMES).map(|f| f.get("0").and_then(Val::num).map(|n| n as usize)).collect::>()?; + let frames: Vec = indices.iter().map(|n| self.frame(*n)).collect::>()?; if frames.is_empty() { return None; } - // The first frame's layout, when the file keeps one: where its lines start. - let (mut anchor, mut lines) = ((0.0, 0.0), vec![]); + // Threaded frames share one orientation: frames that differ aren't read. + let vertical = indices.first().is_some_and(|n| self.frame_vertical(*n)); + if indices.iter().any(|n| self.frame_vertical(*n) != vertical) { + return None; + } + // The first frame's layout, when the file keeps one: where its lines start. Without one, the + // anchor of point type is its frame's point (key 0, where the layout's anchor is too). + let point = indices.first().and_then(|n| self.frames.get(*n)).and_then(|f| f.get("0")).and_then(|f| f.get("0")).and_then(Val::nums); + let (mut anchor, mut lines, mut path_spacing) = ( + match point.as_deref() { + Some([x, y]) if matches!(frames.first(), Some(FrameKind::Point(_))) => (*x, *y), + _ => (0.0, 0.0), + }, + vec![], + 0.0, + ); if let Some(f) = view.get("2").and_then(|l| find_node(l, "F")) { + // Vertical type on a path turns its glyphs across the path: their matrices don't give + // the spacing. + if let Some(FrameKind::OnPath { options, .. }) = frames.first() + && !vertical + { + path_spacing = self::path_spacing(f, options.effect); + } if let Some(a) = f.get("0").and_then(|a| a.get("0")).and_then(Val::nums) && let [x, y, ..] = a.as_slice() { @@ -427,24 +594,35 @@ impl Texts { let mut paras = vec![]; for run in s.get("0")?.get("5").map(|p| p.get("0").map(Val::list).unwrap_or_default()).unwrap_or_default() { let n = run.get("1").and_then(Val::num)? as usize; - let props = run.get("0").and_then(|r| r.get("0")).and_then(|r| r.get("5")); - paras.push((n, self.para(props))); + paras.push((n, self.para(run.get("0").and_then(|r| r.get("0"))))); + } + if paras.is_empty() { + paras.push((text.chars().count(), self.para(None))); } let mut runs = vec![]; for run in s.get("0")?.get("6").map(|p| p.get("0").map(Val::list).unwrap_or_default()).unwrap_or_default() { let n = run.get("1").and_then(Val::num)? as usize; - let props = run.get("0").and_then(|r| r.get("0")).and_then(|r| r.get("6")); - runs.push((n, self.style(props))); + runs.push((n, self.style(run.get("0").and_then(|r| r.get("0"))))); } if runs.is_empty() { runs.push((text.chars().count(), self.style(None))); } - Some(Story { text, anchor, lines, frames, paras, runs }) + Some(Story { text, anchor, lines, frames, paras, runs, path_spacing, vertical }) } - /// A paragraph's attributes: its own keys, else the document's. - fn para(&self, p: Option<&Val>) -> Para { - let pick = |k: &str| p.and_then(|p| p.get(k)).or_else(|| self.para_defaults.get(k)); + /// A paragraph's attributes (`run`: its attributes, key 5, and the paragraph style it is based + /// on, key 6): its own keys, else those of its paragraph style and the ones that is based on, + /// else those of `[Normal Paragraph Style]`, else the document's. + fn para(&self, run: Option<&Val>) -> Para { + let mut chain = vec![]; + let mut at = run; + for _ in 0..=MAX_SHEETS_BASED_ON { + let Some(style) = at else { break }; + chain.extend(style.get("5")); + at = style.get("6").and_then(Val::num).filter(|i| i.is_finite() && *i >= 0.0).and_then(|i| self.para_sheets.get(i as usize)); + } + chain.extend(self.para_sheets.first().and_then(|s| s.get("5"))); + let pick = |k: &str| chain.iter().find_map(|s| s.get(k)).or_else(|| self.para_defaults.get(k)); let num = |k: &str| pick(k).and_then(Val::num).filter(|v| v.abs() < 1e5).unwrap_or(0.0); Para { justify: pick("0").and_then(Val::num).map_or(0, |v| v.clamp(0.0, 6.0) as u8), @@ -458,9 +636,20 @@ impl Texts { } } - /// A character style: its own keys, else the document's. - fn style(&self, s: Option<&Val>) -> Style { - let pick = |k: &str| s.and_then(|s| s.get(k)).or_else(|| self.defaults.get(k)); + /// A run's character style (`run`: its attributes, key 6, and the character style it is based + /// on, key 5): its own keys, else those of its character style and the ones that is based on, + /// else those of `[Normal Character Style]`, else the document's. + fn style(&self, run: Option<&Val>) -> Style { + // The run's attributes, then its character style's, then the styles each is based on. + let mut chain = vec![]; + let mut at = run; + for _ in 0..=MAX_SHEETS_BASED_ON { + let Some(style) = at else { break }; + chain.extend(style.get("6")); + at = style.get("5").and_then(Val::num).filter(|i| i.is_finite() && *i >= 0.0).and_then(|i| self.char_sheets.get(i as usize)); + } + chain.extend(self.char_sheets.first().and_then(|s| s.get("6"))); + let pick = |k: &str| chain.iter().find_map(|s| s.get(k)).or_else(|| self.defaults.get(k)); let num = |k: &str| pick(k).and_then(Val::num); let on = |k: &str| !matches!(pick(k), Some(Val::Bool(false))); let font = num("0").and_then(|i| self.fonts.get(i as usize)).filter(|f| !f.is_empty()).cloned(); @@ -476,6 +665,9 @@ impl Texts { fill: if on("56") { Some(pick("53").and_then(paint).unwrap_or(Color::BLACK)) } else { None }, stroke: if matches!(pick("57"), Some(Val::Bool(true))) { pick("54").and_then(paint) } else { None }, stroke_width: num("63").filter(|v| *v >= 0.0 && *v < 1e4).unwrap_or(1.0), + caps: num("12").filter(|v| *v == 1.0 || *v == 2.0).map_or(0, |v| v as u8), + tate_chu_yoko: num("35") == Some(3.0), + standard_vertical_roman: num("35") == Some(1.0), } } } @@ -569,17 +761,128 @@ fn length_fraction(segments: &[[f64; 8]], t: f64) -> f64 { ((before + within) / total).clamp(0.0, 1.0) } +/// The spacing (Type on a Path Options › Spacing) that the layout `f` of type on a path implies. +/// The file closes its glyphs up round the outside of a curve and opens them up round the inside, +/// even where its frame keeps no spacing; the text engine spaces glyphs that way by the spacing +/// (`vectorcraft_text`'s `path_steps`): between two glyphs' centres, the path's length `s`, their +/// advances' mean `a` and how far it turns `t` (away from their tops) make `s + t × spacing = a`. +/// Fitted over every pair of the layout's glyphs; none where the path doesn't turn under them. +/// The length `s` is on the path: Align to Path moves the baselines off it, by the distance `G` +/// keeps. Under 3D Ribbon the glyphs' baselines stay level, so their feet show how the path turns. +fn path_spacing(f: &Val, effect: PathEffect) -> f64 { + let mut found = vec![]; + find_nodes(f, "G", &mut found); + let (mut sum, mut turns) = (0.0, 0.0); + for g in found { + // How far the baseline lies from the path, towards the glyphs' feet. Only Rainbow's and 3D + // Ribbon's feet are square to the path; Skew's are upright, so its alignment moves every + // baseline the same way and leaves the distances between them. + let offset = if matches!(effect, PathEffect::Rainbow | PathEffect::Ribbon3d) { + g.get("0").and_then(|o| o.get("0")).and_then(Val::nums).and_then(|o| o.get(1).copied()).filter(|o| o.is_finite()).unwrap_or(0.0) + } else { + 0.0 + }; + // Each glyph's origin, its matrix (along its baseline, then towards its foot) and where it + // ends along the line; the lists end with where the line ends. + let Some(at) = g.get("21") else { continue }; + let list = |k: &str| at.get(k).and_then(Val::nums).unwrap_or_default(); + let (xs, ys, matrices, ends) = (list("1"), list("2"), list("3"), list("4")); + if effect == PathEffect::StairStep { + let (s, t) = stair_step_fit(&xs, &ys, &ends); + sum += s; + turns += t; + continue; + } + let glyphs: Vec<(Point, f64, kurbo::Vec2, kurbo::Vec2)> = xs + .iter() + .zip(&ys) + .zip(matrices.as_chunks::<6>().0) + .zip(ends.windows(2)) + .map(|(((x, y), [a, b, c, d, ..]), e)| { + let advance = e.get(1).zip(e.first()).map_or(0.0, |(e1, e0)| e1 - e0); + let along = kurbo::Vec2::new(*a, *b); + (Point::new(*x, *y) + along * (advance * 0.5), advance, along, kurbo::Vec2::new(*c, *d)) + }) + .collect(); + for w in glyphs.windows(2) { + let [(p, a0, along, foot), (q, a1, next, next_foot)] = w else { continue }; + // 3D Ribbon's level baseline faces the way the path runs, so where the path runs left its + // baseline and foot are turned round: `side` turns them back. + let side = |baseline: &kurbo::Vec2| if effect == PathEffect::Ribbon3d && baseline.x < 0.0 { -1.0 } else { 1.0 }; + let (side, next_side) = (side(along), side(next)); + let (along, next) = if effect == PathEffect::Ribbon3d { + (kurbo::Vec2::new(foot.y, -foot.x) * side, kurbo::Vec2::new(next_foot.y, -next_foot.x) * next_side) + } else { + (*along, *next) + }; + // The turn is measured against a foot square to the path: Rainbow's and 3D Ribbon's own, + // else the baseline turned a right angle, as theirs is (Skew's feet stay upright). + let square = + if matches!(effect, PathEffect::Rainbow | PathEffect::Ribbon3d) { *foot * side } else { kurbo::Vec2::new(-along.y, along.x) }; + let turn = next.dot(square).atan2(next.dot(along)); + // The length of the arc between the centres (the path is taken to be round there). A + // corner (a turn of more than a radian between two glyphs) isn't round: left out. So is a + // 3D Ribbon pair either side of where the path turns back, when an alignment puts their + // baselines on opposite sides of the path. + let half = turn.abs() * 0.5; + let chord = (*q - *p).hypot(); + let length = if half > 1e-9 { chord * half / half.sin() } else { chord } + turn * offset * side; + let apart = side != next_side && offset != 0.0; + if !apart && turn.abs() <= 1.0 && length.is_finite() && a0.is_finite() && a1.is_finite() { + sum += ((a0 + a1) * 0.5 - length) * turn; + turns += turn * turn; + } + } + } + let spacing = sum / turns; + if turns > 1e-6 && spacing.is_finite() { spacing.clamp(-1000.0, 1000.0) } else { 0.0 } +} + +/// [`path_spacing`]'s sums for one line of Stair Step type, from its glyphs' origins `xs`, `ys` and +/// where they end along the line, `ends`. Stair Step's glyphs stay upright, so their matrices don't +/// show how the path turns; each origin lies on the path (all of them moved the same way by an +/// alignment), and a glyph's step is the path's length from its origin to the next. The path is taken +/// to be round through three origins in a row, which gives how far it turns over that step `t`; the +/// text engine makes the step `s` with `s + t × spacing = a`, `a` the glyph's advance. +fn stair_step_fit(xs: &[f64], ys: &[f64], ends: &[f64]) -> (f64, f64) { + let origins: Vec = xs.iter().zip(ys).map(|(x, y)| Point::new(*x, *y)).collect(); + let (mut sum, mut turns) = (0.0, 0.0); + for i in 0..origins.len().saturating_sub(1) { + let (Some(p), Some(q)) = (origins.get(i), origins.get(i + 1)) else { continue }; + // The third origin: the one before, else the one after. + let triple = match i.checked_sub(1).and_then(|h| origins.get(h)) { + Some(o) => (*o, *p, *q, *o), + None => match origins.get(i + 2) { + Some(r) => (*p, *q, *r, *r), + None => continue, + }, + }; + let (a, b, c, third) = triple; + // The inscribed angle at the third origin is half the arc's angle from `p` to `q`. + let (to_p, to_q) = ((*p - third).hypot(), (*q - third).hypot()); + let sine = (b - a).cross(c - a) / (to_p * to_q); + if !(sine.is_finite() && sine.abs() < 1.0) { + continue; + } + let turn = 2.0 * sine.asin(); + let half = turn.abs() * 0.5; + let chord = (*q - *p).hypot(); + let length = if half > 1e-9 { chord * half / half.sin() } else { chord }; + let advance = ends.get(i + 1).zip(ends.get(i)).map_or(f64::NAN, |(e1, e0)| e1 - e0); + if turn.abs() <= 1.0 && length.is_finite() && advance.is_finite() { + sum += (advance - length) * turn; + turns += turn * turn; + } + } + (sum, turns) +} + impl Story { /// How many bytes of text the story has. pub(super) fn len(&self) -> usize { self.text.len() } - /// The story's characters, with `\r` ending paragraphs and `\x03` ending lines. - pub(super) fn text(&self) -> &str { - &self.text - } - /// The point frame's matrix (the first frame's, when it is one), else the identity. fn matrix(&self) -> [f64; 6] { match self.frames.first() { @@ -604,7 +907,8 @@ impl Story { .iter() .enumerate() .map(|(i, (lx, ly))| { - let (x, y) = (self.anchor.0 + lx, self.anchor.1 + ly); + // A vertical layout's lines run down the canvas, and each next one is further left. + let (x, y) = if self.vertical { (self.anchor.0 - ly, self.anchor.1 + lx) } else { (self.anchor.0 + lx, self.anchor.1 + ly) }; (text.get(i).copied().unwrap_or_default().to_string(), to_art((a * x + c * y + e, b * x + d * y + f), template)) }) .collect() @@ -616,9 +920,9 @@ impl Story { let size = self.runs.iter().map(|(_, s)| s.size).fold(0.0, f64::max) * art_scale(to_doc); let bounds = |segments: &[[f64; 8]]| path_of(segments, template, to_doc).bounds(); let r = match self.frames.first()? { - FrameKind::Area(s) => bounds(s)?, + FrameKind::Area(s, _) => bounds(s)?, FrameKind::OnPath { segments, .. } => bounds(segments)?.inflate(size * 1.5, size * 1.5), - FrameKind::Point(_) => { + FrameKind::Point(m) => { let longest = self.text.split(['\r', '\x03']).map(|l| l.chars().count()).max().unwrap_or(0) as f64; let reach = longest * size + size; let points: Vec = self.line_starts(template).into_iter().map(|(_, (x, y))| to_doc * Point::new(x, y)).collect(); @@ -626,7 +930,21 @@ impl Story { let (x, y) = self.place(template); to_doc * Point::new(x, y) }); - points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)).inflate(reach, size * 1.5) + // Along the baseline as far as a line reaches, across it a line and a half: turned + // with the type (a dimension's label turned a quarter runs down the page). + // (The canvas is y down, the art y up: see [`to_art`].) + let along = to_doc * Point::new(m[0], -m[1]) - to_doc * Point::ZERO; + let along = if along.hypot() > 1e-9 && along.is_finite() { along / along.hypot() } else { kurbo::Vec2::new(1.0, 0.0) }; + let across = kurbo::Vec2::new(-along.y, along.x); + // Vertical type: its lines run down the page, a quarter turn from the baseline. + let (along, across) = if self.vertical { (across, along) } else { (along, across) }; + let mut r = Rect::from_points(first, first); + for p in points.iter().chain([&first]) { + for (t, n) in [(-reach, -1.5), (-reach, 1.5), (reach, -1.5), (reach, 1.5)] { + r = r.union_pt(*p + along * t + across * (n * size)); + } + } + r } }; r.is_finite().then_some(r) @@ -649,19 +967,33 @@ impl Story { let at = to_doc * Point::new(x, y); (scale, Affine::new([a / scale, b / scale, c / scale, d / scale, at.x, at.y]), TextKind::Point) } - FrameKind::Area(s) => (1.0, Affine::IDENTITY, TextKind::Area { frame: path_of(s, template, to_doc) }), - FrameKind::OnPath { segments, start, end } => { + FrameKind::Area(s, _) => (1.0, Affine::IDENTITY, TextKind::Area { frame: path_of(s, template, to_doc) }), + FrameKind::OnPath { segments, start, end, options } => { let n = segments.len() as f64; // A closed path keeps its end bracket wherever it is (the same place as the start: a - // full turn, see `TextKind::path_span`); an open one's end at its end is none. - let end = (closed(segments) || *end < n - 0.02).then(|| length_fraction(segments, *end)); + // full turn, see `TextKind::path_span`); an open one's end at its end is none, unless + // a flip makes it the place the type starts. + let end = (closed(segments) || options.flip || *end < n - 0.02).then(|| length_fraction(segments, *end)); (1.0, Affine::IDENTITY, TextKind::OnPath { path: path_of(segments, template, to_doc), start: length_fraction(segments, *start), end }) } }; + // A `\x03` ends a line inside its paragraph: a forced line break (U+2028), which the + // paragraph's style runs over. let text: String = if threaded { String::new() } else { - self.text.trim_end_matches('\r').chars().map(|c| if matches!(c, '\r' | '\x03') { '\n' } else { c }).collect() + // The `\r` that ends the story's last paragraph; one before it ends a paragraph, and the + // empty paragraph after it is the story's last. + self.text + .strip_suffix('\r') + .unwrap_or(&self.text) + .chars() + .map(|c| match c { + '\r' => '\n', + '\x03' => '\u{2028}', + c => c, + }) + .collect() }; if text.trim().is_empty() && !threaded { return None; @@ -696,11 +1028,35 @@ impl Story { if paras.len() > 1 && paras.iter().any(|p| *p != t.para) { t.paras = paras; } + if matches!(kind, TextKind::OnPath { .. }) && !threaded { + t.path_spacing = self.path_spacing * scale; + } + // Each frame of a thread keeps its own options. + match self.frames.get(frame) { + Some(FrameKind::Area(_, options)) => options.apply(&mut t.area, scale), + Some(FrameKind::OnPath { options, .. }) => { + t.path_effect = options.effect; + t.path_align = options.align; + } + _ => {} + } + t.vertical = self.vertical; t.kind = kind; t.xf = xf; Some(Node::new(id, NodeKind::Text(Box::new(t)))) } + /// Flips type on a path (`node`, made from frame `frame`) when its frame keeps Flip on. The + /// frame's path runs as it did before the flip, so this runs once, on the path the object ends + /// up with. + pub(super) fn flip_on_path(&self, node: &mut Node, frame: usize) { + if let Some(FrameKind::OnPath { options: PathFrame { flip: true, .. }, .. }) = self.frames.get(frame) + && let NodeKind::Text(t) = &mut node.kind + { + t.flip_on_path(); + } + } + /// Area type that the file lays lines out in, in a frame too short for its first line as it is /// laid out here: a font that isn't available shows in the fallback font, whose lines may be /// taller, and type that doesn't fit its frame isn't drawn. The frame is made taller, from its @@ -709,6 +1065,44 @@ impl Story { !self.lines.is_empty() && vectorcraft_text::fit_first_line(vectorcraft_text::FontDb::global(), t) } + /// Area type (`node`, the story's first frame as [`Self::node`] makes it with `template` and + /// `to_doc`) whose first line the file lays out higher or lower than it is laid out here, as its + /// page draws it: its first baseline is fixed where the file has it. The font's ascent below the + /// frame's top, the first baseline here, isn't where the app that wrote the file puts it for + /// every font. A first baseline its frame `frame` keeps (other than Ascent) stays as it is. + /// Whether it was. + pub(super) fn place_first_line(&self, node: &mut Node, frame: usize, template: (f64, f64), to_doc: Affine) -> bool { + // Closer than this (points of the document) and the line is where the file has it. + const SAME: f64 = 0.5; + if matches!(self.frames.get(frame), Some(FrameKind::Area(_, AreaFrame { first_baseline: Some(_), .. }))) { + return false; + } + let NodeKind::Text(t) = &mut node.kind else { return false }; + if !matches!(t.kind, TextKind::Area { .. }) || t.area.vertical_align != vectorcraft_doc::VerticalAlign::Top { + return false; + } + let Some((_, (x, y))) = self.line_starts(template).into_iter().next() else { return false }; + let at = to_doc * Point::new(x, y); + let db = vectorcraft_text::FontDb::global(); + // A frame too short for the line lays nothing out: as the line needs it (see `fit_first_line`). + let mut probe = TextObject::clone(t); + vectorcraft_text::fit_first_line(db, &mut probe); + let laid = vectorcraft_text::layout(db, &probe); + let Some(first) = laid.lines.first().filter(|l| l.region == 0) else { return false }; + // Where the first baseline goes in the layout's line space. Vertical type's line space is a + // quarter turn from the document (a line's height is how far left of the frame's right edge + // its column is), and the file's line is the column's centre line, the middle of the line + // (as `TextLayout::baselines` has it): the baseline is that far from it. + let want = if t.vertical { -at.x - (first.descent - first.ascent) / 2.0 } else { at.y }; + let min = first.first_baseline + (want - first.baseline); + if (want - first.baseline).abs() <= SAME || !min.is_finite() || min <= 0.0 { + return false; + } + t.area.first_baseline = vectorcraft_doc::FirstBaseline::Fixed; + t.area.first_baseline_min = min; + true + } + /// The leading the file's own line positions imply: the distance from one line to the next, less /// the space between paragraphs that is part of it (a paragraph's space after and the next one's /// space before; a layout's lines are where that space has put them, and the text object adds it @@ -790,6 +1184,9 @@ fn para_style(p: &Para, scale: f64) -> ParaStyle { space_before: p.space_before * scale, space_after: p.space_after * scale, hyphenate: p.hyphenate, + // A right-to-left paragraph lays its text out from the right whatever letters it has + // (" 120.5 mm " reads "mm 120.5"); without the key, from its first strong letter. + direction: p.rtl.then_some(ParaDirection::RightToLeft), ..ParaStyle::default() } } @@ -809,6 +1206,11 @@ fn char_style(s: &Style, scale: f64, leading: Option) -> CharStyle { fill: s.fill.map_or(Paint::None, Paint::solid), stroke: s.stroke.map_or(Paint::None, Paint::solid), stroke_width: if s.stroke.is_some() { s.stroke_width * scale } else { 0.0 }, + all_caps: s.caps == 2, + // At the default Small Caps size of Document Setup: the file's own isn't read. + small_caps: (s.caps == 1).then(|| vectorcraft_doc::DocSetup::default().small_caps_size), + tate_chu_yoko: s.tate_chu_yoko, + standard_vertical_roman: s.standard_vertical_roman, ..CharStyle::default() } } @@ -826,9 +1228,16 @@ mod tests { #[test] fn right_to_left_paragraphs_swap_left_and_right_alignment() { - let texts = - Texts { stories: vec![], fonts: vec![], defaults: Val::Dict(BTreeMap::new()), para_defaults: read(b"/33 1").unwrap(), frames: vec![] }; - let justify = |own: &[u8]| para_style(&texts.para(Some(&read(own).unwrap())), 1.0).justify; + let texts = Texts { + stories: vec![], + fonts: vec![], + defaults: Val::Dict(BTreeMap::new()), + para_defaults: read(b"/33 1").unwrap(), + char_sheets: vec![], + para_sheets: vec![], + frames: vec![], + }; + let justify = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justify; // Right to left from the document's defaults, or the paragraph's own. assert_eq!(justify(b"/0 0"), Justify::Right); assert_eq!(justify(b"/0 1 /33 1"), Justify::Left); @@ -838,6 +1247,142 @@ mod tests { assert_eq!(justify(b"/0 1 /33 0"), Justify::Right); } + /// Where point type lies runs along its baseline: a label turned a quarter (as a vertical + /// dimension's is) lies in a tall box, not a wide one. + #[test] + fn point_type_lies_along_its_baseline() { + let para = Texts { + stories: vec![], + fonts: vec![], + defaults: Val::Dict(BTreeMap::new()), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![], + para_sheets: vec![], + frames: vec![], + } + .para(None); + let mut s = story(" 80 mm ", &[0.0], ¶); + let size = |s: &Story| s.region((0.0, 0.0), Affine::IDENTITY).map(|r| (r.width(), r.height())).unwrap(); + let (w, h) = size(&s); + assert!(w > 3.0 * h, "level: {w} × {h}"); + // Turned −90° on the canvas (y down): the baseline runs down the page. + s.frames = vec![FrameKind::Point([0.0, 1.0, -1.0, 0.0, 0.0, 0.0])]; + let (w, h) = size(&s); + assert!(h > 3.0 * w, "turned: {w} × {h}"); + // Vertical type lies down the page without a turn. + s.frames = vec![FrameKind::Point([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])]; + s.vertical = true; + let (w, h) = size(&s); + assert!(h > 3.0 * w, "vertical: {w} × {h}"); + } + + /// A vertical layout's lines run down the canvas from the anchor, each next one further left: + /// the second column starts one line pitch left of the first, and a centred column (its start + /// before the anchor) starts higher up. + #[test] + fn vertical_lines_start_down_the_canvas_each_further_left() { + let mut s = story("ab\rc\rde\r", &[0.0, 14.4, 28.8], &Para::default()); + s.vertical = true; + s.lines[2].0 = -12.0; + s.anchor = (CANVAS_CENTRE + 100.0, CANVAS_CENTRE - 50.0); + let starts: Vec<(f64, f64)> = s.line_starts((0.0, 0.0)).into_iter().map(|(_, p)| p).collect(); + let [a, b, c] = starts.as_slice() else { panic!("{starts:?}") }; + assert!((a.0 - 100.0).abs() < 1e-9 && (a.1 - 50.0).abs() < 1e-9, "the first column at the anchor: {a:?}"); + assert!((b.0 - 85.6).abs() < 1e-9 && (b.1 - 50.0).abs() < 1e-9, "the next one to the left: {b:?}"); + assert!((c.0 - 71.2).abs() < 1e-9 && (c.1 - 62.0).abs() < 1e-9, "a centred one higher (the art is y up): {c:?}"); + } + + /// Key 1 of what a frame carries is its orientation: 2 vertical; 0, none or any other value + /// horizontal. + #[test] + fn a_frame_is_vertical_only_at_orientation_two() { + let frame = |carries: &str| read(format!("/0 << /2 << /0 0 {carries} >> >>").as_bytes()).unwrap(); + let cases = ["/1 2", "/1 0", "", "/1 1", "/1 2.5", "/1 -2", "/1 (2)", "/1 1e300", "/1 true", "/1 [ 2 ]"]; + let texts = Texts { + stories: vec![], + fonts: vec![], + defaults: Val::Dict(BTreeMap::new()), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![], + para_sheets: vec![], + frames: cases.iter().map(|c| frame(c)).collect(), + }; + let vertical: Vec = (0..cases.len() + 1).map(|i| texts.frame_vertical(i)).collect(); + assert_eq!(vertical, [true, false, false, false, false, false, false, false, false, false, false]); + } + + /// Key 35 of a character style at 3 is Tate-chu-yoko; its other values (1 and 2, how half-width + /// characters stand in a column) and values that aren't that number aren't. + #[test] + fn baseline_direction_three_is_tate_chu_yoko() { + let texts = Texts { + stories: vec![], + fonts: vec![], + defaults: read(b"/35 1").unwrap(), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Block) /6 << /35 3 >>").unwrap()], + para_sheets: vec![], + frames: vec![], + }; + let tcy = |run: &[u8]| texts.style(Some(&read(run).unwrap())).tate_chu_yoko; + assert!(tcy(b"/6 << /35 3 >>"), "the run's own"); + assert!(tcy(b"/5 1 /6 << >>"), "its character style's"); + assert!(!tcy(b"/5 1 /6 << /35 1 >>"), "the run's own wins"); + for other in [&b"/6 << >>"[..], b"/6 << /35 2 >>", b"/6 << /35 3.5 >>", b"/6 << /35 (3) >>", b"/6 << /35 -3 >>", b"/6 << /35 1e308 >>"] { + assert!(!tcy(other), "{}", String::from_utf8_lossy(other)); + } + } + + /// Key 35 of a character style at 1 (Standard) is Standard Vertical Roman Alignment, from the + /// run, its character style or the document's defaults; at 2 (rotated), 3 (Tate-chu-yoko), a + /// value that isn't one of those numbers, or with no key anywhere it is off. + #[test] + fn baseline_direction_one_is_standard_vertical_roman_alignment() { + let texts = |defaults: &[u8]| Texts { + stories: vec![], + fonts: vec![], + defaults: read(defaults).unwrap(), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rotated) /6 << /35 2 >>").unwrap()], + para_sheets: vec![], + frames: vec![], + }; + let roman = |defaults: &[u8], run: &[u8]| texts(defaults).style(Some(&read(run).unwrap())).standard_vertical_roman; + assert!(roman(b"/35 1", b"/6 << >>"), "the document's defaults"); + assert!(roman(b"/35 2", b"/6 << /35 1 >>"), "the run's own"); + assert!(!roman(b"/35 1", b"/6 << /35 2 >>"), "the run's own rotated"); + assert!(!roman(b"/35 1", b"/5 1 /6 << >>"), "its character style's"); + assert!(roman(b"/35 2", b"/5 1 /6 << /35 1 >>"), "the run's own wins over its style"); + assert!(!roman(b"/0 0", b"/6 << >>"), "no key: off"); + for other in + [&b"/6 << /35 3 >>"[..], b"/6 << /35 1.5 >>", b"/6 << /35 (1) >>", b"/6 << /35 -1 >>", b"/6 << /35 true >>", b"/6 << /35 [ 1 ] >>"] + { + assert!(!roman(b"/0 0", other), "{}", String::from_utf8_lossy(other)); + } + assert!(texts(b"/35 3").style(None).tate_chu_yoko && !texts(b"/35 3").style(None).standard_vertical_roman); + } + + /// A right-to-left paragraph is laid out right to left even when it has no right-to-left + /// letters (a dimension's label " 120.5 mm " reads "mm 120.5"); a left-to-right one, or one + /// that doesn't say, goes by its letters. + #[test] + fn right_to_left_paragraphs_set_their_direction() { + let texts = Texts { + stories: vec![], + fonts: vec![], + defaults: Val::Dict(BTreeMap::new()), + para_defaults: read(b"/33 1").unwrap(), + char_sheets: vec![], + para_sheets: vec![], + frames: vec![], + }; + let direction = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).direction; + assert_eq!(direction(b"/0 2"), Some(ParaDirection::RightToLeft), "from the document's defaults"); + assert_eq!(direction(b"/0 2 /33 0"), None, "the paragraph's own"); + let plain = Texts { para_defaults: Val::Dict(BTreeMap::new()), ..texts }; + assert_eq!(para_style(&plain.para(None), 1.0).direction, None); + } + #[test] fn values_read_nested_dictionaries_lists_and_utf16_strings() { let v = read(b" /1 << /0 [ 1 2.5 -3 ] /2 (\xfe\xff\x00h\x00i) /3 true /99 /Name >> /0 (a\\)b\\n)").unwrap(); @@ -861,14 +1406,21 @@ mod tests { /// A text document's frame on a path of `segments` (each `x0 y0 x1 y1 x2 y2 x3 y3`) with the /// range `range`, written by hand. fn on_path_frame(segments: &[[f64; 8]], range: [f64; 2]) -> Option { + on_path_frame_with(segments, range, "") + } + + /// The same with `options` in the frame data too. + fn on_path_frame_with(segments: &[[f64; 8]], range: [f64; 2], options: &str) -> Option { let nums = |v: &[f64]| v.iter().map(|n| format!("{n}")).collect::>().join(" "); let all: Vec = segments.iter().flatten().copied().collect(); - let doc = format!("/0 << /1 << /0 [ {} ] >> /2 << /0 2 /6 [ {} ] >> >>", nums(&all), nums(&range)); + let doc = format!("/0 << /1 << /0 [ {} ] >> /2 << /0 2 /6 [ {} ] {options} >> >>", nums(&all), nums(&range)); let texts = Texts { stories: vec![], fonts: vec![], defaults: Val::Dict(BTreeMap::new()), para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![], + para_sheets: vec![], frames: vec![read(doc.as_bytes()).unwrap()], }; texts.frame(0) @@ -895,6 +1447,123 @@ mod tests { (*t, b - a) } + /// Key 11's codes for the effect and the alignment, each read on its own. The defaults are the + /// keys left out. + #[test] + fn type_on_a_path_keeps_its_effect_and_alignment() { + use PathAlign as A; + use PathEffect as E; + let read = |options: &str| { + let (t, _) = on_path("type", on_path_frame_with(&circle(), [0.0, 3.99], options).unwrap()); + (t.path_effect, t.path_align) + }; + assert_eq!(read(""), (E::Rainbow, A::Baseline)); + assert_eq!(read("/11 << /4 21 /18 21.0 /6 false /22 0.025 >>"), (E::Rainbow, A::Baseline)); + for (code, effect) in [(1, E::Skew), (2, E::Ribbon3d), (3, E::StairStep), (4, E::Gravity)] { + assert_eq!(read(&format!("/11 << /1 {code} >>")), (effect, A::Baseline), "effect {code}"); + } + for (code, align) in [(0, A::Ascender), (1, A::Descender), (2, A::Center)] { + assert_eq!(read(&format!("/11 << /2 {code} >>")), (E::Rainbow, align), "alignment {code}"); + } + assert_eq!(read("/11 << /1 3 /2 1 >>"), (E::StairStep, A::Descender)); + } + + /// A frame with key 6 true keeps the defaults, Flip included. + #[test] + fn type_on_a_path_with_key_6_true_keeps_the_defaults() { + let Some(FrameKind::OnPath { options, .. }) = on_path_frame_with(&circle(), [0.0, 3.99], "/11 << /6 true /0 true /1 1 /2 0 >>") else { + panic!("on a path") + }; + assert_eq!(options, PathFrame::default()); + } + + /// Key 11 where it can't be read leaves the options at their defaults, each on its own. + #[test] + fn type_on_a_path_options_that_cannot_be_read_keep_their_defaults() { + let bad = ["5", "-1", "1.5", "1e300", "(1)", "true", "/Skew", "[ 1 ]", "<< /0 1 >>"]; + for value in bad { + for key in ["1", "2", "0"] { + let Some(FrameKind::OnPath { options, .. }) = on_path_frame_with(&circle(), [0.0, 3.99], &format!("/11 << /{key} {value} >>")) else { + panic!("on a path") + }; + let expected = PathFrame { flip: key == "0" && value == "true", ..PathFrame::default() }; + assert_eq!(options, expected, "key {key} value {value}"); + } + } + for whole in ["3", "true", "(x)", "[ /1 1 ]"] { + let Some(FrameKind::OnPath { options, .. }) = on_path_frame_with(&circle(), [0.0, 3.99], &format!("/11 {whole}")) else { + panic!("on a path") + }; + assert_eq!(options, PathFrame::default(), "{whole}"); + } + // One option that can't be read leaves the other as the frame keeps it. + let Some(FrameKind::OnPath { options, .. }) = on_path_frame_with(&circle(), [0.0, 3.99], "/11 << /1 9 /2 2 >>") else { panic!("on a path") }; + assert_eq!((options.effect, options.align), (PathEffect::Rainbow, PathAlign::Center)); + } + + /// The first point of type on a path's path, and its span. + fn flipped_on_path(frames: Vec, frame: usize) -> (f64, (f64, f64)) { + let mut st = story("type", &[0.0], &Para::default()); + st.frames = frames; + let mut node = st.node(NodeId(1), frame, (0.0, 0.0), Affine::IDENTITY).unwrap(); + st.flip_on_path(&mut node, frame); + let NodeKind::Text(t) = node.kind else { panic!("not type") }; + let vectorcraft_doc::TextKind::OnPath { path, .. } = &t.kind else { panic!("type on a path") }; + let Some(kurbo::PathEl::MoveTo(first)) = path.to_bezpath().elements().first().copied() else { panic!("a path") }; + (first.x + CANVAS_CENTRE, t.kind.path_span().unwrap()) + } + + /// Flip is a flag: the frame's path and range run as before the flip, so the type flips once, + /// keeps its stretch of the path, and the path runs from its far end. + #[test] + fn flipped_type_on_a_path_runs_the_path_the_other_way_once() { + let open = [[0.0, 0.0, 30.0, 0.0, 70.0, 0.0, 100.0, 0.0], [100.0, 0.0, 130.0, 0.0, 170.0, 0.0, 200.0, 0.0]]; + let frame = |options: &str| vec![on_path_frame_with(&open, [0.5, 1.5], options).unwrap()]; + let (first, (from, to)) = flipped_on_path(frame("/11 << /0 false >>"), 0); + assert_eq!(first, 0.0); + assert!((from - 0.25).abs() < 1e-3 && (to - 0.75).abs() < 1e-3, "{from} {to}"); + let (first, (from, to)) = flipped_on_path(frame("/11 << /0 true >>"), 0); + assert_eq!(first, 200.0, "from the path's far end"); + assert!((from - 0.25).abs() < 1e-3 && (to - 0.75).abs() < 1e-3, "the same stretch: {from} {to}"); + } + + /// The end of an open path's range, which doesn't move unflipped type, is where flipped type + /// starts: a range that ends just short of the path's end starts the type that far from it. + #[test] + fn flipped_type_on_an_open_path_starts_at_the_end_of_its_range() { + let third = 100.0 / 3.0; + let line = [[0.0, 0.0, third, 0.0, 2.0 * third, 0.0, 100.0, 0.0]]; + let frame = |options: &str| vec![on_path_frame_with(&line, [0.0, 0.99], options).unwrap()]; + let (_, (from, to)) = flipped_on_path(frame("/11 << /0 true >>"), 0); + assert!((from - 0.01).abs() < 1e-3 && (to - 1.0).abs() < 1e-3, "{from} {to}"); + let (_, (from, to)) = flipped_on_path(frame(""), 0); + assert!(from.abs() < 1e-3 && (to - 1.0).abs() < 1e-3, "unflipped: {from} {to}"); + } + + /// Round a closed path, a flip keeps the stretch too, and each frame of a thread keeps its own + /// options. + #[test] + fn each_frame_of_type_on_a_path_keeps_its_options() { + let mut st = story("type", &[0.0], &Para::default()); + st.frames = vec![ + on_path_frame_with(&circle(), [0.5, 2.5], "/11 << /0 true /1 1 >>").unwrap(), + on_path_frame_with(&circle(), [0.0, 3.99], "/11 << /2 0 >>").unwrap(), + ]; + let mut first = st.node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY).unwrap(); + let mut second = st.node(NodeId(2), 1, (0.0, 0.0), Affine::IDENTITY).unwrap(); + let before = first.clone(); + st.flip_on_path(&mut first, 0); + assert_ne!(before, first, "the first frame flips"); + let before = second.clone(); + st.flip_on_path(&mut second, 1); + assert_eq!(before, second, "the second frame doesn't"); + let (NodeKind::Text(a), NodeKind::Text(b)) = (&first.kind, &second.kind) else { panic!("not type") }; + assert_eq!((a.path_effect, a.path_align), (PathEffect::Skew, PathAlign::Baseline)); + assert_eq!((b.path_effect, b.path_align), (PathEffect::Rainbow, PathAlign::Ascender)); + let (from, to) = a.kind.path_span().unwrap(); + assert!((to - from - 0.5).abs() < 1e-3, "{from} {to}"); + } + /// Round a closed path the file writes the end bracket unwrapped, past the last segment (the /// start plus the run): the type keeps that run, nearly the whole circle here, not the bit /// from the start to the path's end. @@ -960,11 +1629,250 @@ mod tests { fill: Some(Color::BLACK), stroke: None, stroke_width: 1.0, + caps: 0, + tate_chu_yoko: false, + standard_vertical_roman: false, }, )], + path_spacing: 0.0, + vertical: false, } } + /// A layout of glyphs `advances` wide round a circle of radius `radius` (y down), from its left, + /// outside it (their feet towards its centre) or inside it, the length of the circle between + /// their centres `fraction` of their advances' mean. + fn round_layout(advances: &[f64], radius: f64, outside: bool, fraction: f64) -> Val { + round_layout_with(advances, radius, outside, fraction, "", false) + } + + /// The same with `extra` in the line's `G`, and baselines that stay level as 3D Ribbon's do when + /// `level`. + fn round_layout_with(advances: &[f64], radius: f64, outside: bool, fraction: f64, extra: &str, level: bool) -> Val { + let sign = if outside { 1.0 } else { -1.0 }; + let (mut xs, mut ys, mut matrices, mut ends) = (vec![], vec![], vec![], vec![0.0]); + let mut angle = std::f64::consts::PI; + for (i, a) in advances.iter().enumerate() { + if i > 0 { + angle += sign * (advances[i - 1] + a) * 0.5 * fraction / radius; + } + // Outside, clockwise on the page (y down); inside, the other way round. + let along = (-angle.sin() * sign, angle.cos() * sign); + let centre = (radius * angle.cos(), radius * angle.sin()); + let baseline = if level { (1.0, 0.0) } else { along }; + xs.push(centre.0 - baseline.0 * a * 0.5); + ys.push(centre.1 - baseline.1 * a * 0.5); + matrices.extend([baseline.0, baseline.1, -along.1, along.0, 0.0, 0.0]); + ends.push(ends[i] + a); + } + let nums = |v: &[f64]| v.iter().map(|n| format!("{n}")).collect::>().join(" "); + let doc = format!( + "/0 << /99 /F /6 [ << /99 /L /6 [ << /99 /S /6 [ << /99 /G {extra} /21 << /1 [ {} ] /2 [ {} ] /3 [ {} ] /4 [ {} ] >> >> ] >> ] >> ] >>", + nums(&xs), + nums(&ys), + nums(&matrices), + nums(&ends) + ); + read(doc.as_bytes()).unwrap().get("0").unwrap().clone() + } + + /// The file lays type on a path out closer round the outside of a curve and further apart round + /// the inside: the spacing that does that is read from its layout, as the text engine's model + /// has it (length + turn × spacing = advance). + #[test] + fn the_layout_of_type_on_a_path_gives_its_spacing() { + let advances = [20.0, 30.0, 10.0, 25.0, 20.0]; + // Outside a circle of radius 100, 10 above the path: the centres are 100/110 of the advances apart. + let rainbow = PathEffect::Rainbow; + let spacing = path_spacing(&round_layout(&advances, 100.0, true, 100.0 / 110.0), rainbow); + assert!((spacing - 10.0).abs() < 1e-6, "{spacing}"); + // Inside it, 20 above the path: 100/80 of them. + let spacing = path_spacing(&round_layout(&advances, 100.0, false, 100.0 / 80.0), rainbow); + assert!((spacing - 20.0).abs() < 1e-6, "{spacing}"); + // At their advances: none. + assert!(path_spacing(&round_layout(&advances, 100.0, true, 1.0), rainbow).abs() < 1e-6); + // Corners (here a turn of about four radians from glyph to glyph) aren't taken for a curve. + assert_eq!(path_spacing(&round_layout(&advances, 5.0, true, 1.0), rainbow), 0.0); + // A straight line turns nowhere, and a layout without glyphs says nothing. + assert_eq!(path_spacing(&round_layout(&advances, 1e12, true, 0.9), rainbow), 0.0); + assert_eq!(path_spacing(&read(b"/99 /F").unwrap(), rainbow), 0.0); + } + + /// Align to Path moves the baselines off the path, and the spacing is the one on the path. On a + /// circle of radius 100 with spacing 10, the path's length between two centres is 100/110 of + /// their advances. Baselines on a smaller or larger circle are that much closer or further. + #[test] + fn the_spacing_of_aligned_type_is_measured_on_its_path() { + let advances = [20.0, 30.0, 10.0, 25.0, 20.0]; + let fit = + |radius: f64, extra: &str| path_spacing(&round_layout_with(&advances, radius, true, radius / 110.0, extra, false), PathEffect::Rainbow); + // 20 towards the feet: Ascender. + let spacing = fit(80.0, "/0 << /0 [ 0 20 ] >>"); + assert!((spacing - 10.0).abs() < 1e-6, "{spacing}"); + // 8 away from them: Descender. + let spacing = fit(108.0, "/0 << /0 [ 0 -8 ] >>"); + assert!((spacing - 10.0).abs() < 1e-6, "{spacing}"); + // A distance that can't be read counts as none. + for bad in ["/0 3", "/0 << /0 (x) >>", "/0 << /0 [ 0 ] >>"] { + let spacing = fit(100.0, bad); + assert!((spacing - 10.0).abs() < 1e-6, "{bad}: {spacing}"); + } + // Skew's feet are upright: its alignment moves the baselines without changing their + // lengths, so the distance doesn't count. + let layout = |extra: &str| round_layout_with(&advances, 100.0, true, 100.0 / 110.0, extra, false); + let plain = path_spacing(&layout(""), PathEffect::Skew); + let aligned = path_spacing(&layout("/0 << /0 [ 0 20 ] >>"), PathEffect::Skew); + assert!((aligned - plain).abs() < 1e-9, "{plain} {aligned}"); + // 3D Ribbon's feet are square to the path, as Rainbow's are. + let level = round_layout_with(&advances, 80.0, true, 80.0 / 110.0, "/0 << /0 [ 0 20 ] >>", true); + let spacing = path_spacing(&level, PathEffect::Ribbon3d); + assert!((spacing - 10.0).abs() < 1e-6, "{spacing}"); + } + + /// Skew's feet stay upright, so on a straight path at 30 degrees they are not square to it. The + /// path turns nowhere, so glyphs set further apart than their advances give no spacing, going + /// right or left. + #[test] + fn skewed_type_on_a_straight_tilted_path_has_no_spacing() { + let advances = [20.0, 30.0, 10.0, 25.0, 20.0]; + for degrees in [30.0f64, 210.0] { + let along = kurbo::Vec2::new(degrees.to_radians().cos(), degrees.to_radians().sin()); + let (mut at, mut glyphs) = (0.0, vec![]); + for (i, a) in advances.iter().enumerate() { + if i > 0 { + at += (advances[i - 1] + a) * 0.5 * 1.2; + } + glyphs.push((Point::ORIGIN + along * at, along)); + } + let layout = upright_layout(&advances, &glyphs); + for effect in [PathEffect::Skew, PathEffect::StairStep, PathEffect::Gravity] { + let spacing = path_spacing(&layout, effect); + assert!(spacing.abs() < 1e-9, "{degrees}, {effect:?}: {spacing}"); + } + } + } + + /// Round the bottom of a circle the path runs left, and Skew's upright feet point away from the + /// side the path turns to: the turn is still measured as Rainbow's is. Outside a circle of + /// radius 100, 10 above the path, the centres are 100/110 of the advances apart: spacing 10. + #[test] + fn skewed_type_running_left_round_a_curve_gives_its_spacing() { + let advances = [20.0, 30.0, 10.0, 25.0, 20.0]; + let mut angle = std::f64::consts::FRAC_PI_2 - 0.2; + let mut glyphs = vec![]; + for (i, a) in advances.iter().enumerate() { + if i > 0 { + angle += (advances[i - 1] + a) * 0.5 * (100.0 / 110.0) / 100.0; + } + glyphs.push((Point::new(100.0 * angle.cos(), 100.0 * angle.sin()), kurbo::Vec2::new(-angle.sin(), angle.cos()))); + } + let spacing = path_spacing(&upright_layout(&advances, &glyphs), PathEffect::Skew); + assert!((spacing - 10.0).abs() < 1e-6, "{spacing}"); + } + + /// A line's layout whose glyphs have their centres and baselines `glyphs` and upright feet, as + /// Skew's are. + fn upright_layout(advances: &[f64], glyphs: &[(Point, kurbo::Vec2)]) -> Val { + let glyphs: Vec<(Point, [f64; 4])> = glyphs.iter().map(|(centre, along)| (*centre, [along.x, along.y, 0.0, 1.0])).collect(); + line_layout(advances, &glyphs, "") + } + + /// A line's layout, `extra` in its `G`, whose glyphs have their centres and matrices `glyphs`. + fn line_layout(advances: &[f64], glyphs: &[(Point, [f64; 4])], extra: &str) -> Val { + let (mut xs, mut ys, mut matrices, mut ends) = (vec![], vec![], vec![], vec![0.0]); + for (i, (a, (centre, [m0, m1, m2, m3]))) in advances.iter().zip(glyphs).enumerate() { + xs.push(centre.x - m0 * a * 0.5); + ys.push(centre.y - m1 * a * 0.5); + matrices.extend([*m0, *m1, *m2, *m3, 0.0, 0.0]); + ends.push(ends[i] + a); + } + let nums = |v: &[f64]| v.iter().map(|n| format!("{n}")).collect::>().join(" "); + let doc = format!( + "/0 << /99 /F /6 [ << /99 /L /6 [ << /99 /S /6 [ << /99 /G {extra} /21 << /1 [ {} ] /2 [ {} ] /3 [ {} ] /4 [ {} ] >> >> ] >> ] >> ] >>", + nums(&xs), + nums(&ys), + nums(&matrices), + nums(&ends) + ); + read(doc.as_bytes()).unwrap().get("0").unwrap().clone() + } + + /// 3D Ribbon keeps its baselines level, so its glyphs' feet show how the path turns. + #[test] + fn the_spacing_of_3d_ribbon_type_follows_the_feet_of_its_glyphs() { + let advances = [20.0, 30.0, 10.0, 25.0, 20.0]; + let layout = round_layout_with(&advances, 100.0, true, 100.0 / 110.0, "", true); + let spacing = path_spacing(&layout, PathEffect::Ribbon3d); + assert!((spacing - 10.0).abs() < 1e-6, "{spacing}"); + } + + /// Where the path runs left, 3D Ribbon's level baseline faces left and its foot turns round with + /// it. Round a circle of radius 100 through the place where the path runs straight up, the glyphs + /// on either side of it are still read as following one curve: spacing 10. + #[test] + fn the_spacing_of_3d_ribbon_type_holds_where_the_path_turns_back() { + let advances = [20.0, 30.0]; + let mut angle = std::f64::consts::PI - 0.1; + let mut glyphs = vec![]; + for (i, a) in advances.iter().enumerate() { + if i > 0 { + angle += (advances[i - 1] + a) * 0.5 * (100.0 / 110.0) / 100.0; + } + let along = kurbo::Vec2::new(-angle.sin(), angle.cos()); + let side = if along.x < 0.0 { -1.0 } else { 1.0 }; + glyphs.push((Point::new(100.0 * angle.cos(), 100.0 * angle.sin()), [side, 0.0, -along.y * side, along.x * side])); + } + assert!(glyphs.first().is_some_and(|(_, m)| m[0] < 0.0) && glyphs.last().is_some_and(|(_, m)| m[0] > 0.0)); + let spacing = path_spacing(&line_layout(&advances, &glyphs, ""), PathEffect::Ribbon3d); + assert!((spacing - 10.0).abs() < 1e-6, "{spacing}"); + } + + /// Stair Step's glyphs stay upright, each origin on the path, its step the path's length to the + /// next. On a circle of radius 100 with spacing 10, each step is 100/110 of the glyph's advance; + /// moved 20 down by an alignment, the origins give the same spacing. + #[test] + fn the_spacing_of_stair_step_type_follows_the_origins_of_its_glyphs() { + let advances = [20.0, 30.0, 10.0, 25.0, 20.0]; + for rise in [0.0, 20.0] { + let mut s = 0.0; + let mut glyphs = vec![]; + for a in advances { + let angle = std::f64::consts::PI + s / 100.0; + // `line_layout` takes centres: half an advance along the level baseline. + glyphs.push((Point::new(100.0 * angle.cos() + a * 0.5, 100.0 * angle.sin() + rise), [1.0, 0.0, 0.0, 1.0])); + s += a * 100.0 / 110.0; + } + let spacing = path_spacing(&line_layout(&advances, &glyphs, ""), PathEffect::StairStep); + assert!((spacing - 10.0).abs() < 1e-6, "{rise}: {spacing}"); + } + // Two glyphs say nothing of how the path turns. + let two = line_layout(&advances[..2], &[(Point::new(0.0, 0.0), [1.0, 0.0, 0.0, 1.0]), (Point::new(30.0, 5.0), [1.0, 0.0, 0.0, 1.0])], ""); + assert_eq!(path_spacing(&two, PathEffect::StairStep), 0.0); + } + + /// With Ascender (baselines 20 towards the feet), glyphs facing left lie outside the path and + /// glyphs facing right inside it. The pair either side of where the path runs straight up is left + /// out, and the others give spacing 10. + #[test] + fn aligned_3d_ribbon_type_leaves_out_the_pair_where_the_path_turns_back() { + let advances = [20.0, 30.0, 10.0, 25.0, 20.0]; + let mut angle = std::f64::consts::PI - 0.5; + let mut glyphs = vec![]; + for (i, a) in advances.iter().enumerate() { + if i > 0 { + angle += (advances[i - 1] + a) * 0.5 / 110.0; + } + let along = kurbo::Vec2::new(-angle.sin(), angle.cos()); + let side = if along.x < 0.0 { -1.0 } else { 1.0 }; + let radius = 100.0 - 20.0 * side; + glyphs.push((Point::new(radius * angle.cos(), radius * angle.sin()), [side, 0.0, -along.y * side, along.x * side])); + } + let sides: Vec = glyphs.iter().map(|(_, m)| m[0]).collect(); + assert_eq!(sides, [-1.0, -1.0, -1.0, 1.0, 1.0]); + let spacing = path_spacing(&line_layout(&advances, &glyphs, "/0 << /0 [ 0 20 ] >>"), PathEffect::Ribbon3d); + assert!((spacing - 10.0).abs() < 1e-6, "{spacing}"); + } + /// The leading of the text object a story comes in as. fn leading_of(story: &Story) -> Option { let node = story.node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY)?; @@ -1021,6 +1929,21 @@ mod tests { assert_eq!(story("one\r", &[0.0], &Para::default()).line_leading(1.0), None); } + /// A `\x03` ends a line inside its paragraph: it comes in as a forced line break, and the + /// paragraph's style runs over it to the paragraph's end. + #[test] + fn a_soft_return_is_a_line_break_in_its_paragraph() { + let para = Para { space_before: 4.0, space_after: 2.0, first_indent: 6.0, ..Para::default() }; + let mut s = story("A\x03B\rC\r", &[0.0, 15.6, 31.2], ¶); + s.paras[1].1 = Para { left_indent: 3.0, ..para.clone() }; + let node = s.node(NodeId(1), 0, (0.0, 0.0), Affine::IDENTITY).unwrap(); + let NodeKind::Text(t) = &node.kind else { panic!("not text") }; + assert_eq!(t.plain_text(), "A\u{2028}B\nC"); + assert_eq!(t.paras.len(), 2, "{:?}", t.paras); + assert_eq!((t.paras[0].first_line_indent, t.paras[0].left_indent, t.paras[0].space_before), (6.0, 0.0, 4.0)); + assert_eq!((t.paras[1].first_line_indent, t.paras[1].left_indent), (6.0, 3.0)); + } + #[test] fn a_frame_too_short_for_its_first_line_is_made_taller() { // A heading in a frame as tall as its size: a line of the font it shows in here is taller. @@ -1046,4 +1969,229 @@ mod tests { let mut t = area(13.0); assert!(!story("Heading\r", &[], &Para::default()).fit_first_line(&mut t) && height(&t).unwrap().3 == 13.0); } + + #[test] + fn area_type_s_first_line_goes_where_the_file_lays_it_out() { + // GUARDS: area type's first baseline was the font's ascent below the frame's top, where the + // file's own layout (and its page) can have it higher: a heading came in lower than the page's. + let line = |a: (f64, f64), b: (f64, f64)| [a.0, a.1, a.0, a.1, b.0, b.1, b.0, b.1]; + let frame = vec![ + line((10.0, 20.0), (210.0, 20.0)), + line((210.0, 20.0), (210.0, 120.0)), + line((210.0, 120.0), (10.0, 120.0)), + line((10.0, 120.0), (10.0, 20.0)), + ]; + // The canvas is the document here: the art's y up, the document's down. + let (template, to_doc) = ((CANVAS_CENTRE, -CANVAS_CENTRE), Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0])); + let first = |s: &Story| { + let mut node = s.node(NodeId(0), 0, template, to_doc).unwrap(); + let placed = s.place_first_line(&mut node, 0, template, to_doc); + let NodeKind::Text(t) = node.kind else { panic!("area type") }; + let l = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + (placed, l.lines.first().map(|l| l.baseline), t.area.first_baseline) + }; + let mut s = story("Heading\r", &[], &Para::default()); + s.frames = vec![FrameKind::Area(frame, AreaFrame::default())]; + // Where this lays the line out on its own: the file agrees, and nothing changes. + s.lines = vec![(10.0, 20.0)]; + let (_, Some(own), _) = first(&s) else { panic!("a line") }; + s.lines = vec![(10.0, own)]; + assert_eq!(first(&s), (false, Some(own), vectorcraft_doc::FirstBaseline::Ascent)); + // Higher in the file: there. + s.lines = vec![(10.0, own - 3.0)]; + let (placed, at, fb) = first(&s); + assert!(placed && fb == vectorcraft_doc::FirstBaseline::Fixed, "{fb:?}"); + assert!(at.is_some_and(|y| (y - (own - 3.0)).abs() < 1e-6), "{at:?} for {}", own - 3.0); + } + + /// A text document's area frame, the rectangle 10, 20 to 210, 120 of the canvas, whose frame + /// data has `options` besides its kind, written by hand. + fn area_frame(options: &str) -> FrameKind { + let line = |a: (f64, f64), b: (f64, f64)| format!("{} {} {} {} {} {} {} {}", a.0, a.1, a.0, a.1, b.0, b.1, b.0, b.1); + let segments = [ + line((10.0, 20.0), (210.0, 20.0)), + line((210.0, 20.0), (210.0, 120.0)), + line((210.0, 120.0), (10.0, 120.0)), + line((10.0, 120.0), (10.0, 20.0)), + ]; + let doc = format!("/0 << /1 << /0 [ {} ] >> /2 << /0 1 {options} >> >>", segments.join(" ")); + let texts = Texts { + stories: vec![], + fonts: vec![], + defaults: Val::Dict(BTreeMap::new()), + para_defaults: Val::Dict(BTreeMap::new()), + char_sheets: vec![], + para_sheets: vec![], + frames: vec![read(doc.as_bytes()).unwrap()], + }; + texts.frame(0).unwrap() + } + + /// The area options of the text object a story of `frames` comes in as at frame `frame`, the + /// art's units `scale` document points each. + fn area_of(frames: Vec, frame: usize, scale: f64) -> vectorcraft_doc::AreaOptions { + let mut s = story("Some area type\r", &[], &Para::default()); + s.frames = frames; + let to_doc = Affine::scale(scale) * Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]); + let NodeKind::Text(t) = s.node(NodeId(0), frame, (CANVAS_CENTRE, -CANVAS_CENTRE), to_doc).unwrap().kind else { panic!("area type") }; + t.area + } + + #[test] + fn area_frame_options_are_read() { + // GUARDS: area type came in with one row, one column and the 18 pt gutter whatever its frame kept. + let a = area_of(vec![area_frame("/3 2 /4 3 /7 20 /8 24")], 0, 1.0); + assert_eq!((a.rows, a.columns, a.gutter, a.row_gutter), (2, 3, 24.0, Some(20.0))); + // The same gutter between rows and columns is one gutter. + let a = area_of(vec![area_frame("/3 2 /4 3 /7 20 /8 20")], 0, 1.0); + assert_eq!((a.gutter, a.row_gutter), (20.0, None)); + // Lengths scale with the art's units (a Large Canvas copy measures in tenths of the page). + let a = area_of(vec![area_frame("/7 2 /8 2.4 /10 << /0 3 /1 3 >>")], 0, 10.0); + assert!((a.gutter - 24.0).abs() < 1e-9 && a.row_gutter == Some(20.0), "{a:?}"); + assert!((a.first_baseline_min - 30.0).abs() < 1e-9, "{a:?}"); + } + + #[test] + fn area_frame_first_baseline_kinds_and_minimum_are_read() { + use vectorcraft_doc::FirstBaseline as F; + for (code, kind) in [(0, F::Fixed), (2, F::CapHeight), (3, F::Leading), (4, F::XHeight)] { + let a = area_of(vec![area_frame(&format!("/10 << /0 {code} /1 30 >>"))], 0, 2.0); + assert_eq!((a.first_baseline, a.first_baseline_min), (kind, 60.0), "code {code}"); + } + // A kind without its own first baseline here, or none known, leaves Ascent. + for code in ["1", "5", "6", "7", "-1", "2.5", "(x)"] { + let a = area_of(vec![area_frame(&format!("/10 << /0 {code} /1 30 >>"))], 0, 1.0); + assert_eq!((a.first_baseline, a.first_baseline_min), (F::Ascent, 0.0), "code {code}"); + } + // A minimum that can't be read is none. + let a = area_of(vec![area_frame("/10 << /0 3 /1 -4 >>")], 0, 1.0); + assert_eq!((a.first_baseline, a.first_baseline_min), (F::Leading, 0.0)); + } + + /// A first baseline the frame keeps stays as it is: the first line isn't moved to where the + /// file lays it out. + #[test] + fn a_first_baseline_the_frame_keeps_is_not_moved() { + let (template, to_doc) = ((CANVAS_CENTRE, -CANVAS_CENTRE), Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0])); + // Where this lays the first line out on its own. + let mut s = story("Heading\r", &[], &Para::default()); + s.frames = vec![area_frame("")]; + let NodeKind::Text(t) = s.node(NodeId(0), 0, template, to_doc).unwrap().kind else { panic!("area type") }; + let own = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).lines.first().map(|l| l.baseline).unwrap(); + let placed_in = |frames: &[&str]| { + let mut s = story("Heading\r", &[], &Para::default()); + s.frames = frames.iter().map(|o| area_frame(o)).collect(); + // Higher in the file. + s.lines = vec![(10.0, own - 3.0)]; + let mut node = s.node(NodeId(0), 0, template, to_doc).unwrap(); + let placed = s.place_first_line(&mut node, 0, template, to_doc); + let NodeKind::Text(t) = node.kind else { panic!("area type") }; + (placed, t.area.first_baseline) + }; + let placed = |options: &str| placed_in(&[options]); + assert_eq!(placed("/10 << /0 2 /1 0 >>"), (false, vectorcraft_doc::FirstBaseline::CapHeight)); + // Without one (Ascent), or with one that isn't read, the line goes where the file has it. + assert_eq!(placed(""), (true, vectorcraft_doc::FirstBaseline::Fixed)); + assert_eq!(placed("/10 << /0 5 /1 0 >>"), (true, vectorcraft_doc::FirstBaseline::Fixed)); + // Another frame of the thread keeping one doesn't count for the first. + assert_eq!(placed_in(&["", "/10 << /0 2 /1 0 >>"]), (true, vectorcraft_doc::FirstBaseline::Fixed)); + } + + #[test] + fn area_frame_options_that_cannot_be_read_keep_their_defaults() { + let defaults = vectorcraft_doc::AreaOptions::default(); + let bad = [ + "/3 0 /4 2.5 /7 -1 /8 (x)", + "/3 NaN /4 inf /7 NaN /8 -inf /10 [ 1 2 ]", + "/3 (2) /4 [ 3 ] /7 << /0 1 >> /8 true /10 3", + "/10 << /1 30 >>", + ]; + for options in bad { + assert_eq!(area_of(vec![area_frame(options)], 0, 1.0), defaults, "{options}"); + } + // Too many rows and columns, and too long gutters, are capped. + let a = area_of(vec![area_frame("/3 1e9 /4 101 /7 1e300 /8 5e4")], 0, 1.0); + assert_eq!((a.rows, a.columns, a.gutter, a.row_gutter), (100, 100, MAX_AREA_LENGTH, None)); + // The cap holds after the lengths scale with the art's units. + let a = area_of(vec![area_frame("/7 1e4 /8 2e3 /10 << /0 0 /1 1e4 >>")], 0, 10.0); + assert_eq!((a.gutter, a.row_gutter, a.first_baseline_min), (MAX_AREA_LENGTH, None, MAX_AREA_LENGTH)); + // One that can be read is read beside one that can't. + let a = area_of(vec![area_frame("/3 2 /4 -3 /8 12 /7 NaN")], 0, 1.0); + assert_eq!((a.rows, a.columns, a.gutter, a.row_gutter), (2, 1, 12.0, Some(18.0))); + } + + #[test] + fn area_frame_without_options_comes_in_as_before() { + assert_eq!(area_of(vec![area_frame("")], 0, 1.0), vectorcraft_doc::AreaOptions::default()); + assert_eq!(area_frame(""), FrameKind::Area(area_segments(), AreaFrame::default())); + } + + /// The segments [`area_frame`] writes. + fn area_segments() -> Vec<[f64; 8]> { + let line = |a: (f64, f64), b: (f64, f64)| [a.0, a.1, a.0, a.1, b.0, b.1, b.0, b.1]; + vec![ + line((10.0, 20.0), (210.0, 20.0)), + line((210.0, 20.0), (210.0, 120.0)), + line((210.0, 120.0), (10.0, 120.0)), + line((10.0, 120.0), (10.0, 20.0)), + ] + } + + #[test] + fn each_frame_of_a_thread_keeps_its_own_options() { + let frames = vec![area_frame("/3 2 /7 10 /8 10 /10 << /0 0 /1 12 >>"), area_frame("/4 3 /7 6 /8 8")]; + let (first, second) = (area_of(frames.clone(), 0, 1.0), area_of(frames, 1, 1.0)); + assert_eq!((first.rows, first.columns, first.gutter, first.row_gutter), (2, 1, 10.0, None)); + assert_eq!((first.first_baseline, first.first_baseline_min), (vectorcraft_doc::FirstBaseline::Fixed, 12.0)); + assert_eq!((second.rows, second.columns, second.gutter, second.row_gutter), (1, 3, 8.0, Some(6.0))); + assert_eq!(second.first_baseline, vectorcraft_doc::FirstBaseline::Ascent); + } + + /// Vertical area type: the file's first line is its first column's centre line, so far left of + /// the frame's right edge; the column goes there. + #[test] + fn vertical_area_type_s_first_column_goes_where_the_file_lays_it_out() { + let line = |a: (f64, f64), b: (f64, f64)| [a.0, a.1, a.0, a.1, b.0, b.1, b.0, b.1]; + let frame = vec![ + line((10.0, 20.0), (210.0, 20.0)), + line((210.0, 20.0), (210.0, 120.0)), + line((210.0, 120.0), (10.0, 120.0)), + line((10.0, 120.0), (10.0, 20.0)), + ]; + let (template, to_doc) = ((CANVAS_CENTRE, -CANVAS_CENTRE), Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0])); + // Whether the first line was placed, the first column's centre line (its x on the document) + // and the first baseline setting. + let first = |s: &Story, place: bool| { + let mut node = s.node(NodeId(0), 0, template, to_doc).unwrap(); + let placed = place && s.place_first_line(&mut node, 0, template, to_doc); + let NodeKind::Text(t) = node.kind else { panic!("area type") }; + assert!(t.vertical); + let l = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + (placed, l.baselines().first().map(|b| b.0.x), t.area.first_baseline) + }; + let mut s = story("§§\r", &[], &Para::default()); + s.frames = vec![FrameKind::Area(frame, AreaFrame::default())]; + s.vertical = true; + s.anchor = (210.0, 20.0); + s.lines = vec![(0.0, 0.0)]; + let (_, Some(own), _) = first(&s, false) else { panic!("a column") }; + assert!(own < 210.0 && own > 190.0, "near the right edge: {own}"); + // The file's column where this lays it out on its own (so far left of the anchor, the + // frame's top right): nothing changes. + s.lines = vec![(0.0, 210.0 - own)]; + assert_eq!(first(&s, true), (false, Some(own), vectorcraft_doc::FirstBaseline::Ascent)); + // Further right in the file: there. + s.lines = vec![(0.0, 210.0 - own - 3.0)]; + let (placed, at, fb) = first(&s, true); + assert!(placed && fb == vectorcraft_doc::FirstBaseline::Fixed, "{fb:?}"); + assert!(at.is_some_and(|x| (x - (own + 3.0)).abs() < 1e-6), "{at:?} for {}", own + 3.0); + // Scaled characters (a column of another width) go there too. + s.runs[0].1.v_scale = 2.0; + s.runs[0].1.h_scale = 2.0; + s.lines = vec![(0.0, 0.0)]; + let (_, Some(own), _) = first(&s, false) else { panic!("a column") }; + s.lines = vec![(0.0, 210.0 - own - 3.0)]; + let (placed, at, _) = first(&s, true); + assert!(placed && at.is_some_and(|x| (x - (own + 3.0)).abs() < 1e-6), "{at:?} for {}", own + 3.0); + } } diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index d049e39a9d..e3268b240a 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -1,15 +1,19 @@ use super::ops::MAX_DATA; use super::{ - DecodeSettings, Decoder, DecoderContext, DictRef, EncodingMode, ImageBlob, Key, Obj, PsError, Rc, Res, find, hex_decode, jpeg_components, ps, - ps_err, + DecodeSettings, Decoder, DecoderContext, DictRef, EncodingMode, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, + jpeg_components, ps, ps_err, }; /// A file object: the program itself, or data a filter decoded. #[derive(Debug)] pub(crate) enum Stream { Current, - /// Filters over the program's own data, decoded when first read. - Pending(Vec), + /// Filters over the data the program reads, decoded when first read, from the file they were + /// made over: a file being run (`from`), or else the program's own file. + Pending { + chain: Vec, + from: Option>>, + }, Buf { data: Vec, pos: usize, diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index 3b4046de91..4397a0e230 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -7,6 +7,8 @@ use super::{ /// Most bytes one filter or image reads. pub(super) const MAX_DATA: usize = 1 << 28; +/// The longest chain of filters over one pending file (real programs stack two or three). +const MAX_FILTER_CHAIN: usize = 64; /// Most pixels an image may have. const MAX_PIXELS: usize = 1 << 26; @@ -29,7 +31,10 @@ impl Interp<'_> { pub fn data_op(&mut self, op: Op) -> Res { use Op::*; match op { - CurrentFile => self.push(Obj::File { stream: Rc::new(RefCell::new(Stream::Current)), exec: false })?, + CurrentFile => { + let stream = self.running.last().cloned().unwrap_or_else(|| Rc::new(RefCell::new(Stream::Current))); + self.push(Obj::File { stream, exec: false })?; + } Filter => self.filter()?, ReadHexString | ReadString => { let s = self.pop_str()?; @@ -94,7 +99,7 @@ impl Interp<'_> { let n = match &*f.borrow() { Stream::Current => self.lex.rest().len(), Stream::Buf { data, pos, .. } => data.len().saturating_sub(*pos), - Stream::Pending(_) => 0, + Stream::Pending { .. } => 0, }; self.push(Obj::Int(n as i64))?; } @@ -163,18 +168,7 @@ impl Interp<'_> { self.push(o)?; } Obj::File { stream: f, .. } => { - self.materialize(&f)?; - let (o, immediate) = match &mut *f.borrow_mut() { - Stream::Current => (self.lex.next()?, self.lex.immediate), - Stream::Buf { data, pos, .. } => { - let rest = data.get(*pos..).unwrap_or_default(); - let mut lex = Lexer::new(rest); - let o = lex.next()?; - *pos += rest.len() - lex.data().len(); - (o, lex.immediate) - } - Stream::Pending(_) => (None, false), - }; + let (o, immediate) = self.next_in(&f)?; let Some(o) = o else { return self.push(Obj::Bool(false)) }; let o = self.scanned(o, immediate)?; self.push(o)?; @@ -184,6 +178,23 @@ impl Interp<'_> { self.push(Obj::Bool(true)) } + /// The next object in file `f` (`token`, and a file being run), read with the whitespace + /// after it, and whether it has `//name`s in it. + pub(in super::super) fn next_in(&mut self, f: &Rc>) -> Res<(Option, bool)> { + self.materialize(f)?; + Ok(match &mut *f.borrow_mut() { + Stream::Current => (self.lex.next()?, self.lex.immediate), + Stream::Buf { data, pos, .. } => { + let rest = data.get(*pos..).unwrap_or_default(); + let mut lex = Lexer::new(rest); + let o = lex.next()?; + *pos += rest.len() - lex.data().len(); + (o, lex.immediate) + } + Stream::Pending { .. } => (None, false), + }) + } + /// Up to `n` bytes of file `f`. fn read(&mut self, f: &Rc>, n: usize) -> Res> { self.materialize(f)?; @@ -201,7 +212,7 @@ impl Interp<'_> { *pos = end; data.get(start..end).unwrap_or_default().to_vec() } - Stream::Pending(_) => vec![], + Stream::Pending { .. } => vec![], }) } @@ -220,7 +231,7 @@ impl Interp<'_> { *pos += 1; } } - Stream::Pending(_) => {} + Stream::Pending { .. } => {} } } @@ -259,7 +270,9 @@ impl Interp<'_> { let name = self.pop()?.text().ok_or(PsError::Ps("typecheck", "filter".into()))?; let sub = if &*name == "SubFileDecode" { let eod = self.pop_str()?.to_vec(); - let count = self.pop_count()?; + // The count bounds what the filter reads, not what it allocates: a stream of several + // megabytes read through `currentfile N () /SubFileDecode filter` gives its length. + let count = usize::try_from(self.pop_int()?).map_err(|_| PsError::Ps("rangecheck", "a count".into()))?; (count, eod) } else { (0, vec![]) @@ -275,23 +288,37 @@ impl Interp<'_> { let spec = Filter { name, sub, predictor, fax }; let stream = match self.pop()? { Obj::File { stream: f, .. } => { - if let Stream::Buf { data, pos, .. } = &*f.borrow() { - self.alloc(data.len().saturating_sub(*pos))?; + // A filter over the program's own file or the file being run waits until it is + // first read, and keeps which of them it reads, wherever the program runs by then. + let running = self.running.last().is_some_and(|r| Rc::ptr_eq(r, &f)); + match &*f.borrow() { + Stream::Buf { data, pos, .. } if !running => self.alloc(data.len().saturating_sub(*pos))?, + _ => {} } - let chain = match &*f.borrow() { - Stream::Current => Some(vec![]), - Stream::Pending(c) => Some(c.clone()), + let pending = match &*f.borrow() { + Stream::Current => Some((vec![], None)), + Stream::Buf { .. } if running => Some((vec![], Some(f.clone()))), + Stream::Pending { chain, from } => { + // Cloning the chain copies each filter's delimiter: bound and charge it. + if chain.len() >= MAX_FILTER_CHAIN { + return Err(PsError::Limit("too many filters over one file")); + } + let copied = chain.iter().map(|c| c.sub.1.len() + 1).sum::(); + self.alloc(copied)?; + self.spend((copied / 256) as u64)?; + Some((chain.clone(), from.clone())) + } Stream::Buf { .. } => None, }; - match chain { - Some(mut c) => { + match pending { + Some((mut chain, from)) => { // The new filter reads a pending one's data: it has none left of its own // (`flushfile` on it skips nothing more). - if !c.is_empty() { + if !chain.is_empty() { *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; } - c.push(spec); - Stream::Pending(c) + chain.push(spec); + Stream::Pending { chain, from } } None => { let mut b = f.borrow_mut(); @@ -325,15 +352,6 @@ impl Interp<'_> { self.push(Obj::File { stream, exec: false }) } - /// The data an executable file runs as a program: what is left of it. `None` for the - /// program's own file, which is being run already. - pub(in super::super) fn program_of(&mut self, f: &Rc>) -> Res>> { - if matches!(&*f.borrow(), Stream::Current) { - return Ok(None); - } - self.read(f, MAX_DATA).map(Some) - } - /// The decoded data left in file `f`, without reading it (a shading's or function's data). pub(in super::super) fn peek_all(&mut self, f: &Rc>) -> Res> { self.materialize(f)?; @@ -343,20 +361,32 @@ impl Interp<'_> { }) } - /// Decode the filters a file waits to run over the program's data, from where it is now. - fn materialize(&mut self, f: &Rc>) -> Res { - let chain = match &*f.borrow() { - Stream::Pending(c) => c.clone(), + /// Decode the filters a file waits to run over the data the program reads, from where it is + /// now in the file they were made over: a file being run, or the program's own file. + pub(in super::super) fn materialize(&mut self, f: &Rc>) -> Res { + let (chain, from) = match &*f.borrow() { + Stream::Pending { chain, from } => (chain.clone(), from.clone()), _ => return Ok(()), }; let mut buf: Option<(Vec, Option)> = None; for spec in &chain { buf = Some(match buf.take() { None => { - let raw = self.lex.data(); - let (data, used, rgb) = decode(spec, raw)?; + let (data, rgb) = match &from { + Some(r) => { + let mut b = r.borrow_mut(); + let Stream::Buf { data, pos, .. } = &mut *b else { return io("filter") }; + let (out, used, rgb) = decode(spec, data.get(*pos..).unwrap_or_default())?; + *pos = pos.saturating_add(used); + (out, rgb) + } + None => { + let (out, used, rgb) = decode(spec, self.lex.data())?; + self.lex.advance(used); + (out, rgb) + } + }; self.charge_decoded(data.len())?; - self.lex.advance(used); (data, rgb) } Some((prev, was)) => { @@ -371,6 +401,30 @@ impl Interp<'_> { Ok(()) } + /// Skip the data an image left out (too large to read) would read from the program's own + /// file, so the program doesn't go on to read that data as PostScript. The filters that find + /// their own end without decompressing (`ASCIIHexDecode`, `ASCII85Decode`, `SubFileDecode`) + /// read the file up to it, the way the image reading all its data would leave it; the + /// filters over them, which would only decode what those pass, aren't run. When the first + /// filter decompresses, it is run alone, and a failure (data too large to hold) leaves the + /// data where it was, as before. + fn skip_data(&mut self, src: &Source) { + let Source::File(f) = src else { return }; + let (chain, from) = match &*f.borrow() { + Stream::Pending { chain, from } => (chain.clone(), from.clone()), + _ => return, + }; + let delimited = chain.iter().take_while(|c| matches!(&*c.name, "ASCIIHexDecode" | "ASCII85Decode" | "SubFileDecode")).count(); + let head = chain.get(..delimited.max(1)).unwrap_or_default().to_vec(); + *f.borrow_mut() = Stream::Pending { chain: head, from: from.clone() }; + // A failure leaves the file as it was; the import goes on without the image either way. + if self.materialize(f).is_err() { + *f.borrow_mut() = Stream::Pending { chain, from }; + return; + } + *f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None }; + } + /// The bytes a data procedure gives, called until it gives an empty string or `n` bytes. fn gather(&mut self, p: &Obj, n: usize) -> Res> { Ok(self.read_sources(&[Source::Proc(p.clone())], n, n)?.pop().unwrap_or_default()) @@ -418,10 +472,11 @@ impl Interp<'_> { Ok(out) } - /// `eexec`: an encrypted font program follows. It is skipped (type is drawn in the app's - /// fonts, by name): the font dictionary it would complete is defined as it is. + /// `file eexec`: an encrypted font program follows in `file`. It is skipped there, up to the + /// `cleartomark` that ends it (type is drawn in the app's fonts, by name): the font + /// dictionary it would complete is defined as it is. fn eexec(&mut self) -> Res { - self.pop()?; + let src = self.pop()?; if let Some(Obj::Dict(d)) = self.stack.last().cloned() { let name = d.borrow().get(&Key::name("FontName")).cloned(); if let Some(k) = name.and_then(|n| n.key()) { @@ -429,9 +484,24 @@ impl Interp<'_> { self.fonts.borrow_mut().insert(k, Obj::Dict(d)); } } - let rest = self.lex.data(); - let at = find(rest, b"cleartomark").ok_or(PsError::Ps("ioerror", "eexec".into()))?; - self.lex.advance(at); + // `currentfile eexec`: the program's own file or the file being run. A string operand + // skips in the file being read. + let f = match src { + Obj::File { stream, .. } => stream, + _ => self.running.last().cloned().unwrap_or_else(|| Rc::new(RefCell::new(Stream::Current))), + }; + self.materialize(&f)?; + let missing = || PsError::Ps("ioerror", "eexec".into()); + match &mut *f.borrow_mut() { + Stream::Buf { data, pos, .. } => { + let at = find(data.get(*pos..).unwrap_or_default(), b"cleartomark").ok_or_else(missing)?; + *pos += at; + } + _ => { + let at = find(self.lex.data(), b"cleartomark").ok_or_else(missing)?; + self.lex.advance(at); + } + } self.push(Obj::Mark) } @@ -474,6 +544,9 @@ impl Interp<'_> { let n = image.space.n(); if image.w.saturating_mul(image.h) > MAX_PIXELS || stencil.w.saturating_mul(stencil.h) > MAX_PIXELS { self.out.warn(TOO_LARGE); + for src in image.sources.iter().chain(&stencil.sources) { + self.skip_data(src); + } return Ok(None); } if interleave != 3.0 { @@ -580,6 +653,9 @@ impl Interp<'_> { } if s.w.saturating_mul(s.h) > MAX_PIXELS { self.out.warn(TOO_LARGE); + for src in &s.sources { + self.skip_data(src); + } return Ok(None); } self.alloc(s.w * s.h * 4)?; diff --git a/crates/eps/src/import/graphics.rs b/crates/eps/src/import/graphics.rs index bd6f252876..46fd148db9 100644 --- a/crates/eps/src/import/graphics.rs +++ b/crates/eps/src/import/graphics.rs @@ -21,9 +21,11 @@ mod ops; mod paint; mod path; mod state; +mod strips; pub(crate) use paint::collapse; pub(crate) use state::{GState, Out, Space, process}; +pub(crate) use strips::merge_strips; /// Most objects one file makes. const MAX_NODES: usize = 1 << 20; @@ -31,7 +33,7 @@ const MAX_NODES: usize = 1 << 20; /// are left out. const LIMIT: f64 = 1e6; /// Width of a zero-width line (the thinnest a device draws), points. -const HAIRLINE: f64 = 0.25; +pub(super) const HAIRLINE: f64 = 0.25; /// Most inks a `DeviceN` space has (PostScript's own limit). const MAX_INKS: usize = 32; /// Most dashes `strokepath` makes of a path (more and it outlines the path undashed). @@ -42,7 +44,7 @@ const MAX_DASH_ENTRIES: usize = 65_535; /// Most entries an indexed colour space's table has. const MAX_HIVAL: usize = 4095; /// Most elements the current path may have. -const MAX_PATH: usize = 1 << 20; +pub(crate) const MAX_PATH: usize = 1 << 20; /// Most path elements drawn in all (each object's clips and groups counting as elements too). const MAX_DRAWN: usize = 1 << 24; /// Samples taken of a shading function that isn't a plain interpolation. diff --git a/crates/eps/src/import/graphics/path.rs b/crates/eps/src/import/graphics/path.rs index f9580077e7..3d4f244dc9 100644 --- a/crates/eps/src/import/graphics/path.rs +++ b/crates/eps/src/import/graphics/path.rs @@ -193,7 +193,7 @@ impl Interp<'_> { // ---------- painting ---------- - pub(super) fn fill_path(&mut self, bp: BezPath, rule: FillRule) -> Res { + pub(in super::super) fn fill_path(&mut self, bp: BezPath, rule: FillRule) -> Res { if bp.elements().is_empty() || self.g.null { return Ok(()); } diff --git a/crates/eps/src/import/graphics/strips.rs b/crates/eps/src/import/graphics/strips.rs new file mode 100644 index 0000000000..9f0b39a24f --- /dev/null +++ b/crates/eps/src/import/graphics/strips.rs @@ -0,0 +1,323 @@ +//! Gradients a program paints as a row of abutting strips, each in one colour (the way many +//! PostScript writers draw a smooth shading at Level 2, which has no `shfill`), read as one +//! linear gradient. +//! +//! Drawn one by one, abutting strips leave seams: a renderer that anti-aliases each fill lets the +//! art below show through along every shared edge (PDF 32000-1:2008 §10.6.4 notes the effect, +//! "conflation", for adjacent areas painted separately), which reads as thin stripes across the +//! gradient, and as a tint of the colour below over the whole of it where the strips are only a +//! pixel or two wide. A run of them under the same clips becomes one object filled with a linear +//! gradient through the strips' colours, which has no seams and stays editable. +//! +//! Only strips that clearly are a gradient merge: at least [`MIN_STRIPS`] parallelograms of one +//! length, side by side in one direction with no gap or overlap, each a small step in colour from +//! the one before ([`MAX_STEP`]). Abutting blocks of distinct colours (a bar chart, a row of +//! swatches) stay as they are. + +use super::{ + Affine, Appearance, AppearanceItem, BezPath, Color, Drawn, FillLayer, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, HashSet, + MAX_STITCH_STOPS, Node, NodeId, NodeKind, Paint, PathData, PathEl, Point, Vec2, +}; + +/// Fewest strips (that paint something) a gradient is read from. +const MIN_STRIPS: usize = 6; +/// Largest change of any colour component (0 to 1) from one strip to the next. +const MAX_STEP: f32 = 0.08; +/// How far apart corners may be and still meet (points). +const EPS: f64 = 0.01; +/// Largest change of any colour component a stop left out may make to the gradient. +const TOLERANCE: f32 = 0.5 / 255.0; + +/// A filled parallelogram in one process colour. +struct Strip { + corners: [Point; 4], + model: u8, + comps: [f32; 4], + color: Color, + overprint: bool, +} + +/// The parallelogram `n` fills, in one process colour: `None` for anything else. +fn strip_of(n: &Node) -> Option { + let NodeKind::Path { path, live: None, clipping: false, guide: false, .. } = &n.kind else { return None }; + if n.appearance.items.len() != 1 { + return None; + } + let Some(AppearanceItem::Fill(f)) = n.appearance.items.first() else { return None }; + if f.opacity != 1.0 || !f.visible || !f.effects.is_empty() || f.blend != vectorcraft_color::BlendMode::Normal { + return None; + } + let Paint::Solid { color, swatch: None, .. } = &f.paint else { return None }; + let (model, comps) = match *color { + Color::Rgb { r, g, b } => (0, [r, g, b, 0.0]), + Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]), + Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]), + Color::Lab { .. } => return None, + }; + let [sp] = path.subpaths.as_slice() else { return None }; + let mut pts: Vec = Vec::with_capacity(5); + for a in &sp.anchors { + if a.h_in != a.p || a.h_out != a.p { + return None; + } + pts.push(a.p); + } + if pts.len() == 5 && pts.first().zip(pts.last()).is_some_and(|(a, b)| a.distance(*b) <= EPS) { + pts.pop(); + } + let [a, b, c, d] = pts.as_slice() else { return None }; + // Opposite corners share a midpoint. + if (a.to_vec2() + c.to_vec2() - b.to_vec2() - d.to_vec2()).hypot() > EPS { + return None; + } + Some(Strip { corners: [*a, *b, *c, *d], model, comps, color: *color, overprint: f.overprint }) +} + +/// The edge two strips share, as it runs along the first: `(k, from, to)`, from its corner `k`. +fn shared_edge(a: &Strip, b: &Strip) -> Option<(usize, Point, Point)> { + let near = |p: Point, q: Point| p.distance(q) <= EPS; + for k in 0..4 { + let (p, q) = (a.corners[k], a.corners[(k + 1) % 4]); + if p.distance(q) <= EPS { + continue; + } + for j in 0..4 { + let (r, s) = (b.corners[j], b.corners[(j + 1) % 4]); + if (near(p, r) && near(q, s)) || (near(p, s) && near(q, r)) { + return Some((k, p, q)); + } + } + } + None +} + +/// Coordinates along a run of strips: a point is `o + s·w + t·v`, `v` along the strips (their +/// shared edges run from `t` = 0 to 1), `w` across them. +struct Axes { + o: Point, + w: Vec2, + v: Vec2, + inv: Affine, +} + +impl Axes { + fn of(a: &Strip, b: &Strip) -> Option { + let (k, from, to) = shared_edge(a, b)?; + let w = a.corners[(k + 2) % 4] - a.corners[(k + 1) % 4]; + let v = to - from; + let m = Affine::new([w.x, w.y, v.x, v.y, from.x, from.y]); + if w.hypot() <= EPS || m.determinant().abs() < 1e-9 * w.hypot() * v.hypot() { + return None; + } + Some(Self { o: from, w, v, inv: m.inverse() }) + } + + fn at(&self, s: f64, t: f64) -> Point { + self.o + self.w * s + self.v * t + } + + /// Does `p` lie within the run's length, and across it from `lo` to `hi`? + fn holds(&self, p: Point, lo: f64, hi: f64) -> bool { + let (ts, ss) = (EPS / self.v.hypot(), EPS / self.w.hypot()); + let l = self.inv * p; + l.x >= lo - ss && l.x <= hi + ss && l.y >= -ts && l.y <= 1.0 + ts + } + + /// The strip's extent across the run (`s` from, to), when it spans the run's length exactly. + fn band(&self, st: &Strip) -> Option<(f64, f64)> { + let (ts, ss) = (EPS / self.v.hypot(), EPS / self.w.hypot()); + let local: Vec = st.corners.iter().map(|p| self.inv * *p).collect(); + let lo = local.iter().map(|p| p.x).fold(f64::INFINITY, f64::min); + let hi = local.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max); + let fits = local + .iter() + .all(|p| ((p.y).abs() <= ts || (p.y - 1.0).abs() <= ts) && ((p.x - lo).abs() <= ss || (p.x - hi).abs() <= ss) && p.x.is_finite()); + // Each end of the strip touches both edges of the run. + let ends = [0.0, 1.0].iter().all(|t| local.iter().filter(|p| (p.y - t).abs() <= ts).count() == 2); + (fits && ends).then_some((lo, hi)) + } +} + +/// A run of strips found at one place in what was drawn: where it ends (exclusive), the object +/// it becomes, and whether that object covers the clip around it (so the clip path filled with +/// the gradient paints no more than the strips did). +struct Run { + start: usize, + end: usize, + node: Node, + covers_clip: bool, +} + +/// Is `s` (from, to) too thin to paint anything? +fn thin(b: (f64, f64), axes: &Axes) -> bool { + (b.1 - b.0) * axes.w.hypot() <= EPS +} + +/// The run of strips starting at `i`, if one does. +fn run_at(drawn: &Drawn, strips: &[Option], i: usize) -> Option { + let chain = |k: usize| drawn.get(k).map(|(c, _)| c.iter().map(|c| c.id).collect::>()); + let here = chain(i)?; + let strip = |k: usize| strips.get(k).and_then(Option::as_ref).filter(|_| chain(k).as_ref() == Some(&here)); + let first = strip(i)?; + // The run's axes come from its first two strips that paint something; a line before them + // (a strip of no width, as some writers draw first) joins the run where it lies on its edge. + let (lead, a, b) = match (strip(i + 1), strip(i + 2)) { + (Some(b), _) if Axes::of(first, b).is_some_and(|ax| ax.band(first).is_some_and(|f| !thin(f, &ax))) => (None, first, b), + (Some(a), Some(b)) => (Some(first), a, b), + _ => return None, + }; + let axes = Axes::of(a, b)?; + let (ba, bb) = (axes.band(a)?, axes.band(b)?); + if thin(ba, &axes) || thin(bb, &axes) { + return None; + } + let ss = EPS / axes.w.hypot(); + let forward = if (bb.0 - ba.1).abs() <= ss { + true + } else if (bb.1 - ba.0).abs() <= ss { + false + } else { + return None; + }; + let mut edge = if forward { ba.0 } else { ba.1 }; + if let Some(l) = lead { + let lb = axes.band(l)?; + if !thin(lb, &axes) || (lb.0 - edge).abs() > ss { + return None; + } + } + let at = i + usize::from(lead.is_some()); + let mut bands: Vec<(f64, f64, &Strip)> = vec![]; + let mut end = at; + while bands.len() < MAX_STITCH_STOPS { + let Some(st) = strip(end) else { break }; + let Some(band) = axes.band(st) else { break }; + let meets = if forward { (band.0 - edge).abs() <= ss } else { (band.1 - edge).abs() <= ss }; + if !meets || st.overprint != a.overprint { + break; + } + if !thin(band, &axes) { + if let Some((_, _, prev)) = bands.last() + && (prev.model != st.model || prev.comps.iter().zip(&st.comps).any(|(x, y)| (x - y).abs() > MAX_STEP)) + { + break; + } + bands.push((band.0, band.1, st)); + } + edge = if forward { band.1 } else { band.0 }; + end += 1; + } + if bands.len() < MIN_STRIPS { + return None; + } + let lo = bands.iter().map(|b| b.0).fold(f64::INFINITY, f64::min); + let hi = bands.iter().map(|b| b.1).fold(f64::NEG_INFINITY, f64::max); + if !(hi - lo).is_finite() || hi - lo <= 0.0 { + return None; + } + bands.sort_by(|x, y| x.0.total_cmp(&y.0)); + let stops: Vec<(f32, &Strip)> = bands.iter().map(|(s0, s1, st)| ((((s0 + s1) / 2.0 - lo) / (hi - lo)) as f32, *st)).collect(); + let stops: Vec = simplify(&stops).into_iter().map(|(t, st)| GradientStop::new(t, st.color)).collect(); + // The gradient runs across the strips, square to them, from the run's edge at `lo`. + let len = axes.v.hypot(); + let mut n = Vec2::new(-axes.v.y / len, axes.v.x / len); + let across = axes.w.dot(n) * (hi - lo); + if across < 0.0 { + n = -n; + } + let start = axes.at(lo, 0.0); + let mut g = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); + g.geom = Some(GradientGeom { start, end: start + n * across.abs(), aspect: 1.0, focal: None }); + let mut bp = BezPath::new(); + bp.move_to(axes.at(lo, 0.0)); + bp.line_to(axes.at(hi, 0.0)); + bp.line_to(axes.at(hi, 1.0)); + bp.line_to(axes.at(lo, 1.0)); + bp.close_path(); + let item = AppearanceItem::Fill(FillLayer { overprint: a.overprint, ..FillLayer::new(Paint::Gradient(Box::new(g))) }); + let (clips, first_node) = drawn.get(i)?; + // Every point of a clip's path, control points included, inside the run: its curves are too + // (each lies in the hull of its points), and the run's area is convex. + let covers_clip = clips.last().and_then(|c| c.region.as_ref()).is_some_and(|(clip, _)| { + clip.elements().iter().all(|el| match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => axes.holds(p, lo, hi), + PathEl::QuadTo(a, p) => axes.holds(a, lo, hi) && axes.holds(p, lo, hi), + PathEl::CurveTo(a, b, p) => axes.holds(a, lo, hi) && axes.holds(b, lo, hi) && axes.holds(p, lo, hi), + PathEl::ClosePath => true, + }) + }); + let node = Node::path(first_node.id, PathData::from_bezpath(&bp), Appearance { items: vec![item], ..Appearance::default() }); + Some(Run { start: i, end, node, covers_clip }) +} + +/// The stops `stops` (offset, strip) needs: those the gradient between the stops kept on either +/// side wouldn't come within [`TOLERANCE`] of are kept. +fn simplify<'a>(stops: &[(f32, &'a Strip)]) -> Vec<(f32, &'a Strip)> { + let mut kept: Vec<(f32, &Strip)> = vec![]; + let Some(&first) = stops.first() else { return kept }; + kept.push(first); + let mut from = 0; + while from + 1 < stops.len() { + // The furthest stop reachable from `from` with every stop between on the line. + let mut to = from + 1; + while to + 1 < stops.len() && on_line(stops, from, to + 1) { + to += 1; + } + if let Some(&s) = stops.get(to) { + kept.push(s); + } + from = to; + } + kept +} + +/// Do the stops between `a` and `b` lie on the blend between those two? +fn on_line(stops: &[(f32, &Strip)], a: usize, b: usize) -> bool { + let (Some((ta, sa)), Some((tb, sb))) = (stops.get(a), stops.get(b)) else { return false }; + let span = tb - ta; + stops.get(a + 1..b).unwrap_or_default().iter().all(|(t, s)| { + let f = if span > 0.0 { (t - ta) / span } else { 0.0 }; + sa.comps.iter().zip(&sb.comps).zip(&s.comps).all(|((x, y), z)| (x + (y - x) * f - z).abs() <= TOLERANCE) + }) +} + +/// Runs of strips in `drawn` become one gradient-filled object each; one that covers its clip is +/// marked in `shadings`, so a clipping group of nothing else is its clip path filled with the +/// gradient (a clip larger than the strips keeps clipping the gradient to them). +pub(crate) fn merge_strips(drawn: &mut Drawn, shadings: &mut HashSet) { + let strips: Vec> = drawn.iter().map(|(_, n)| strip_of(n)).collect(); + if strips.iter().filter(|s| s.is_some()).count() < MIN_STRIPS { + return; + } + let mut runs: Vec = vec![]; + let mut i = 0; + while i < drawn.len() { + match run_at(drawn, &strips, i) { + Some(r) => { + i = r.end.max(i + 1); + runs.push(r); + } + None => i += 1, + } + } + if runs.is_empty() { + return; + } + let old = std::mem::take(drawn); + let mut runs = runs.into_iter().peekable(); + let mut skip_to = 0; + for (k, item) in old.into_iter().enumerate() { + if k < skip_to { + continue; + } + if let Some(r) = runs.next_if(|r| r.start == k) { + skip_to = r.end; + if r.covers_clip { + shadings.insert(r.node.id); + } + drawn.push((item.0, r.node)); + continue; + } + drawn.push(item); + } +} diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 5e8d12661b..d3d9c2bdd0 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -4,16 +4,22 @@ //! Every operation counts against a budget and procedures nest only so deep, so a looping or //! recursing program ends with [`PsError::Limit`] instead of hanging. +use std::cell::RefCell; +use std::collections::HashSet; use std::rc::Rc; use vectorcraft_geom::Affine; +use super::data::Stream; use super::graphics::{GState, Out}; -use super::lex::{IMMEDIATE, Lexer}; +use super::lex::{IMMEDIATE, Lexer, number}; use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, Shared, ps_err}; -/// Most operations one file may run. +/// Most operations one file may run, whatever its length. const MAX_OPS: u64 = 50_000_000; +/// More operations a file may run for each byte of its program: a large file that draws a lot +/// runs proportionally more, and stays bounded by its length. +const OPS_PER_BYTE: u64 = 64; /// Deepest procedure nesting. const MAX_DEPTH: u32 = 400; /// Most operands on the stack. @@ -24,6 +30,8 @@ pub(crate) const MAX_ALLOC: usize = 1 << 22; const MAX_DICTS: usize = 1000; /// Most saved graphics states. pub(crate) const MAX_GSAVE: usize = 1000; +/// Most read-only procedures remembered (see `Interp::readonly`); each keeps its procedure. +const MAX_READONLY: usize = 1 << 16; /// Most memory (bytes) a program may ask for in all: strings, arrays, decoded data, images, /// saved paths. const MAX_MEMORY: usize = 1 << 30; @@ -32,6 +40,9 @@ pub(crate) struct Interp<'a> { /// The list of the arrays and dictionaries made since this started ([`super::obj::track`]). made: u64, pub lex: Lexer<'a>, + /// The files being run (`cvx exec`), innermost last: the program reads from the last one, and + /// it is `currentfile` while it runs. + pub running: Vec>>, pub stack: Vec, pub dicts: Vec, system: DictRef, @@ -47,6 +58,8 @@ pub(crate) struct Interp<'a> { resources: DictRef, depth: u32, ops: u64, + /// Most operations this program may run: [`MAX_OPS`] and [`OPS_PER_BYTE`] for each byte. + max_ops: u64, /// Bytes asked for so far (see [`MAX_MEMORY`]). allocated: usize, seed: u32, @@ -60,12 +73,23 @@ pub(crate) struct Interp<'a> { pub fault: Option, /// The width a Type 3 glyph procedure gave (`setcachedevice`, `setcharwidth`). pub glyph_width: Option<[f64; 2]>, + /// The TrueType data of the Type 42 fonts drawn so far, by their `sfnts` array (see + /// `type42`; `None` when it can't be read), the most recently used last. + pub type42: Type42Cache, + /// The `sfnts` arrays whose TrueType data has been counted against [`MAX_MEMORY`]: a font + /// read again after it left `type42` doesn't count again. + pub type42_counted: HashSet>, pub g: GState, pub saved: Vec, pub out: Out, /// The program is in the legacy Illustrator format: its group operators `u` … `U` (at the top /// level, whatever its prolog defines them as) are groups (see the module docs of `import`). pub illustrator: bool, + /// Procedures that are read-only: those `bind` went into inside another procedure, and those + /// given to `readonly`, `executeonly` or `noaccess`. `bind` leaves them alone (PLRM 3rd ed., + /// `bind` in chapter 8), so a procedure bound when it was defined keeps the names it didn't + /// bind then, whatever operators they name by the time a later procedure that holds it is bound. + readonly: HashSet>, } /// Where a PostScript error was raised: the operator that raised it (none for an unknown name) @@ -76,6 +100,9 @@ pub(crate) struct Fault { pub procs: Vec>, } +/// The TrueType data of Type 42 fonts by their `sfnts` array (see [`Interp::type42`]). +pub(crate) type Type42Cache = Vec<(Shared, Option>>)>; + /// Most procedure names a [`Fault`] keeps. const FAULT_PROCS: usize = 3; @@ -105,13 +132,18 @@ impl<'a> Interp<'a> { pub fn new(src: &'a [u8], g: GState, out: Out) -> Self { let made = super::obj::track(); let system = new_dict(); + // The standard encodings are also instances of the Encoding category, the same arrays + // (PLRM 3rd ed., §3.9.2 and `findencoding`, ). + let encodings = new_dict(); { let mut d = system.borrow_mut(); for (op, name) in Op::ALL { d.insert(Key::name(name), Obj::Op(*op)); } for name in ["StandardEncoding", "ISOLatin1Encoding"] { - d.insert(Key::name(name), encoding()); + let e = encoding(); + d.insert(Key::name(name), e.clone()); + encodings.borrow_mut().insert(Key::name(name), e); } // An integer, as interpreters have it (`systemdict /languagelevel get 2 ge`): run, the // name pushes it all the same. @@ -122,6 +154,7 @@ impl<'a> Interp<'a> { CATEGORIES.split_whitespace().map(|c| (Key::name(c), Obj::dict(Dict::from([(Key::name("Category"), Obj::name(c))])))).collect(); let resources = new_dict(); resources.borrow_mut().insert(Key::name("Category"), Obj::dict(categories)); + resources.borrow_mut().insert(Key::name("Encoding"), Obj::Dict(encodings)); let fonts = new_dict(); system.borrow_mut().insert(Key::name("FontDirectory"), Obj::Dict(fonts.clone())); for name in ["GlobalFontDirectory", "SharedFontDirectory"] { @@ -145,6 +178,7 @@ impl<'a> Interp<'a> { Self { made, lex: Lexer::new(src), + running: vec![], stack: vec![], dicts: vec![system.clone(), global.clone(), user.clone()], system, @@ -157,16 +191,20 @@ impl<'a> Interp<'a> { resources, depth: 0, ops: 0, + max_ops: MAX_OPS.saturating_add((src.len() as u64).saturating_mul(OPS_PER_BYTE)), allocated: 0, seed: 1, saves: vec![], journal: vec![], fault: None, glyph_width: None, + type42: vec![], + type42_counted: HashSet::new(), g, saved: vec![], out, illustrator: false, + readonly: HashSet::new(), } } @@ -333,11 +371,17 @@ impl<'a> Interp<'a> { self.spend(1) } - /// Count `ops` operations' worth of work against [`MAX_OPS`]: what an operator that costs + /// Charge for work on `n` bytes or objects in one operator: one operation per 256, as `search` + /// charges per 64 bytes, so a loop of big copies runs out of the budget. + pub fn spend_bytes(&mut self, n: usize) -> Res { + self.spend((n / 256) as u64) + } + + /// Count `ops` operations' worth of work against the budget (`max_ops`): what an operator that costs /// far more than one operation (laying out type) does in a loop has to end too. pub fn spend(&mut self, ops: u64) -> Res { self.ops = self.ops.saturating_add(ops); - if self.ops > MAX_OPS { + if self.ops > self.max_ops { return Err(PsError::Limit("the program runs too long")); } Ok(()) @@ -376,10 +420,7 @@ impl<'a> Interp<'a> { pub fn call(&mut self, v: Obj) -> Res { match v { Obj::Array { items, exec: true } => self.run_proc(&items), - Obj::File { stream, exec: true } => match self.program_of(&stream)? { - Some(program) => self.run_program(&program), - None => Ok(()), - }, + Obj::File { stream, exec: true } => self.run_file(&stream), Obj::ExecStr(s) => self.run_program(&s.to_vec()), // Through the depth guard: `stopped` and the like call back into here. Obj::Op(op) => { @@ -416,7 +457,35 @@ impl<'a> Interp<'a> { r } - /// Run `program` (what is left of an executable file, an executable string), token by token. + /// Run file `f` (`cvx exec`), reading its objects from it as it goes. While it runs it is + /// `currentfile`, the topmost file being run (PLRM 3rd ed., `currentfile`, ), + /// so data the program reads from there (an inline image's samples) comes from `f`, after the + /// object that reads it. The program's own file is being run already. + fn run_file(&mut self, f: &Rc>) -> Res { + if matches!(&*f.borrow(), Stream::Current) { + return Ok(()); + } + // Its data, decoded from the program it was made over, before it becomes the program. + self.materialize(f)?; + self.enter()?; + self.running.push(f.clone()); + let r = loop { + match self.next_in(f) { + Ok((Some(o), immediate)) => { + if let Err(e) = self.scanned(o, immediate).and_then(|o| self.exec_token(o)) { + break Err(e); + } + } + Ok((None, _)) => break Ok(()), + Err(e) => break Err(e), + } + }; + self.running.pop(); + self.depth -= 1; + r + } + + /// Run `program` (an executable string), token by token. fn run_program(&mut self, program: &[u8]) -> Res { self.enter()?; let mut lex = Lexer::new(program); @@ -661,6 +730,7 @@ impl<'a> Interp<'a> { let n = self.pop_count()?; let at = self.stack.len().checked_sub(n).ok_or(PsError::Ps("rangecheck", String::new()))?; if n > 0 { + self.spend_bytes(n)?; let k = j.rem_euclid(n as i64) as usize; if let Some(s) = self.stack.get_mut(at..) { s.rotate_right(k); @@ -687,6 +757,7 @@ impl<'a> Interp<'a> { self.pop_to_mark()?; } CountToMark => { + self.spend_bytes(self.stack.len())?; let n = self.stack.iter().rev().position(|o| matches!(o, Obj::Mark)).ok_or(PsError::Ps("unmatchedmark", String::new()))?; self.push(Obj::Int(n as i64))?; } @@ -721,7 +792,7 @@ impl<'a> Interp<'a> { }, Cvi => { let v = match self.pop()? { - Obj::Str(s) => String::from_utf8_lossy(&s.borrow()).trim().parse::().map_err(|_| PsError::Ps("typecheck", String::new()))?, + Obj::Str(s) => string_number(&s.borrow())?, o => o.as_num().ok_or(PsError::Ps("typecheck", String::new()))?, }; if !(v.is_finite() && v.abs() < 9e15) { @@ -731,7 +802,7 @@ impl<'a> Interp<'a> { } Cvr => { let v = match self.pop()? { - Obj::Str(s) => String::from_utf8_lossy(&s.borrow()).trim().parse::().map_err(|_| PsError::Ps("typecheck", String::new()))?, + Obj::Str(s) => string_number(&s.borrow())?, o => o.as_num().ok_or(PsError::Ps("typecheck", String::new()))?, }; self.push_num(v)?; @@ -771,7 +842,7 @@ impl<'a> Interp<'a> { }, Bitshift => { let (s, v) = (self.pop_int()?, self.pop_int()?); - let r = if s >= 0 { v.checked_shl(s.min(63) as u32) } else { v.checked_shr((-s).min(63) as u32) }; + let r = if s >= 0 { v.checked_shl(s.min(63) as u32) } else { v.checked_shr(s.saturating_neg().min(63) as u32) }; self.push(Obj::Int(r.unwrap_or(0)))?; } True => self.push(Obj::Bool(true))?, @@ -860,6 +931,7 @@ impl<'a> Interp<'a> { } Cvn => { let s = self.pop_str()?; + self.spend_bytes(s.len())?; // The name is a copy of the string (a bigger one when bytes are replaced). self.alloc(s.len().saturating_mul(3))?; let n: Rc = Rc::from(String::from_utf8_lossy(&s.borrow()).as_ref()); @@ -882,10 +954,9 @@ impl<'a> Interp<'a> { } self.push_interval(Obj::Str(s), 0, text.len())?; } - ReadOnly | ExecuteOnly | NoAccess | SetPacking | SetGlobal | SetObjectFormat => { - if matches!(op, SetPacking | SetGlobal | SetObjectFormat) { - self.pop()?; - } + ReadOnly | ExecuteOnly | NoAccess => self.restrict_access(), + SetPacking | SetGlobal | SetObjectFormat => { + self.pop()?; } Rcheck | Wcheck => { self.pop()?; @@ -966,8 +1037,14 @@ impl<'a> Interp<'a> { let src = self.pop()?; let at = self.pop_count()?; let written = match (self.pop()?, src) { - (Obj::Array { items, .. }, Obj::Array { items: from, .. }) => items.write(at, &from.to_vec()), - (Obj::Str(s), Obj::Str(from)) => s.write(at, &from.to_vec()), + (Obj::Array { items, .. }, Obj::Array { items: from, .. }) => { + self.spend_bytes(from.len())?; + items.write(at, &from.to_vec()) + } + (Obj::Str(s), Obj::Str(from)) => { + self.spend_bytes(from.len())?; + s.write(at, &from.to_vec()) + } _ => return ps_err("typecheck", ""), }; if !written { @@ -1029,10 +1106,10 @@ impl<'a> Interp<'a> { self.insert(&d, k, Some(v))?; } Known => { - let k = self.pop()?.key().ok_or(PsError::Ps("typecheck", String::new()))?; + let k = self.pop()?; let d = self.pop_dict()?; - let known = d.borrow().contains_key(&k); - self.push(Obj::Bool(known))?; + let found = known(&d, &k)?; + self.push(Obj::Bool(found))?; } Where => { let k = self.pop()?.key().ok_or(PsError::Ps("typecheck", String::new()))?; @@ -1120,9 +1197,12 @@ impl<'a> Interp<'a> { PdfMark => { self.pop_to_mark()?; } + // True for a simple object, and for a composite one in global VM (PLRM 3rd ed., `gcheck`); + // every composite here is in local VM. Procsets that copy values into global VM leave + // alone those whose `gcheck` is true, such as a halftone's numbers. Gcheck | Scheck => { - self.pop()?; - self.push(Obj::Bool(false))?; + let simple = !self.pop()?.is_composite(); + self.push(Obj::Bool(simple))?; } CurrentShared => self.push(Obj::Bool(false))?, SetShared | SetVmThreshold | VmReclaim | Echo => { @@ -1171,6 +1251,7 @@ impl<'a> Interp<'a> { /// The objects above the topmost mark, which is removed. fn pop_to_mark(&mut self) -> Res> { + self.spend_bytes(self.stack.len())?; let at = self.stack.iter().rposition(|o| matches!(o, Obj::Mark)).ok_or(PsError::Ps("unmatchedmark", String::new()))?; let items = self.stack.split_off(at + 1); self.stack.pop(); @@ -1202,6 +1283,7 @@ impl<'a> Interp<'a> { } Obj::Str(s) => { let from = self.pop_str()?.to_vec(); + self.spend_bytes(from.len())?; if !s.write(0, &from) { return ps_err("rangecheck", "copy"); } @@ -1270,7 +1352,7 @@ impl<'a> Interp<'a> { /// Replace the names in a procedure that stand for operators by the operators, down through /// nested procedures. fn bind(&mut self, items: &Shared, depth: u32) -> Res { - if depth > 64 { + if depth > 64 || self.readonly.contains(items) { return Ok(()); } for i in 0..items.len() { @@ -1283,13 +1365,34 @@ impl<'a> Interp<'a> { items.write(i, &[o]); } } - Some(Obj::Array { items: inner, exec: true }) if !inner.shares(items) => self.bind(&inner, depth + 1)?, + Some(Obj::Array { items: inner, exec: true }) if !inner.shares(items) => { + self.bind(&inner, depth + 1)?; + // `bind` makes each procedure it goes into read-only. + self.mark_readonly(inner); + } _ => {} } } Ok(()) } + /// `readonly`, `executeonly`, `noaccess`: the object stays on the stack; a procedure is + /// recorded as read-only, the only access the reader keeps (for `bind`). + fn restrict_access(&mut self) { + if let Some(Obj::Array { items, exec: true }) = self.stack.last() { + let items = items.clone(); + self.mark_readonly(items); + } + } + + /// Record procedure `items` as read-only, for [`Self::bind`]. Past [`MAX_READONLY`] of them + /// the rest stay writable: a later `bind` may then bind their names, as it did before. + fn mark_readonly(&mut self, items: Shared) { + if self.readonly.len() < MAX_READONLY { + self.readonly.insert(items); + } + } + /// Put `v` under `k` in `d` (`None`: remove it), within [`MAX_ALLOC`] entries; while a `save` /// is open the old value is kept for `restore`. fn insert(&mut self, d: &DictRef, k: Key, v: Option) -> Res { @@ -1385,6 +1488,17 @@ impl<'a> Interp<'a> { } /// An array or string index. +/// The number a string holds by the PostScript syntax (`cvi`, `cvr`: PLRM 3rd ed., chapter 8), +/// radix numbers such as `16#20` included. +fn string_number(s: &[u8]) -> Res { + let text = String::from_utf8_lossy(s); + match number(text.trim_matches(|c: char| c.is_ascii_whitespace() || c == '\0')) { + Some(Obj::Int(i)) => Ok(i as f64), + Some(Obj::Real(r)) => Ok(r), + _ => ps_err("typecheck", ""), + } +} + fn index(k: &Obj) -> Res { match *k { Obj::Int(i) if i >= 0 => Ok(i as usize), @@ -1392,6 +1506,17 @@ fn index(k: &Obj) -> Res { } } +/// `known`: a key may be any object but null (PLRM 3rd ed., §3.3.9, ), +/// and one that can't be a key here (an array, a dictionary, a real with a fraction) is in no +/// dictionary, since `put` here refuses it. +fn known(d: &DictRef, k: &Obj) -> Res { + match k.key() { + Some(key) => Ok(d.borrow().contains_key(&key)), + None if matches!(k, Obj::Null) => ps_err("typecheck", "known"), + None => Ok(false), + } +} + /// `eq`: numbers by value, strings and names by text, composites by identity. fn equal(a: &Obj, b: &Obj) -> bool { match (a, b) { diff --git a/crates/eps/src/import/lex.rs b/crates/eps/src/import/lex.rs index 57d3e73e24..e01b90c23e 100644 --- a/crates/eps/src/import/lex.rs +++ b/crates/eps/src/import/lex.rs @@ -276,7 +276,7 @@ pub(crate) fn hex_decode(body: &[u8]) -> Option> { } /// A number token (`12`, `-3.5`, `.5`, `1e-3`, `16#ff`), or `None`. -fn number(w: &str) -> Option { +pub(crate) fn number(w: &str) -> Option { let first = w.bytes().next()?; if !(first.is_ascii_digit() || matches!(first, b'+' | b'-' | b'.')) { return None; diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index 42f968faa5..a7858e46b2 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -12,16 +12,20 @@ //! colours, gradients, transparency and images of the art. //! //! Text objects are slots in that document: their characters, fonts and places are in the file's -//! text document (see `ate`). Type that shows comes from the page, which draws it, into the slot -//! whose text is where the page has it. Type that doesn't show (a hidden layer or object, or off -//! the page) is made from the text document; where that can't be read (area type, type on a path) -//! it's left out, with a warning. +//! text document (see `ate`). When the text document has the type of every text object that shows, +//! all the type is made from it, each text object in its own place, and the page's type is only +//! compared with it. Otherwise the type it has is still made from it, and the page's type that +//! lies elsewhere goes into the text objects it can't make, by where the text document puts their +//! lines or else in painting order. A text object whose type neither has (a frame of a kind it +//! doesn't read, on a hidden layer or object) is left out, with a warning. //! //! What a layer that shows has that `ai` doesn't read makes the file come in as its page, as it did //! before; on a layer that doesn't show it is left out of that layer, with a warning. The page is //! also the safety net: when the layers' art looks different from it (one draws an object the //! other doesn't, or much of it differs; an EPS whose page is its art's box has nothing printed -//! outside it), the page is used. +//! outside it), the page is used. A `.ai` whose text document makes all of its type, with no +//! object unread and nothing else that the page would decide, opens from its layers without its +//! PDF part being imported, so nothing is compared ([`ai_layers_alone`]). //! //! Where a file doesn't match what this module expects, it is left alone and its page is imported. @@ -30,7 +34,7 @@ use std::collections::BTreeSet; use std::sync::Arc; use vectorcraft_color::BlendMode; -use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, Scaling, TextKind, Unit}; +use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, Scaling, TextKind, Unit, VariableKind}; use vectorcraft_geom::{Affine, PathData, Point, Rect, Vec2}; use super::Imported; @@ -38,17 +42,21 @@ use super::ai::{self, Structure, slot_of}; use super::ate::{Story, Texts}; mod build; -mod compare; +pub(super) mod compare; mod layers; mod plan; mod slots; +pub(crate) use build::scale_document; #[cfg(test)] use build::{Frame, MADE, prune_unseen}; #[cfg(test)] -use compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour}; -pub use layers::{ai_alone, layered_ai}; +use compare::{ + MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour, +}; +pub use layers::{AiLayers, ai_alone, ai_alone_on_page, ai_layers_alone, ai_opened_artboard, layered_ai, layered_ai_from}; pub(super) use layers::{layered, program_alone}; +pub(crate) use slots::MAX_TEXT; pub use slots::is_loss; #[cfg(test)] use slots::join_pieces; @@ -86,9 +94,9 @@ mod tests { ring(&mut layers, Some(MADE), red, 6.0, square); ring(&mut layers, Some(MADE), red, 2.0, Rect::new(40.0, 40.0, 60.0, 60.0)); let rect = page.artboards[0].rect; - let frame = Frame { page: &page, page_rect: rect, rect, whole: false }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; let mut view = PageView::new(&frame); - assert_eq!(prune_unseen(&frame, &mut view, &mut layers), 1, "only the ring the page doesn't draw"); + assert_eq!(prune_unseen(&frame, &mut view, &mut layers, false), 1, "only the ring the page doesn't draw"); let widths: Vec = layers.layers[0].children().unwrap().iter().filter_map(|n| n.appearance.stroke().map(|s| s.width)).collect(); assert_eq!(widths, [12.0, 6.0]); // Taken by lightness alone, the red and the dark red are alike. @@ -99,6 +107,33 @@ mod tests { assert!(!differ(&px(dark), &px(red)) && differ_in_colour(&px(dark), &px(red))); } + /// The share of a rectangle's pixels in the areas, however many areas there are: none for one + /// that only shares their edge, lies off the drawing or isn't a number. + #[test] + fn the_share_of_a_rectangle_in_the_areas_counts_its_pixels() { + let in_areas = |areas: &[Rect], w: usize, h: usize| { + let marks: Vec = (0..w * h) + .map(|k| { + let (x, y) = ((k % w) as f64 + 0.5, (k / w) as f64 + 0.5); + areas.iter().any(|a| a.contains(Point::new(x, y))) + }) + .collect(); + let shares = Shares::of(&marks, w, h); + move |r: &Rect| shares.share(r) + }; + let share = in_areas(&[Rect::new(10.0, 10.0, 20.0, 20.0), Rect::new(30.0, 0.0, 31.0, 1.0)], 40, 40); + assert_eq!((share(&Rect::new(12.0, 12.0, 22.0, 18.0)), share(&Rect::new(10.0, 10.0, 30.0, 20.0))), (0.8, 0.5)); + assert_eq!((share(&Rect::new(15.0, 15.0, 30.0, 30.0)), share(&Rect::new(30.2, 0.2, 30.8, 0.8))), (25.0 / 225.0, 1.0)); + assert_eq!( + [share(&Rect::new(20.0, 20.0, 30.0, 30.0)), share(&Rect::new(0.0, 0.0, 5.0, 5.0)), share(&Rect::new(50.0, 50.0, 60.0, 60.0))], + [0.0; 3] + ); + assert_eq!(share(&Rect::new(f64::NAN, 0.0, 39.0, 39.0)), 0.0); + let many: Vec = (0..5000).map(|i| Rect::new(f64::from(i % 70), 50.0, f64::from(i % 70) + 1.0, 51.0)).collect(); + let share = in_areas(&many, 80, 80); + assert_eq!((share(&Rect::new(60.0, 50.0, 75.0, 51.0)), share(&Rect::new(70.0, 50.0, 75.0, 51.0))), (10.0 / 15.0, 0.0)); + } + fn piece(text: &str, x: f64, y: f64) -> Arc { Arc::new(Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(x, y), text, CharStyle::default()))))) } @@ -161,11 +196,73 @@ mod tests { let a = comparison_render(&mut renderer, &page, rect, 0.4, 1); let b = comparison_render(&mut vectorcraft_render::Renderer::new(), &vector, rect, 0.4, 1); assert!(compared(&a, &b, &[], &[]).solid > MAX_SOLID_DIFFERENCE, "the old point sampling falsely refused this page"); - let frame = Frame { page: &page, page_rect: rect, rect, whole: false }; + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; let mut view = PageView::new(&frame); - assert!(compare(&frame, &mut view, &vector).is_ok()); - assert!(compare(&frame, &mut view, &Document::new(1000.0, 500.0)).is_err(), "missing artwork remains an error"); + assert!(compare(&frame, &mut view, &vector, false).is_ok()); + assert!(compare(&frame, &mut view, &Document::new(1000.0, 500.0), false).is_err(), "missing artwork remains an error"); let shifted = Rect::new(0.0, 0.0, 500.0, 500.0); - assert!(view.difference(&vector, shifted).any > MAX_DIFFERENCE, "wrong framing remains an error"); + assert!(view.difference_on_every_page(&vector, shifted, false).any > MAX_DIFFERENCE, "wrong framing remains an error"); + } + + /// The boxes `solid_regions_on_every_page` gives for a page of images are in the page's points: the + /// comparison is drawn at a multiple of the scale and resized, and the two sizes round + /// differently on the short side, so a box at the far edge does not drift out of the object + /// that makes it. + #[test] + fn solid_regions_of_a_raster_page_lie_in_the_object_that_differs() { + for bottom in (884..=900).map(f64::from) { + let object = Rect::new(1000.0, 0.0, 3000.0, bottom); + for r in raster_page_regions(object, 4000.0, 1006.0) { + assert!( + r.x0 >= object.x0 - 1.0 && r.y0 >= object.y0 - 1.0 && r.x1 <= object.x1 + 1.0 && r.y1 <= object.y1 + 1.0, + "{r:?} lies outside {object:?}" + ); + } + } + } + + /// The boxes `solid_regions_on_every_page` gives for a `width` × `height` page that is one image of a black + /// `object`, compared with layers that hold nothing. + fn raster_page_regions(object: Rect, width: f64, height: f64) -> Vec { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, ImageBlob, ImageObject}; + let mut vector = Document::new(width, height); + let layer = vector.layers[0].id; + let n = Node::path( + vector.alloc_id(), + vectorcraft_geom::shapes::rectangle(object), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + vector.insert(Some(layer), usize::MAX, n).unwrap(); + let rect = vector.artboards[0].rect; + let source = vectorcraft_render::Renderer::new().render_region(&vector, rect, 1.0, true); + let mut png = Vec::new(); + image::RgbaImage::from_raw(source.width, source.height, source.to_straight()) + .unwrap() + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let blob = ImageBlob::new("image/png", png); + let key = blob.content_key(); + let mut page = Document::new(width, height); + page.images.insert(key.clone(), blob); + let image = Node::new( + page.alloc_id(), + NodeKind::Image(Box::new(ImageObject { + key, + width: source.width, + height: source.height, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + })), + ); + page.insert(Some(page.layers[0].id), usize::MAX, image).unwrap(); + assert_eq!(comparison_samples(&page), 4); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; + let mut view = PageView::new(&frame); + let (_, regions) = view.solid_regions_on_every_page(&Document::new(width, height), false).unwrap(); + assert!(!regions.is_empty()); + regions } } diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 995e8e8d3f..9400bd56ea 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -1,10 +1,15 @@ -use super::compare::{MAX_DIFFERENCE, PageView, compare}; -use super::plan::plan; -use super::slots::{ - ART_LEFT_OUT, Content, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, extent, few, fill_slots, - text_objects, +use super::compare::{ + MAX_DIFFERENCE, MAX_PAGES_COMPARED, MAX_PIXELS_COMPARED, MAX_SOLID_DIFFERENCE, PageView, compare, comparison_samples, difference, pixels_compared, }; -use super::{Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, Vec2, ai}; +use super::plan::{made_only, make_slots, plan, readable_all}; +use super::slots::{ + ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, + collect_slots, extent, few, fill_slots, letters, text_objects, words, +}; +use super::{ + Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, VariableKind, Vec2, ai, +}; +use vectorcraft_doc::PlacedDocument; /// Which box of the editing copy is the page. #[derive(Clone, Copy)] @@ -15,6 +20,11 @@ pub(super) enum Page { Artboard, } +/// How art moved from a page to its place in the layers' document transforms: its pattern tiles +/// move with it. +pub(super) const PAGE_MOVE: Scaling = + Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: false, patterns: true, keep_fit_when_flat: false }; + /// The page (`visible`, the file read as its page) and the place of its area in the layers' /// document. pub(super) struct Frame<'a> { @@ -26,6 +36,12 @@ pub(super) struct Frame<'a> { /// The page holds all the art that prints (an EPS's page is its art's box, unless it was /// saved as its artboard): the layers print nothing outside it. pub(super) whole: bool, + /// The PDF page areas and their moves into the editing document. + pub(super) pages: Vec<(Rect, Affine)>, + /// The pages after the first that show artboards of the layers' document, each with that + /// artboard (as many as [`MAX_PIXELS_COMPARED`] allows): the layers are compared with them as + /// with the first. + pub(super) more: Vec<(Rect, Rect)>, } /// The document of the editing copy `data`, with the text (and strokes round it) of `visible`, the @@ -44,14 +60,176 @@ pub(super) fn build( ) -> Result<(Document, Vec), String> { // An EPS (its page is its art) draws a Large Canvas page at full size; a `.ai` keeps its art // space, as its PDF part may (#2031). - let Structure { mut doc, to_doc, bbox, artboard, template, hidden_unread, slot_names, restyled, warnings } = - ai::read(data, matches!(page, Page::Art))?; - // Editing data in the units of the page's user space ([`in_units`]) is compared with the page - // scaled down to those units, and the document read from it is scaled up by `unit`. + let large_canvas = matches!(page, Page::Art); + let structure = if visible.is_some() { ai::read_over_page(data, large_canvas)? } else { ai::read(data, large_canvas)? }; + build_from(structure, data, visible, page, outlined, trust, unit) +} + +/// [`build`] without a page, for a `.ai` whose PDF part can't be read, its first page `page` +/// (width and height, either way round) points large in units of `unit` points: the document is +/// drawn `unit` times as large when its first artboard, or its art's box, has the page's size in +/// those units and not in points, as [`build_from`] decides with a page; else as many times as +/// large as its declared large canvas scale when it has the page's size at that scale. +pub(super) fn build_on_page(data: &[u8], page: (f64, f64), unit: f64) -> Result<(Document, Vec), String> { + let structure = ai::read(data, false)?; + let board = structure.artboard.map(|a| structure.to_doc.transform_rect_bbox(a)); + let art = structure.bbox.map(|[a, b, c, d]| structure.to_doc.transform_rect_bbox(Rect::new(a, b, c, d))); + let (w, h) = page; + let fits = |r: Option, k: f64| { + r.is_some_and(|r| [(w, h), (h, w)].iter().any(|(a, b)| (r.width() - a / k).abs() <= 0.5 && (r.height() - b / k).abs() <= 0.5)) + }; + let in_units = |r: Option, k: f64| k.is_finite() && k > 1.0 && fits(r, k) && !fits(r, 1.0); + let scale = [unit, structure.canvas_scale].into_iter().find(|&k| in_units(board, k) || (!fits(board, 1.0) && in_units(art, k))); + let styles = structure.styles_read; + let (mut doc, notes) = build_from(structure, data, None, Page::Artboard, false, false, 1.0)?; + if let Some(k) = scale { + // The graphic styles read from the file are drawn in its units too. + scale_document(&mut doc, k, styles); + relayout_wrapped(&mut doc); + } + Ok((doc, notes)) +} + +/// A document read from the editing copy and its notes, or why it can't be read. +pub(super) type Built = Result<(Document, Vec), String>; + +/// [`build`] of a `.ai` without importing its PDF part, whose pages (each its trim box in points, +/// width and height) are `pages` and are in units of `unit` points: the document read from +/// `structure` (the editing copy `data` read) with nothing compared with the pages, when the file's +/// text document makes the type of every text object (at least one shows, and none is type that a +/// look draws), no object is unread or has another placement or drawn art that the page would +/// choose, no linked image shows a placeholder, and its artboards are the pages, one for one and of their size, in points or in the pages' +/// units ([`page_scale_alone`]). The document is drawn at that scale. Else `Err(structure)`, for +/// [`build_from`] with the page. +pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f64, f64)], unit: f64) -> Result> { + let Some(scale) = page_scale_alone(&structure, pages, unit).filter(|_| nothing_waits_on_page(&structure) && type_all_made(&structure, data)) + else { + return Err(Box::new(structure)); + }; + let styles = structure.styles_read; + let built = build_from(structure, data, None, Page::Artboard, false, false, 1.0).map(|(mut doc, notes)| { + if scale != 1.0 { + // The graphic styles read from the file are drawn in its units too. + scale_document(&mut doc, scale, styles); + relayout_wrapped(&mut doc); + } + (doc, notes) + }); + Ok(built) +} + +/// Is nothing in `structure` waiting on the page: no object unread (the page's art takes its +/// place), no placed file with another placement, no live envelope with the drawn art it replaced +/// (the comparison with the page chooses between them), no linked image showing a placeholder +/// where the page has its pixels? +fn nothing_waits_on_page(structure: &Structure) -> bool { + structure.placeholders.is_empty() + && structure.unread.is_empty() + && structure.unread_elsewhere.is_empty() + && structure.placed_elsewhere.is_empty() + && structure.envelopes_drawn.is_empty() +} + +/// Does the text document of `data` (read as `structure`) make the type of every text object, those +/// that don't show included, with at least one that shows, and none of them type that a look draws? +fn type_all_made(structure: &Structure, data: &[u8]) -> bool { + let mut infos = vec![]; + collect_slots(&structure.doc.layers, true, &mut infos); + if !infos.iter().any(|i| i.shown) || infos.iter().any(|i| i.look.is_some()) { + return false; + } + let frames = ai::text_frames(data); + for info in &mut infos { + info.art_path = info.story.and_then(|s| frames.get(&(s, info.frame))).map(|p| PathData::from_bezpath(&(structure.to_doc * p.clone()))); + } + let Some(texts) = Texts::read(data) else { return false }; + let mut read: std::collections::BTreeMap>> = Default::default(); + let stories: Vec>> = infos + .iter() + .map(|i| { + let n = i.story?; + read.entry(n).or_insert_with(|| texts.story(n as usize).map(Arc::new)).clone() + }) + .collect(); + // A slot without its story is made from nothing; past the text `build_from` reads, nothing is + // made either: it refuses the file. + if stories.iter().any(Option::is_none) || stories.iter().flatten().map(|s| s.len()).sum::() > MAX_TEXT { + return false; + } + let template = structure.template.map(|t| ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0)); + make_slots(&infos, &stories, template, structure.to_doc, &mut vec![]).iter().all(Option::is_some) +} + +/// The scale at which the artboards of `structure` are the pages `pages` (each its width and height +/// in points), one for one and in order, each within half a point: 1 when they are in points, else +/// `unit` (the pages' `UserUnit`) when they are in those units, as [`page_scale`] finds it with the +/// page. `None` when they aren't the pages, and for a file that declares a large canvas scale (a +/// `.ai` saved without its PDF part reads one at that scale, [`super::ai_alone`]). +fn page_scale_alone(structure: &Structure, pages: &[(f64, f64)], unit: f64) -> Option { + let boards = &structure.doc.artboards; + if boards.is_empty() || boards.len() != pages.len() || structure.canvas_scale != 1.0 { + return None; + } + let fits = |k: f64| boards.iter().zip(pages).all(|(b, (w, h))| (b.rect.width() - w / k).abs() <= 0.5 && (b.rect.height() - h / k).abs() <= 0.5); + [1.0, unit].into_iter().find(|&k| k.is_finite() && k >= 1.0 && fits(k)) +} + +/// The areas left out of the comparisons with `page`: the `restyled` looks', and on a PostScript +/// page, which draws nothing for them, the linked images' `placeholders`. A PDF part draws those +/// images' pixels, which the placeholders don't match. +fn left_out_of_comparisons(page: Page, mut restyled: Vec, placeholders: Vec) -> Vec { + if matches!(page, Page::Art) { + restyled.extend(placeholders); + } + restyled +} + +/// [`build`] from `structure`, the editing copy `data` already read. +pub(super) fn build_from( + structure: Structure, + data: &[u8], + visible: Option<&Document>, + page: Page, + outlined: bool, + trust: bool, + unit: f64, +) -> Result<(Document, Vec), String> { + let Structure { + mut doc, + to_doc, + bbox, + artboard, + template, + hidden_unread, + unread, + unread_elsewhere, + slot_names, + restyled, + placeholders, + placed_elsewhere, + placed_pages, + envelopes_drawn, + styles_read, + canvas_scale, + xml_ids, + bindings, + bindings_skipped, + warped_type, + warnings, + } = structure; + let mut restyled = left_out_of_comparisons(page, restyled, placeholders); + // Editing data in the units of the page's user space ([`in_units`]), or at its declared large + // canvas scale ([`page_scale`]), is compared with the page scaled down to those units, and the + // document read from it is scaled up by `unit`. let board = artboard.map(|a| to_doc.transform_rect_bbox(a)); - let small = visible.filter(|v| matches!(page, Page::Artboard) && in_units(board, v, unit)).map(|v| { + // A page cropped to the art (see below) is in those units as well, when the art's box is and + // the artboard isn't the page in points. + let art = bbox.map(|[a, b, c, d]| to_doc.transform_rect_bbox(Rect::new(a, b, c, d))); + let scaled = page_scale(board, art, visible.filter(|_| matches!(page, Page::Artboard)), unit, canvas_scale); + let unit = scaled.unwrap_or(unit); + let small = visible.filter(|_| scaled.is_some()).map(|v| { let mut v = v.clone(); - scale_document(&mut v, 1.0 / unit); + scale_document(&mut v, 1.0 / unit, false); v }); let visible = small.as_ref().or(visible); @@ -67,8 +245,25 @@ pub(super) fn build( let page_rect = visible.artboards.first().map(|a| a.rect).ok_or("it has no page")?; // The layers' art in the document's terms: a Large Canvas editing copy is written at 1/N // scale, which `to_doc` carries, so its art and the page reach the same size (#2031). - let rect = to_doc.transform_rect_bbox(art_box); - if (rect.width() - page_rect.width()).abs() > 0.5 || (rect.height() - page_rect.height()).abs() > 0.5 { + let fits = |r: &Rect| (r.width() - page_rect.width()).abs() <= 0.5 && (r.height() - page_rect.height()).abs() <= 0.5; + let mut rect = to_doc.transform_rect_bbox(art_box); + // A PDF saved with some of its artboards has pages for those only, the first of them not + // always the first artboard: the editing data keeps them all (`first`, the page's). + let first = shown_artboard(&doc, visible, page, page_rect, fits); + rect = doc.artboards.get(first).filter(|_| first > 0).map_or(rect, |a| a.rect); + // A `.ai` whose PDF part's pages are cropped to its art (each page the box of all of it, + // the editing data's bounding box) rather than to its artboards: the layers are compared + // with the page on that box, and keep their artboards. Each page then holds all the art + // again, so every page must be that box. + let mut cropped = false; + if matches!(page, Page::Artboard) + && !fits(&rect) + && visible.artboards.iter().all(|a| fits(&a.rect)) + && let Some(art) = art.filter(fits) + { + (rect, cropped) = (art, true); + } + if !fits(&rect) { // Both sizes in points as the fields show them, and the editing data's page to the // file's as a scale (1:10 is a tenth of its size) when its sides are in proportion and // the scale doesn't round to 1:1. @@ -95,26 +290,49 @@ pub(super) fn build( lone.push(vec![Arc::new(n.clone())]); } }); - // A `.ai` read as its PDF part has a page for each artboard, in a row: the type on each - // goes where the layers have that artboard. + // A `.ai` read as its PDF part has a page for each artboard it was saved with, in a row: + // the type on each goes where the layers have that artboard. let pages: Vec = visible.artboards.iter().map(|a| a.rect).collect(); - let same = - |(a, p): (&vectorcraft_doc::Artboard, &Rect)| (a.rect.width() - p.width()).abs() <= 0.5 && (a.rect.height() - p.height()).abs() <= 0.5; - let boards = (pages.len() == doc.artboards.len() && doc.artboards.iter().zip(&pages).all(same)).then_some(&doc.artboards); - for object in shown.iter_mut().chain(hidden.iter_mut()).chain(lone.iter_mut()) { - // The page with most of it, the first for what is on none. - let on = extent(object).and_then(|r| { + let boards = page_boards(&doc, visible, first, &pages); + // The first page's type goes to the first artboard only when that artboard is the page's + // (every artboard has a page); otherwise it goes to `rect`, the art's box or the editing + // data's artboard. + let first_board = first > 0 || pages.len() == doc.artboards.len(); + let board_of = |i: usize| boards.as_ref()?.get(i).filter(|_| i > 0 || first_board); + let page_moves: Vec<(Rect, Affine)> = pages + .iter() + .enumerate() + .map(|(i, page)| { + let move_to_doc = board_of(i).map(|board| Affine::translate(board.rect.origin() - page.origin())).unwrap_or(shift); + (*page, move_to_doc) + }) + .collect(); + // The page with most of an object, the first for what is on none. + let page_of = |object: &[Arc]| { + extent(object).and_then(|r| { let inside = |p: &Rect| p.intersect(r).area().max(0.0); pages.iter().enumerate().skip(1).filter(|(_, p)| inside(p) > inside(&page_rect)).max_by(|a, b| inside(a.1).total_cmp(&inside(b.1))) - }); - let shift = match on.and_then(|(i, page)| Some((boards?.get(i)?, page))) { + }) + }; + // Pages cropped to the art are copies of one another: the type is the first page's. + if cropped { + for objects in [&mut shown, &mut hidden, &mut lone] { + objects.retain(|o| page_of(o).is_none()); + } + } + for object in shown.iter_mut().chain(hidden.iter_mut()).chain(lone.iter_mut()) { + let on = page_of(object); + let shift = match on.and_then(|(i, page)| Some((board_of(i)?, page))) { Some((board, page)) => Affine::translate(board.rect.origin() - page.origin()), None => shift, }; for n in object.iter_mut() { - Arc::make_mut(n).transform(shift, false); + Arc::make_mut(n).transform(shift, PAGE_MOVE); } } + // Pages cropped to the art are copies of the first, and a PDF saved with some of the + // artboards can hold any of them. + let more = more_pages(boards.as_deref().filter(|b| !cropped && b.len() == doc.artboards.len()), &pages, comparison_samples(visible)); // An EPS saved as its artboard has the art outside it left out of its page. let artboard_page = artboard.is_some_and(|a| [a.x0 - art_box.x0, a.y0 - art_box.y0, a.x1 - art_box.x1, a.y1 - art_box.y1].iter().all(|d| d.abs() <= 1.0)); @@ -123,14 +341,17 @@ pub(super) fn build( // Its page is the file's own (its bounding box), as when it comes in as its page: art // reaching past the editing data's artboard stays on it (#1102). doc.artboards.truncate(1); + doc.opened_artboard = None; if let Some(a) = doc.artboards.first_mut() { a.rect = rect; } + drop_guides_off_boards(&mut doc); } - frame = Some(Frame { page: visible, page_rect, rect, whole }); + frame = Some(Frame { page: visible, page_rect, rect, whole, pages: page_moves, more }); } let mut infos = vec![]; collect_slots(&doc.layers, true, &mut infos); + super::slots::limit_look_slots(&mut doc.layers, &mut infos, shown.len(), outlined); // Each text object's own frame or path, by its story and frame. let frames = ai::text_frames(data); for info in &mut infos { @@ -140,13 +361,12 @@ pub(super) fn build( if outlined && infos.iter().any(|i| i.shown) { return Err("its type is to come in as outlines, which only its page has".into()); } - if infos.iter().all(|i| !i.shown) && !shown.is_empty() { - return Err("its page has text, and its layers have no text objects to put it in".into()); - } - // The page's type is compared with every text object of the layers: that has its limits. - if infos.len() > MAX_SLOTS || infos.len().saturating_mul(shown.len()) > MAX_PAIRS { - return Err("it has too many text objects".into()); - } + // The page's type inside an unread object's box comes in with the page's art that replaces the + // object (see [`replace_unread`]), not in a text object. + let unread_type = take_unread_type(&doc, frame.as_ref(), &unread, &unread_elsewhere, &mut shown); + // The page's type that needs no text object of the layers: the layers' own legacy text, or + // placed files that show it. + let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?; let texts = Texts::read(data); // Each story is read once, however many text objects name it. let mut read: std::collections::BTreeMap>> = Default::default(); @@ -162,7 +382,8 @@ pub(super) fn build( } let template = template.map(|t| ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0)); let mut notes = warnings; - let content = plan(&infos, &stories, template, to_doc, [&shown, &hidden], &mut notes); + let own = (!outlined).then(|| outside_placed_files(&shown, &doc, &placed_elsewhere)); + let (content, reflow) = slot_content(&infos, &stories, template, to_doc, own.as_deref(), [&shown, &hidden], &mut notes)?; // The glyphs left out with the rest of the page's art, and how many text objects take type of // the page right next to them (not counted past `MAX_PAIRS` comparisons). let compared = lone.len().saturating_mul(shown.iter().chain(&hidden).map(Vec::len).sum()); @@ -171,25 +392,47 @@ pub(super) fn build( matches!(n.kind, NodeKind::Text(_)) && n.visual_bounds().is_some_and(|b| missing.iter().any(|r| !b.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).is_zero_area())) }; - let short = content.iter().filter(|c| matches!(c, Content::Page(p) | Content::Made(_, _, _, p) if p.iter().any(next_to_missing))).count(); + let short = content.iter().filter(|c| matches!(c, Content::Page(p) if p.iter().any(next_to_missing))).count(); let mut empty = 0; let mut layers = std::mem::take(&mut doc.layers); let mut made = vec![]; - fill_slots(&mut doc, &mut layers, &mut content.into_iter(), &slot_names, &mut empty, &mut made, &mut vec![]); + let mut filled = std::collections::HashMap::new(); + fill_slots(&mut doc, &mut layers, &mut content.into_iter(), &slot_names, &mut empty, &mut made, &mut vec![], &mut filled); doc.layers = layers; - // A story in several frames is threaded type: its frames in order (the first holds the story). made.sort(); + let threaded_frames: BTreeSet = + made.chunk_by(|a, b| a.0 == b.0).filter(|thread| thread.len() > 1).flatten().map(|(_, _, id)| *id).collect(); + if !unread.is_empty() { + let Some(frame) = frame.as_ref() else { return Err(unread_error(&unread)) }; + let mut copied = BTreeSet::new(); + let kinds = replace_unread(&mut doc, frame, &unread, &unread_elsewhere, &threaded_frames, &mut copied)?; + // With the text objects filled, the page art chosen can differ from the first try's: the + // page's type set aside for it, and no other, must be in it. + let all_copied = |o: &Vec>| !o.is_empty() && o.iter().all(|n| copied.contains(&n.id)); + if !unread_type.iter().all(all_copied) || shown.iter().any(all_copied) { + return Err("the page's type in an unread object's box isn't in its page art".into()); + } + notes.push(format!("{}: they came in as the page's art", kinds.join(", "))); + } + // A story in several frames is threaded type: its frames in order (the first holds the story). for thread in made.chunk_by(|a, b| a.0 == b.0) { if thread.len() > 1 { doc.text_threads.push(thread.iter().map(|(_, _, id)| *id).collect()); } } + // Area type flows around the wrap objects above it before it is compared with the page. + resolve_text_wrap(&mut doc)?; + let bound_text = text_bound_slots(&doc, &bindings, &xml_ids); + settle_warped_type(warped_type, &mut doc, &filled, &threaded_frames, &bound_text, &mut restyled, &mut notes)?; if empty > 0 { notes.push(format!("{empty} {}", if frame.is_some() { TEXT_LEFT_OUT } else { TYPE_LEFT_OUT })); } if short > 0 { notes.push(format!("{short} {PAGE_TYPE_WITHOUT_OUTLINES}")); } + if as_outlines > 0 { + notes.push(format!("{as_outlines} {PAGE_TYPE_AS_OUTLINES}")); + } if !hidden_unread.is_empty() { notes.push(format!("{ART_LEFT_OUT} ({}), left out of them", few(hidden_unread))); } @@ -197,25 +440,1011 @@ pub(super) fn build( Some(frame) => { let mut view = PageView::new(&frame); view.restyled(&restyled, frame.rect); - let unseen = prune_unseen(&frame, &mut view, &mut doc); - if unseen > 0 { - notes.push(format!("{unseen} {UNSEEN_TEXT}")); - } - match compare(&frame, &mut view, &doc) { - Ok(note) => notes.extend(note), - Err(why) if trust => notes.push(format!("{why}: they come from its editing data all the same")), - Err(why) => return Err(why), + // The placed files' other placement starts from the layers as read: which text the page + // doesn't draw is weighed again with the images there, since an image that covered a + // text object at the first placement may not cover it at the other. + let other = elsewhere(&doc, &placed_elsewhere); + let unseen = prune_unseen(&frame, &mut view, &mut doc, reflow); + let unseen_note = |n: usize| (n > 0).then(|| format!("{n} {UNSEEN_TEXT}")); + match compare(&frame, &mut view, &doc, reflow) { + // Placed files at the other point their data gives, where that draws closer to the + // page: a small image in the wrong place differs too little to fail. + Ok(note) => { + let closer = other.and_then(|mut other| { + let unseen = prune_unseen(&frame, &mut view, &mut other, reflow); + let closer = view.difference_on_every_page(&other, frame.rect, reflow).any + < view.difference_on_every_page(&doc, frame.rect, reflow).any; + closer.then(|| compare(&frame, &mut view, &other, reflow).ok()).flatten().map(|note| (other, unseen, note)) + }); + match closer { + Some((other, unseen, note)) => { + doc = other; + notes.extend(unseen_note(unseen).into_iter().chain(note)); + } + None => notes.extend(unseen_note(unseen).into_iter().chain(note)), + } + } + // Placed files at the other point their data gives, where that draws as the page. + Err(why) => match other.map(|mut other| { + let unseen = prune_unseen(&frame, &mut view, &mut other, reflow); + (compare(&frame, &mut view, &other, reflow), other, unseen) + }) { + Some((Ok(note), other, unseen)) => { + doc = other; + notes.extend(unseen_note(unseen).into_iter().chain(note)); + } + other => match drawn_or_trusted(&frame, &mut view, &mut doc, &envelopes_drawn, ¬es, unseen, trust, why, reflow) { + Ok(more) => notes.extend(more), + // The objects that draw differently from the page come in as its art, from + // the placement that draws closer to it. + Err(why) => { + let other = other.map(|(_, other, unseen)| (other, unseen)); + let placements = closer_first(&frame, &mut view, (doc, unseen), other, reflow); + let Some((kept, unseen, kept_notes)) = placements.into_iter().find_map(|(base, unseen)| { + keep_differing(&base, &frame, &mut view, &threaded_frames, &shown, reflow).map(|(kept, n)| (kept, unseen, n)) + }) else { + return Err(why); + }; + doc = kept; + notes.extend(unseen_note(unseen).into_iter().chain(kept_notes)); + } + }, + }, } } None => unmark(&mut doc.layers, true, true, &mut vec![]), } doc.limit_depth_noting(&mut notes); + bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes); + placed_documents(&mut doc, &placed_pages); if small.is_some() { - scale_document(&mut doc, unit); + scale_document(&mut doc, unit, styles_read); + relayout_wrapped(&mut doc); } Ok((doc, notes)) } +/// The linked images of `pages` that are still in `doc`, opacity-mask art included, as placed +/// documents of their page and box, over the same place, each showing the same preview until its +/// file is read. An image bound to an image variable stays a linked image, the object an image +/// variable binds. +fn placed_documents(doc: &mut Document, pages: &[ai::PlacedPage]) { + if pages.is_empty() { + return; + } + let vars = &doc.variables; + let image_bound = |id: &NodeId| { + vars.bindings.get(id).is_some_and(|names| names.iter().any(|v| vars.variable(v).is_some_and(|v| v.kind == VariableKind::Image))) + }; + let pages: std::collections::HashMap = pages.iter().filter(|p| !image_bound(&p.id)).map(|p| (p.id, *p)).collect(); + for layer in &mut doc.layers { + to_placed_documents(Arc::make_mut(layer), &pages); + } +} + +/// [`placed_documents`] in `n` and everything in it. +fn to_placed_documents(n: &mut Node, pages: &std::collections::HashMap) { + // A box too small to take the image's pixels to (its transform not finite) keeps the linked image. + if let Some(page) = pages.get(&n.id) + && let NodeKind::Image(im) = &n.kind + && let Some(link) = &im.link + && let (width, height) = page.size + && let xf = im.xf * Affine::scale_non_uniform(f64::from(im.width) / width, f64::from(im.height) / height) + && xf.as_coeffs().iter().all(|v| v.is_finite()) + && xf.determinant().abs() > 1e-12 + { + let link = vectorcraft_doc::LinkInfo { page: Some(page.page), ..link.clone() }; + let placed = PlacedDocument { + link, + key: im.key.clone(), + bounding: page.bounding, + page_box: page.page_box, + width, + height, + xf, + placement: im.placement, + }; + n.kind = NodeKind::PlacedDocument(Box::new(placed)); + } + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + to_placed_documents(Arc::make_mut(&mut m.art), pages); + } + for c in n.children_mut().into_iter().flatten() { + to_placed_documents(Arc::make_mut(c), pages); + } +} + +/// Bind the objects of `doc` to the variables of its library that `bindings` binds them to, each +/// object named by its XML id (`ids`: the object read with that id, or what `filled` made of a text +/// object's slot: for a visibility variable every object that took the slot's place, for a text +/// variable the one text object among them). An object is bound when it is of the variable's kind: +/// type for a text variable, a linked image for an image variable, any object for a visibility +/// variable. Locked and hidden objects, objects in locked or hidden layers and groups, and objects +/// on locked artboards keep their bindings. Graph variables and +/// variables of unknown kind bind nothing. The note counts the bindings that weren't made, with +/// `skipped` more that the reader left out. +fn bind_variables( + doc: &mut Document, + bindings: &[ai::BindingRef], + skipped: usize, + ids: &std::collections::HashMap>, + filled: &std::collections::HashMap, + notes: &mut Vec, +) { + let mut skipped = skipped; + if bindings.is_empty() { + notes.extend(ai::bindings_note(skipped)); + return; + } + let mut bound = vec![]; + for b in bindings { + let kind = doc.variables.variable(&b.variable).map(|v| v.kind); + let targets = match (b.target.as_ref().and_then(|t| ids.get(t).copied().flatten()), kind) { + (Some(id), Some(kind)) => match filled.get(&id) { + Some(f) if kind == VariableKind::Visibility => f.objects.clone(), + Some(f) => match f.text.as_slice() { + [one] => vec![*one], + _ => vec![], + }, + None => vec![id], + }, + _ => vec![], + }; + // Those still in the document: a part of a slot can have been taken out since. + let targets: Vec = targets.into_iter().filter(|id| doc.node(*id).is_some()).collect(); + let fits = |id: &NodeId| { + doc.node(*id).is_some_and(|n| match (kind, &n.kind) { + (Some(VariableKind::Visibility), _) => true, + (Some(VariableKind::Text), NodeKind::Text(_)) => true, + (Some(VariableKind::Image), NodeKind::Image(im)) => im.link.is_some(), + _ => false, + }) + }; + if !targets.is_empty() && targets.iter().all(fits) { + bound.push((targets, b.variable.as_str())); + } else { + skipped += 1; + } + } + for (targets, variable) in bound { + for id in targets { + doc.variables.bind(id, variable); + } + } + notes.extend(ai::bindings_note(skipped)); +} + +/// The text object slots of `doc` that `bindings` binds to a text variable, each named by its XML id +/// (`ids`). +fn text_bound_slots(doc: &Document, bindings: &[ai::BindingRef], ids: &std::collections::HashMap>) -> BTreeSet { + bindings + .iter() + .filter(|b| doc.variables.variable(&b.variable).is_some_and(|v| v.kind == VariableKind::Text)) + .filter_map(|b| b.target.as_ref().and_then(|t| ids.get(t).copied().flatten())) + .collect() +} + +/// Warped type stays type where its live warp draws as its look, and where a text variable binds it +/// (`bound_text`, by slot). Elsewhere the look takes its place, and one note says how many did. +/// `filled` says what each slot became, and the comparisons with the page leave out the boxes in +/// `restyled`. Fails as [`resolve_text_wrap`] does when the looks give the wrap shapes too many +/// anchors. +fn settle_warped_type( + warped: ai::WarpedType, + doc: &mut Document, + filled: &std::collections::HashMap, + threaded: &BTreeSet, + bound_text: &BTreeSet, + restyled: &mut Vec, + notes: &mut Vec, +) -> Result<(), String> { + let made = |slot| match filled.get(&slot).map(|f| f.text.as_slice()).filter(|_| !bound_text.contains(&slot)) { + Some(&[one]) => Some(one), + _ => None, + }; + let replaced = warped.settle(doc, made, threaded, restyled); + if replaced > 0 { + notes.push(format!("{}: {replaced}", ai::WARPED_TYPE_DRAWN)); + resolve_text_wrap(doc)?; + } + Ok(()) +} + +/// Most anchors copied into the wrap shapes of a file's area type ([`vectorcraft_doc::text::wrap_work`]). +const MAX_WRAP_WORK: usize = 2_000_000; + +/// [`relayout_wrapped`], or an error when the wrap shapes would hold more than [`MAX_WRAP_WORK`] +/// anchors. +fn resolve_text_wrap(doc: &mut Document) -> Result<(), String> { + if has_wraps(doc) && vectorcraft_doc::text::wrap_work(doc) > MAX_WRAP_WORK { + return Err("it has too many text objects".into()); + } + relayout_wrapped(doc); + Ok(()) +} + +/// Does an object of `doc` have text wrap options, or a text object wrap shapes? +fn has_wraps(doc: &Document) -> bool { + let mut wraps = false; + doc.walk(|n| wraps |= n.extras().wrap.is_some() || matches!(&n.kind, NodeKind::Text(t) if !t.wrap.is_empty())); + wraps +} + +/// Resolve the wrap shapes of the area type in `doc` that has wrap objects above it (see +/// [`vectorcraft_doc::text::resolve_wrap`]); the type whose shapes changed is laid out again. +/// Nothing is resolved when the shapes would hold more than [`MAX_WRAP_WORK`] anchors (such a +/// file isn't read from its layers: see [`resolve_text_wrap`]). +fn relayout_wrapped(doc: &mut Document) { + if !has_wraps(doc) || vectorcraft_doc::text::wrap_work(doc) > MAX_WRAP_WORK { + return; + } + for id in vectorcraft_doc::text::resolve_wrap(None, doc) { + if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) { + t.cached_bounds = None; + t.cached_baselines.clear(); + } + } +} + +/// A visible page node, with its source order and subtree range. +struct PageArt { + node: Arc, + bounds: Rect, + page: usize, + end: usize, + stateful_ancestor: bool, +} + +const ART_MARGIN: f64 = 1.0; + +fn inside(art: Rect, bounds: Rect) -> bool { + art.x0 >= bounds.x0 - ART_MARGIN && art.y0 >= bounds.y0 - ART_MARGIN && art.x1 <= bounds.x1 + ART_MARGIN && art.y1 <= bounds.y1 + ART_MARGIN +} + +/// Pick the page holding the most of a box. The first page wins a tie. +fn page_for(bounds: Rect, pages: &[Rect]) -> usize { + let mut best = (0, 0.0); + for (i, page) in pages.iter().enumerate() { + let area = page.intersect(bounds).area().max(0.0); + if area > best.1 { + best = (i, area); + } + } + best.0 +} + +fn collect_live(node: &Node, unread: &BTreeSet, live: &mut Vec) { + if !node.visible || unread.contains(&node.id) { + return; + } + if let Some(children) = node.children() { + for child in children { + collect_live(child, unread, live); + } + } else if let Some(bounds) = node.visual_bounds() { + live.push(bounds); + } +} + +fn page_node_has_drawing_state(node: &Node) -> bool { + node.clips() + || matches!(node.kind, NodeKind::Path { clipping: true, .. }) + || node.opacity < 1.0 + || node.blend != super::BlendMode::Normal + || node.isolate + || node.knockout != vectorcraft_doc::Knockout::Neutral + || node.extras().mask.is_some() + || !node.appearance.items.is_empty() + || !node.appearance.effects.is_empty() +} + +fn index_page(node: &Arc, pages: &[Rect], moves: &[Affine], art: &mut Vec, stateful_ancestor: bool) { + if !node.visible { + return; + } + let start = art.len(); + let mut indexed = false; + if let Some(bounds) = node.visual_bounds() { + let page = page_for(bounds, pages); + if let Some(shift) = moves.get(page) { + art.push(PageArt { node: Arc::clone(node), bounds: shift.transform_rect_bbox(bounds), page, end: start + 1, stateful_ancestor }); + indexed = true; + } + } + if let Some(children) = node.children() { + for child in children { + index_page(child, pages, moves, art, stateful_ancestor || page_node_has_drawing_state(node)); + } + } + let end = art.len(); + if indexed && let Some(entry) = art.get_mut(start) { + entry.end = end; + } +} + +/// Node IDs belong to the importing document, not to the pattern's drawing. +fn same_pattern_art(existing: &vectorcraft_doc::PatternDef, source: &vectorcraft_doc::PatternDef) -> bool { + fn clear_ids(node: &mut Node) { + node.id = NodeId(0); + if let Some(children) = node.children_mut() { + for child in children { + clear_ids(Arc::make_mut(child)); + } + } + if let Some(mask) = &mut node.extras_mut().mask { + clear_ids(Arc::make_mut(&mut mask.art)); + } + } + + let mut a = existing.clone(); + let mut b = source.clone(); + for pattern in [&mut a, &mut b] { + for node in &mut pattern.art { + clear_ids(Arc::make_mut(node)); + } + } + a == b +} + +/// Bring document resources used by page art across before reassigning its node IDs. +fn copy_page_resources(doc: &mut Document, page: &Document, nodes: &[&Node]) -> Result<(), String> { + fn collect(node: &Node, images: &mut BTreeSet, patterns: &mut BTreeSet, swatches: &mut BTreeSet) { + if let NodeKind::Image(im) = &node.kind { + images.insert(im.key.clone()); + } + for item in &node.appearance.items { + match item.paint() { + vectorcraft_color::Paint::Solid { swatch: Some(name), .. } => { + swatches.insert(name.clone()); + } + vectorcraft_color::Paint::Gradient(gradient) => { + if let Some(name) = &gradient.swatch { + swatches.insert(name.clone()); + } + for stop in &gradient.gradient.stops { + if let Some(name) = &stop.swatch { + swatches.insert(name.clone()); + } + } + } + vectorcraft_color::Paint::Pattern { pattern, .. } => { + patterns.insert(pattern.clone()); + } + _ => {} + } + } + if let Some(mask) = &node.extras().mask { + collect(&mask.art, images, patterns, swatches); + } + for child in node.children().into_iter().flatten() { + collect(child, images, patterns, swatches); + } + } + + let (mut images, mut patterns, mut swatches) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new()); + for node in nodes { + collect(node, &mut images, &mut patterns, &mut swatches); + } + let mut copied = BTreeSet::new(); + while let Some(name) = patterns.pop_first() { + if !copied.insert(name.clone()) { + continue; + } + let Some(source) = page.pattern(&name) else { return Err(format!("page art is missing pattern {name}")) }; + if let Some(existing) = doc.pattern(&name) { + if !same_pattern_art(existing, source) { + return Err(format!("page art conflicts with pattern {name}")); + } + } else { + for node in &source.art { + collect(node, &mut images, &mut patterns, &mut swatches); + } + let mut pattern = source.clone(); + pattern.art = pattern.art.iter().map(|node| Arc::new(reid_page_art(doc, node))).collect(); + doc.patterns.push(pattern); + } + } + for key in images { + let Some(blob) = page.images.get(&key) else { return Err(format!("page art is missing image data for {key}")) }; + if doc.images.get(&key).is_some_and(|existing| existing.bytes != blob.bytes) { + return Err(format!("page art conflicts with image data for {key}")); + } + doc.images.entry(key).or_insert_with(|| blob.clone()); + } + for name in swatches { + let Some(source) = page.swatch(&name) else { return Err(format!("page art is missing swatch {name}")) }; + if let Some(existing) = doc.swatch(&name) { + if existing != source { + return Err(format!("page art conflicts with swatch {name}")); + } + } else { + doc.swatches.push(source.clone()); + } + } + Ok(()) +} + +/// The PDF importer keeps group transparency on a group, or folds it into its only child. +/// If the editing object's state cannot be located in that art, use the PDF page as a whole. +/// Every selected page object must carry the state, on itself or down a chain of only children. +fn page_carries_state(editing: &Node, page: &[&Node]) -> bool { + fn carried(node: &Node, matches: &dyn Fn(&Node) -> bool) -> bool { + matches(node) + || match node.children().map(Vec::as_slice) { + Some([only]) => carried(only, matches), + _ => false, + } + } + let has = |matches: &dyn Fn(&Node) -> bool| !page.is_empty() && page.iter().all(|node| carried(node, matches)); + let opacity = editing.opacity >= 0.999 || has(&|node: &Node| (node.opacity - editing.opacity).abs() < 0.001); + let blend = editing.blend == super::BlendMode::Normal || has(&|node: &Node| node.blend == editing.blend); + let isolate = !editing.isolate || has(&|node: &Node| node.isolate); + let knockout = matches!(editing.knockout, vectorcraft_doc::Knockout::Neutral | vectorcraft_doc::Knockout::Off) + || has(&|node: &Node| node.knockout == editing.knockout); + let appearance = !matches!(editing.kind, NodeKind::Group { .. }) || *editing.appearance == vectorcraft_doc::Appearance::default(); + opacity && blend && isolate && knockout && appearance +} + +/// The error for unread objects with no page art to use: what isn't read, as the reader names it. +fn unread_error(unread: &[(NodeId, Vec)]) -> String { + let kinds: BTreeSet<&str> = unread.iter().flat_map(|(_, kinds)| kinds.iter().map(String::as_str)).collect(); + let (ops, other): (Vec<&str>, Vec<&str>) = kinds.into_iter().partition(|k| k.starts_with('`')); + let mut list: BTreeSet = other.into_iter().map(String::from).collect(); + if !ops.is_empty() { + list.insert(format!("operators VectorCraft doesn't know ({})", ops.join(", "))); + } + let list: Vec<&str> = list.iter().map(String::as_str).collect(); + format!("it has {}, which VectorCraft doesn't read from it yet", ai::join_and(&list)) +} + +/// The page's text objects in `shown` that the page objects replacing `doc`'s unread objects hold +/// (see [`replace_unread`], tried on a copy of `doc` before its text objects are filled), taken out +/// of `shown`. +fn take_unread_type( + doc: &Document, + frame: Option<&Frame<'_>>, + unread: &[(NodeId, Vec)], + elsewhere: &[(NodeId, Rect)], + shown: &mut Vec>>, +) -> Vec>> { + let Some(frame) = frame.filter(|_| !unread.is_empty() && !shown.is_empty()) else { return vec![] }; + let mut copied = BTreeSet::new(); + if replace_unread(&mut doc.clone(), frame, unread, elsewhere, &BTreeSet::new(), &mut copied).is_err() { + return vec![]; + } + let (taken, kept) = std::mem::take(shown).into_iter().partition(|o| !o.is_empty() && o.iter().all(|n| copied.contains(&n.id))); + *shown = kept; + taken +} + +/// Replace each unread top-level object with painted page objects inside its readable bounds. +/// `copied` gets the ids of the page's nodes copied. +fn replace_unread( + doc: &mut Document, + frame: &Frame<'_>, + unread: &[(NodeId, Vec)], + elsewhere: &[(NodeId, Rect)], + threaded_frames: &BTreeSet, + copied: &mut BTreeSet, +) -> Result, String> { + fn holds_threaded_frame(node: &Node, frames: &BTreeSet) -> bool { + frames.contains(&node.id) || node.children().is_some_and(|children| children.iter().any(|child| holds_threaded_frame(child, frames))) + } + fn subtree(node: &Node, ids: &mut BTreeSet) { + ids.insert(node.id); + for child in node.children().into_iter().flatten() { + subtree(child, ids); + } + } + + let unread_ids: BTreeSet = unread.iter().map(|(id, _)| *id).collect(); + let mut live = Vec::new(); + for layer in &doc.layers { + collect_live(layer, &unread_ids, &mut live); + } + live.sort_by(|a, b| a.x0.total_cmp(&b.x0)); + + let source_pages: Vec = frame.pages.iter().map(|(page, _)| *page).collect(); + let moves: Vec = frame.pages.iter().map(|(_, shift)| *shift).collect(); + let destination_pages: Vec = frame.pages.iter().map(|(page, shift)| shift.transform_rect_bbox(*page)).collect(); + let mut art = Vec::new(); + for layer in &frame.page.layers { + if layer.visible + && let Some(children) = layer.children() + { + for child in children { + index_page(child, &source_pages, &moves, &mut art, false); + } + } + } + let mut by_x: Vec = (0..art.len()).collect(); + by_x.sort_by(|a, b| art[*a].bounds.x0.total_cmp(&art[*b].bounds.x0)); + let mut claimed = std::collections::BTreeMap::::new(); + let mut counts = std::collections::BTreeMap::::new(); + for (id, kinds) in unread { + let Some((bounds, name, visible, locked, editing)) = + doc.node(*id).and_then(|n| n.visual_bounds().map(|b| (b, n.name.clone(), n.visible, n.locked, n.clone()))) + else { + return Err("an unread object has no readable bounds".into()); + }; + if !bounds.area().is_finite() || bounds.area() <= 0.0 { + return Err("an unread object has no readable bounds".into()); + } + let mut selected = Vec::new(); + let mut page = 0; + let mut first_rejection = None; + 'candidate: for candidate in std::iter::once(bounds).chain(elsewhere.iter().filter(|(other, _)| *other == *id).map(|(_, b)| *b)) { + let live_start = live.partition_point(|b| b.x0 < candidate.x0 - ART_MARGIN); + let live_end = live.partition_point(|b| b.x0 <= candidate.x1 + ART_MARGIN); + if live[live_start..live_end].iter().any(|art| inside(*art, candidate)) { + first_rejection.get_or_insert("an unread object's bounds also contain live art"); + continue; + } + // Each page has its own copy of art across artboards: one page's art can't stand in for it. + if destination_pages.iter().filter(|page| page.intersect(candidate).area() > 0.0).count() > 1 { + first_rejection.get_or_insert("an unread object lies on more than one artboard"); + continue; + } + let candidate_page = page_for(candidate, &destination_pages); + // An artboard that has no page (a PDF part saved with some of the artboards) has no art + // on the page for the object's part on it. + if let Some(page) = destination_pages.get(candidate_page) + && doc.artboards.iter().map(|a| a.rect.intersect(candidate)).any(|part| part.area() > page.intersect(part).area().max(0.0)) + { + first_rejection.get_or_insert("an unread object lies on an artboard that has no page"); + continue; + } + let start = by_x.partition_point(|i| art[*i].bounds.x0 < candidate.x0 - ART_MARGIN); + let end = by_x.partition_point(|i| art[*i].bounds.x0 <= candidate.x1 + ART_MARGIN); + let mut candidates: Vec = + by_x[start..end].iter().copied().filter(|i| art[*i].page == candidate_page && inside(art[*i].bounds, candidate)).collect(); + candidates.sort_unstable(); + let mut covered_until = 0; + let mut candidate_selected = Vec::new(); + for i in candidates { + if i < covered_until || matches!(art[i].node.kind, NodeKind::Path { clipping: true, .. }) { + continue; + } + if art[i].stateful_ancestor { + first_rejection.get_or_insert("an unread object's page art depends on a clipping or appearance ancestor"); + continue 'candidate; + } + covered_until = art[i].end; + candidate_selected.push(i); + } + if !candidate_selected.is_empty() + && !page_carries_state(&editing, &candidate_selected.iter().map(|&i| art[i].node.as_ref()).collect::>()) + { + first_rejection.get_or_insert("an unread object's appearance is not identifiable in the page art"); + continue; + } + if candidate_selected.iter().any(|&i| claimed.range(..art[i].end).next_back().is_some_and(|(_, end)| *end > i)) { + first_rejection.get_or_insert("one page object matches more than one unread object"); + continue; + } + if !candidate_selected.is_empty() { + selected = candidate_selected; + page = candidate_page; + break; + } + } + if selected.is_empty() { + return Err(first_rejection.unwrap_or("an unread object's page art wasn't found in its bounds").into()); + } + if holds_threaded_frame(&editing, threaded_frames) { + return Err("an unread object holds a frame of threaded type".into()); + } + copy_page_resources(doc, frame.page, &selected.iter().map(|&i| art[i].node.as_ref()).collect::>())?; + let mut found = Vec::new(); + for &i in &selected { + let mut copy = Node::clone(&art[i].node); + if let Some(shift) = moves.get(page) { + copy.transform(*shift, PAGE_MOVE); + } + found.push(Arc::new(reid_page_art(doc, ©))); + claimed.insert(i, art[i].end); + subtree(&art[i].node, copied); + } + let mut replacement = Node::group(*id, found); + replacement.name = name; + replacement.visible = visible; + replacement.locked = locked; + let Some(target) = doc.node_mut(*id) else { return Err("an unread object is missing from its layer".into()) }; + *target = replacement; + for kind in kinds { + *counts.entry(kind.clone()).or_default() += 1; + } + } + Ok(counts.into_iter().map(|(kind, count)| format!("{kind} ({count})")).collect()) +} + +/// Most objects of the layers that come in as the page's art where they draw differently from it. +const MAX_DIFFERING: usize = 64; + +/// Most pairs of a patch where the layers and the page differ and a top-level object that may hold +/// it, weighed to find the objects that come in as the page's art. +const MAX_PATCH_PAIRS: usize = 4_000_000; + +/// The layers as read and at the placed files' other placement (each with its count of text +/// objects the page doesn't draw), the one that draws closer to the page first. `reflow` as in +/// [`PageView::difference`]. +fn closer_first( + frame: &Frame<'_>, + view: &mut PageView, + doc: (Document, usize), + other: Option<(Document, usize)>, + reflow: bool, +) -> Vec<(Document, usize)> { + match other { + Some(other) + if view.difference_on_every_page(&other.0, frame.rect, reflow).any < view.difference_on_every_page(&doc.0, frame.rect, reflow).any => + { + vec![other, doc] + } + Some(other) => vec![doc, other], + None => vec![doc], + } +} + +/// `doc`, whose layers draw differently from the page (an object in another color, or one that only +/// one of them draws), with each of its top-level objects that holds such a difference replaced by the +/// page's art in its bounds, when that makes the two look alike → the document and its notes: the +/// comparison's, and how many objects were replaced on each layer (by name, in the layers' order). +/// `None` when only edges or type differ, a difference lies outside every object, more than half +/// of the objects (or more than [`MAX_DIFFERING`]) hold one, one of them holds type or a wrap +/// object, the page's art can't replace one of them ([`replace_unread`]), the page's type of a text +/// object that stays is copied into a replacement, or the two still differ. `shown` is the page's +/// type of each text object that shows. `reflow` as in [`PageView::difference`]. +fn keep_differing( + doc: &Document, + frame: &Frame<'_>, + view: &mut PageView, + threaded_frames: &BTreeSet, + shown: &[Vec>], + reflow: bool, +) -> Option<(Document, Vec)> { + /// The top-level objects that show and print (the outermost objects under a layer or + /// sublayer), with the name of that layer or sublayer as the Layers panel shows it and their + /// bounds. + fn top_level(nodes: &[Arc], layer: &str, out: &mut Vec<(String, NodeId, Rect)>) { + for n in nodes.iter().filter(|n| n.visible) { + match &n.kind { + NodeKind::Layer { printable: false, .. } => {} + NodeKind::Layer { .. } => { + let name = Some(n.display_name()).filter(|name| !name.is_empty()).unwrap_or_else(|| format!("<{}>", n.kind_label())); + top_level(n.children().map_or(&[], Vec::as_slice), &name, out); + } + NodeKind::Path { guide: true, .. } => {} + _ => { + if let Some(b) = n.visual_bounds().filter(|b| b.area().is_finite() && b.area() > 0.0) { + out.push((layer.to_string(), n.id, b)); + } + } + } + } + } + + // Where only spread edges or type differ, or only the art around the page, no object is + // replaced. + let (diff, regions) = view.solid_regions_on_every_page(doc, reflow)?; + if diff.solid <= MAX_SOLID_DIFFERENCE { + return None; + } + let mut objects = vec![]; + top_level(&doc.layers, "", &mut objects); + let pages = view.regions(frame.rect); + objects.retain(|(_, _, b)| pages.iter().any(|page| !b.intersect(*page).is_zero_area())); + if regions.len().saturating_mul(objects.len()) > MAX_PATCH_PAIRS { + return None; + } + // Each patch is the smallest object's that holds it. + let most = MAX_DIFFERING.min(objects.len() / 2); + let mut targets = BTreeSet::new(); + for region in regions { + let (_, id, _) = objects.iter().filter(|(_, _, b)| inside(region, *b)).min_by(|a, b| a.2.area().total_cmp(&b.2.area()))?; + targets.insert(*id); + if targets.len() > most { + return None; + } + } + if targets.is_empty() { + return None; + } + // A replaced wrap object keeps its wrap options, and the area type is wrapped around the page's + // art that replaces it. An object inside a replaced group can't keep them, so such a group isn't + // replaced. Neither is an object that holds type: the page's art that replaces it would hold + // type the page draws for other text objects too. + let mut wraps = vec![]; + for id in &targets { + let node = doc.node(*id)?; + let mut held = matches!(node.kind, NodeKind::Text(_)); + for child in node.children().into_iter().flatten() { + child.walk(&mut |n| held |= n.extras().wrap.is_some() || matches!(n.kind, NodeKind::Text(_))); + } + if held { + return None; + } + if let Some(wrap) = node.extras().wrap { + wraps.push((*id, wrap)); + } + } + let mut kept = doc.clone(); + let replace: Vec<(NodeId, Vec)> = targets.iter().map(|id| (*id, vec![])).collect(); + let mut copied = BTreeSet::new(); + replace_unread(&mut kept, frame, &replace, &[], threaded_frames, &mut copied).ok()?; + // A text object that stays draws its page type, so a copy of that type would draw it twice. + if shown.iter().flatten().any(|n| copied.contains(&n.id)) { + return None; + } + for (id, wrap) in wraps { + kept.node_mut(id)?.extras_mut().wrap = Some(wrap); + } + resolve_text_wrap(&mut kept).ok()?; + let note = compare(frame, view, &kept, reflow).ok()?; + let mut layers: Vec<(String, usize)> = vec![]; + for (layer, _, _) in objects.iter().filter(|(_, id, _)| targets.contains(id)) { + match layers.iter_mut().find(|(name, _)| name == layer) { + Some((_, count)) => *count += 1, + None => layers.push((layer.clone(), 1)), + } + } + let layers: Vec = layers.into_iter().map(|(layer, count)| format!("{layer} ({count})")).collect(); + Some((kept, note.into_iter().chain([format!("{DREW_DIFFERENTLY}: {}", layers.join(", "))]).collect())) +} + +/// Copy page drawing IDs, including mask art outside the ordinary child tree. +pub(super) fn reid_page_art(doc: &mut Document, source: &Node) -> Node { + let mut copy = doc.reid(source); + if let Some(mask) = &mut copy.extras_mut().mask { + mask.art = Arc::new(reid_page_art(doc, &mask.art)); + } + if let Some(children) = copy.children_mut() { + for child in children { + let node = reid_page_art_masks(doc, child); + *child = Arc::new(node); + } + } + copy +} + +fn reid_page_art_masks(doc: &mut Document, source: &Node) -> Node { + let mut copy = source.clone(); + if let Some(mask) = &mut copy.extras_mut().mask { + mask.art = Arc::new(reid_page_art(doc, &mask.art)); + } + if let Some(children) = copy.children_mut() { + for child in children { + *child = Arc::new(reid_page_art_masks(doc, child)); + } + } + copy +} + +/// What goes into each of `infos`' slots, and whether the type is all made from the file's text +/// document. When the text document makes the type of every text object that shows (and the type +/// isn't asked for as outlines: `own` has the page's text objects that show outside placed files), +/// each slot takes its own made type and the page's type is only compared with it: type laid out +/// again, in another font where the file's isn't installed, may differ from the page's. Otherwise +/// see [`plan`], with `pages` (the page's text objects that show and that don't). +fn slot_content( + infos: &[SlotInfo], + stories: &[Option>], + template: Option<(f64, f64)>, + to_doc: Affine, + own: Option<&[Vec>]>, + pages: [&[Vec>]; 2], + notes: &mut Vec, +) -> Result<(Vec, bool), String> { + let made = make_slots(infos, stories, template, to_doc, notes); + if let Some(own) = own.filter(|_| readable_all(infos, &made)) { + return Ok((made_only(infos, made, [own, pages[1]], notes), true)); + } + // The page's type is matched with every text object whose type isn't made, and weighed against + // where every made one draws: that has its limits (the slots of type that looks draw are within + // them, see `build_from`). + let open = infos.iter().zip(&made).filter(|(i, m)| i.look.is_none() && m.is_none()).count(); + if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS { + return Err("it has too many text objects".into()); + } + Ok((plan(infos, stories, made, template, to_doc, pages, notes), false)) +} + +/// The layers `doc` don't draw as the page (`why`), `unseen` text objects of them taken out: the +/// notes to add when `doc` with each live envelope `drawn` lists replaced by the drawn art it took +/// the place of (see [`ai::Structure::envelopes_drawn`]) draws as the page, `doc` then being that; +/// else, with `trust`, the notes for `doc` as it is. An error, `why`, otherwise. The envelope note +/// is added unless `notes` has it. +#[allow(clippy::too_many_arguments)] +fn drawn_or_trusted( + frame: &Frame<'_>, + view: &mut PageView, + doc: &mut Document, + drawn: &[(NodeId, Node)], + notes: &[String], + unseen: usize, + trust: bool, + why: String, + reflow: bool, +) -> Result, String> { + let unseen_note = |n: usize| (n > 0).then(|| format!("{n} {UNSEEN_TEXT}")); + let mut put_back = doc.clone(); + let mut any = false; + for (id, art) in drawn { + if let Some(n) = put_back.node_mut(*id) { + *n = art.clone(); + any = true; + } + } + if any { + let more = prune_unseen(frame, view, &mut put_back, reflow); + if let Ok(note) = compare(frame, view, &put_back, reflow) { + *doc = put_back; + let envelope = (!notes.iter().any(|n| n == ai::ENVELOPE_DRAWN)).then(|| ai::ENVELOPE_DRAWN.to_string()); + return Ok(envelope.into_iter().chain(unseen_note(unseen + more)).chain(note).collect()); + } + } + if trust { + return Ok(unseen_note(unseen).into_iter().chain([format!("{why}: they come from its editing data all the same")]).collect()); + } + Err(why) +} + +/// `doc` with the placed files `placed` lists at their other placement (see +/// [`ai::Structure::placed_elsewhere`]): each image's transform followed by its move. `None` when +/// no listed image survives replacement. +fn elsewhere(doc: &Document, placed: &[(NodeId, Affine)]) -> Option { + if placed.is_empty() { + return None; + } + let mut doc = doc.clone(); + let mut moved = false; + for (id, shift) in placed { + if let Some(NodeKind::Image(im)) = doc.node_mut(*id).map(|n| &mut n.kind) { + im.xf *= *shift; + moved = true; + } + } + // Area type wrapped around a moved image flows around it where it now is. + if moved { + relayout_wrapped(&mut doc); + } + moved.then_some(doc) +} + +/// The page's type that needs no text object of the layers, taken out of `shown` and `hidden` (the +/// page's text objects that show and that don't): how many of them the layers have as outlines. +/// Type in the legacy format (`To` … `TO`, as files saved for Illustrator 10 and earlier keep it) +/// is read as text objects of the layers' own, with no slot (`no_slots`) for the page's type; the +/// page's type that their words don't hold is outlines on the layers, and the comparison with the +/// page says whether they draw it. Without such text and with no slot that shows (`none_shown`), +/// the page's type must all lie inside placed files, which show it. +fn page_type_elsewhere( + no_slots: bool, + none_shown: bool, + shown: &mut Vec>>, + hidden: &mut Vec>>, + doc: &Document, + placed: &[(NodeId, Affine)], +) -> Result { + let mut own = vec![]; + own_text(&doc.layers, &mut own); + let mut as_outlines = 0; + if no_slots && !own.is_empty() { + as_outlines = shown.iter().filter(|o| !in_own_text(o, &own)).count(); + shown.clear(); + hidden.clear(); + } + if none_shown && !shown.is_empty() && own.is_empty() { + if !in_placed_files(shown, doc, placed) { + return Err("its page has text, and its layers have no text objects to put it in".into()); + } + // The page's type is all inside placed files: it is theirs, which their previews show, and + // needs no text object. + shown.clear(); + } + Ok(as_outlines) +} + +/// Is the page's text object `object` the layers' own text (`own`, from [`own_text`]): one with its +/// words next to it? The rest of the page's type is what the editing data keeps as outlines (what +/// the legacy format can't hold), and the comparison with the page says whether the layers draw it. +fn in_own_text(object: &[Arc], own: &[(Rect, String)]) -> bool { + let Some(r) = extent(object) else { return false }; + let near: String = + own.iter().filter(|(b, _)| !b.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(r).is_zero_area()).map(|(_, l)| l.as_str()).collect(); + let page_words: Vec = object + .iter() + .filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(words(&t.plain_text().to_lowercase())) } else { None }) + .flatten() + .collect(); + !near.is_empty() && page_words.iter().all(|w| near.contains(w.as_str())) +} + +/// The text objects of their own (not slots for the page's type) that show in `nodes`: their +/// bounds and their letters, in lower case. +fn own_text(nodes: &[Arc], out: &mut Vec<(Rect, String)>) { + for n in nodes.iter().filter(|n| n.visible) { + match &n.kind { + NodeKind::Text(t) => out.extend(n.visual_bounds().map(|b| (b, letters(&t.plain_text().to_lowercase())))), + NodeKind::Compound { .. } => {} + _ => { + if let Some(c) = n.children() { + own_text(c, out); + } + } + } + } +} + +/// Has `r` the size of `page`'s first artboard (in points)? +fn same_size(r: Option, page: &Document) -> bool { + let (Some(r), Some(p)) = (r, page.artboards.first().map(|a| a.rect)) else { return false }; + (r.width() - p.width()).abs() <= 0.5 && (r.height() - p.height()).abs() <= 0.5 +} + +/// Does all of `objects` (the page's text objects) lie inside placed files that show in `doc`? The +/// page draws a placed file, type and all, where the layers show its preview (a linked image, see +/// `ai::Reader::end_place`), at its first placement or at the other one that `placed` lists (see +/// [`elsewhere`]). +fn in_placed_files(objects: &[Vec>], doc: &Document, placed: &[(NodeId, Affine)]) -> bool { + let inside = |d: &Document| { + let mut files = vec![]; + placed_files(&d.layers, &mut files); + !files.is_empty() + && objects + .iter() + .all(|o| extent(o).is_some_and(|r| files.iter().any(|f: &Rect| f.inflate(OUTLINE_REACH, OUTLINE_REACH).contains_rect(r)))) + }; + inside(doc) || elsewhere(doc, placed).is_some_and(|other| inside(&other)) +} + +/// The page's text objects in `objects` that don't lie inside a placed file that shows in `doc`, at +/// either placement (see [`in_placed_files`]): the placed file's preview has the others. +fn outside_placed_files(objects: &[Vec>], doc: &Document, placed: &[(NodeId, Affine)]) -> Vec>> { + let mut files = vec![]; + placed_files(&doc.layers, &mut files); + if let Some(other) = elsewhere(doc, placed) { + placed_files(&other.layers, &mut files); + } + if files.is_empty() { + return objects.to_vec(); + } + let inside = |o: &[Arc]| extent(o).is_some_and(|r| files.iter().any(|f| f.inflate(OUTLINE_REACH, OUTLINE_REACH).contains_rect(r))); + objects.iter().filter(|o| !inside(o)).cloned().collect() +} + +/// Where the placed files that show in `nodes` are: the linked images the editing data's reader +/// makes of them. +fn placed_files(nodes: &[Arc], out: &mut Vec) { + for n in nodes.iter().filter(|n| n.visible) { + match &n.kind { + NodeKind::Image(im) if im.link.is_some() => out.extend(n.visual_bounds()), + _ => { + if let Some(c) = n.children() { + placed_files(c, out); + } + } + } + } +} + +/// Is the editing data in units of `unit` points beside `page` ([`in_units`])? Its first artboard +/// `board` is, or, when that isn't the page in points, its art's box `art` is (a page cropped to the +/// art). +fn in_units_or_art(board: Option, art: Option, page: &Document, unit: f64) -> bool { + in_units(board, page, unit) || (!same_size(board, page) && in_units(art, page, unit)) +} + +/// The size in points of a unit of the editing data whose first artboard is `board` and whose +/// art's box is `art` (the document's coordinates), read beside `page`: `unit` (the page's +/// `UserUnit`) when the data is in those units ([`in_units_or_art`]), else `canvas_scale` (its +/// declared large canvas scale) when the data is at that scale; `None` when it is in points or +/// there is no page. +fn page_scale(board: Option, art: Option, page: Option<&Document>, unit: f64, canvas_scale: f64) -> Option { + let page = page?; + [unit, canvas_scale].into_iter().find(|&k| in_units_or_art(board, art, page, k)) +} + /// Does the editing data's first artboard `board` (in the document read from it: art space through /// `to_doc`) have the size of `page`'s first artboard in units of `unit` points, `unit` being above /// 1, and not its size in points? `page` is a PDF part read in points from pages of `unit` points a @@ -226,17 +1455,173 @@ fn in_units(board: Option, page: &Document, unit: f64) -> bool { unit.is_finite() && unit > 1.0 && fits(unit) && !fits(1.0) } -/// Draw `doc`'s layers and artboards `k` times as large, from the origin, with their strokes, -/// effects and pattern tiles. -fn scale_document(doc: &mut Document, k: f64) { +/// The most artboards [`shown_artboard`] weighs for the first page, and the most [`page_boards`] +/// weighs for all the pages after it together, a render each. +const MAX_BOARDS_WEIGHED: usize = 16; + +/// Does artboard `a` have the size of `page`? +fn board_fits(a: &vectorcraft_doc::Artboard, page: &Rect) -> bool { + (a.rect.width() - page.width()).abs() <= 0.5 && (a.rect.height() - page.height()).abs() <= 0.5 +} + +/// The last of the artboards `boards` that each page of `pages` can show when every page shows +/// one, in the pages' order. A page after the first shows an artboard of its size. Working from +/// the last page back, each page's entry is the last artboard of its size before the next page's +/// entry. The first page's entry is the artboard before the second page's entry, or the last +/// artboard when there is one page. `None` when the pages after the first have no such artboards. +fn last_boards(boards: &[vectorcraft_doc::Artboard], pages: &[Rect]) -> Option> { + let mut last = vec![0; pages.len()]; + let mut end = boards.len(); + for (i, page) in pages.iter().enumerate().skip(1).rev() { + let j = (1..end).rev().find(|&j| boards.get(j).is_some_and(|a| board_fits(a, page)))?; + *last.get_mut(i)? = j; + end = j; + } + if let Some(l) = last.first_mut() { + *l = end.checked_sub(1)?; + } + Some(last) +} + +/// Which of the artboards of `doc` (the layers' document) the page `page_rect` of `visible` shows, +/// when `visible` has fewer pages than `doc` has artboards (a PDF saved with a range of them): of +/// those of the page's size (`fits`) that leave an artboard for each later page ([`last_boards`]), +/// the one whose art draws most like the page, the first of them on a tie. Else (and for an EPS, +/// whose page is its art) the first artboard (0). +fn shown_artboard(doc: &Document, visible: &Document, page: Page, page_rect: Rect, fits: impl Fn(&Rect) -> bool) -> usize { + if matches!(page, Page::Art) || visible.artboards.len() >= doc.artboards.len() { + return 0; + } + let pages: Vec = visible.artboards.iter().map(|a| a.rect).collect(); + let last = last_boards(&doc.artboards, &pages).and_then(|l| l.first().copied()).unwrap_or(usize::MAX); + let sized: Vec = + doc.artboards.iter().enumerate().filter(|(i, a)| *i <= last && fits(&a.rect)).map(|(i, _)| i).take(MAX_BOARDS_WEIGHED).collect(); + if let [only] = sized.as_slice() { + return *only; + } + let mut best: Option<(usize, f64)> = None; + for (i, a) in sized.iter().filter_map(|&i| Some((i, doc.artboards.get(i)?))) { + let d = difference(visible, page_rect, doc, a.rect).any; + if best.is_none_or(|(_, b)| d < b) { + best = Some((i, d)); + } + } + best.map_or(0, |(i, _)| i) +} + +/// The pages after the first, each with the artboard it shows ([`page_boards`]), as [`Frame::more`] +/// holds them: none when the pages don't show the artboards. They stop before the page that would +/// take the pixels the comparisons draw (`samples`, [`comparison_samples`]), the first page's +/// included, past [`MAX_PIXELS_COMPARED`], and after [`MAX_PAGES_COMPARED`] pages. +fn more_pages(boards: Option<&[vectorcraft_doc::Artboard]>, pages: &[Rect], samples: u32) -> Vec<(Rect, Rect)> { + let Some(boards) = boards else { return vec![] }; + let mut left = MAX_PIXELS_COMPARED; + pages + .iter() + .zip(boards) + .map_while(|(page, board)| { + left = left.checked_sub(pixels_compared(*page, samples))?; + Some((*page, board.rect)) + }) + .take(MAX_PAGES_COMPARED) + .skip(1) + .collect() +} + +/// The artboards (or other areas) of `pages` that `bounds` lies on, with `margin` (points) round it: +/// the pages whose drawings taking it out can change. +fn pages_touched(bounds: Rect, pages: &[Rect], margin: f64) -> Vec { + let b = bounds.inflate(margin, margin); + pages.iter().enumerate().filter(|(_, p)| !b.intersect(**p).is_zero_area()).map(|(i, _)| i).collect() +} + +/// The artboards of the layers' document (`doc`) that the pages of `visible` (`pages`) show, one a +/// page, the first page's being `first`, each of its page's size. The artboards are in the pages' +/// order. A page after the first shows an artboard after the previous page's, and only one that +/// leaves an artboard for each later page ([`last_boards`]). When several artboards can be the +/// page's (a PDF saved with some of them), the page shows the one whose art draws most like it, +/// the first of them on a tie. At most [`MAX_BOARDS_WEIGHED`] artboards are weighed for all the +/// later pages together, each page's candidates in order: a page takes the best of its candidates +/// that were weighed, or its first candidate when none of them were. `None` when the pages have no +/// such artboards. +fn page_boards(doc: &Document, visible: &Document, first: usize, pages: &[Rect]) -> Option> { + let boards = &doc.artboards; + let same = |j: usize, p: &Rect| boards.get(j).is_some_and(|a| board_fits(a, p)); + let last = last_boards(boards, pages)?; + if !pages.first().is_some_and(|p| same(first, p)) || last.first().is_none_or(|&l| first > l) { + return None; + } + let mut shown = vec![boards.get(first)?.clone()]; + let (mut after, mut weighed) = (first + 1, 0); + for (i, page) in pages.iter().enumerate().skip(1) { + let sized: Vec = (after..=*last.get(i)?).filter(|&j| same(j, page)).collect(); + let j = match sized.as_slice() { + [] => return None, + [only] => *only, + many => { + let weigh: Vec = many.iter().copied().take(MAX_BOARDS_WEIGHED.saturating_sub(weighed)).collect(); + weighed += weigh.len(); + let mut best: Option<(usize, f64)> = None; + for (j, a) in weigh.iter().filter_map(|&j| Some((j, boards.get(j)?))) { + let d = difference(visible, *page, doc, a.rect).any; + if best.is_none_or(|(_, b)| d < b) { + best = Some((j, d)); + } + } + best.map_or(many.first().copied(), |(j, _)| Some(j))? + } + }; + shown.push(boards.get(j)?.clone()); + after = j + 1; + } + Some(shown) +} + +/// Drops the guides of artboards `doc` no longer has: an artboard guide goes with its artboard. +fn drop_guides_off_boards(doc: &mut Document) { + let kept: Vec = doc.artboards.iter().map(|a| a.id).collect(); + doc.guides.retain(|g| g.artboard.is_none_or(|id| kept.contains(&id))); +} + +/// Draw `doc`'s layers, artboards and guides `k` times as large, from the origin, with their +/// strokes, effects and pattern tiles, and with `styles` the strokes and effects of its graphic +/// styles. +pub(crate) fn scale_document(doc: &mut Document, k: f64, styles: bool) { let a = Affine::scale(k); let scaling = Scaling { strokes: true, effects: Some(vectorcraft_effects::scale_effect), patterns: true, ..Default::default() }; for layer in &mut doc.layers { - Arc::make_mut(layer).transform(a, scaling); + let layer = Arc::make_mut(layer); + layer.transform(a, scaling); + scale_wrap_offsets(layer, k); } for board in &mut doc.artboards { board.rect = a.transform_rect_bbox(board.rect); } + for guide in &mut doc.guides { + guide.pos *= k; + } + if styles { + for g in doc.graphic_styles.iter_mut() { + g.appearance.scale_strokes(k); + g.appearance.scale_effects(k, vectorcraft_effects::scale_effect); + } + } +} + +/// The text wrap offsets of `n` and what it holds, times `k` (within the -1000 to 1000 points +/// they may be). +fn scale_wrap_offsets(n: &mut Node, k: f64) { + if let Some(w) = n.extras_if_any().and_then(|e| e.wrap.as_mut()) { + let v = w.offset * k; + if !v.is_nan() { + w.offset = v.clamp(-1000.0, 1000.0); + } + } + if let Some(children) = n.children_mut() { + for c in children { + scale_wrap_offsets(Arc::make_mut(c), k); + } + } } /// Marks (in a node's name, until [`prune_unseen`] has looked) the text objects made from the file's @@ -253,6 +1638,9 @@ const UNSEEN_TEXT: &str = "text objects that the file keeps but its page doesn't /// left out. const PAGE_TYPE_WITHOUT_OUTLINES: &str = "text objects hold their type as the page draws it, without the characters the page has only as outlines"; +/// The page's text objects that the layers have as outlines, as the editing data keeps them. +const PAGE_TYPE_AS_OUTLINES: &str = "text objects of the page are outlines on the layers, as the file's editing data keeps them"; + /// How much more of the page (0 to 1) the layers may differ without a text object and still look no worse. const UNSEEN_MARGIN: f64 = 5e-5; @@ -290,44 +1678,768 @@ fn take_out(nodes: &mut Vec>, id: NodeId, hide: bool) -> bool { nodes.iter_mut().any(|n| !matches!(n.kind, NodeKind::Compound { .. }) && Arc::make_mut(n).children_mut().is_some_and(|c| take_out(c, id, hide))) } -/// The text objects made from the file's text document that show and print on the page's area, -/// where the page has no type to match them, and that the layers look no worse without, are not -/// drawn by the app that wrote the file (which paints every shown text object; it keeps the type -/// of what was turned to outlines): they are taken out. How many. -pub(super) fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document) -> usize { +/// The text objects made from the file's text document that show and print on a page's area (the +/// frame's first page or another one, [`Frame::more`]), where the page has no type to match them, and +/// that the layers look no worse without on every page they lie on, are not drawn by the app that +/// wrote the file (which paints every shown text object; it keeps the type of what was turned to +/// outlines): they are taken out. How many. `reflow`: the type is all laid out again from the text +/// document (see [`compare`]). +pub(super) fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document, reflow: bool) -> usize { let mut found = vec![]; unmark(&mut doc.layers, true, true, &mut found); - let rect = frame.rect; if found.is_empty() || found.len() > MAX_WEIGHED { return 0; } - let with = view.difference(doc, rect).any; - // Taking a text object out changes only what is drawn in its box. When the art would still - // differ from the page by more than `compare` allows with every candidate gone, the layers - // aren't used whatever is pruned: don't draw them again for each one (#758). + let pages = view.regions(frame.rect); + // Taking a text object out changes only what is drawn in its box. When the art on a page would + // still differ from it by more than `compare` allows with every candidate gone, pruning doesn't + // make that page pass: the objects on it aren't drawn again one by one (#758). let margin = OUTLINE_REACH + 1.0; - let boxes: f64 = found.iter().filter_map(|(_, b)| *b).map(|b| b.inflate(margin, margin).intersect(rect).area().max(0.0)).sum(); - if with - boxes / rect.area().max(1e-9) > MAX_DIFFERENCE { - return 0; - } + let hopeless: Vec = view + .differences(doc, frame.rect, reflow) + .iter() + .zip(&pages) + .map(|(with, rect)| { + let boxes: f64 = found.iter().filter_map(|(_, b)| *b).map(|b| b.inflate(margin, margin).intersect(*rect).area().max(0.0)).sum(); + with.weighed(reflow) - boxes / rect.area().max(1e-9) > MAX_DIFFERENCE + }) + .collect(); // Weighed by colour, not only lightness: a text object's red stroke over a dark red one is no - // less there for being about as light (#1102). - let mut with = view.colour_difference(doc, rect); + // less there for being about as light (#1102). The view keeps each page's drawing and share: a + // removal has only the pages in `on` drawn again. let mut removed = 0; for (id, bounds) in found { - if bounds.is_none_or(|b| b.intersect(rect).is_zero_area()) { + // A removal before it can have let its area type flow differently. + let bounds = if removed > 0 { doc.node(id).and_then(|n| n.visual_bounds()) } else { bounds }; + let Some(b) = bounds else { continue }; + let mut lies = pages_touched(b, &pages, 0.0); + if lies.is_empty() { + continue; + } + // The pages its strokes and effects can reach past its box are drawn again too. + let mut on = pages_touched(b, &pages, margin); + // Area type that flows around it can reach other pages: they are all weighed. + if has_wraps(doc) { + (lies, on) = ((0..pages.len()).collect(), (0..pages.len()).collect()); + } + if lies.iter().any(|i| hopeless.get(*i).copied().unwrap_or(true)) { continue; } let mut without = doc.clone(); if !take_out(&mut without.layers, id, true) { continue; } - let d = view.colour_difference(&without, rect); - if d - with <= UNSEEN_MARGIN { + // Area type that wrapped around the text object flows without it. + relayout_wrapped(&mut without); + let shares = view.weigh_without(doc, &without, &on); + if shares.len() == on.len() && shares.iter().all(|(_, before, after)| after - before <= UNSEEN_MARGIN) { take_out(&mut doc.layers, id, false); - with = d; + relayout_wrapped(doc); + // Only the pages in `on` can draw differently (every page when type wraps). + view.adopt(doc); removed += 1; } } removed } + +#[cfg(test)] +mod candidate_tests { + use super::*; + + use vectorcraft_doc::{ImageBlob, ImageObject}; + + /// The pages compared stop where their drawings would take more than the pixels allowed. + #[test] + fn the_pages_compared_stop_at_the_pixel_bound() { + let pages: Vec = (0..1000).map(|i| Rect::new(f64::from(i) * 700.0, 0.0, f64::from(i) * 700.0 + 612.0, 792.0)).collect(); + let doc = Document::new(612.0, 792.0); + let boards: Vec = pages + .iter() + .map(|page| { + let mut board = doc.artboards[0].clone(); + board.rect = *page; + board + }) + .collect(); + let more = more_pages(Some(&boards), &pages, 1); + let each = pixels_compared(pages[0], 1); + assert_eq!(more.len() + 1, (MAX_PIXELS_COMPARED / each) as usize); + assert!(more.len() >= 64, "{}", more.len()); + assert_eq!(more_pages(Some(&boards[..3]), &pages[..3], 1).len(), 2); + // Pages drawn with 4 × 4 samples a pixel take 16 times the pixels. + assert_eq!(more_pages(Some(&boards), &pages, 4).len() + 1, (MAX_PIXELS_COMPARED / (each * 16)) as usize); + // Tiny pages stop at the page count. + let tiny: Vec = (0..1000).map(|i| Rect::new(f64::from(i) * 2.0, 0.0, f64::from(i) * 2.0 + 1.0, 1.0)).collect(); + let tiny_boards: Vec = + boards.iter().zip(&tiny).map(|(b, r)| vectorcraft_doc::Artboard { rect: *r, ..b.clone() }).collect(); + assert_eq!(more_pages(Some(&tiny_boards), &tiny, 1).len() + 1, MAX_PAGES_COMPARED); + } + + /// A page after the first doesn't take an artboard that a later page of another size needs, + /// even one that draws more like it. + #[test] + fn a_later_page_leaves_an_artboard_of_each_later_pages_size() { + let square = |doc: &mut Document, x: f64| { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(x, 10.0, x + 20.0, 30.0)), + vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::None, + 0.0, + ), + ); + let layer = doc.layers[0].id; + doc.insert(Some(layer), 0, art).unwrap(); + }; + let board = |doc: &Document, x0: f64, width: f64| vectorcraft_doc::Artboard { + rect: Rect::new(x0, 0.0, x0 + width, 100.0), + ..doc.artboards[0].clone() + }; + // Artboards of 100, 100, 200, 100 and 100 points, a square on the fourth. + let mut doc = Document::new(100.0, 100.0); + doc.artboards = [(0.0, 100.0), (150.0, 100.0), (300.0, 200.0), (550.0, 100.0), (700.0, 100.0)].map(|(x, w)| board(&doc, x, w)).to_vec(); + square(&mut doc, 560.0); + // Pages of 100, 100 and 200 points, the second with the fourth artboard's square. + let mut page = Document::new(100.0, 100.0); + let pages = [Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(120.0, 0.0, 220.0, 100.0), Rect::new(240.0, 0.0, 440.0, 100.0)]; + page.artboards = pages.iter().map(|r| board(&page, r.x0, r.width())).collect(); + square(&mut page, 130.0); + let shown = page_boards(&doc, &page, 0, &pages).map(|b| b.iter().map(|a| a.rect.x0).collect::>()); + assert_eq!(shown, Some(vec![0.0, 150.0, 300.0])); + } + + /// The pages after the first weigh at most [`MAX_BOARDS_WEIGHED`] artboards together: a page + /// takes the best of its candidates that were weighed, and a page left with none to weigh + /// takes its first candidate, even when a later candidate draws like it. + #[test] + fn the_later_pages_weigh_a_bounded_number_of_artboards() { + let square = |doc: &mut Document, x: f64| { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(x, 10.0, x + 20.0, 30.0)), + vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::None, + 0.0, + ), + ); + let layer = doc.layers[0].id; + doc.insert(Some(layer), 0, art).unwrap(); + }; + let board = |doc: &Document, x0: f64, width: f64| vectorcraft_doc::Artboard { + rect: Rect::new(x0, 0.0, x0 + width, 100.0), + ..doc.artboards[0].clone() + }; + // Artboards 0 to 17 are 100 points wide, 150 apart; artboards 18 and 19 are 200 points + // wide. The second page's square is on artboard 17 and the third page's on artboard 19. + let n = MAX_BOARDS_WEIGHED + 2; + let mut doc = Document::new(100.0, 100.0); + let mut boards: Vec = (0..n).map(|i| board(&doc, i as f64 * 150.0, 100.0)).collect(); + let wide = n as f64 * 150.0; + boards.push(board(&doc, wide, 200.0)); + boards.push(board(&doc, wide + 250.0, 200.0)); + doc.artboards = boards; + square(&mut doc, (n - 1) as f64 * 150.0 + 10.0); + square(&mut doc, wide + 260.0); + let mut page = Document::new(100.0, 100.0); + let pages = [Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(120.0, 0.0, 220.0, 100.0), Rect::new(240.0, 0.0, 440.0, 100.0)]; + page.artboards = pages.iter().map(|r| board(&page, r.x0, r.width())).collect(); + square(&mut page, 130.0); + square(&mut page, 250.0); + // The second page weighs artboards 1 to 16, which draw alike, and takes artboard 1. The + // third page has no weighing left and takes artboard 18. + let shown = page_boards(&doc, &page, 0, &pages).map(|b| b.iter().map(|a| a.rect.x0).collect::>()); + assert_eq!(shown, Some(vec![0.0, 150.0, wide])); + } + + /// The first page of a PDF of some artboards shows an artboard that leaves one for each later + /// page, even when a later artboard draws more like it. + #[test] + fn the_first_page_leaves_an_artboard_for_each_later_page() { + let square = |doc: &mut Document, x: f64| { + let art = Node::path( + doc.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(x, 10.0, x + 20.0, 30.0)), + vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::None, + 0.0, + ), + ); + let layer = doc.layers[0].id; + doc.insert(Some(layer), 0, art).unwrap(); + }; + let board = |doc: &Document, x0: f64| vectorcraft_doc::Artboard { rect: Rect::new(x0, 0.0, x0 + 100.0, 100.0), ..doc.artboards[0].clone() }; + // Three artboards of one size, a square on the third. + let mut doc = Document::new(100.0, 100.0); + doc.artboards = [0.0, 150.0, 300.0].map(|x| board(&doc, x)).to_vec(); + square(&mut doc, 310.0); + // Two pages, the square on the first. + let mut page = Document::new(100.0, 100.0); + let pages = [Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(120.0, 0.0, 220.0, 100.0)]; + page.artboards = pages.iter().map(|r| board(&page, r.x0)).collect(); + square(&mut page, 10.0); + let fits = |r: &Rect| (r.width() - 100.0).abs() <= 0.5 && (r.height() - 100.0).abs() <= 0.5; + let first = shown_artboard(&doc, &page, Page::Artboard, pages[0], fits); + assert_eq!(first, 0); + let shown = page_boards(&doc, &page, first, &pages).map(|b| b.iter().map(|a| a.rect.x0).collect::>()); + assert_eq!(shown, Some(vec![0.0, 150.0])); + } + + /// A linked image showing a placeholder (`XF`) waits on the page, whose PDF part draws its + /// pixels: the layers aren't used without it. + #[test] + fn a_linked_image_placeholder_waits_on_the_page() { + let raster = "%AI5_File:\n%AI5_BeginRaster\n(photo.tif) 0 XG\n[ 1 0 0 1 0 4 ] 0 0 4 4 4 4 8 3 0 0 0 0 XF\n%AI5_EndRaster\n"; + let data = format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n{raster}LB\n%AI5_EndLayer--\n%%Trailer\n" + ); + let structure = ai::read(data.as_bytes(), false).unwrap(); + assert_eq!(structure.placeholders.len(), 1); + assert!(!nothing_waits_on_page(&structure)); + } + + /// The pages a box touches with a margin round it include those it only comes near. + #[test] + fn the_pages_within_reach_of_a_box_count_as_touched() { + let pages = [Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(110.0, 0.0, 210.0, 100.0)]; + let near_the_second = Rect::new(60.0, 40.0, 106.0, 60.0); + assert_eq!(pages_touched(near_the_second, &pages, 0.0), vec![0]); + assert_eq!(pages_touched(near_the_second, &pages, OUTLINE_REACH + 1.0), vec![0, 1]); + } + + /// Layers read in the units of a page scaled up to points take their wrap offsets with their art, + /// within ±1000 points. + #[test] + fn scaling_the_document_scales_its_wrap_offsets() { + let mut doc = Document::new(100.0, 100.0); + let mut ids = vec![]; + for (x, offset) in [(0.0, 6.0), (20.0, 200.0), (40.0, -150.0)] { + let id = doc.alloc_id(); + let mut n = Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Default::default()); + n.extras_mut().wrap = Some(vectorcraft_doc::TextWrap { offset, invert: true }); + doc.insert(Some(doc.layers[0].id), 0, n).unwrap(); + ids.push(id); + } + scale_document(&mut doc, 10.0, false); + let offsets: Vec<_> = ids.iter().map(|id| doc.node(*id).and_then(|n| n.extras().wrap)).collect(); + let wrap = |offset| Some(vectorcraft_doc::TextWrap { offset, invert: true }); + assert_eq!(offsets, [wrap(60.0), wrap(1000.0), wrap(-1000.0)]); + } + + /// Area type in `doc`'s first layer at `index`, in the frame `r`. + fn insert_area(doc: &mut Document, index: usize, r: Rect) -> NodeId { + let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "Wrapped", Default::default()); + t.kind = vectorcraft_doc::TextKind::Area { frame: vectorcraft_geom::shapes::rectangle(r) }; + let id = doc.alloc_id(); + doc.insert(Some(doc.layers[0].id), index, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap() + } + + /// A wrap object on top of `doc`'s first layer: a closed path of `anchors` anchors in `r`. + fn insert_wrap(doc: &mut Document, r: Rect, anchors: usize) -> NodeId { + let mut bp = kurbo::BezPath::new(); + bp.move_to((r.x0, r.y0)); + for i in 1..anchors { + let t = i as f64 / anchors as f64; + bp.line_to((r.x0 + r.width() * t, if i % 2 == 0 { r.y0 } else { r.y1 })); + } + bp.close_path(); + let id = doc.alloc_id(); + let mut n = Node::path(id, PathData::from_bezpath(&bp), Default::default()); + n.extras_mut().wrap = Some(vectorcraft_doc::TextWrap::default()); + let top = doc.layers[0].children().map_or(0, Vec::len); + doc.insert(Some(doc.layers[0].id), top, n).unwrap() + } + + fn wrap_shapes(doc: &Document, id: NodeId) -> usize { + match doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => t.wrap.len(), + _ => panic!("area type"), + } + } + + /// A file whose wrap shapes would copy more than `MAX_WRAP_WORK` anchors isn't read from its + /// layers; one below that is. + #[test] + fn wrap_shapes_of_too_many_text_objects_are_refused() { + for (texts, ok) in [(150, true), (250, false)] { + let mut doc = Document::new(100.0, 100.0); + let ids: Vec = (0..texts).map(|_| insert_area(&mut doc, 0, Rect::new(0.0, 0.0, 100.0, 100.0))).collect(); + insert_wrap(&mut doc, Rect::new(40.0, 0.0, 60.0, 100.0), 10_000); + assert!(vectorcraft_doc::text::wrap_work(&doc) >= texts * 10_000); + assert_eq!(resolve_text_wrap(&mut doc).is_ok(), ok, "{texts} text objects"); + // Nor is anything copied on the way, as the placed files' other placement does. + relayout_wrapped(&mut doc); + assert!(ids.iter().all(|id| wrap_shapes(&doc, *id) == usize::from(ok)), "{texts} text objects"); + } + } + + /// Warped type whose look takes its place, with the type's wrap setting, is held to the same + /// limit on wrap shapes: a file whose looks would copy more than `MAX_WRAP_WORK` anchors isn't + /// read from its layers. + #[test] + fn warped_type_replaced_by_its_look_is_held_to_the_wrap_limit() { + for (texts, ok) in [(150, true), (250, false)] { + let mut doc = Document::new(100.0, 100.0); + (0..texts).for_each(|_| _ = insert_area(&mut doc, 0, Rect::new(0.0, 0.0, 100.0, 100.0))); + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(50.0, 50.0), "TILT", Default::default()); + let mut text = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + let mut appearance = vectorcraft_doc::Appearance::default(); + appearance.effects.push(vectorcraft_doc::Effect { id: "warp.arc".into(), params: serde_json::json!({"bend": 40.0}), visible: true }); + text.appearance = appearance.into(); + text.extras_mut().wrap = Some(vectorcraft_doc::TextWrap::default()); + let top = doc.layers[0].children().map_or(0, Vec::len); + let id = doc.insert(Some(doc.layers[0].id), top, text).unwrap(); + let look = insert_wrap(&mut doc, Rect::new(40.0, 0.0, 60.0, 100.0), 10_000); + let look = doc.remove(look).unwrap(); + assert!(resolve_text_wrap(&mut doc).is_ok()); + let warped = ai::WarpedType::unchecked(vec![(id, (*look).clone())]); + let filled = std::collections::HashMap::from([(id, Filled { text: vec![id], objects: vec![id] })]); + let mut notes = vec![]; + let settled = settle_warped_type(warped, &mut doc, &filled, &BTreeSet::new(), &BTreeSet::new(), &mut vec![], &mut notes); + assert_eq!(settled.is_ok(), ok, "{texts} text objects"); + assert_eq!(notes, ["warped text objects that came in as drawn art, not as editable type: 1"]); + } + } + + /// Area type that wrapped around an object taken out of the layers flows without it. + #[test] + fn wrap_shapes_go_with_their_wrap_object() { + let mut doc = Document::new(100.0, 100.0); + let text = insert_area(&mut doc, 0, Rect::new(0.0, 0.0, 100.0, 100.0)); + let wrap = insert_wrap(&mut doc, Rect::new(40.0, 0.0, 60.0, 100.0), 4); + resolve_text_wrap(&mut doc).unwrap(); + assert_eq!(wrap_shapes(&doc, text), 1); + doc.remove(wrap).unwrap(); + relayout_wrapped(&mut doc); + assert_eq!(wrap_shapes(&doc, text), 0); + } + + /// An image variable binds the linked image its XML id names, and not an embedded image or a + /// path; a text variable binds the type a slot became, and not a slot that became two text + /// objects; a visibility variable binds every object that took a slot's place and is still in + /// the document; a graph variable + /// binds nothing. A locked object, one in a hidden group and objects on a locked artboard are + /// bound too. Every binding left out, and those the reader left out, are counted in one note. + #[test] + fn variable_bindings_take_objects_of_their_kind() { + use vectorcraft_doc::{LinkInfo, Variable, Variables}; + let mut doc = Document::new(100.0, 100.0); + let made = insert_area(&mut doc, 0, Rect::new(0.0, 0.0, 50.0, 50.0)); + let (one, two) = (insert_area(&mut doc, 1, Rect::new(50.0, 0.0, 60.0, 10.0)), insert_area(&mut doc, 2, Rect::new(60.0, 0.0, 70.0, 10.0))); + let path = insert_wrap(&mut doc, Rect::new(0.0, 60.0, 10.0, 70.0), 4); + let locked = insert_wrap(&mut doc, Rect::new(20.0, 60.0, 30.0, 70.0), 4); + let image = |doc: &mut Document, link: Option| { + let id = doc.alloc_id(); + let im = ImageObject { key: "k".into(), width: 1, height: 1, xf: Affine::IDENTITY, link, placement: Default::default(), pixels: None }; + doc.insert(Some(doc.layers[0].id), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + id + }; + let (linked, embedded) = (image(&mut doc, Some(LinkInfo::new("/a.png"))), image(&mut doc, None)); + doc.node_mut(locked).unwrap().locked = true; + let hidden = doc.alloc_id(); + let inside = doc.alloc_id(); + let mut group = Node::group( + hidden, + vec![Arc::new(Node::new( + inside, + NodeKind::Image(Box::new(ImageObject { + key: "k".into(), + width: 1, + height: 1, + xf: Affine::IDENTITY, + link: Some(LinkInfo::new("/b.png")), + placement: Default::default(), + pixels: None, + })), + ))], + ); + group.visible = false; + doc.insert(Some(doc.layers[0].id), 0, group).unwrap(); + doc.artboards[0].locked = true; + let var = |name: &str, kind| Variable { name: name.into(), kind }; + doc.variables = Variables { + variables: vec![ + var("v_image", VariableKind::Image), + var("v_text", VariableKind::Text), + var("v_shown", VariableKind::Visibility), + var("v_graph", VariableKind::Graph), + ], + ..Default::default() + } + .into(); + // The slots the text objects came from are gone; their ids are the ones the reader gave. + let (slot, split) = (NodeId(9000), NodeId(9001)); + let ids: std::collections::HashMap> = [ + ("linked", Some(linked)), + ("embedded", Some(embedded)), + ("path", Some(path)), + ("locked", Some(locked)), + ("inside", Some(inside)), + ("slot", Some(slot)), + ("split", Some(split)), + ] + .map(|(k, v)| (k.to_string(), v)) + .into(); + let filled: std::collections::HashMap = [ + (slot, Filled { text: vec![made], objects: vec![made] }), + (split, Filled { text: vec![one, two], objects: vec![one, two, NodeId(9002)] }), + ] + .into(); + let bind = |variable: &str, target: &str| ai::BindingRef { variable: variable.into(), target: Some(target.into()) }; + let refs = [ + bind("v_image", "linked"), + bind("v_image", "embedded"), + bind("v_image", "path"), + bind("v_image", "inside"), + bind("v_text", "slot"), + bind("v_text", "split"), + bind("v_shown", "split"), + bind("v_shown", "locked"), + bind("v_graph", "path"), + ]; + let mut notes = vec![]; + bind_variables(&mut doc, &refs, 3, &ids, &filled, &mut notes); + let sorted = |mut v: Vec| { + v.sort(); + v + }; + assert_eq!(sorted(doc.variables.objects_of("v_image")), sorted(vec![linked, inside])); + assert_eq!(doc.variables.objects_of("v_text"), [made]); + assert_eq!(sorted(doc.variables.objects_of("v_shown")), sorted(vec![one, two, locked])); + assert!(doc.variables.objects_of("v_graph").is_empty()); + assert_eq!(notes, ai::bindings_note(4 + 3).into_iter().collect::>()); + } + + /// Area type wrapped around a placed image flows around it at the image's other placement. + #[test] + fn wrap_shapes_follow_an_image_to_its_other_placement() { + let mut doc = Document::new(100.0, 100.0); + let text = insert_area(&mut doc, 0, Rect::new(0.0, 0.0, 100.0, 100.0)); + let image = doc.alloc_id(); + let mut n = Node::new( + image, + NodeKind::Image(Box::new(ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: Affine::translate(Vec2::new(10.0, 10.0)), + link: None, + placement: Default::default(), + pixels: None, + })), + ); + n.extras_mut().wrap = Some(vectorcraft_doc::TextWrap::default()); + doc.insert(Some(doc.layers[0].id), 1, n).unwrap(); + resolve_text_wrap(&mut doc).unwrap(); + let x0 = |d: &Document| match d.node(text).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => t.wrap.first().and_then(|w| w.path.bounds()).map(|b| b.x0), + _ => None, + }; + assert_eq!(x0(&doc), Some(10.0)); + let moved = elsewhere(&doc, &[(image, Affine::translate(Vec2::new(50.0, 0.0)))]).unwrap(); + assert_eq!(x0(&moved), Some(60.0)); + } + + /// A page image with a different proxy keeps its editing layer and original blob. + #[test] + fn page_image_with_different_proxy_keeps_editing_layer() { + let mut doc = Document::new(100.0, 100.0); + let placeholder_id = doc.alloc_id(); + let placeholder = Node::path(placeholder_id, vectorcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 54.0, 54.0)), Default::default()); + doc.insert(Some(doc.layers[0].id), 0, placeholder).unwrap(); + + let mut page = Document::new(100.0, 100.0); + let mut editing_blob = ImageBlob::new("image/png", vec![1, 2, 3]); + editing_blob.proxy = Some(Arc::new(vec![4, 5, 6])); + let page_blob = ImageBlob::new("image/png", vec![1, 2, 3]); + let key = editing_blob.content_key(); + assert_eq!(key, page_blob.content_key()); + doc.images.insert(key.clone(), editing_blob.clone()); + page.images.insert(key.clone(), page_blob); + let image = Node::new( + page.alloc_id(), + NodeKind::Image(Box::new(ImageObject { + key: key.clone(), + width: 4, + height: 4, + xf: Affine::translate(Vec2::new(50.0, 50.0)), + link: None, + placement: Default::default(), + pixels: None, + })), + ); + page.insert(Some(page.layers[0].id), 0, image).unwrap(); + + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; + let kinds = replace_unread( + &mut doc, + &frame, + &[(placeholder_id, vec!["placed files".into()])], + &[(placeholder_id, Rect::new(50.0, 50.0, 54.0, 54.0))], + &BTreeSet::new(), + &mut BTreeSet::new(), + ) + .unwrap(); + assert_eq!(kinds, ["placed files (1)"]); + let replacement = doc.node(placeholder_id).unwrap(); + let [image] = replacement.children().unwrap().as_slice() else { panic!("{replacement:?}") }; + assert!(matches!(image.kind, NodeKind::Image(_))); + assert_eq!(doc.images.get(&key), Some(&editing_blob)); + } + + /// An unread object across two artboards isn't replaced by the art of one page only. + #[test] + fn unread_object_across_two_pages_is_not_replaced() { + let mut doc = Document::new(200.0, 100.0); + let id = doc.alloc_id(); + doc.insert( + Some(doc.layers[0].id), + 0, + Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(90.0, 10.0, 110.0, 20.0)), Default::default()), + ) + .unwrap(); + let mut page = Document::new(200.0, 100.0); + for bounds in [Rect::new(91.0, 11.0, 99.0, 19.0), Rect::new(101.0, 11.0, 109.0, 19.0)] { + let art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(bounds), + vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::None, + 0.0, + ), + ); + page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); + } + let (first, second) = (Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(100.0, 0.0, 200.0, 100.0)); + let frame = Frame { + page: &page, + page_rect: first, + rect: first, + whole: false, + pages: vec![(first, Affine::IDENTITY), (second, Affine::IDENTITY)], + more: vec![], + }; + let result = replace_unread(&mut doc, &frame, &[(id, vec!["placed files".into()])], &[], &BTreeSet::new(), &mut BTreeSet::new()); + assert_eq!(result.unwrap_err(), "an unread object lies on more than one artboard"); + } + + /// An unread object reaching an artboard that has no page isn't replaced by the page's part of it. + #[test] + fn unread_object_on_an_artboard_without_a_page_is_not_replaced() { + let mut doc = Document::new(100.0, 100.0); + doc.artboards.push(vectorcraft_doc::Artboard { id: 2, rect: Rect::new(100.0, 0.0, 200.0, 100.0), ..doc.artboards[0].clone() }); + let id = doc.alloc_id(); + doc.insert( + Some(doc.layers[0].id), + 0, + Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(90.0, 10.0, 110.0, 20.0)), Default::default()), + ) + .unwrap(); + let mut page = Document::new(100.0, 100.0); + let art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(91.0, 11.0, 99.0, 19.0)), + vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0), + ); + page.insert(Some(page.layers[0].id), 0, art).unwrap(); + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; + let result = replace_unread(&mut doc, &frame, &[(id, vec!["placed files".into()])], &[], &BTreeSet::new(), &mut BTreeSet::new()); + assert_eq!(result.unwrap_err(), "an unread object lies on an artboard that has no page"); + + // Half a point onto it is still on it. + let narrow = Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(90.0, 10.0, 100.5, 20.0)), Default::default()); + *doc.node_mut(id).unwrap() = narrow; + let result = replace_unread(&mut doc, &frame, &[(id, vec!["placed files".into()])], &[], &BTreeSet::new(), &mut BTreeSet::new()); + assert_eq!(result.unwrap_err(), "an unread object lies on an artboard that has no page"); + } + + /// A nested placeholder's corner cannot replace its readable sibling. + #[test] + fn nested_placeholder_corner_cannot_replace_readable_sibling() { + let mut doc = Document::new(100.0, 100.0); + let group_id = doc.alloc_id(); + let placeholder = Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), Default::default()); + let placeholder_id = placeholder.id; + let sibling = Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(70.0, 70.0, 74.0, 74.0)), Default::default()); + let sibling_id = sibling.id; + let group = Node::group(group_id, vec![Arc::new(placeholder), Arc::new(sibling)]); + doc.insert(Some(doc.layers[0].id), 0, group).unwrap(); + + let mut page = Document::new(100.0, 100.0); + let art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(81.0, 81.0, 89.0, 89.0)), + vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0), + ); + page.insert(Some(page.layers[0].id), 0, art).unwrap(); + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; + let result = replace_unread( + &mut doc, + &frame, + &[(group_id, vec!["placed files".into()])], + &[(placeholder_id, Rect::new(80.0, 80.0, 90.0, 90.0))], + &BTreeSet::new(), + &mut BTreeSet::new(), + ); + assert_eq!(result.unwrap_err(), "an unread object's page art wasn't found in its bounds"); + let group = doc.node(group_id).unwrap(); + assert!(group.children().unwrap().iter().any(|child| child.id == sibling_id)); + } + + /// An alternative box may carry opacity missing from the first box. + #[test] + fn alternative_box_can_carry_opacity_when_first_box_cannot() { + let mut doc = Document::new(100.0, 100.0); + let id = doc.alloc_id(); + let mut editing = Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), Default::default()); + editing.opacity = 0.5; + doc.insert(Some(doc.layers[0].id), 0, editing).unwrap(); + + let mut page = Document::new(100.0, 100.0); + for (bounds, opacity) in [(Rect::new(11.0, 11.0, 19.0, 19.0), 1.0), (Rect::new(51.0, 51.0, 59.0, 59.0), 0.5)] { + let mut art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(bounds), + vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::None, + 0.0, + ), + ); + art.opacity = opacity; + page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); + } + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; + let kinds = replace_unread( + &mut doc, + &frame, + &[(id, vec!["placed files".into()])], + &[(id, Rect::new(50.0, 50.0, 60.0, 60.0))], + &BTreeSet::new(), + &mut BTreeSet::new(), + ) + .unwrap(); + assert_eq!(kinds, ["placed files (1)"]); + let replacement = doc.node(id).unwrap(); + let [art] = replacement.children().unwrap().as_slice() else { panic!("{replacement:?}") }; + assert_eq!(art.opacity, 0.5); + assert_eq!(art.geometric_bounds(), Some(Rect::new(51.0, 51.0, 59.0, 59.0))); + } + + /// Opacity on one of two page objects in the box is not the unread object's opacity. + #[test] + fn opacity_on_one_of_two_page_objects_is_not_identifiable() { + let mut doc = Document::new(100.0, 100.0); + let id = doc.alloc_id(); + let mut editing = Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(10.0, 10.0, 40.0, 40.0)), Default::default()); + editing.opacity = 0.5; + doc.insert(Some(doc.layers[0].id), 0, editing).unwrap(); + + let mut page = Document::new(100.0, 100.0); + for (bounds, opacity) in [(Rect::new(11.0, 11.0, 19.0, 19.0), 0.5), (Rect::new(21.0, 21.0, 39.0, 39.0), 1.0)] { + let mut art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(bounds), + vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::None, + 0.0, + ), + ); + art.opacity = opacity; + page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); + } + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; + let result = replace_unread(&mut doc, &frame, &[(id, vec!["placed files".into()])], &[], &BTreeSet::new(), &mut BTreeSet::new()); + assert_eq!(result.unwrap_err(), "an unread object's appearance is not identifiable in the page art"); + } + + /// A claimed first box lets a second unread object use its own corner box. + #[test] + fn second_unread_object_tries_corner_after_first_box_is_claimed() { + let mut doc = Document::new(100.0, 100.0); + let first = doc.alloc_id(); + let second = doc.alloc_id(); + for (id, bounds) in [(first, Rect::new(10.0, 10.0, 20.0, 20.0)), (second, Rect::new(12.0, 12.0, 22.0, 22.0))] { + let node = Node::path(id, vectorcraft_geom::shapes::rectangle(bounds), Default::default()); + doc.insert(Some(doc.layers[0].id), doc.layers[0].children().unwrap().len(), node).unwrap(); + } + + let mut page = Document::new(100.0, 100.0); + for bounds in [Rect::new(14.0, 14.0, 16.0, 16.0), Rect::new(51.0, 51.0, 59.0, 59.0)] { + let art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(bounds), + vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::None, + 0.0, + ), + ); + page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); + } + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; + let unread = [(first, vec!["placed files".into()]), (second, vec!["placed files".into()])]; + let mut one_box_doc = doc.clone(); + let kinds = replace_unread(&mut doc, &frame, &unread, &[(second, Rect::new(50.0, 50.0, 60.0, 60.0))], &BTreeSet::new(), &mut BTreeSet::new()) + .unwrap(); + assert_eq!(kinds, ["placed files (2)"]); + let first_art = doc.node(first).unwrap().children().unwrap()[0].geometric_bounds(); + let second_art = doc.node(second).unwrap().children().unwrap()[0].geometric_bounds(); + assert_eq!(first_art, Some(Rect::new(14.0, 14.0, 16.0, 16.0))); + assert_eq!(second_art, Some(Rect::new(51.0, 51.0, 59.0, 59.0))); + assert_eq!( + replace_unread(&mut one_box_doc, &frame, &unread, &[], &BTreeSet::new(), &mut BTreeSet::new()).unwrap_err(), + "one page object matches more than one unread object" + ); + } + + /// Only the page's type in the page art that replaces an unread object is taken out of the + /// page's type for the text objects: type in the object's other box, which isn't used, stays. + #[test] + fn only_page_type_in_the_chosen_box_is_taken_for_an_unread_object() { + let mut doc = Document::new(100.0, 100.0); + let id = doc.alloc_id(); + doc.insert( + Some(doc.layers[0].id), + 0, + Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), Default::default()), + ) + .unwrap(); + let mut page = Document::new(100.0, 100.0); + let mut nodes = vec![]; + for bounds in [Rect::new(12.0, 12.0, 18.0, 18.0), Rect::new(52.0, 52.0, 58.0, 58.0)] { + let art = Node::path( + page.alloc_id(), + vectorcraft_geom::shapes::rectangle(bounds), + vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + vectorcraft_color::Paint::None, + 0.0, + ), + ); + nodes.push(Arc::new(art.clone())); + page.insert(Some(page.layers[0].id), page.layers[0].children().unwrap().len(), art).unwrap(); + } + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let frame = Frame { page: &page, page_rect: rect, rect, whole: false, pages: vec![(rect, Affine::IDENTITY)], more: vec![] }; + let unread = [(id, vec!["placed files".into()])]; + let mut shown: Vec>> = nodes.iter().map(|n| vec![Arc::clone(n)]).collect(); + let taken = take_unread_type(&doc, Some(&frame), &unread, &[(id, Rect::new(50.0, 50.0, 60.0, 60.0))], &mut shown); + assert_eq!(taken.iter().flatten().map(|n| n.id).collect::>(), [nodes[0].id]); + assert_eq!(shown.iter().flatten().map(|n| n.id).collect::>(), [nodes[1].id]); + let mut copied = BTreeSet::new(); + replace_unread(&mut doc, &frame, &unread, &[], &BTreeSet::new(), &mut copied).unwrap(); + assert!(copied.contains(&nodes[0].id) && !copied.contains(&nodes[1].id)); + } +} diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index cf86445e59..044dbd2401 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -47,7 +47,10 @@ const WHITE: u32 = 8; /// Do two pixels look different: in lightness, or one inked (as a light yellow is) where the other /// is white? -pub(super) fn differ(p: &[u8; 4], q: &[u8; 4]) -> bool { +pub(in crate::import) fn differ(p: &[u8; 4], q: &[u8; 4]) -> bool { + if p == q { + return false; + } let (p, q) = (on_white(p), on_white(q)); let (a, b) = (ink(p), ink(q)); lightness(p).abs_diff(lightness(q)) > SAME_PIXEL || (a.min(b) <= WHITE && a.abs_diff(b) > SAME_PIXEL) @@ -59,7 +62,10 @@ const SAME_COLOUR: u32 = 64; /// Are two pixels different colours ([`differ`] also takes a red and a dark red of about the same /// lightness to be alike)? -pub(super) fn differ_in_colour(p: &[u8; 4], q: &[u8; 4]) -> bool { +pub(in crate::import) fn differ_in_colour(p: &[u8; 4], q: &[u8; 4]) -> bool { + if p == q { + return false; + } let (p, q) = (on_white(p), on_white(q)); p.iter().zip(q).any(|(a, b)| a.abs_diff(b) > SAME_COLOUR) } @@ -73,10 +79,30 @@ pub(super) struct Difference { pub(super) any: f64, art: f64, pub(super) solid: f64, + /// The share that differs in the type's areas (`any` less `art`), kept on its own when the + /// shares of several regions are taken together ([`Self::max`]). + typed: f64, +} + +impl Difference { + /// The share [`compare`] holds to [`MAX_DIFFERENCE`]: every pixel that differs, or with `reflow` + /// (type laid out again from the file's text) those away from type. + pub(super) fn weighed(&self, reflow: bool) -> f64 { + if reflow { self.art } else { self.any } + } + + /// The larger of each share of `self` and `other`: how two regions differ, the one that differs + /// most for each. + fn max(self, other: Self) -> Self { + Self { any: self.any.max(other.any), art: self.art.max(other.art), solid: self.solid.max(other.solid), typed: self.typed.max(other.typed) } + } + + /// Two drawings that can't be compared: every pixel differs. + const ALL: Self = Self { any: 1.0, art: 1.0, solid: 1.0, typed: 0.0 }; } /// The scale the comparisons draw a region at: about 400 pixels along its longer side. -fn compare_scale(r: Rect) -> f64 { +pub(in crate::import) fn compare_scale(r: Rect) -> f64 { (400.0 / r.width().max(r.height()).max(1.0)).min(4.0) } @@ -118,70 +144,506 @@ pub(super) fn comparison_render( vectorcraft_render::Rendered { width, height, pixels } } -/// The page drawn once, to weigh the layers' art against it: [`Self::difference`] draws the layers -/// with a renderer of their own, which keeps their decoded images between draws (the page's images -/// can share their keys and not their pixels, so the two don't share one). -pub(super) struct PageView { - page: vectorcraft_render::Rendered, +/// The most pixels the pages of a frame are drawn in for a comparison, all of them together +/// ([`pixels_compared`]): the pages after those that reach it aren't compared. It holds about 67 +/// letter-size pages drawn with one sample a pixel, and 4 drawn with 4 × 4 ([`comparison_samples`]). +pub(super) const MAX_PIXELS_COMPARED: u64 = 1 << 23; + +/// The most pages of a frame compared, the first included, however few pixels they take. +pub(super) const MAX_PAGES_COMPARED: usize = 128; + +/// How many pixels the comparisons draw the page `page` of the PDF part in, at [`compare_scale`] +/// with `samples` × `samples` samples a pixel ([`comparison_samples`]): `u64::MAX` for one that +/// can't be drawn. +pub(super) fn pixels_compared(page: Rect, samples: u32) -> u64 { + let samples = u64::from(samples) * u64::from(samples); + vectorcraft_render::raster_size(page, compare_scale(page)).map_or(u64::MAX, |(w, h)| (u64::from(w) * u64::from(h)).saturating_mul(samples)) +} + +/// The longest side (pixels) of a sheet ([`Sheet`]). +const MAX_SHEET_SIDE: f64 = 8192.0; + +/// How many times its pages' pixels a sheet may have, the gaps between them included. +const SHEET_SPREAD: f64 = 2.0; + +/// One page of the PDF part, drawn once. +struct Page { + drawn: vectorcraft_render::Rendered, /// Where the page's own type is, in its pixels. page_type: Vec, /// Where objects read with their art style lie, in its pixels: the page has Illustrator's /// rendering of the style there, the layers VectorCraft's live effects, and the two aren't /// held to look alike. restyled: Vec, - layers: vectorcraft_render::Renderer, + /// The column and row of its pixels that its move ([`Self::region`]) took partly off its area, + /// where the layers can draw a neighboring artboard's art and the page the space between pages: + /// they count as alike. + edges: Vec, + /// Where the page draws anything (its type, or its own outlines of type) or has its type, in its + /// pixels row by row. + page_marks: Vec, scale: f64, + /// The page area's width and height ([`sized`]). + size: (f64, f64), + /// The area of the layers' document the page is compared with: its artboard ([`sized`]), moved + /// by up to half a pixel to start on a pixel of its sheet, the page's area with it. + region: Rect, +} + +impl Page { + /// The area `ra` of `page`, `drawn` at `scale` ([`compare_scale`]), to be compared with the layers + /// on `region`, both moved by (`dx`, `dy`) pixels from where the artboard and page lie. + fn on(page: &Document, drawn: vectorcraft_render::Rendered, ra: Rect, region: Rect, scale: f64, (dx, dy): (f64, f64)) -> Self { + let mut page_type = vec![]; + type_areas(&page.layers, ra, scale, &mut page_type); + let (w, h) = (drawn.width as usize, drawn.height as usize); + let typed = in_areas(&page_type, w, h); + // A pixel with nothing drawn on it is white. + let page_marks: Vec = + drawn.pixels.as_chunks::<4>().0.iter().zip(&typed).map(|(p, t)| *t || (p[3] != 0 && ink(on_white(p)) > WHITE)).collect(); + let (wf, hf) = (f64::from(drawn.width), f64::from(drawn.height)); + let mut edges = vec![]; + // Moved left (or up), the first column (or row) starts before the area; moved right (or + // down), the last one ends past it. + match dx { + d if d > 1e-6 => edges.push(Rect::new(0.0, 0.0, 1.0, hf)), + d if d < -1e-6 => edges.push(Rect::new(wf - 1.0, 0.0, wf, hf)), + _ => {} + } + match dy { + d if d > 1e-6 => edges.push(Rect::new(0.0, 0.0, wf, 1.0)), + d if d < -1e-6 => edges.push(Rect::new(0.0, hf - 1.0, wf, hf)), + _ => {} + } + Self { drawn, page_type, restyled: vec![], edges, page_marks, scale, size: (ra.width(), ra.height()), region } + } + + /// The pixels that count as alike: the restyled looks' and the edges'. + fn skipped(&self) -> Vec { + self.restyled.iter().chain(&self.edges).copied().collect() + } + + /// Where [`PageView::difference_on_every_page`] counts `b`'s (on `rb`) and the page's pixels as + /// type, in the page's pixels. With `reflow` (`b`'s type laid out again from the file's text), + /// type counts as type only where both have something: `b`'s where the page has type or draws + /// anything in at least [`MARKED`] of it, the page's where at least half of it lies where `b` has + /// a text object, shown or not, or a placed file. Elsewhere it is art the other lacks. + fn counted_type(&self, b: &Document, rb: Rect, reflow: bool) -> Vec { + let mut areas = vec![]; + type_areas(&b.layers, rb, self.scale, &mut areas); + if reflow { + let (w, h) = (self.drawn.width as usize, self.drawn.height as usize); + let marked = shares(&self.page_marks, w, h, &areas); + areas = areas.into_iter().zip(marked).filter(|(_, share)| *share >= MARKED).map(|(r, _)| r).collect(); + let mut texts = vec![]; + all_type_areas(&b.layers, rb, self.scale, &mut texts); + let on_layers = shares(&in_areas(&texts, w, h), w, h, &self.page_type); + areas.extend(self.page_type.iter().zip(on_layers).filter(|(_, share)| *share >= 0.5).map(|(r, _)| *r)); + } else { + areas.extend(&self.page_type); + } + areas + } +} + +/// `rb`, or when its sides are within half a point of `size` (a page area's, as an artboard taken for +/// its page is), the area of that size at its top-left: the layers are drawn on it, so that both +/// drawings have the same number of pixels. +fn sized((w, h): (f64, f64), rb: Rect) -> Rect { + if (rb.width() - w).abs() <= 0.5 && (rb.height() - h).abs() <= 0.5 { Rect::new(rb.x0, rb.y0, rb.x0 + w, rb.y0 + h) } else { rb } +} + +/// An area of the layers' document that holds the areas of some of the pages drawn at one scale, +/// each starting on one of its pixels: the layers are drawn on it once for all of them, and cut +/// apart. +struct Sheet { + rect: Rect, + scale: f64, + /// Its pages, as [`PageView::regions`] counts them. + pages: Vec, + /// How many pixels its pages take. + pixels: f64, +} + +impl Sheet { + /// The move (less than half a pixel) that makes `region` start on one of the sheet's pixels, and + /// the sheet's area with it: `None` when the sheet would then be too large ([`MAX_SHEET_SIDE`], + /// [`SHEET_SPREAD`]). + fn room(&self, region: Rect) -> Option<((f64, f64), Rect)> { + let s = self.scale; + let off = |v: f64, from: f64| { + let px = (v - from) * s; + (px - px.round()) / s + }; + let (dx, dy) = (off(region.x0, self.rect.x0), off(region.y0, self.rect.y0)); + let moved = Rect::new(region.x0 - dx, region.y0 - dy, region.x1 - dx, region.y1 - dy); + let all = self.rect.union(moved); + let (w, h) = (all.width() * s, all.height() * s); + let pixels = self.pixels + moved.width() * s * moved.height() * s; + (w.is_finite() && h.is_finite() && w.max(h) <= MAX_SHEET_SIDE && w * h <= SHEET_SPREAD * pixels).then_some(((dx, dy), all)) + } +} + +/// How many documents' drawings a [`PageView`] keeps. +const KEPT_DOCUMENTS: usize = 2; + +/// The layers of one document as drawn on the pages' areas, kept between comparisons. +struct Drawn { + /// The document's layers, held so that a document changed since never shares them. Only the + /// layers are compared: the import changes the documents it compares in their layers, and two + /// documents with the same layers and other symbols, patterns, swatches or color mode would + /// share their drawings. + layers: Vec>, + /// Each page's drawing, once drawn. + pages: Vec>, +} + +impl Drawn { + /// Are these the drawings of `b`, for `n` pages? + fn of(&self, b: &Document, n: usize) -> bool { + self.pages.len() == n && self.layers.len() == b.layers.len() && self.layers.iter().zip(&b.layers).all(|(x, y)| Arc::ptr_eq(x, y)) + } +} + +/// The layers drawn on one page's area, with how they differ from the page once weighed. +struct Layered { + pixels: vectorcraft_render::Rendered, + /// [`compared`] as [`PageView::difference_on_every_page`] weighs it, without and with `reflow`. + laid: Option, + reflowed: Option, + /// [`colour_share`]. + colour: Option, +} + +/// The pages drawn once, to weigh the layers' art against them, and the layers' drawings of the last +/// two documents weighed. The layers are drawn with a renderer of their own, which keeps their decoded +/// images between draws (the page's images can share their keys and not their pixels, so the two +/// don't share one). +pub(super) struct PageView { + /// The frame's first page, then its other pages ([`Frame::more`]). + pages: Vec, + /// The areas in the layers' document that the pages are compared on, as the frame gives them. + boards: Vec, + sheets: Vec, samples: u32, + layers: vectorcraft_render::Renderer, + /// The drawings of the last [`KEPT_DOCUMENTS`] documents weighed, the last one weighed last (the + /// import weighs two readings of a file back and forth). + drawn: Vec, + /// The drawings of the last document [`Self::weigh_without`] weighed, with their shares. + without: Vec<(usize, vectorcraft_render::Rendered, f64)>, + /// How many times the layers were drawn. + draws: usize, } impl PageView { pub(super) fn new(frame: &Frame<'_>) -> Self { - let ra = frame.page_rect; - let scale = compare_scale(ra); + let samples = comparison_samples(frame.page); + // Each page's area, the area of the layers' document it is compared with, and its scale. + let (mut planned, mut boards, mut sheets) = (vec![], vec![], Vec::::new()); + for (ra, rb) in std::iter::once((frame.page_rect, frame.rect)).chain(frame.more.iter().copied()) { + let (scale, i) = (compare_scale(ra), planned.len()); + let region = sized((ra.width(), ra.height()), rb); + let pixels = region.width() * scale * region.height() * scale; + // A page whose drawings are resampled ([`comparison_samples`]) is drawn on its own. + // Pages of one size can have scales a rounding error apart: they take the sheet's. + let room = sheets.last().filter(|s| samples == 1 && (s.scale - scale).abs() <= scale * 1e-9).and_then(|s| s.room(region)); + let (dx, dy, scale) = match (room, sheets.last_mut()) { + (Some(((dx, dy), all)), Some(sheet)) => { + sheet.rect = all; + sheet.pixels += pixels; + sheet.pages.push(i); + (dx, dy, sheet.scale) + } + _ => { + sheets.push(Sheet { rect: region, scale, pages: vec![i], pixels }); + (0.0, 0.0, scale) + } + }; + let moved = |r: Rect| Rect::new(r.x0 - dx, r.y0 - dy, r.x1 - dx, r.y1 - dy); + planned.push((moved(ra), moved(region), scale, (dx * scale, dy * scale))); + boards.push(rb); + } // Drawn on nothing and then seen on white: blending modes have no page to blend with, as in // the app that wrote the file. - let samples = comparison_samples(frame.page); - let page = comparison_render(&mut vectorcraft_render::Renderer::new(), frame.page, ra, scale, samples); - let mut page_type = vec![]; - type_areas(&frame.page.layers, ra, scale, &mut page_type); - Self { page, page_type, restyled: vec![], layers: vectorcraft_render::Renderer::new(), scale, samples } - } - - /// Leave the drawn looks in `looks` (on `region`, the page's area in the layers' document) out - /// of the comparisons ([`Structure::restyled`](ai::Structure)). - pub(super) fn restyled(&mut self, looks: &[Rect], region: Rect) { - let s = self.scale; - self.restyled = looks - .iter() - .map(|r| r.inflate(OUTLINE_REACH, OUTLINE_REACH)) - .map(|r| Rect::new((r.x0 - region.x0) * s, (r.y0 - region.y0) * s, (r.x1 - region.x0) * s, (r.y1 - region.y0) * s)) + let mut renderer = vectorcraft_render::Renderer::new(); + let pages = planned + .into_iter() + .map(|(ra, region, scale, moved)| { + Page::on(frame.page, comparison_render(&mut renderer, frame.page, ra, scale, samples), ra, region, scale, moved) + }) .collect(); + Self { pages, boards, sheets, samples, layers: vectorcraft_render::Renderer::new(), drawn: vec![], without: vec![], draws: 0 } } - /// How `b` on `rb` (a rectangle the page's size) draws differently from the page ([`compared`]). - pub(super) fn difference(&mut self, b: &Document, rb: Rect) -> Difference { + /// The areas in the layers' document that the pages are compared on: `rb` for the first page, + /// then each other page's artboard. + pub(super) fn regions(&self, rb: Rect) -> Vec { + std::iter::once(rb).chain(self.boards.iter().skip(1).copied()).collect() + } + + /// Leave the drawn looks in `looks` (on `region`, the first page's area in the layers' document) + /// out of the comparisons ([`Structure::restyled`](ai::Structure)), on the other pages' artboards + /// too. + pub(super) fn restyled(&mut self, looks: &[Rect], region: Rect) { + for (i, page) in self.pages.iter_mut().enumerate() { + let (s, region) = (page.scale, if i == 0 { region } else { page.region }); + page.restyled = looks + .iter() + .map(|r| r.inflate(OUTLINE_REACH, OUTLINE_REACH)) + .map(|r| Rect::new((r.x0 - region.x0) * s, (r.y0 - region.y0) * s, (r.x1 - region.x0) * s, (r.y1 - region.y0) * s)) + .collect(); + } + self.drawn.clear(); + } + + /// `b`, as printed, drawn on the areas of the pages `wanted`: on their sheet when they are more + /// than one and take at least half its pixels, else each on its own. + fn draw(&mut self, b: &Document, wanted: &[usize]) -> Vec<(usize, vectorcraft_render::Rendered)> { + let mut out = vec![]; + for sheet in &self.sheets { + let on: Vec = sheet.pages.iter().copied().filter(|i| wanted.contains(i)).collect(); + let s = sheet.scale; + let taken: f64 = on.iter().filter_map(|i| self.pages.get(*i)).map(|p| p.region.width() * s * p.region.height() * s).sum(); + // A pixel more on the right and at the bottom, for the pages' areas rounded up. + let whole = (on.len() > 1 && taken * 2.0 >= sheet.rect.width() * s * sheet.rect.height() * s).then(|| { + self.draws += 1; + let r = sheet.rect; + comparison_render(&mut self.layers, b, Rect::new(r.x0, r.y0, r.x1 + 1.0 / s, r.y1 + 1.0 / s), s, 1) + }); + for i in on { + let Some(page) = self.pages.get(i) else { continue }; + let r = page.region; + let part = whole + .as_ref() + .zip(vectorcraft_render::raster_size(r, s).ok()) + .and_then(|(whole, (w, h))| cut(whole, (r.x0 - sheet.rect.x0) * s, (r.y0 - sheet.rect.y0) * s, w, h)); + let drawn = match part { + Some(part) => part, + None => { + self.draws += 1; + comparison_render(&mut self.layers, b, r, page.scale, self.samples) + } + }; + out.push((i, drawn)); + } + } + out + } + + /// Have the layers of `b` drawn on the pages `wanted`, keeping those already drawn when `b` is the + /// document last drawn. + fn layered(&mut self, b: &Document, wanted: &[usize]) { + let n = self.pages.len(); + match self.drawn.iter().position(|d| d.of(b, n)) { + Some(at) => { + let kept = self.drawn.remove(at); + self.drawn.push(kept); + } + None => { + if self.drawn.len() >= KEPT_DOCUMENTS { + self.drawn.remove(0); + } + self.drawn.push(Drawn { layers: b.layers.clone(), pages: (0..n).map(|_| None).collect() }); + } + } + let missing: Vec = + wanted.iter().copied().filter(|i| self.drawn.last().and_then(|d| d.pages.get(*i)).is_some_and(Option::is_none)).collect(); + if missing.is_empty() { + return; + } // The page doesn't print what isn't printed. let printed = as_printed(b); - let b = printed.as_ref().unwrap_or(b); - let y = comparison_render(&mut self.layers, b, rb, self.scale, self.samples); - let mut areas = self.page_type.clone(); - type_areas(&b.layers, rb, self.scale, &mut areas); - compared(&self.page, &y, &areas, &self.restyled) + for (i, pixels) in self.draw(printed.as_ref().unwrap_or(b), &missing) { + if let Some(slot) = self.drawn.last_mut().and_then(|d| d.pages.get_mut(i)) { + *slot = Some(Layered { pixels, laid: None, reflowed: None, colour: None }); + } + } } - /// The share (0 to 1) of the pixels where `b` on `rb` draws another colour than the page - /// ([`differ_in_colour`]), type included: what taking an object out of the layers changes - /// there, when it is covered by one of about the same lightness (#1102). - pub(super) fn colour_difference(&mut self, b: &Document, rb: Rect) -> f64 { + /// How `b` draws differently from each page ([`compared`]), the first on `rb` (its frame's area, + /// or another rectangle its size), the others on their artboards. + pub(super) fn differences(&mut self, b: &Document, rb: Rect, reflow: bool) -> Vec { + let all: Vec = (0..self.pages.len()).collect(); + self.layered(b, &all); + let printed = as_printed(b); + let printed = printed.as_ref().unwrap_or(b); + let mut out = vec![]; + for i in all { + let d = if i == 0 && self.boards.first() != Some(&rb) { self.elsewhere(printed, rb, reflow) } else { self.weighed(i, printed, reflow) }; + out.push(d); + } + out + } + + /// The first page compared with `b` (as printed) on `rb`, drawn for it alone. + fn elsewhere(&mut self, b: &Document, rb: Rect, reflow: bool) -> Difference { + let Some(page) = self.pages.first() else { return Difference::ALL }; + let rb = sized(page.size, rb); + self.draws += 1; + let y = comparison_render(&mut self.layers, b, rb, page.scale, self.samples); + compared(&page.drawn, &y, &page.counted_type(b, rb, reflow), &page.skipped()) + } + + /// Page `i` compared with its drawing of `b` (as printed, already drawn), weighed once. + fn weighed(&mut self, i: usize, b: &Document, reflow: bool) -> Difference { + let Some((page, Some(layered))) = self.pages.get(i).zip(self.drawn.last_mut().and_then(|d| d.pages.get_mut(i))) else { + return Difference::ALL; + }; + let memo = if reflow { &mut layered.reflowed } else { &mut layered.laid }; + *memo.get_or_insert_with(|| compared(&page.drawn, &layered.pixels, &page.counted_type(b, page.region, reflow), &page.skipped())) + } + + /// [`Self::differences`] taken together: each share is that of the page that differs most. + pub(super) fn difference_on_every_page(&mut self, b: &Document, rb: Rect, reflow: bool) -> Difference { + self.differences(b, rb, reflow).into_iter().reduce(Difference::max).unwrap_or(Difference::ALL) + } + + /// How `b` draws differently from the pages ([`Self::difference_on_every_page`]), and the boxes + /// (in `b`'s terms) around each patch of the pixels counted in its `solid` share (they and all + /// their neighbors differ, away from type), neighbors touching corner to corner counting as one + /// patch. `None` when the two drawings of a page aren't the same size. + pub(super) fn solid_regions_on_every_page(&mut self, b: &Document, reflow: bool) -> Option<(Difference, Vec)> { + let all: Vec = (0..self.pages.len()).collect(); + self.layered(b, &all); let printed = as_printed(b); let b = printed.as_ref().unwrap_or(b); - let y = comparison_render(&mut self.layers, b, rb, self.scale, self.samples); - if (y.width, y.height) != (self.page.width, self.page.height) { - return 1.0; + let (mut diff, mut regions) = (Difference { any: 0.0, art: 0.0, solid: 0.0, typed: 0.0 }, vec![]); + for (page, layered) in self.pages.iter().zip(&self.drawn.last()?.pages) { + let y = &layered.as_ref()?.pixels; + let (d, solid) = compared_with_solid(&page.drawn, y, &page.counted_type(b, page.region, reflow), &page.skipped()); + regions.extend(patches(solid, y.width as usize, y.height as usize, page.region, page.scale, self.samples)?); + diff = diff.max(d); } - let differing = self.page.pixels.as_chunks::<4>().0.iter().zip(y.pixels.as_chunks::<4>().0).filter(|(p, q)| differ_in_colour(p, q)).count(); - differing as f64 / (f64::from(y.width) * f64::from(y.height)).max(1.0) + Some((diff, regions)) } + + /// The share (0 to 1) of the pixels where `b` on page `i`'s area draws another color than the + /// page ([`colour_share`]). + fn colour_difference(&mut self, i: usize, b: &Document) -> f64 { + self.layered(b, &[i]); + let Some((page, Some(layered))) = self.pages.get(i).zip(self.drawn.last_mut().and_then(|d| d.pages.get_mut(i))) else { return 1.0 }; + *layered.colour.get_or_insert_with(|| colour_share(&page.drawn, &layered.pixels, &page.edges)) + } + + /// `doc`'s and `without`'s shares ([`colour_share`]) on each of the pages `on`, `without` being + /// `doc` with an object taken out that lies on those pages only. `without`'s drawings are kept + /// for [`Self::adopt`]. + pub(super) fn weigh_without(&mut self, doc: &Document, without: &Document, on: &[usize]) -> Vec<(usize, f64, f64)> { + self.layered(doc, on); + let printed = as_printed(without); + let drawn = self.draw(printed.as_ref().unwrap_or(without), on); + let mut shares = vec![]; + self.without.clear(); + for (i, pixels) in drawn { + let before = self.colour_difference(i, doc); + let Some(page) = self.pages.get(i) else { continue }; + let after = colour_share(&page.drawn, &pixels, &page.edges); + shares.push((i, before, after)); + self.without.push((i, pixels, after)); + } + shares + } + + /// `doc` now has the object [`Self::weigh_without`] last took out taken out: its drawings are the + /// ones made without the object on the pages it lay on, and the ones kept on the others. + pub(super) fn adopt(&mut self, doc: &Document) { + let without = std::mem::take(&mut self.without); + let Some(drawn) = self.drawn.last_mut() else { return }; + drawn.layers = doc.layers.clone(); + // The type areas on a page can reach past the object's box. + for layered in drawn.pages.iter_mut().flatten() { + (layered.laid, layered.reflowed) = (None, None); + } + for (i, pixels, colour) in without { + if let Some(slot) = drawn.pages.get_mut(i) { + *slot = Some(Layered { pixels, laid: None, reflowed: None, colour: Some(colour) }); + } + } + } +} + +/// The `w` × `h` pixels of `from` from pixel (`x`, `y`): `None` unless they lie in it, from a pixel. +fn cut(from: &vectorcraft_render::Rendered, x: f64, y: f64, w: u32, h: u32) -> Option { + let (rx, ry) = (x.round(), y.round()); + if !((x - rx).abs() < 0.01 && (y - ry).abs() < 0.01 && rx >= 0.0 && ry >= 0.0) { + return None; + } + let (x, y, wu, hu) = (rx as usize, ry as usize, w as usize, h as usize); + let stride = from.width as usize * 4; + if x + wu > from.width as usize || y + hu > from.height as usize { + return None; + } + let mut pixels = Vec::with_capacity(wu * hu * 4); + for row in y..y + hu { + pixels.extend_from_slice(from.pixels.get(row * stride + x * 4..row * stride + (x + wu) * 4)?); + } + Some(vectorcraft_render::Rendered { width: w, height: h, pixels }) +} + +/// The boxes (in the terms of the document drawn on `rb` at `scale` with `samples` × `samples` +/// samples a pixel, [`comparison_render`]) around each patch of the `w` × `h` pixels `solid` marks, +/// neighbors touching corner to corner counting as one patch. `None` when `solid` doesn't have that +/// many pixels. +fn patches(mut solid: Vec, w: usize, h: usize, rb: Rect, scale: f64, samples: u32) -> Option> { + if solid.len() != w * h { + return None; + } + // A pixel's size in points: [`comparison_render`] draws at `scale * samples`, rounds that + // raster to whole pixels and resizes it to `w` × `h`, so the two sizes can round differently. + let k = f64::from(samples); + let drawn = vectorcraft_render::raster_size(rb, scale * k).map_or((w as f64, h as f64), |(dw, dh)| (f64::from(dw), f64::from(dh))); + let pitch = (drawn.0 / (w as f64 * k * scale), drawn.1 / (h as f64 * k * scale)); + let mut regions = vec![]; + let mut stack = vec![]; + for start in 0..solid.len() { + if !solid.get(start).copied().unwrap_or(false) { + continue; + } + // The patch's pixels are cleared as they are taken, so each is taken once. + if let Some(s) = solid.get_mut(start) { + *s = false; + } + stack.push(start); + let (mut i0, mut j0, mut i1, mut j1) = (start % w, start / w, start % w, start / w); + while let Some(k) = stack.pop() { + let (i, j) = (k % w, k / w); + (i0, j0, i1, j1) = (i0.min(i), j0.min(j), i1.max(i), j1.max(j)); + for n in j.saturating_sub(1)..=(j + 1).min(h - 1) { + for m in i.saturating_sub(1)..=(i + 1).min(w - 1) { + if let Some(s) = solid.get_mut(n * w + m).filter(|s| **s) { + *s = false; + stack.push(n * w + m); + } + } + } + } + let at = |i: usize, j: usize| (rb.x0 + i as f64 * pitch.0, rb.y0 + j as f64 * pitch.1); + let ((x0, y0), (x1, y1)) = (at(i0, j0), at(i1 + 1, j1 + 1)); + regions.push(Rect::new(x0, y0, x1, y1)); + } + Some(regions) +} + +/// The share (0 to 1) of the pixels where `y` draws another color than the page `x` +/// ([`differ_in_colour`]), type included and pixels in `skip` counting as alike: what taking an +/// object out of the layers changes there, when it is covered by one of about the same lightness +/// (#1102). +fn colour_share(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered, skip: &[Rect]) -> f64 { + if (y.width, y.height) != (x.width, x.height) { + return 1.0; + } + let skipped = in_areas(skip, x.width as usize, x.height as usize); + let differing = x + .pixels + .as_chunks::<4>() + .0 + .iter() + .zip(y.pixels.as_chunks::<4>().0) + .zip(&skipped) + .filter(|((p, q), s)| !**s && differ_in_colour(p, q)) + .count(); + differing as f64 / (f64::from(y.width) * f64::from(y.height)).max(1.0) } /// How `a` on `ra` and `b` on `rb` (rectangles of the same size) draw differently ([`compared`]), @@ -205,24 +667,41 @@ pub(super) fn difference(a: &Document, ra: Rect, b: &Document, rb: Rect) -> Diff /// at all ([`differ`]): the page of an RGB document is written in the colours' CMYK equivalents, /// and what the comparison looks for is art that is missing or out of place. pub(super) fn compared(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered, areas: &[Rect], skip: &[Rect]) -> Difference { + compared_with_solid(x, y, areas, skip).0 +} + +/// [`compared`], and which of the pixels (row by row) are counted in its `solid` share: none when +/// the drawings can't be compared. +fn compared_with_solid(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered, areas: &[Rect], skip: &[Rect]) -> (Difference, Vec) { if x.width == 0 || x.height == 0 || x.width != y.width || x.height != y.height { - return Difference { any: 1.0, art: 1.0, solid: 1.0 }; + return (Difference { any: 1.0, art: 1.0, solid: 1.0, typed: 0.0 }, vec![]); } let (w, h) = (x.width as usize, x.height as usize); // Pixels in `skip` count as alike. let skipped = in_areas(skip, w, h); let differs: Vec = x.pixels.as_chunks::<4>().0.iter().zip(y.pixels.as_chunks::<4>().0).zip(&skipped).map(|((p, q), s)| !*s && differ(p, q)).collect(); - let at = |i: usize, j: usize| j.checked_mul(w).and_then(|row| row.checked_add(i)).and_then(|k| differs.get(k)).copied().unwrap_or(false); + if !differs.contains(&true) { + return (Difference { any: 0.0, art: 0.0, solid: 0.0, typed: 0.0 }, vec![false; w * h]); + } let typed = in_areas(areas, w, h); let art = differs.iter().zip(&typed).filter(|(d, t)| **d && !**t).count(); + // Which pixels differ with their left and right neighbors. + let mut across = vec![false; w * h]; + for (k, a) in across.iter_mut().enumerate() { + let i = k % w; + *a = i > 0 && i + 1 < w && differs.get(k - 1..=k + 1).is_some_and(|d| d.iter().all(|d| *d)); + } // A pixel on the region's edge has neighbours outside it, which don't count as differing. - let solid = (1..h.saturating_sub(1)) - .flat_map(|j| (1..w.saturating_sub(1)).map(move |i| (i, j))) - .filter(|&(i, j)| !typed.get(j * w + i).copied().unwrap_or(true) && (j - 1..=j + 1).all(|n| (i - 1..=i + 1).all(|m| at(m, n)))) - .count(); + let mut solid = vec![false; w * h]; + for (k, s) in solid.iter_mut().enumerate().skip(w).take(w * h.saturating_sub(2)) { + *s = !typed.get(k).copied().unwrap_or(true) && [k - w, k, k + w].iter().all(|n| across.get(*n).copied().unwrap_or(false)); + } let area = (w as f64 * h as f64).max(1.0); - Difference { any: differs.iter().filter(|d| **d).count() as f64 / area, art: art as f64 / area, solid: solid as f64 / area } + let any = differs.iter().filter(|d| **d).count() as f64 / area; + let art = art as f64 / area; + let shares = Difference { any, art, solid: solid.iter().filter(|s| **s).count() as f64 / area, typed: any - art }; + (shares, solid) } /// Where the type that shows in `nodes` is, in pixels of `region` drawn at `scale` (with a margin @@ -241,57 +720,164 @@ fn type_areas(nodes: &[Arc], region: Rect, scale: f64, out: &mut Vec } } +/// Where every text object in `nodes` is, shown or not, as [`type_areas`] gives it, and every placed +/// file (whose preview draws the type it has). +fn all_type_areas(nodes: &[Arc], region: Rect, scale: f64, out: &mut Vec) { + for n in nodes { + let placed = matches!(&n.kind, NodeKind::Image(im) if im.link.is_some()); + if (placed || matches!(n.kind, NodeKind::Text(_))) + && let Some(b) = n.visual_bounds() + { + let b = b.inflate(OUTLINE_REACH, OUTLINE_REACH); + out.push(Rect::new((b.x0 - region.x0) * scale, (b.y0 - region.y0) * scale, (b.x1 - region.x0) * scale, (b.y1 - region.y0) * scale)); + } else if let Some(c) = n.children() { + all_type_areas(c, region, scale, out); + } + } +} + +/// Which of `w` × `h` pixels are marked, counted so that the share of any rectangle's pixels that +/// are is read at once. +pub(super) struct Shares { + /// How many of the marked pixels lie above and left of each pixel corner. + sums: Vec, + w: usize, + h: usize, +} + +impl Shares { + /// The pixels `marks` marks (row by row). + pub(super) fn of(marks: &[bool], w: usize, h: usize) -> Self { + let stride = w + 1; + let mut sums = vec![0u32; stride * (h + 1)]; + // Row by row: the marked pixels left of each corner in its row, added to the row above's. + let mut above = vec![0u32; stride]; + for (j, out) in sums.chunks_exact_mut(stride).skip(1).enumerate() { + let row = marks.get(j * w..).unwrap_or(&[]).iter().copied().chain(std::iter::repeat(false)).take(w); + let mut run = 0u32; + for ((marked, s), up) in row.zip(out.iter_mut().skip(1)).zip(above.iter().skip(1)) { + run += u32::from(marked); + *s = up + run; + } + above.copy_from_slice(out); + } + Self { sums, w, h } + } + + /// The share (0 to 1) of `r`'s pixels that are marked: 0 for one with none of the pixels. + pub(super) fn share(&self, r: &Rect) -> f64 { + let (w, h, stride) = (self.w, self.h, self.w + 1); + let (x0, y0, x1, y1) = pixel_box(r, w, h); + if !r.is_finite() || x1 <= x0 || y1 <= y0 { + return 0.0; + } + let at = |x: usize, y: usize| self.sums.get(y * stride + x).copied().unwrap_or(0); + let inside = (at(x1, y1) + at(x0, y0)).saturating_sub(at(x0, y1) + at(x1, y0)); + f64::from(inside) / ((x1 - x0) as f64 * (y1 - y0) as f64) + } +} + +/// The pixels `r` touches of `w` × `h` (first and last column and row, the last ones excluded). +fn pixel_box(r: &Rect, w: usize, h: usize) -> (usize, usize, usize, usize) { + let clamp = |v: f64, max: usize| if v.is_finite() { v.clamp(0.0, max as f64) as usize } else { 0 }; + (clamp(r.x0.floor(), w), clamp(r.y0.floor(), h), clamp(r.x1.ceil(), w), clamp(r.y1.ceil(), h)) +} + +/// [`Shares::share`] of each of `rects` for the `w` × `h` pixels `marks` marks: counted one by one +/// when the rectangles hold fewer pixels in all than there are, else with [`Shares`]. +fn shares(marks: &[bool], w: usize, h: usize, rects: &[Rect]) -> Vec { + let few = rects + .iter() + .map(|r| pixel_box(r, w, h)) + .try_fold(0usize, |n, (x0, y0, x1, y1)| n.checked_add(x1.saturating_sub(x0).checked_mul(y1.saturating_sub(y0))?)); + if !few.is_some_and(|n| n <= w * h) { + let counted = Shares::of(marks, w, h); + return rects.iter().map(|r| counted.share(r)).collect(); + } + let share = |r: &Rect| { + let (x0, y0, x1, y1) = pixel_box(r, w, h); + if !r.is_finite() || x1 <= x0 || y1 <= y0 { + return 0.0; + } + let inside: usize = (y0..y1).map(|y| marks.get(y * w + x0..y * w + x1).map_or(0, |row| row.iter().filter(|m| **m).count())).sum(); + inside as f64 / ((x1 - x0) as f64 * (y1 - y0) as f64) + }; + rects.iter().map(share).collect() +} + /// Which of `w` × `h` pixels (row by row) lie in one of `areas`. fn in_areas(areas: &[Rect], w: usize, h: usize) -> Vec { + if areas.is_empty() { + return vec![false; w * h]; + } + let pixels: Vec<(usize, usize, usize, usize)> = areas.iter().map(|r| pixel_box(r, w, h)).collect(); + // Areas that cover fewer pixels in all than there are are marked one by one. + let covered = + pixels.iter().try_fold(0usize, |n, &(x0, y0, x1, y1)| if x1 < x0 || y1 < y0 { None } else { n.checked_add((x1 - x0).checked_mul(y1 - y0)?) }); + if covered.is_some_and(|n| n <= w * h) { + let mut inside = vec![false; w * h]; + for (x0, y0, x1, y1) in pixels { + for y in y0..y1 { + if let Some(row) = inside.get_mut(y * w + x0..y * w + x1) { + row.fill(true); + } + } + } + return inside; + } // Each area adds one inside it: corners marked, then summed along the rows and down the columns. let stride = w + 1; let mut count = vec![0i64; stride * (h + 1)]; - let clamp = |v: f64, max: usize| if v.is_finite() { v.clamp(0.0, max as f64) as usize } else { 0 }; - for r in areas { - let (x0, y0, x1, y1) = (clamp(r.x0.floor(), w), clamp(r.y0.floor(), h), clamp(r.x1.ceil(), w), clamp(r.y1.ceil(), h)); + for (x0, y0, x1, y1) in pixels { for (x, y, d) in [(x0, y0, 1), (x1, y0, -1), (x0, y1, -1), (x1, y1, 1)] { if let Some(c) = count.get_mut(y * stride + x) { *c += d; } } } - for row in count.chunks_mut(stride) { - let mut run = 0; - for c in row { - run += *c; - *c = run; - } + let mut inside = vec![false; w * h]; + if w == 0 { + return inside; } let mut column = vec![0i64; stride]; - for row in count.chunks_mut(stride) { - for (c, sum) in row.iter_mut().zip(column.iter_mut()) { - *sum += *c; - *c = *sum; + for (row, out) in count.chunks_exact(stride).zip(inside.chunks_exact_mut(w)) { + let mut run = 0; + for ((c, sum), o) in row.iter().zip(column.iter_mut()).zip(out) { + run += *c; + *sum += run; + *o = *sum > 0; } } - (0..h).flat_map(|j| (0..w).map(move |i| (i, j))).map(|(i, j)| count.get(j * stride + i).is_some_and(|c| *c > 0)).collect() + inside } +/// The least share of a text object's area (with the margin round it) where the page draws anything +/// or has type, for its type laid out again to count as type. +const MARKED: f64 = 0.05; + /// More of the page than this differing between the layers' art and the page's own, and the /// layers aren't used. -pub(super) const MAX_DIFFERENCE: f64 = 0.05; +pub(in crate::import) const MAX_DIFFERENCE: f64 = 0.05; /// More than this and the import says so. const NOTABLE_DIFFERENCE: f64 = 0.002; /// More of the page than this where one draws an object that the other doesn't (see /// [`Difference`]), and the layers aren't used: about a centimetre square on a letter page. -pub(super) const MAX_SOLID_DIFFERENCE: f64 = 0.001; +pub(in crate::import) const MAX_SOLID_DIFFERENCE: f64 = 0.001; /// How far (points) the art the layers print may reach past a page that holds it all. const PAST_THE_PAGE: f64 = 1.0; /// Do the layers' art and the page's own look alike (where the page holds all the art that prints, -/// also round it)? An error says they don't; `Ok` has the note to give when they differ a little: -/// with the share of the pixels that differ away from type when that is notable, otherwise with the -/// share of those that differ in the type's areas. -pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document) -> Result, String> { - let mut diff = view.difference(layered, frame.rect); +/// also round it), on every page the frame has ([`Frame::more`])? An error says they don't; `Ok` has +/// the notes to give when they differ a little: with the share of the pixels that differ away from +/// type when that is notable, otherwise with the share of those that differ in the type's areas, on +/// the page that differs most. With `type_reflow` (all the type laid out again from the file's text, +/// which may show in another font), type that differs doesn't make them differ: only art away from +/// type does, and the type's share is a note of its own. +pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document, type_reflow: bool) -> Result, String> { + let mut diff = view.difference_on_every_page(layered, frame.rect, type_reflow); if frame.whole && let Some(art) = vectorcraft_render::encode::art_bounds(as_printed(layered).as_ref().unwrap_or(layered)) .filter(|a| !frame.rect.inflate(PAST_THE_PAGE, PAST_THE_PAGE).contains_rect(*a)) @@ -299,24 +885,203 @@ pub(super) fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document // The page and the art the layers print beyond it, each in its own document's place. let all = frame.rect.union(art); let (dx, dy) = (frame.page_rect.x0 - frame.rect.x0, frame.page_rect.y0 - frame.rect.y0); - let round = difference(frame.page, Rect::new(all.x0 + dx, all.y0 + dy, all.x1 + dx, all.y1 + dy), layered, all); - diff = Difference { any: diff.any.max(round.any), art: diff.art.max(round.art), solid: diff.solid.max(round.solid) }; + diff = diff.max(difference(frame.page, Rect::new(all.x0 + dx, all.y0 + dy, all.x1 + dx, all.y1 + dy), layered, all)); } - if diff.any > MAX_DIFFERENCE || diff.solid > MAX_SOLID_DIFFERENCE { - return Err(format!("the art on them differs from the page's in {:.1}% of it", diff.any * 100.0)); + if diff.weighed(type_reflow) > MAX_DIFFERENCE || diff.solid > MAX_SOLID_DIFFERENCE { + return Err(format!("the art on them differs from the page's in {:.1}% of it", diff.weighed(type_reflow) * 100.0)); } if diff.any <= NOTABLE_DIFFERENCE { - return Ok(None); + return Ok(vec![]); + } + let art = format!( + "the art on the layers differs from the file's own page in about {:.1}% of it (brush strokes, live effects and the like that the layers' data doesn't describe)", + diff.art * 100.0 + ); + let typed = format!( + "the type on the layers differs from the file's own page in about {:.1}% of it (type laid out again from the file's text, or drawn in another font)", + diff.typed * 100.0 + ); + let art_notable = diff.art > NOTABLE_DIFFERENCE; + Ok(match (art_notable, type_reflow && diff.typed > NOTABLE_DIFFERENCE) { + (true, true) => vec![art, typed], + (true, false) => vec![art], + (false, _) => vec![typed], + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// One page that differs only in its type and another that differs only in its art keep both + /// shares when they are taken together. + #[test] + fn the_type_share_of_one_page_stays_beside_the_art_share_of_another() { + let typed = Difference { any: 0.03, art: 0.0, solid: 0.0, typed: 0.03 }; + let art = Difference { any: 0.04, art: 0.04, solid: 0.0, typed: 0.0 }; + let both = typed.max(art); + assert_eq!((both.any, both.art, both.typed), (0.04, 0.04, 0.03)); + } + + /// Shares and areas counted pixel by pixel match those read from sums. + #[test] + fn pixels_counted_one_by_one_match_the_sums() { + let (w, h) = (37, 23); + let marks: Vec = (0..w * h).map(|k| (k * 7 + k / 5) % 3 == 0).collect(); + let rects = + [Rect::new(-2.0, 3.5, 10.2, 9.0), Rect::new(5.0, 5.0, 12.0, 12.0), Rect::new(3.0, 3.0, 3.0, 8.0), Rect::new(10.5, 2.2, 20.7, 22.9)]; + // 66 + 49 + 0 + 231 pixels, fewer than the 851 there are: counted one by one. + let held: usize = rects.iter().map(|r| pixel_box(r, w, h)).map(|(x0, y0, x1, y1)| x1.saturating_sub(x0) * y1.saturating_sub(y0)).sum(); + assert_eq!(held, 346); + let summed = Shares::of(&marks, w, h); + let one_by_one = shares(&marks, w, h, &rects); + assert_eq!(one_by_one, rects.iter().map(|r| summed.share(r)).collect::>()); + // So many rectangles that they hold more pixels than there are: read from sums. + let many: Vec = rects.iter().cycle().take(40).copied().collect(); + assert_eq!(shares(&marks, w, h, &many)[..4], one_by_one[..]); + assert_eq!(in_areas(&many, w, h), in_areas(&rects, w, h)); + assert!(in_areas(&rects, w, h).contains(&true)); + } + + /// A document with a 40-point gray square in each of `n` 100-point areas side by side, `gap` + /// apart (the one in area `nudged` 20 points to the right), the areas, and the squares' ids. + fn squares(n: usize, gap: f64, nudged: Option) -> (Document, Vec, Vec) { + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let (mut areas, mut ids) = (vec![], vec![]); + for i in 0..n { + let x = i as f64 * (100.0 + gap); + areas.push(Rect::new(x, 0.0, x + 100.0, 100.0)); + let x = if nudged == Some(i) { x + 20.0 } else { x }; + ids.push(square(&mut doc, layer, Rect::new(x + 30.0, 30.0, x + 70.0, 70.0))); + } + (doc, areas, ids) + } + + /// A gray square on `rect` added to `layer` of `doc`: its id. + fn square(doc: &mut Document, layer: vectorcraft_doc::NodeId, rect: Rect) -> vectorcraft_doc::NodeId { + filled(doc, layer, rect, 0.5) + } + + /// A rectangle on `rect` filled with `k` black added to `layer` of `doc`: its id. + fn filled(doc: &mut Document, layer: vectorcraft_doc::NodeId, rect: Rect, k: f32) -> vectorcraft_doc::NodeId { + let paint = vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, k)); + let appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint))], + ..Default::default() + }; + let node = Node::path(doc.alloc_id(), vectorcraft_geom::shapes::rectangle(rect), appearance); + let id = node.id; + doc.insert(Some(layer), 0, node).unwrap(); + id + } + + /// A frame of `page`'s `areas`, each its own artboard. + fn frame_of<'a>(page: &'a Document, areas: &[Rect]) -> Frame<'a> { + let first = areas[0]; + Frame { page, page_rect: first, rect: first, whole: false, pages: vec![], more: areas[1..].iter().map(|r| (*r, *r)).collect() } + } + + /// The layers are drawn once for all the pages of a sheet, a fraction of a pixel apart as they + /// are, and the drawings are kept until the document changes. + #[test] + fn the_layers_are_drawn_once_for_the_pages_and_kept() { + let (doc, areas, _) = squares(4, 20.3, None); + let frame = frame_of(&doc, &areas); + let mut view = PageView::new(&frame); + assert_eq!(view.sheets.len(), 1); + let each = view.differences(&doc, areas[0], false); + assert_eq!(each.len(), 4); + assert!(each.iter().all(|d| d.any == 0.0), "{:?}", each.iter().map(|d| d.any).collect::>()); + assert_eq!(view.draws, 1, "one drawing for the four pages"); + assert!(compare(&frame, &mut view, &doc, false).is_ok()); + assert_eq!(view.difference_on_every_page(&doc, areas[0], true).any, 0.0); + assert_eq!(view.draws, 1, "the same document isn't drawn again"); + let (nudged, _, _) = squares(4, 20.3, Some(3)); + let each = view.differences(&nudged, areas[0], false); + assert_eq!(view.draws, 2); + assert!(each[3].solid > MAX_SOLID_DIFFERENCE && each[..3].iter().all(|d| d.any == 0.0)); + } + + /// Taking an object out of the layers has only the pages it lies on drawn again; the other + /// pages' drawings are kept for the document without it. + #[test] + fn a_removal_draws_again_only_the_pages_it_lies_on() { + let (page, areas, _) = squares(4, 20.3, None); + let (mut layers, _, _) = squares(4, 20.3, None); + let layer = layers.layers[0].id; + let extra = square(&mut layers, layer, Rect::new(2.0 * 120.3 + 5.0, 5.0, 2.0 * 120.3 + 25.0, 25.0)); + let frame = frame_of(&page, &areas); + let mut view = PageView::new(&frame); + let before = view.differences(&layers, areas[0], false); + assert!(before[2].any > 0.0); + let mut without = layers.clone(); + without.node_mut(extra).unwrap().visible = false; + let shares = view.weigh_without(&layers, &without, &[2]); + assert_eq!(view.draws, 2, "only the third page is drawn without it"); + assert!(shares.len() == 1 && shares[0].2 < shares[0].1, "{shares:?}"); + view.adopt(&without); + let after = view.differences(&without, areas[0], false); + assert_eq!(view.draws, 2, "the other pages' drawings are kept"); + let again = PageView::new(&frame).differences(&without, areas[0], false); + for (a, b) in after.iter().zip(&again) { + assert!((a.any - b.any).abs() < 1e-3 && (a.solid - b.solid).abs() < 1e-3); + } + assert_eq!(after[2].any, 0.0); + } + + /// Pages far apart are drawn on sheets of their own, and a long row of them on sheets no longer + /// than the limit. + #[test] + fn sheets_stay_within_their_limits() { + let (doc, areas, _) = squares(3, 5000.0, None); + assert_eq!(PageView::new(&frame_of(&doc, &areas)).sheets.len(), 3); + let (doc, areas, _) = squares(40, 0.0, None); + let frame = frame_of(&doc, &areas); + let mut view = PageView::new(&frame); + assert!(view.sheets.len() > 1); + assert!(view.sheets.iter().all(|s| s.rect.width() * s.scale <= MAX_SHEET_SIDE)); + assert!(view.differences(&doc, areas[0], false).iter().all(|d| d.any == 0.0)); + assert_eq!(view.draws, view.sheets.len()); + let before = view.draws; + assert_eq!(view.draw(&doc, &[0, 1]).len(), 2); + assert_eq!(view.draws, before + 2, "two pages of a long sheet are drawn on their own"); + } + + /// A page moved by a fraction of a pixel onto its sheet doesn't count the column its move took + /// off its artboard, where the layers have art past the artboard before it and the page has none. + #[test] + fn the_column_a_page_moved_onto_doesnt_count() { + // The second area starts 400.4 pixels from the first at 4 pixels a point: it moves 0.4 pixels + // to the left, and its first column starts at 100 points. + let areas = [Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(100.1, 0.0, 200.1, 100.0)]; + let mut page = Document::new(100.0, 100.0); + let layer = page.layers[0].id; + filled(&mut page, layer, areas[0], 1.0); + let mut layers = page.clone(); + let layer = layers.layers[0].id; + // Black reaching past the first artboard, into the space between the two. + filled(&mut layers, layer, Rect::new(99.0, 0.0, 100.1, 100.0), 1.0); + let frame = frame_of(&page, &areas); + let mut view = PageView::new(&frame); + assert_eq!(view.sheets.len(), 1); + let each = view.differences(&layers, areas[0], false); + assert!(each.iter().all(|d| d.any == 0.0), "{:?}", each.iter().map(|d| d.any).collect::>()); + assert_eq!(compare(&frame, &mut view, &layers, false), Ok(vec![])); + assert_eq!(view.colour_difference(1, &layers), 0.0); + } + + /// The drawings of two documents weighed in turn are both kept. + #[test] + fn the_drawings_of_two_documents_are_kept() { + let (doc, areas, _) = squares(4, 20.3, None); + let (other, _, _) = squares(4, 20.3, Some(1)); + let frame = frame_of(&doc, &areas); + let mut view = PageView::new(&frame); + for _ in 0..3 { + view.differences(&doc, areas[0], false); + view.differences(&other, areas[0], false); + } + assert_eq!(view.draws, 2, "each document is drawn once"); } - Ok(Some(if diff.art > NOTABLE_DIFFERENCE { - format!( - "the art on the layers differs from the file's own page in about {:.1}% of it (brush strokes, live effects and the like that the layers' data doesn't describe)", - diff.art * 100.0 - ) - } else { - format!( - "the type on the layers differs from the file's own page in about {:.1}% of it (type laid out again from the file's text, or drawn in another font)", - (diff.any - diff.art) * 100.0 - ) - })) } diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index c4403cdcf9..9fd54cc252 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -1,4 +1,4 @@ -use super::build::{Page, build}; +use super::build::{PAGE_MOVE, Page, build, build_from, build_on_page, build_without_page, reid_page_art}; use super::slots::LAYERS_UNREAD; use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect, Vec2, ai}; @@ -6,31 +6,93 @@ use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect /// its program in the legacy format, see [`editing_copy`]): its layers (the /// hidden ones too), groups, compound paths, clipping groups and artboards, with the text and the /// strokes around it of the page. When the file has no editing copy, `visible` as it was; when it -/// has one that can't be used, `visible` with a warning that says why, and with the swatches of -/// the editing copy's palette ([`use_palette`]) when it could be read. -pub(in super::super) fn layered(ps: &[u8], visible: Imported, trust: bool) -> Imported { - let Some(data) = editing_copy(ps) else { return visible }; - let result = data.as_deref().map_err(Clone::clone).and_then(|data| build(data, Some(&visible.document), Page::Art, false, trust, 1.0)); +/// has one that can't be used, `visible` with a warning that says why, with the swatches of the +/// editing copy's palette ([`use_palette`]), its graphic styles ([`use_styles`]), its symbols +/// ([`use_symbols`]) and its variable library ([`use_variables`]) when it could be read, and with +/// its layer tree, empty, below the page's layer when that could be read (#2033). A program in the +/// legacy format without layers (`illustrator`, see [`program_alone`]) is read with its art on one +/// layer; when that can't be used, the file is `visible` as it was. +pub(in super::super) fn layered(ps: &[u8], visible: Imported, trust: bool, illustrator: bool) -> Imported { + let Some(data) = editing_copy(ps) else { + let read = illustrator.then(|| one_layer(ps)).flatten().and_then(|p| build(&p, Some(&visible.document), Page::Art, false, trust, 1.0).ok()); + return match read { + Some((document, warnings)) => with_page_notes(document, warnings, &visible), + None => visible, + }; + }; + // The layer tree is kept from the structure read, for the page to come in on when the layers + // can't be used. + // Private data kept apart from the program: the program's own header gives the author and + // custom colors the private data's header may lack. + let read = |d: &[u8]| if matches!(data, Ok(Cow::Owned(_))) { ai::read_beside(d, true, ps, true) } else { ai::read_over_page(d, true) }; + let (tree, result) = match data.as_deref() { + Ok(d) => match read(d) { + Ok(s) => (layer_tree(&s.doc.layers), build_from(s, d, Some(&visible.document), Page::Art, false, trust, 1.0)), + Err(why) => (vec![], Err(why)), + }, + Err(why) => (vec![], Err(why.clone())), + }; match result { - Ok((document, mut warnings)) => { - for w in &visible.warnings { - if !warnings.contains(w) { - warnings.push(w.clone()); - } - } - Imported { document, warnings, preview: false } - } + Ok((document, warnings)) => with_page_notes(document, warnings, &visible), Err(why) => { let mut v = visible; if let Ok(data) = &data { - use_palette(data, &mut v.document); + let have = v.document.patterns.len(); + let own_palette = use_palette(data, &mut v.document); + use_brushes(data, &mut v.document, have, &mut v.warnings); + use_styles(data, &mut v.document, true, 1.0, None); + use_symbols(data, &mut v.document, own_palette, &mut v.warnings); + use_variables(data, &mut v.document, &mut v.warnings); } - v.warnings.push(format!("{LAYERS_UNREAD} ({why}): it comes in as its page, in one layer")); + if tree.is_empty() { + v.warnings.push(format!("{LAYERS_UNREAD} ({why}): it comes in as its page, in one layer")); + return v; + } + let doc = &mut v.document; + let mut layers: Vec> = tree.iter().map(|l| Arc::new(doc.reid(l))).collect(); + let taken: Vec> = layers.iter().map(|l| l.name.clone()).collect(); + layers.append(&mut doc.layers); + doc.layers = layers; + // The page's layer takes a name of its own: the file's layers usually have its `Layer 1`. + for i in taken.len()..doc.layers.len() { + if doc.layers.get(i).is_some_and(|l| taken.contains(&l.name)) { + let name = doc.next_layer_name(); + if let Some(l) = doc.layers.get_mut(i) { + Arc::make_mut(l).name = Some(name); + } + } + } + v.warnings.push(format!("{LAYERS_UNREAD} ({why}): it comes in as its page, on a layer above its layers, which come in empty")); v } } } +/// `document`, read from the editing copy with the notes `warnings`, followed by the notes of +/// reading `visible` that it doesn't already have. +fn with_page_notes(document: Document, mut warnings: Vec, visible: &Imported) -> Imported { + for w in &visible.warnings { + if !warnings.contains(w) { + warnings.push(w.clone()); + } + } + Imported { document, warnings, preview: false } +} + +/// The layers in `nodes` with only their sublayers in them: names, order and options without the art. +fn layer_tree(nodes: &[Arc]) -> Vec> { + let layers = nodes.iter().filter(|n| matches!(n.kind, NodeKind::Layer { .. })); + layers + .map(|l| { + let mut l = Node::clone(l); + if let Some(children) = l.children_mut() { + *children = layer_tree(children); + } + Arc::new(l) + }) + .collect() +} + /// The `.ai` `visible` (read as its PDF part), or a PDF saved with the editing data, read through /// its editing copy (`private`, the joined `AIPrivateData` or `AIPDFPrivateData` streams) instead, /// as [`layered`] reads an EPS: with the layers and objects of the file, its artboards (with the @@ -39,43 +101,72 @@ pub(in super::super) fn layered(ps: &[u8], visible: Imported, trust: bool) -> Im /// notes, or a note saying why the layers weren't read when the editing data can't be decompressed /// or its layers can't be read. The flag returned is `true` when the document is the one read from /// the layers; else the document is `visible`, its pages moved by `place_pages` when the editing -/// data was decompressed but its layers can't be read, and its swatches those of the editing data's -/// palette ([`use_palette`]) when it was decompressed. `outlined`: the PDF part's type was read as -/// outlines (a file whose type shows then comes in as its PDF part). +/// data was decompressed but its layers can't be read, and its swatches, brushes, graphic styles, +/// symbols and variables those of the editing data's palette ([`use_palette`]), brushes +/// ([`use_brushes`]), styles ([`use_styles`]), symbols ([`use_symbols`]) and variable library +/// ([`use_variables`]) when it was decompressed: a graphic style library or a symbol library, which +/// has no layers, opens with its styles or its symbols, and editing data with no layers opens +/// on the page of its active artboard under the checks of `place_pages`. `outlined`: the PDF part's type was +/// read as outlines (a file whose type shows then comes in as its PDF part). /// `trust`: layers that draw differently from the PDF part are used all the same, with a warning. /// `unit`: the size in points of a unit of the PDF part's user space, its first page's `UserUnit`, /// by which its art came in scaled. Editing data whose artboard matches the page only in those /// units comes in `unit` times as large, and so does the artboard layout `place_pages` takes from /// it. pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec, outlined: bool, trust: bool, unit: f64) -> (Document, Vec, bool) { + layered_ai_from(AiLayers::decode(private), visible, warnings, outlined, trust, unit) +} + +/// [`layered_ai`] of the editing copy `layers`, as far as it was already decoded and read. +pub fn layered_ai_from( + layers: AiLayers, + visible: Document, + warnings: Vec, + outlined: bool, + trust: bool, + unit: f64, +) -> (Document, Vec, bool) { let unread = |mut all: Vec, why: &str| { all.push(format!("{LAYERS_UNREAD} from its editing data ({why}): they come from its PDF part")); all }; - let data = match ai::decode_private(private) { + let AiLayers { data, structure } = layers; + let data = match data { Ok(data) => data, Err(why) => return (visible, unread(warnings, &why), false), }; if !has_layers(&data) { - let mut visible = visible; - use_palette(&data, &mut visible); + let (mut visible, mut warnings) = (visible, warnings); + let (boards, active) = ai::artboards(&data); + if board_scale(&boards, &visible, unit).is_some() { + visible.opened_artboard = active_page(active, &visible); + } + let have = visible.patterns.len(); + let own_palette = use_palette(&data, &mut visible); + use_brushes(&data, &mut visible, have, &mut warnings); + use_styles(&data, &mut visible, false, unit, Some(&boards)); + use_symbols(&data, &mut visible, own_palette, &mut warnings); + use_variables(&data, &mut visible, &mut warnings); return (visible, warnings, false); } // The PDF part, its pages placed and named as the editing data's artboards are, when the // layers can't be used (`why`). - let from_pdf_part = |mut visible: Document, warnings: Vec, why: &str| { - place_pages(&ai::artboards(&data), &mut visible, unit); - use_palette(&data, &mut visible); + let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str| { + let (boards, active) = ai::artboards(&data); + place_pages(&boards, active, &mut visible, unit); + let have = visible.patterns.len(); + let own_palette = use_palette(&data, &mut visible); + use_brushes(&data, &mut visible, have, &mut warnings); + use_styles(&data, &mut visible, false, unit, Some(&boards)); let mut all = unread(warnings, why); - all.extend(ai::variables(&data).note()); + use_symbols(&data, &mut visible, own_palette, &mut all); + use_variables(&data, &mut visible, &mut all); (visible, all, false) }; - match build(&data, Some(&visible), Page::Artboard, outlined, trust, unit) { - // An image too large for the editing data's reader would be missing from the layers, while - // the PDF part has it: the file comes in as its PDF part instead (#1479). - Ok((_, notes)) if notes.iter().any(|n| n == ai::IMAGE_TOO_LARGE) => { - from_pdf_part(visible, warnings, "an image is too large to read from them") - } + let built = structure + .unwrap_or_else(|| ai::read_over_page(&data, false).map(Box::new)) + .and_then(|structure| build_from(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit)); + match built { Ok((mut done, notes)) => { done.setup.bleed = visible.setup.bleed; let mut all = warnings; @@ -86,19 +177,87 @@ pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec, outl } } +/// The `.ai` whose editing copy is `private` (as [`layered_ai`] takes it) from its layers alone, +/// without its PDF part, whose pages (each its trim box in points, width and height) are `pages` +/// and are in units of `unit` points (its first page's `UserUnit`): the document and the notes of +/// reading it, when the file's text document makes all of its type and nothing in its layers needs +/// the PDF part (see `build_without_page`). Nothing is compared with the PDF part. Else, as the +/// error, what was decoded and read of the editing copy, for [`layered_ai_from`] once the PDF part +/// is imported. +pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64) -> Result<(Document, Vec), AiLayers> { + let data = match ai::decode_private(private) { + Ok(data) => data, + Err(why) => return Err(AiLayers { data: Err(why), structure: None }), + }; + if !has_layers(&data) { + return Err(AiLayers { data: Ok(data), structure: None }); + } + // An image past the hard limits is read as an unread box, which the PDF part's art replaces. + let structure = match ai::read_over_page(&data, false) { + Ok(structure) => structure, + Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)) }), + }; + match build_without_page(structure, &data, pages, unit) { + Ok(Ok((doc, notes))) => Ok((doc, notes)), + Ok(_) => Err(AiLayers { data: Ok(data), structure: None }), + Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)) }), + } +} + +/// A `.ai`'s editing copy decoded, and its layers read when they were, for [`layered_ai_from`]: +/// what [`ai_layers_alone`] read isn't decoded or read again. +pub struct AiLayers { + /// The editing copy decoded, or why it can't be. + data: Result, String>, + /// Its layers read with [`ai::read`] as [`layered_ai`] reads them, or why they can't be; `None` + /// when they are still to be read. + structure: Option, String>>, +} + +impl AiLayers { + /// The editing copy `private` (as [`layered_ai`] takes it), decoded. + pub fn decode(private: &[u8]) -> Self { + Self { data: ai::decode_private(private), structure: None } + } +} + +/// The id of the artboard of `doc` that the editing copy `private` (as [`layered_ai`] takes it) +/// names as its active one (`CropAreaActive`, an index into its `ArtboardArray`), for `doc` +/// restored from the document a `.ai` file carries beside that copy: `None` when the copy names +/// the first artboard, names none, can't be decoded, or names an artboard `doc` doesn't have. +pub fn ai_opened_artboard(private: &[u8], doc: &Document) -> Option { + let data = ai::decode_private(private).ok()?; + active_page(ai::active_artboard(&data), doc) +} + +/// `doc` (a file read as its page or PDF part, in place of its layers) with the variables, data +/// sets, active data set and lock of the variable library of its editing data `data`, as [`build`] +/// gives a document read from the layers, and the note about what of the library wasn't read +/// added to `warnings`: its bindings aren't, as the objects they bind aren't the layers' objects. +/// Left as it is when the editing data has no library. +fn use_variables(data: &[u8], doc: &mut Document, warnings: &mut Vec) { + let read = ai::variables(data); + warnings.extend(read.note()); + warnings.extend(ai::bindings_note(read.bindings.len() + read.bindings_skipped)); + if read.present { + doc.variables = read.variables.into(); + } +} + /// `doc` (a `.ai` read as its PDF part, in place of its layers) with the swatches and color groups /// of the palette of its editing data `data` in place of the default ones, as [`build`] gives a /// document read from the layers. The spot and pattern swatches of the PDF part's art that the -/// palette doesn't have follow the palette's swatches. The patterns that the editing data defines and -/// the PDF part lacks come in for the palette's pattern swatches, with the images they show. Left as -/// it is when the palette is empty. -fn use_palette(data: &[u8], doc: &mut Document) { - let Some(ai::PaletteSwatches { swatches, groups, patterns, images }) = ai::palette(data, &doc.patterns) else { return }; +/// palette doesn't have follow the palette's swatches. The patterns that the editing data defines come +/// in for the palette's pattern swatches, with the images they show; one whose name a pattern of +/// the PDF part already has takes a free variant of it ([`ai::palette`]). Left as +/// it is when the palette is empty. Whether the palette's swatches came in. +fn use_palette(data: &[u8], doc: &mut Document) -> bool { + let Some(ai::PaletteSwatches { swatches, groups, patterns, images }) = ai::palette(data, &doc.patterns) else { return false }; for (key, blob) in images { doc.images.entry(key).or_insert(blob); } for mut p in patterns { - p.art = p.art.iter().map(|n| Arc::new(doc.reid(n))).collect(); + p.art = p.art.iter().map(|n| Arc::new(reid_page_art(doc, n))).collect(); doc.patterns.push(p); } let named = |name: &str| swatches.iter().chain(groups.iter().flat_map(|g| &g.swatches)).any(|s| s.name == name); @@ -107,34 +266,161 @@ fn use_palette(data: &[u8], doc: &mut Document) { let mut swatches = swatches; swatches.extend(art); (doc.swatches, doc.swatch_groups) = (swatches.into(), groups.into()); + true } -/// The pages of `doc` (a `.ai` read as its PDF part: a page per artboard, in a row) named as -/// `boards` (the artboards of its editing data, in art space) name them, and moved, with the art on -/// each, to where they are, so the artboards keep their names and layout when the layers can't be -/// read (#1068). Left as they are unless there are as many artboards as pages, each the size of its -/// page in points, or, when `unit` is above 1, each the size of its page in units of `unit` points: -/// then the layout is drawn `unit` times as large. -fn place_pages(boards: &[(String, Rect)], doc: &mut Document, unit: f64) { - if boards.is_empty() || boards.len() != doc.artboards.len() { +/// `doc` (a file read as its page or PDF part, in place of its layers) with the brushes of its +/// editing data `data` in place of the default ones, as [`build`] gives a document read from the +/// layers, the patterns of the editing data their art paints with (named apart from the first +/// `have` patterns of `doc`, those of the page or PDF part, as [`use_palette`] names them, which +/// may have added some of them already), and the note for the brushes left out added to +/// `warnings`. Left as it is when the editing data has no brushes. +fn use_brushes(data: &[u8], doc: &mut Document, have: usize, warnings: &mut Vec) { + let page = doc.patterns.get(..have).unwrap_or(&doc.patterns); + let Some(ai::Brushes { brushes, patterns, images, note }) = ai::brushes(data, page) else { return }; + for (key, blob) in images { + doc.images.entry(key).or_insert(blob); + } + for mut p in patterns { + if doc.pattern(&p.name).is_some() { + continue; + } + p.art = p.art.iter().map(|n| Arc::new(reid_page_art(doc, n))).collect(); + doc.patterns.push(p); + } + vectorcraft_brush::store(doc, &brushes); + warnings.extend(note.filter(|n| !warnings.contains(n))); +} + +/// `doc` (a file read as its page or PDF part, in place of its layers) with the graphic styles of +/// its editing data `data` in place of the default ones, as [`build`] gives a document read from +/// the layers ([`ai::graphic_styles`], `large_canvas` as it takes it). Unless `large_canvas` is set, +/// their strokes and effects are drawn `unit` times as large when the editing data's artboards are +/// the size of `doc`'s pages in units of `unit` points, else as many times as large as the data's +/// declared large canvas scale when they are the pages' size at that scale ([`board_scale`]). +/// `boards`: the editing data's artboards when they were already read. Left as it is when the +/// editing data has no style this reads. +fn use_styles(data: &[u8], doc: &mut Document, large_canvas: bool, unit: f64, boards: Option<&[(String, Rect)]>) { + let (mut styles, canvas) = ai::graphic_styles(data, large_canvas); + if styles.is_empty() { return; } + if !large_canvas && (unit != 1.0 || canvas != 1.0) { + let read; + let boards = match boards { + Some(b) => b, + None => { + read = ai::artboards(data).0; + &read + } + }; + let k = board_scale(boards, doc, unit).or_else(|| board_scale(boards, doc, canvas)); + if let Some(k) = k.filter(|k| *k != 1.0) { + for g in &mut styles { + g.appearance.scale_strokes(k); + g.appearance.scale_effects(k, vectorcraft_effects::scale_effect); + } + } + } + doc.graphic_styles = styles.into(); +} + +/// `doc` (a file read as its page or PDF part, in place of its layers) with the symbols of its +/// editing data `data` ([`ai::symbols`]), their registration points, the images their art shows and +/// the global and spot colors it is linked to that `doc` has no such swatch for (a color whose name +/// another swatch has takes that swatch's place when it is a default swatch and not `own_palette`, +/// the swatches being those of the editing data's palette, and else comes in under a free variant +/// of the name, which the art then names, as does one whose name a color group has), as [`build`] gives a document read from the layers, and +/// the note about instances that can't be drawn added to `warnings`. An object of their art linked +/// to a graphic style keeps the link when [`use_styles`] gave `doc` the editing data's styles. The +/// symbols' art keeps the editing data's units, as in a document read from the layers: when +/// [`use_styles`] draws the styles' strokes and effects larger (a file in larger units), linked art +/// isn't scaled with them. Left as it is when `doc` has symbols already or the editing data has +/// none this reads. +fn use_symbols(data: &[u8], doc: &mut Document, own_palette: bool, warnings: &mut Vec) { + if !doc.symbols.is_empty() { + return; + } + let Some(ai::Symbols { symbols, images, swatches }) = ai::symbols(data) else { return }; + for (key, blob) in images { + doc.images.entry(key).or_insert(blob); + } + // A color whose name a swatch of another color has takes that swatch's place when it is a + // default swatch, and else a free variant of the name, as does one whose name a color group has. + let (defaults, groups) = vectorcraft_color::default_swatches(doc.color_mode.model()); + let is_default = + |have: &vectorcraft_color::Swatch| !own_palette && defaults.iter().chain(groups.iter().flat_map(|g| &g.swatches)).any(|d| d == have); + let mut renamed = std::collections::HashMap::new(); + for s in swatches { + match doc.swatch(&s.name) { + None if !doc.swatch_name_taken(&s.name) => doc.swatches.push(s), + Some(have) if have == &s || (s.name.starts_with('[') && s.name.ends_with(']')) => {} + Some(have) if is_default(have) => { + if let Some(default) = doc.swatch_mut(&s.name) { + *default = s; + } + } + _ => { + let name = doc.free_swatch_name(&s.name); + renamed.insert(s.name.clone(), name.clone()); + doc.swatches.push(vectorcraft_color::Swatch { name, ..s }); + } + } + } + let mut follow = |_: &mut vectorcraft_color::Color, link: &mut Option, _: &mut f32| { + let Some(new) = link.as_ref().and_then(|l| renamed.get(l)) else { return false }; + *link = Some(new.clone()); + true + }; + for (mut symbol, registration) in symbols { + let mut art = reid_page_art(doc, &symbol.art); + if !renamed.is_empty() { + vectorcraft_doc::swatches::map_node_solid_paints(&mut art, &mut follow); + } + symbol.art = Arc::new(art); + doc.set_symbol_registration(&symbol.name, registration); + doc.symbols.push(symbol); + } + // Symbols that hold instances of themselves can't be drawn: those instances go. + doc.limit_depth_noting(warnings); +} + +/// How many points a unit of `boards` (the artboards of a file's editing data, in art space) is in +/// `doc` (the file read as its PDF part: a page per artboard): 1 when there are as many artboards as +/// pages, each the size of its page in points, or `unit` when `unit` is above 1 and each is the size +/// of its page in units of `unit` points. `None` otherwise. +fn board_scale(boards: &[(String, Rect)], doc: &Document, unit: f64) -> Option { + if boards.is_empty() || boards.len() != doc.artboards.len() { + return None; + } let differ = |k: f64| { boards .iter() .zip(&doc.artboards) .any(|((_, b), a)| (b.width() - a.rect.width() / k).abs() > 0.5 || (b.height() - a.rect.height() / k).abs() > 0.5) }; - let k = if !differ(1.0) { - 1.0 + if !differ(1.0) { + Some(1.0) } else if unit.is_finite() && unit > 1.0 && !differ(unit) { - unit + Some(unit) } else { - return; - }; + None + } +} + +/// The pages of `doc` (a `.ai` read as its PDF part: a page per artboard, in a row) named as +/// `boards` (the artboards of its editing data, in art space) name them, and moved, with the art on +/// each, to where they are, so the artboards keep their names and layout when the layers can't be +/// read (#1068); the page of the artboard at `active` (the active one) is the active artboard. Left +/// as they are unless there are as many artboards as pages, each the size of its page in points, +/// or, when `unit` is above 1, each the size of its page in units of `unit` points: then the layout +/// is drawn `unit` times as large. +fn place_pages(boards: &[(String, Rect)], active: Option, doc: &mut Document, unit: f64) { + let Some(k) = board_scale(boards, doc, unit) else { return }; for ((name, _), a) in boards.iter().zip(&mut doc.artboards) { a.name.clone_from(name); } + doc.opened_artboard = active_page(active, doc); let [(_, first), _, ..] = boards else { return }; // Art space (y up) → the document, the first artboard's top left at the origin, as `read` has it, // `k` points a unit. @@ -149,6 +435,13 @@ fn place_pages(boards: &[(String, Rect)], doc: &mut Document, unit: f64) { } } +/// The id of the page of `doc` (a `.ai` read as its PDF part: a page per artboard) for the artboard +/// at `active` among those of its editing data, to open the file on: `None` for the first, which a +/// file opens on anyway, or when `doc` has no such page. +fn active_page(active: Option, doc: &Document) -> Option { + active.filter(|i| *i > 0).and_then(|i| doc.artboards.get(i)).map(|a| a.id) +} + /// The objects in `layer` (and its sublayers) moved by the move of the page they are on. fn place_art(layer: &mut Node, pages: &[Rect], moves: &[Vec2]) { let Some(children) = layer.children_mut() else { return }; @@ -163,16 +456,27 @@ fn place_art(layer: &mut Node, pages: &[Rect], moves: &[Vec2]) { let fit = |p: &Rect| (p.intersect(r).area().max(0.0), -(p.center() - r.center()).hypot()); let Some((i, _)) = pages.iter().map(fit).enumerate().max_by(|(_, a), (_, b)| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))) else { continue }; if let Some(v) = moves.get(i).filter(|v| **v != Vec2::ZERO) { - Arc::make_mut(child).transform(Affine::translate(*v), false); + Arc::make_mut(child).transform(Affine::translate(*v), PAGE_MOVE); } } } /// A `.ai` saved without its PDF part (its pages show only a placeholder) from its editing copy /// alone (`private`, the joined `AIPrivateData` streams) → the document and the import's notes. +/// Editing data written on a large canvas comes in at its declared scale: no page holds the size. pub fn ai_alone(private: &[u8]) -> Result<(Document, Vec), String> { let data = ai::decode_private(private)?; - build(&data, None, Page::Artboard, false, false, 1.0) + build_from(ai::read(&data, true)?, &data, None, Page::Artboard, false, false, 1.0) +} + +/// [`ai_alone`] for a `.ai` whose PDF part can't be read, its first page `page` (width and height) +/// points large in units of `unit` points (its `UserUnit`): editing data whose first artboard, or +/// whose art's box, has the page's size in those units, and not in points, comes in `unit` times as +/// large, as [`layered_ai`] reads it. A page turned a quarter (`/Rotate 90`) is measured either +/// way round. +pub fn ai_alone_on_page(private: &[u8], page: (f64, f64), unit: f64) -> Result<(Document, Vec), String> { + let data = ai::decode_private(private)?; + build_on_page(&data, page, unit) } /// Does the editing data (or a program in the legacy format) have layers? @@ -202,7 +506,7 @@ pub(in super::super) fn program_alone(ps: &[u8], illustrator: bool) -> Option